diff --git a/.eslintrc.json b/.eslintrc.json index 819d042c25b16..b1140d983d10f 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -81,6 +81,7 @@ { "selector": "enumMember", "format": ["camelCase", "PascalCase"], "leadingUnderscore": "allow", "filter": { "regex": "^[A-Za-z]+_[A-Za-z]+$", "match": false } }, { "selector": "property", "format": null } ], + "@typescript-eslint/no-unnecessary-type-assertion": "error", // Rules enabled in typescript-eslint configs that are not applicable here "@typescript-eslint/ban-ts-comment": "off", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000000000..501e7f04c273d --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,2518 @@ +lockfileVersion: '6.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +devDependencies: + '@esfx/canceltoken': + specifier: ^1.0.0 + version: 1.0.0 + '@octokit/rest': + specifier: ^19.0.13 + version: 19.0.13 + '@types/chai': + specifier: ^4.3.4 + version: 4.3.4 + '@types/glob': + specifier: ^8.1.0 + version: 8.1.0 + '@types/microsoft__typescript-etw': + specifier: ^0.1.1 + version: 0.1.1 + '@types/minimist': + specifier: ^1.2.2 + version: 1.2.2 + '@types/mocha': + specifier: ^10.0.1 + version: 10.0.1 + '@types/ms': + specifier: ^0.7.31 + version: 0.7.31 + '@types/node': + specifier: latest + version: 20.8.8 + '@types/source-map-support': + specifier: ^0.5.6 + version: 0.5.6 + '@types/which': + specifier: ^2.0.1 + version: 2.0.1 + '@typescript-eslint/eslint-plugin': + specifier: ^6.0.0 + version: 6.0.0(@typescript-eslint/parser@6.0.0)(eslint@8.22.0)(typescript@5.0.2) + '@typescript-eslint/parser': + specifier: ^6.0.0 + version: 6.0.0(eslint@8.22.0)(typescript@5.0.2) + '@typescript-eslint/utils': + specifier: ^6.0.0 + version: 6.0.0(eslint@8.22.0)(typescript@5.0.2) + azure-devops-node-api: + specifier: ^12.0.0 + version: 12.0.0 + c8: + specifier: ^7.14.0 + version: 7.14.0 + chai: + specifier: ^4.3.7 + version: 4.3.7 + chalk: + specifier: ^4.1.2 + version: 4.1.2 + chokidar: + specifier: ^3.5.3 + version: 3.5.3 + diff: + specifier: ^5.1.0 + version: 5.1.0 + dprint: + specifier: ^0.41.0 + version: 0.41.0 + esbuild: + specifier: ^0.19.0 + version: 0.19.0 + eslint: + specifier: ^8.22.0 + version: 8.22.0 + eslint-formatter-autolinkable-stylish: + specifier: ^1.2.0 + version: 1.2.0(eslint@8.22.0) + eslint-plugin-local: + specifier: ^1.0.0 + version: 1.0.0 + eslint-plugin-no-null: + specifier: ^1.0.2 + version: 1.0.2(eslint@8.22.0) + eslint-plugin-simple-import-sort: + specifier: ^10.0.0 + version: 10.0.0(eslint@8.22.0) + fast-xml-parser: + specifier: ^4.0.11 + version: 4.0.11 + glob: + specifier: ^8.1.0 + version: 8.1.0 + hereby: + specifier: ^1.6.4 + version: 1.6.4 + jsonc-parser: + specifier: ^3.2.0 + version: 3.2.0 + minimist: + specifier: ^1.2.8 + version: 1.2.8 + mocha: + specifier: ^10.2.0 + version: 10.2.0 + mocha-fivemat-progress-reporter: + specifier: ^0.1.0 + version: 0.1.0 + ms: + specifier: ^2.1.3 + version: 2.1.3 + node-fetch: + specifier: ^3.2.10 + version: 3.2.10 + playwright: + specifier: ^1.38.0 + version: 1.38.0 + source-map-support: + specifier: ^0.5.21 + version: 0.5.21 + tslib: + specifier: ^2.5.0 + version: 2.5.0 + typescript: + specifier: ^5.0.2 + version: 5.0.2 + which: + specifier: ^2.0.2 + version: 2.0.2 + +packages: + + /@aashutoshrathi/word-wrap@1.2.6: + resolution: {integrity: sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==} + engines: {node: '>=0.10.0'} + dev: true + + /@bcoe/v8-coverage@0.2.3: + resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==} + dev: true + + /@dprint/darwin-arm64@0.41.0: + resolution: {integrity: sha512-P9PtcQI0mrI4U6yyd+/iI664BHSqC9KTS6ogq0ptEdnLtlaWzf09D1nv6FBaHiG9m3conuBRlPsoUqt3j6PZ2w==} + cpu: [arm64] + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /@dprint/darwin-x64@0.41.0: + resolution: {integrity: sha512-mSYnSoH0uyCkjgIWTny2DZAcaiRTe3kRWY5SeZECLGO37e+SdVg+ZjSzndhOvvEb9pv8EeBO1NJ9gHOSceT5Xw==} + cpu: [x64] + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /@dprint/linux-arm64-glibc@0.41.0: + resolution: {integrity: sha512-U4xWzjjO/aAct8cSSMZFhg8l1jWy6VahXh8zWjGBufwX7t3xEcxMG9RyAp/ioYSY6wl4YXAmnUHywhC+wSjDHQ==} + cpu: [arm64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@dprint/linux-x64-glibc@0.41.0: + resolution: {integrity: sha512-wjv5l4mGns7E8i32E8FfAk45tw5O7v4NM17gtvhe6ggOiOD6quHowOH00pLfEakMLMF9y0J5ZO2hxJ/w06bXmQ==} + cpu: [x64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@dprint/linux-x64-musl@0.41.0: + resolution: {integrity: sha512-ZZOqiur9Xi/2uhz0Ce215VTSajAlSrduX/5k/hpIjI7Rgz22Vn77p5fmYxzWkTt/Li1zq5zboTvmGYx0QVNMrQ==} + cpu: [x64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@dprint/win32-x64@0.41.0: + resolution: {integrity: sha512-mFx6x4Hn848/D4gPbDm7g1wlnOh2SGoVF9c9HMGCuOobUU2WIBztzV4L5qlFCB3gprlS0ru9BhlMpGhrp0CBYA==} + cpu: [x64] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@esbuild/android-arm64@0.19.0: + resolution: {integrity: sha512-AzsozJnB+RNaDncBCs3Ys5g3kqhPFUueItfEaCpp89JH2naFNX2mYDIvUgPYMqqjm8hiFoo+jklb3QHZyR3ubw==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + requiresBuild: true + dev: true + optional: true + + /@esbuild/android-arm@0.19.0: + resolution: {integrity: sha512-GAkjUyHgWTYuex3evPd5V7uV/XS4LMKr1PWHRPW1xNyy/Jx08x3uTrDFRefBYLKT/KpaWM8/YMQcwbp5a3yIDA==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + requiresBuild: true + dev: true + optional: true + + /@esbuild/android-x64@0.19.0: + resolution: {integrity: sha512-SUG8/qiVhljBDpdkHQ9DvOWbp7hFFIP0OzxOTptbmVsgBgzY6JWowmMd6yJuOhapfxmj/DrvwKmjRLvVSIAKZg==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + requiresBuild: true + dev: true + optional: true + + /@esbuild/darwin-arm64@0.19.0: + resolution: {integrity: sha512-HkxZ8k3Jvcw0FORPNTavA8BMgQjLOB6AajT+iXmil7BwY3gU1hWvJJAyWyEogCmA4LdbGvKF8vEykdmJ4xNJJQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /@esbuild/darwin-x64@0.19.0: + resolution: {integrity: sha512-9IRWJjqpWFHM9a5Qs3r3bK834NCFuDY5ZaLrmTjqE+10B6w65UMQzeZjh794JcxpHolsAHqwsN/33crUXNCM2Q==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /@esbuild/freebsd-arm64@0.19.0: + resolution: {integrity: sha512-s7i2WcXcK0V1PJHVBe7NsGddsL62a9Vhpz2U7zapPrwKoFuxPP9jybwX8SXnropR/AOj3ppt2ern4ItblU6UQQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + requiresBuild: true + dev: true + optional: true + + /@esbuild/freebsd-x64@0.19.0: + resolution: {integrity: sha512-NMdBSSdgwHCqCsucU5k1xflIIRU0qi1QZnM6+vdGy5fvxm1c8rKh50VzsWsIVTFUG3l91AtRxVwoz3Lcvy3I5w==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-arm64@0.19.0: + resolution: {integrity: sha512-I4zvE2srSZxRPapFnNqj+NL3sDJ1wkvEZqt903OZUlBBgigrQMvzUowvP/TTTu2OGYe1oweg5MFilfyrElIFag==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-arm@0.19.0: + resolution: {integrity: sha512-2F1+lH7ZBcCcgxiSs8EXQV0PPJJdTNiNcXxDb61vzxTRJJkXX1I/ye9mAhfHyScXzHaEibEXg1Jq9SW586zz7w==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-ia32@0.19.0: + resolution: {integrity: sha512-dz2Q7+P92r1Evc8kEN+cQnB3qqPjmCrOZ+EdBTn8lEc1yN8WDgaDORQQiX+mxaijbH8npXBT9GxUqE52Gt6Y+g==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-loong64@0.19.0: + resolution: {integrity: sha512-IcVJovJVflih4oFahhUw+N7YgNbuMSVFNr38awb0LNzfaiIfdqIh518nOfYaNQU3aVfiJnOIRVJDSAP4k35WxA==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-mips64el@0.19.0: + resolution: {integrity: sha512-bZGRAGySMquWsKw0gIdsClwfvgbsSq/7oq5KVu1H1r9Il+WzOcfkV1hguntIuBjRVL8agI95i4AukjdAV2YpUw==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-ppc64@0.19.0: + resolution: {integrity: sha512-3LC6H5/gCDorxoRBUdpLV/m7UthYSdar0XcCu+ypycQxMS08MabZ06y1D1yZlDzL/BvOYliRNRWVG/YJJvQdbg==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-riscv64@0.19.0: + resolution: {integrity: sha512-jfvdKjWk+Cp2sgLtEEdSHXO7qckrw2B2eFBaoRdmfhThqZs29GMMg7q/LsQpybA7BxCLLEs4di5ucsWzZC5XPA==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-s390x@0.19.0: + resolution: {integrity: sha512-ofcucfNLkoXmcnJaw9ugdEOf40AWKGt09WBFCkpor+vFJVvmk/8OPjl/qRtks2Z7BuZbG3ztJuK1zS9z5Cgx9A==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/linux-x64@0.19.0: + resolution: {integrity: sha512-Fpf7zNDBti3xrQKQKLdXT0hTyOxgFdRJIMtNy8x1az9ATR9/GJ1brYbB/GLWoXhKiHsoWs+2DLkFVNNMTCLEwA==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + requiresBuild: true + dev: true + optional: true + + /@esbuild/netbsd-x64@0.19.0: + resolution: {integrity: sha512-AMQAp/5oENgDOvVhvOlbhVe1pWii7oFAMRHlmTjSEMcpjTpIHtFXhv9uAFgUERHm3eYtNvS9Vf+gT55cwuI6Aw==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + requiresBuild: true + dev: true + optional: true + + /@esbuild/openbsd-x64@0.19.0: + resolution: {integrity: sha512-fDztEve1QUs3h/Dw2AUmBlWGkNQbhDoD05ppm5jKvzQv+HVuV13so7m5RYeiSMIC2XQy7PAjZh+afkxAnCRZxA==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + requiresBuild: true + dev: true + optional: true + + /@esbuild/sunos-x64@0.19.0: + resolution: {integrity: sha512-bKZzJ2/rvUjDzA5Ddyva2tMk89WzNJEibZEaq+wY6SiqPlwgFbqyQLimouxLHiHh1itb5P3SNCIF1bc2bw5H9w==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + requiresBuild: true + dev: true + optional: true + + /@esbuild/win32-arm64@0.19.0: + resolution: {integrity: sha512-NQJ+4jmnA79saI+sE+QzcEls19uZkoEmdxo7r//PDOjIpX8pmoWtTnWg6XcbnO7o4fieyAwb5U2LvgWynF4diA==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@esbuild/win32-ia32@0.19.0: + resolution: {integrity: sha512-uyxiZAnsfu9diHm9/rIH2soecF/HWLXYUhJKW4q1+/LLmNQ+55lRjvSUDhUmsgJtSUscRJB/3S4RNiTb9o9mCg==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@esbuild/win32-x64@0.19.0: + resolution: {integrity: sha512-jl+NXUjK2StMgqnZnqgNjZuerFG8zQqWXMBZdMMv4W/aO1ZKQaYWZBxTrtWKphkCBVEMh0wMVfGgOd2BjOZqUQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + requiresBuild: true + dev: true + optional: true + + /@esfx/cancelable@1.0.0: + resolution: {integrity: sha512-2dry/TuOT9ydpw86f396v09cyi/gLeGPIZSH4Gx+V/qKQaS/OXCRurCY+Cn8zkBfTAgFsjk9NE15d+LPo2kt9A==} + dependencies: + '@esfx/disposable': 1.0.0 + dev: true + + /@esfx/canceltoken@1.0.0: + resolution: {integrity: sha512-/TgdzC5O89w5v0TgwE2wcdtampWNAFOxzurCtb4RxYVr3m72yk3Bg82vMdznx+H9nnf28zVDR0PtpZO9FxmOkw==} + dependencies: + '@esfx/cancelable': 1.0.0 + '@esfx/disposable': 1.0.0 + tslib: 2.5.0 + dev: true + + /@esfx/disposable@1.0.0: + resolution: {integrity: sha512-hu7EI+YxlEWEKrb2himbS13HNaq5mlUePASf99KeQqkiNeqiAZbKqG4w59uDcLZs8JrV3qJqS/NYib5ZMhbfTQ==} + dev: true + + /@eslint-community/eslint-utils@4.4.0(eslint@8.22.0): + resolution: {integrity: sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + dependencies: + eslint: 8.22.0 + eslint-visitor-keys: 3.4.3 + dev: true + + /@eslint-community/regexpp@4.9.1: + resolution: {integrity: sha512-Y27x+MBLjXa+0JWDhykM3+JE+il3kHKAEqabfEWq3SDhZjLYb6/BHL/JKFnH3fe207JaXkyDo685Oc2Glt6ifA==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + dev: true + + /@eslint/eslintrc@1.4.1: + resolution: {integrity: sha512-XXrH9Uarn0stsyldqDYq8r++mROmWRI1xKMXa640Bb//SY1+ECYX6VzT6Lcx5frD0V30XieqJ0oX9I2Xj5aoMA==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + dependencies: + ajv: 6.12.6 + debug: 4.3.4(supports-color@8.1.1) + espree: 9.6.1 + globals: 13.23.0 + ignore: 5.2.4 + import-fresh: 3.3.0 + js-yaml: 4.1.0 + minimatch: 3.1.2 + strip-json-comments: 3.1.1 + transitivePeerDependencies: + - supports-color + dev: true + + /@humanwhocodes/config-array@0.10.7: + resolution: {integrity: sha512-MDl6D6sBsaV452/QSdX+4CXIjZhIcI0PELsxUjk4U828yd58vk3bTIvk/6w5FY+4hIy9sLW0sfrV7K7Kc++j/w==} + engines: {node: '>=10.10.0'} + dependencies: + '@humanwhocodes/object-schema': 1.2.1 + debug: 4.3.4(supports-color@8.1.1) + minimatch: 3.1.2 + transitivePeerDependencies: + - supports-color + dev: true + + /@humanwhocodes/gitignore-to-minimatch@1.0.2: + resolution: {integrity: sha512-rSqmMJDdLFUsyxR6FMtD00nfQKKLFb1kv+qBbOVKqErvloEIJLo5bDTJTQNTYgeyp78JsA7u/NPi5jT1GR/MuA==} + dev: true + + /@humanwhocodes/object-schema@1.2.1: + resolution: {integrity: sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==} + dev: true + + /@istanbuljs/schema@0.1.3: + resolution: {integrity: sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==} + engines: {node: '>=8'} + dev: true + + /@jridgewell/resolve-uri@3.1.1: + resolution: {integrity: sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==} + engines: {node: '>=6.0.0'} + dev: true + + /@jridgewell/sourcemap-codec@1.4.15: + resolution: {integrity: sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==} + dev: true + + /@jridgewell/trace-mapping@0.3.20: + resolution: {integrity: sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==} + dependencies: + '@jridgewell/resolve-uri': 3.1.1 + '@jridgewell/sourcemap-codec': 1.4.15 + dev: true + + /@nodelib/fs.scandir@2.1.5: + resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} + engines: {node: '>= 8'} + dependencies: + '@nodelib/fs.stat': 2.0.5 + run-parallel: 1.2.0 + dev: true + + /@nodelib/fs.stat@2.0.5: + resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} + engines: {node: '>= 8'} + dev: true + + /@nodelib/fs.walk@1.2.8: + resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} + engines: {node: '>= 8'} + dependencies: + '@nodelib/fs.scandir': 2.1.5 + fastq: 1.15.0 + dev: true + + /@octokit/auth-token@3.0.4: + resolution: {integrity: sha512-TWFX7cZF2LXoCvdmJWY7XVPi74aSY0+FfBZNSXEXFkMpjcqsQwDSYVv5FhRFaI0V1ECnwbz4j59T/G+rXNWaIQ==} + engines: {node: '>= 14'} + dev: true + + /@octokit/core@4.2.4: + resolution: {integrity: sha512-rYKilwgzQ7/imScn3M9/pFfUf4I1AZEH3KhyJmtPdE2zfaXAn2mFfUy4FbKewzc2We5y/LlKLj36fWJLKC2SIQ==} + engines: {node: '>= 14'} + dependencies: + '@octokit/auth-token': 3.0.4 + '@octokit/graphql': 5.0.6 + '@octokit/request': 6.2.8 + '@octokit/request-error': 3.0.3 + '@octokit/types': 9.3.2 + before-after-hook: 2.2.3 + universal-user-agent: 6.0.0 + transitivePeerDependencies: + - encoding + dev: true + + /@octokit/endpoint@7.0.6: + resolution: {integrity: sha512-5L4fseVRUsDFGR00tMWD/Trdeeihn999rTMGRMC1G/Ldi1uWlWJzI98H4Iak5DB/RVvQuyMYKqSK/R6mbSOQyg==} + engines: {node: '>= 14'} + dependencies: + '@octokit/types': 9.3.2 + is-plain-object: 5.0.0 + universal-user-agent: 6.0.0 + dev: true + + /@octokit/graphql@5.0.6: + resolution: {integrity: sha512-Fxyxdy/JH0MnIB5h+UQ3yCoh1FG4kWXfFKkpWqjZHw/p+Kc8Y44Hu/kCgNBT6nU1shNumEchmW/sUO1JuQnPcw==} + engines: {node: '>= 14'} + dependencies: + '@octokit/request': 6.2.8 + '@octokit/types': 9.3.2 + universal-user-agent: 6.0.0 + transitivePeerDependencies: + - encoding + dev: true + + /@octokit/openapi-types@18.1.1: + resolution: {integrity: sha512-VRaeH8nCDtF5aXWnjPuEMIYf1itK/s3JYyJcWFJT8X9pSNnBtriDf7wlEWsGuhPLl4QIH4xM8fqTXDwJ3Mu6sw==} + dev: true + + /@octokit/plugin-paginate-rest@6.1.2(@octokit/core@4.2.4): + resolution: {integrity: sha512-qhrmtQeHU/IivxucOV1bbI/xZyC/iOBhclokv7Sut5vnejAIAEXVcGQeRpQlU39E0WwK9lNvJHphHri/DB6lbQ==} + engines: {node: '>= 14'} + peerDependencies: + '@octokit/core': '>=4' + dependencies: + '@octokit/core': 4.2.4 + '@octokit/tsconfig': 1.0.2 + '@octokit/types': 9.3.2 + dev: true + + /@octokit/plugin-request-log@1.0.4(@octokit/core@4.2.4): + resolution: {integrity: sha512-mLUsMkgP7K/cnFEw07kWqXGF5LKrOkD+lhCrKvPHXWDywAwuDUeDwWBpc69XK3pNX0uKiVt8g5z96PJ6z9xCFA==} + peerDependencies: + '@octokit/core': '>=3' + dependencies: + '@octokit/core': 4.2.4 + dev: true + + /@octokit/plugin-rest-endpoint-methods@7.2.3(@octokit/core@4.2.4): + resolution: {integrity: sha512-I5Gml6kTAkzVlN7KCtjOM+Ruwe/rQppp0QU372K1GP7kNOYEKe8Xn5BW4sE62JAHdwpq95OQK/qGNyKQMUzVgA==} + engines: {node: '>= 14'} + peerDependencies: + '@octokit/core': '>=3' + dependencies: + '@octokit/core': 4.2.4 + '@octokit/types': 10.0.0 + dev: true + + /@octokit/request-error@3.0.3: + resolution: {integrity: sha512-crqw3V5Iy2uOU5Np+8M/YexTlT8zxCfI+qu+LxUB7SZpje4Qmx3mub5DfEKSO8Ylyk0aogi6TYdf6kxzh2BguQ==} + engines: {node: '>= 14'} + dependencies: + '@octokit/types': 9.3.2 + deprecation: 2.3.1 + once: 1.4.0 + dev: true + + /@octokit/request@6.2.8: + resolution: {integrity: sha512-ow4+pkVQ+6XVVsekSYBzJC0VTVvh/FCTUUgTsboGq+DTeWdyIFV8WSCdo0RIxk6wSkBTHqIK1mYuY7nOBXOchw==} + engines: {node: '>= 14'} + dependencies: + '@octokit/endpoint': 7.0.6 + '@octokit/request-error': 3.0.3 + '@octokit/types': 9.3.2 + is-plain-object: 5.0.0 + node-fetch: 2.7.0 + universal-user-agent: 6.0.0 + transitivePeerDependencies: + - encoding + dev: true + + /@octokit/rest@19.0.13: + resolution: {integrity: sha512-/EzVox5V9gYGdbAI+ovYj3nXQT1TtTHRT+0eZPcuC05UFSWO3mdO9UY1C0i2eLF9Un1ONJkAk+IEtYGAC+TahA==} + engines: {node: '>= 14'} + dependencies: + '@octokit/core': 4.2.4 + '@octokit/plugin-paginate-rest': 6.1.2(@octokit/core@4.2.4) + '@octokit/plugin-request-log': 1.0.4(@octokit/core@4.2.4) + '@octokit/plugin-rest-endpoint-methods': 7.2.3(@octokit/core@4.2.4) + transitivePeerDependencies: + - encoding + dev: true + + /@octokit/tsconfig@1.0.2: + resolution: {integrity: sha512-I0vDR0rdtP8p2lGMzvsJzbhdOWy405HcGovrspJ8RRibHnyRgggUSNO5AIox5LmqiwmatHKYsvj6VGFHkqS7lA==} + dev: true + + /@octokit/types@10.0.0: + resolution: {integrity: sha512-Vm8IddVmhCgU1fxC1eyinpwqzXPEYu0NrYzD3YZjlGjyftdLBTeqNblRC0jmJmgxbJIsQlyogVeGnrNaaMVzIg==} + dependencies: + '@octokit/openapi-types': 18.1.1 + dev: true + + /@octokit/types@9.3.2: + resolution: {integrity: sha512-D4iHGTdAnEEVsB8fl95m1hiz7D5YiRdQ9b/OEb3BYRVwbLsGHcRVPz+u+BgRLNk0Q0/4iZCBqDN96j2XNxfXrA==} + dependencies: + '@octokit/openapi-types': 18.1.1 + dev: true + + /@types/chai@4.3.4: + resolution: {integrity: sha512-KnRanxnpfpjUTqTCXslZSEdLfXExwgNxYPdiO2WGUj8+HDjFi8R3k5RVKPeSCzLjCcshCAtVO2QBbVuAV4kTnw==} + dev: true + + /@types/glob@8.1.0: + resolution: {integrity: sha512-IO+MJPVhoqz+28h1qLAcBEH2+xHMK6MTyHJc7MTnnYb6wsoLR29POVGJ7LycmVXIqyy/4/2ShP5sUwTXuOwb/w==} + dependencies: + '@types/minimatch': 5.1.2 + '@types/node': 20.8.10 + dev: true + + /@types/istanbul-lib-coverage@2.0.5: + resolution: {integrity: sha512-zONci81DZYCZjiLe0r6equvZut0b+dBRPBN5kBDjsONnutYNtJMoWQ9uR2RkL1gLG9NMTzvf+29e5RFfPbeKhQ==} + dev: true + + /@types/json-schema@7.0.14: + resolution: {integrity: sha512-U3PUjAudAdJBeC2pgN8uTIKgxrb4nlDF3SF0++EldXQvQBGkpFZMSnwQiIoDU77tv45VgNkl/L4ouD+rEomujw==} + dev: true + + /@types/microsoft__typescript-etw@0.1.1: + resolution: {integrity: sha512-zdgHyZJEwbFKI6zhOqWPsNMhlrAk6qMrn9VMA6VQtRt/F+jNJKeaHIMysuO9oTLv0fWcli0gwUrMv8MeFyb3Sw==} + dev: true + + /@types/minimatch@5.1.2: + resolution: {integrity: sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA==} + dev: true + + /@types/minimist@1.2.2: + resolution: {integrity: sha512-jhuKLIRrhvCPLqwPcx6INqmKeiA5EWrsCOPhrlFSrbrmU4ZMPjj5Ul/oLCMDO98XRUIwVm78xICz4EPCektzeQ==} + dev: true + + /@types/mocha@10.0.1: + resolution: {integrity: sha512-/fvYntiO1GeICvqbQ3doGDIP97vWmvFt83GKguJ6prmQM2iXZfFcq6YE8KteFyRtX2/h5Hf91BYvPodJKFYv5Q==} + dev: true + + /@types/ms@0.7.31: + resolution: {integrity: sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==} + dev: true + + /@types/node@20.8.10: + resolution: {integrity: sha512-TlgT8JntpcbmKUFzjhsyhGfP2fsiz1Mv56im6enJ905xG1DAYesxJaeSbGqQmAw8OWPdhyJGhGSQGKRNJ45u9w==} + dependencies: + undici-types: 5.26.5 + dev: true + + /@types/node@20.8.8: + resolution: {integrity: sha512-YRsdVxq6OaLfmR9Hy816IMp33xOBjfyOgUd77ehqg96CFywxAPbDbXvAsuN2KVg2HOT8Eh6uAfU+l4WffwPVrQ==} + dependencies: + undici-types: 5.25.3 + dev: true + + /@types/semver@7.5.4: + resolution: {integrity: sha512-MMzuxN3GdFwskAnb6fz0orFvhfqi752yjaXylr0Rp4oDg5H0Zn1IuyRhDVvYOwAXoJirx2xuS16I3WjxnAIHiQ==} + dev: true + + /@types/source-map-support@0.5.6: + resolution: {integrity: sha512-b2nJ9YyXmkhGaa2b8VLM0kJ04xxwNyijcq12/kDoomCt43qbHBeK2SLNJ9iJmETaAj+bKUT05PQUu3Q66GvLhQ==} + dependencies: + source-map: 0.6.1 + dev: true + + /@types/which@2.0.1: + resolution: {integrity: sha512-Jjakcv8Roqtio6w1gr0D7y6twbhx6gGgFGF5BLwajPpnOIOxFkakFhCq+LmyyeAz7BX6ULrjBOxdKaCDy+4+dQ==} + dev: true + + /@typescript-eslint/eslint-plugin@6.0.0(@typescript-eslint/parser@6.0.0)(eslint@8.22.0)(typescript@5.0.2): + resolution: {integrity: sha512-xuv6ghKGoiq856Bww/yVYnXGsKa588kY3M0XK7uUW/3fJNNULKRfZfSBkMTSpqGG/8ZCXCadfh8G/z/B4aqS/A==} + engines: {node: ^16.0.0 || >=18.0.0} + peerDependencies: + '@typescript-eslint/parser': ^6.0.0 || ^6.0.0-alpha + eslint: ^7.0.0 || ^8.0.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + dependencies: + '@eslint-community/regexpp': 4.9.1 + '@typescript-eslint/parser': 6.0.0(eslint@8.22.0)(typescript@5.0.2) + '@typescript-eslint/scope-manager': 6.0.0 + '@typescript-eslint/type-utils': 6.0.0(eslint@8.22.0)(typescript@5.0.2) + '@typescript-eslint/utils': 6.0.0(eslint@8.22.0)(typescript@5.0.2) + '@typescript-eslint/visitor-keys': 6.0.0 + debug: 4.3.4(supports-color@8.1.1) + eslint: 8.22.0 + grapheme-splitter: 1.0.4 + graphemer: 1.4.0 + ignore: 5.2.4 + natural-compare: 1.4.0 + natural-compare-lite: 1.4.0 + semver: 7.5.4 + ts-api-utils: 1.0.3(typescript@5.0.2) + typescript: 5.0.2 + transitivePeerDependencies: + - supports-color + dev: true + + /@typescript-eslint/parser@6.0.0(eslint@8.22.0)(typescript@5.0.2): + resolution: {integrity: sha512-TNaufYSPrr1U8n+3xN+Yp9g31vQDJqhXzzPSHfQDLcaO4tU+mCfODPxCwf4H530zo7aUBE3QIdxCXamEnG04Tg==} + engines: {node: ^16.0.0 || >=18.0.0} + peerDependencies: + eslint: ^7.0.0 || ^8.0.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + dependencies: + '@typescript-eslint/scope-manager': 6.0.0 + '@typescript-eslint/types': 6.0.0 + '@typescript-eslint/typescript-estree': 6.0.0(typescript@5.0.2) + '@typescript-eslint/visitor-keys': 6.0.0 + debug: 4.3.4(supports-color@8.1.1) + eslint: 8.22.0 + typescript: 5.0.2 + transitivePeerDependencies: + - supports-color + dev: true + + /@typescript-eslint/scope-manager@6.0.0: + resolution: {integrity: sha512-o4q0KHlgCZTqjuaZ25nw5W57NeykZT9LiMEG4do/ovwvOcPnDO1BI5BQdCsUkjxFyrCL0cSzLjvIMfR9uo7cWg==} + engines: {node: ^16.0.0 || >=18.0.0} + dependencies: + '@typescript-eslint/types': 6.0.0 + '@typescript-eslint/visitor-keys': 6.0.0 + dev: true + + /@typescript-eslint/type-utils@6.0.0(eslint@8.22.0)(typescript@5.0.2): + resolution: {integrity: sha512-ah6LJvLgkoZ/pyJ9GAdFkzeuMZ8goV6BH7eC9FPmojrnX9yNCIsfjB+zYcnex28YO3RFvBkV6rMV6WpIqkPvoQ==} + engines: {node: ^16.0.0 || >=18.0.0} + peerDependencies: + eslint: ^7.0.0 || ^8.0.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + dependencies: + '@typescript-eslint/typescript-estree': 6.0.0(typescript@5.0.2) + '@typescript-eslint/utils': 6.0.0(eslint@8.22.0)(typescript@5.0.2) + debug: 4.3.4(supports-color@8.1.1) + eslint: 8.22.0 + ts-api-utils: 1.0.3(typescript@5.0.2) + typescript: 5.0.2 + transitivePeerDependencies: + - supports-color + dev: true + + /@typescript-eslint/types@6.0.0: + resolution: {integrity: sha512-Zk9KDggyZM6tj0AJWYYKgF0yQyrcnievdhG0g5FqyU3Y2DRxJn4yWY21sJC0QKBckbsdKKjYDV2yVrrEvuTgxg==} + engines: {node: ^16.0.0 || >=18.0.0} + dev: true + + /@typescript-eslint/typescript-estree@6.0.0(typescript@5.0.2): + resolution: {integrity: sha512-2zq4O7P6YCQADfmJ5OTDQTP3ktajnXIRrYAtHM9ofto/CJZV3QfJ89GEaM2BNGeSr1KgmBuLhEkz5FBkS2RQhQ==} + engines: {node: ^16.0.0 || >=18.0.0} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + dependencies: + '@typescript-eslint/types': 6.0.0 + '@typescript-eslint/visitor-keys': 6.0.0 + debug: 4.3.4(supports-color@8.1.1) + globby: 11.1.0 + is-glob: 4.0.3 + semver: 7.5.4 + ts-api-utils: 1.0.3(typescript@5.0.2) + typescript: 5.0.2 + transitivePeerDependencies: + - supports-color + dev: true + + /@typescript-eslint/utils@6.0.0(eslint@8.22.0)(typescript@5.0.2): + resolution: {integrity: sha512-SOr6l4NB6HE4H/ktz0JVVWNXqCJTOo/mHnvIte1ZhBQ0Cvd04x5uKZa3zT6tiodL06zf5xxdK8COiDvPnQ27JQ==} + engines: {node: ^16.0.0 || >=18.0.0} + peerDependencies: + eslint: ^7.0.0 || ^8.0.0 + dependencies: + '@eslint-community/eslint-utils': 4.4.0(eslint@8.22.0) + '@types/json-schema': 7.0.14 + '@types/semver': 7.5.4 + '@typescript-eslint/scope-manager': 6.0.0 + '@typescript-eslint/types': 6.0.0 + '@typescript-eslint/typescript-estree': 6.0.0(typescript@5.0.2) + eslint: 8.22.0 + eslint-scope: 5.1.1 + semver: 7.5.4 + transitivePeerDependencies: + - supports-color + - typescript + dev: true + + /@typescript-eslint/visitor-keys@6.0.0: + resolution: {integrity: sha512-cvJ63l8c0yXdeT5POHpL0Q1cZoRcmRKFCtSjNGJxPkcP571EfZMcNbzWAc7oK3D1dRzm/V5EwtkANTZxqvuuUA==} + engines: {node: ^16.0.0 || >=18.0.0} + dependencies: + '@typescript-eslint/types': 6.0.0 + eslint-visitor-keys: 3.4.3 + dev: true + + /acorn-jsx@5.3.2(acorn@8.10.0): + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + dependencies: + acorn: 8.10.0 + dev: true + + /acorn@8.10.0: + resolution: {integrity: sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==} + engines: {node: '>=0.4.0'} + hasBin: true + dev: true + + /ajv@6.12.6: + resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + dev: true + + /ansi-colors@4.1.1: + resolution: {integrity: sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==} + engines: {node: '>=6'} + dev: true + + /ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + dev: true + + /ansi-styles@3.2.1: + resolution: {integrity: sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==} + engines: {node: '>=4'} + dependencies: + color-convert: 1.9.3 + dev: true + + /ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + dependencies: + color-convert: 2.0.1 + dev: true + + /anymatch@3.1.3: + resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} + engines: {node: '>= 8'} + dependencies: + normalize-path: 3.0.0 + picomatch: 2.3.1 + dev: true + + /argparse@2.0.1: + resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + dev: true + + /array-back@3.1.0: + resolution: {integrity: sha512-TkuxA4UCOvxuDK6NZYXCalszEzj+TLszyASooky+i742l9TqsOdYCMJJupxRic61hwquNtppB3hgcuq9SVSH1Q==} + engines: {node: '>=6'} + dev: true + + /array-back@4.0.2: + resolution: {integrity: sha512-NbdMezxqf94cnNfWLL7V/im0Ub+Anbb0IoZhvzie8+4HJ4nMQuzHuy49FkGYCJK2yAloZ3meiB6AVMClbrI1vg==} + engines: {node: '>=8'} + dev: true + + /array-union@2.1.0: + resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==} + engines: {node: '>=8'} + dev: true + + /assertion-error@1.1.0: + resolution: {integrity: sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==} + dev: true + + /azure-devops-node-api@12.0.0: + resolution: {integrity: sha512-S6Il++7dQeMlZDokBDWw7YVoPeb90tWF10pYxnoauRMnkuL91jq9M7SOYRVhtO3FUC5URPkB/qzGa7jTLft0Xw==} + dependencies: + tunnel: 0.0.6 + typed-rest-client: 1.8.11 + dev: true + + /balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + dev: true + + /before-after-hook@2.2.3: + resolution: {integrity: sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==} + dev: true + + /binary-extensions@2.2.0: + resolution: {integrity: sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==} + engines: {node: '>=8'} + dev: true + + /brace-expansion@1.1.11: + resolution: {integrity: sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==} + dependencies: + balanced-match: 1.0.2 + concat-map: 0.0.1 + dev: true + + /brace-expansion@2.0.1: + resolution: {integrity: sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==} + dependencies: + balanced-match: 1.0.2 + dev: true + + /braces@3.0.2: + resolution: {integrity: sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==} + engines: {node: '>=8'} + dependencies: + fill-range: 7.0.1 + dev: true + + /browser-stdout@1.3.1: + resolution: {integrity: sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==} + dev: true + + /buffer-from@1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + dev: true + + /c8@7.14.0: + resolution: {integrity: sha512-i04rtkkcNcCf7zsQcSv/T9EbUn4RXQ6mropeMcjFOsQXQ0iGLAr/xT6TImQg4+U9hmNpN9XdvPkjUL1IzbgxJw==} + engines: {node: '>=10.12.0'} + hasBin: true + dependencies: + '@bcoe/v8-coverage': 0.2.3 + '@istanbuljs/schema': 0.1.3 + find-up: 5.0.0 + foreground-child: 2.0.0 + istanbul-lib-coverage: 3.2.0 + istanbul-lib-report: 3.0.1 + istanbul-reports: 3.1.6 + rimraf: 3.0.2 + test-exclude: 6.0.0 + v8-to-istanbul: 9.1.3 + yargs: 16.2.0 + yargs-parser: 20.2.9 + dev: true + + /call-bind@1.0.5: + resolution: {integrity: sha512-C3nQxfFZxFRVoJoGKKI8y3MOEo129NQ+FgQ08iye+Mk4zNZZGdjfs06bVTr+DBSlA66Q2VEcMki/cUCP4SercQ==} + dependencies: + function-bind: 1.1.2 + get-intrinsic: 1.2.2 + set-function-length: 1.1.1 + dev: true + + /callsites@3.1.0: + resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} + engines: {node: '>=6'} + dev: true + + /camelcase@6.3.0: + resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==} + engines: {node: '>=10'} + dev: true + + /chai@4.3.7: + resolution: {integrity: sha512-HLnAzZ2iupm25PlN0xFreAlBA5zaBSv3og0DdeGA4Ar6h6rJ3A0rolRUKJhSF2V10GZKDgWF/VmAEsNWjCRB+A==} + engines: {node: '>=4'} + dependencies: + assertion-error: 1.1.0 + check-error: 1.0.3 + deep-eql: 4.1.3 + get-func-name: 2.0.2 + loupe: 2.3.7 + pathval: 1.1.1 + type-detect: 4.0.8 + dev: true + + /chalk@2.4.2: + resolution: {integrity: sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==} + engines: {node: '>=4'} + dependencies: + ansi-styles: 3.2.1 + escape-string-regexp: 1.0.5 + supports-color: 5.5.0 + dev: true + + /chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + dependencies: + ansi-styles: 4.3.0 + supports-color: 7.2.0 + dev: true + + /check-error@1.0.3: + resolution: {integrity: sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==} + dependencies: + get-func-name: 2.0.2 + dev: true + + /chokidar@3.5.3: + resolution: {integrity: sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==} + engines: {node: '>= 8.10.0'} + dependencies: + anymatch: 3.1.3 + braces: 3.0.2 + glob-parent: 5.1.2 + is-binary-path: 2.1.0 + is-glob: 4.0.3 + normalize-path: 3.0.0 + readdirp: 3.6.0 + optionalDependencies: + fsevents: 2.3.3 + dev: true + + /cliui@7.0.4: + resolution: {integrity: sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==} + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 7.0.0 + dev: true + + /color-convert@1.9.3: + resolution: {integrity: sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==} + dependencies: + color-name: 1.1.3 + dev: true + + /color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + dependencies: + color-name: 1.1.4 + dev: true + + /color-name@1.1.3: + resolution: {integrity: sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==} + dev: true + + /color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + dev: true + + /command-line-args@5.2.1: + resolution: {integrity: sha512-H4UfQhZyakIjC74I9d34fGYDwk3XpSr17QhEd0Q3I9Xq1CETHo4Hcuo87WyWHpAF1aSLjLRf5lD9ZGX2qStUvg==} + engines: {node: '>=4.0.0'} + dependencies: + array-back: 3.1.0 + find-replace: 3.0.0 + lodash.camelcase: 4.3.0 + typical: 4.0.0 + dev: true + + /command-line-usage@6.1.3: + resolution: {integrity: sha512-sH5ZSPr+7UStsloltmDh7Ce5fb8XPlHyoPzTpyyMuYCtervL65+ubVZ6Q61cFtFl62UyJlc8/JwERRbAFPUqgw==} + engines: {node: '>=8.0.0'} + dependencies: + array-back: 4.0.2 + chalk: 2.4.2 + table-layout: 1.0.2 + typical: 5.2.0 + dev: true + + /concat-map@0.0.1: + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + dev: true + + /convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + dev: true + + /cross-spawn@7.0.3: + resolution: {integrity: sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==} + engines: {node: '>= 8'} + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + dev: true + + /data-uri-to-buffer@4.0.1: + resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==} + engines: {node: '>= 12'} + dev: true + + /debug@4.3.4(supports-color@8.1.1): + resolution: {integrity: sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + dependencies: + ms: 2.1.2 + supports-color: 8.1.1 + dev: true + + /decamelize@4.0.0: + resolution: {integrity: sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==} + engines: {node: '>=10'} + dev: true + + /deep-eql@4.1.3: + resolution: {integrity: sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==} + engines: {node: '>=6'} + dependencies: + type-detect: 4.0.8 + dev: true + + /deep-extend@0.6.0: + resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==} + engines: {node: '>=4.0.0'} + dev: true + + /deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + dev: true + + /define-data-property@1.1.1: + resolution: {integrity: sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==} + engines: {node: '>= 0.4'} + dependencies: + get-intrinsic: 1.2.2 + gopd: 1.0.1 + has-property-descriptors: 1.0.1 + dev: true + + /deprecation@2.3.1: + resolution: {integrity: sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==} + dev: true + + /diff@5.0.0: + resolution: {integrity: sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==} + engines: {node: '>=0.3.1'} + dev: true + + /diff@5.1.0: + resolution: {integrity: sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw==} + engines: {node: '>=0.3.1'} + dev: true + + /dir-glob@3.0.1: + resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==} + engines: {node: '>=8'} + dependencies: + path-type: 4.0.0 + dev: true + + /doctrine@3.0.0: + resolution: {integrity: sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==} + engines: {node: '>=6.0.0'} + dependencies: + esutils: 2.0.3 + dev: true + + /dprint@0.41.0: + resolution: {integrity: sha512-9Ctv6EnwOy5Ai566DczI/QhAC6y+AhWDA2gFU8Zz4xezUy1BevHaIYhfdLWZQxh4Qf4H28lRu1Lq+hhIm1US9w==} + hasBin: true + requiresBuild: true + optionalDependencies: + '@dprint/darwin-arm64': 0.41.0 + '@dprint/darwin-x64': 0.41.0 + '@dprint/linux-arm64-glibc': 0.41.0 + '@dprint/linux-x64-glibc': 0.41.0 + '@dprint/linux-x64-musl': 0.41.0 + '@dprint/win32-x64': 0.41.0 + dev: true + + /emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + dev: true + + /esbuild@0.19.0: + resolution: {integrity: sha512-i7i8TP4vuG55bKeLyqqk5sTPu1ZjPH3wkcLvAj/0X/222iWFo3AJUYRKjbOoY6BWFMH3teizxHEdV9Su5ESl0w==} + engines: {node: '>=12'} + hasBin: true + requiresBuild: true + optionalDependencies: + '@esbuild/android-arm': 0.19.0 + '@esbuild/android-arm64': 0.19.0 + '@esbuild/android-x64': 0.19.0 + '@esbuild/darwin-arm64': 0.19.0 + '@esbuild/darwin-x64': 0.19.0 + '@esbuild/freebsd-arm64': 0.19.0 + '@esbuild/freebsd-x64': 0.19.0 + '@esbuild/linux-arm': 0.19.0 + '@esbuild/linux-arm64': 0.19.0 + '@esbuild/linux-ia32': 0.19.0 + '@esbuild/linux-loong64': 0.19.0 + '@esbuild/linux-mips64el': 0.19.0 + '@esbuild/linux-ppc64': 0.19.0 + '@esbuild/linux-riscv64': 0.19.0 + '@esbuild/linux-s390x': 0.19.0 + '@esbuild/linux-x64': 0.19.0 + '@esbuild/netbsd-x64': 0.19.0 + '@esbuild/openbsd-x64': 0.19.0 + '@esbuild/sunos-x64': 0.19.0 + '@esbuild/win32-arm64': 0.19.0 + '@esbuild/win32-ia32': 0.19.0 + '@esbuild/win32-x64': 0.19.0 + dev: true + + /escalade@3.1.1: + resolution: {integrity: sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==} + engines: {node: '>=6'} + dev: true + + /escape-string-regexp@1.0.5: + resolution: {integrity: sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==} + engines: {node: '>=0.8.0'} + dev: true + + /escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + dev: true + + /eslint-formatter-autolinkable-stylish@1.2.0(eslint@8.22.0): + resolution: {integrity: sha512-fID9VwZBc2iLcefBvhwU08KRBa0SQkWoVVtm70o9F8w/nYQaJVtBBzNeTJHRFyt3gOm1NGqyDRxAcddfZ6JQzA==} + engines: {node: '>=0.10.0'} + peerDependencies: + eslint: ^8.3.0 + dependencies: + chalk: 4.1.2 + eslint: 8.22.0 + plur: 4.0.0 + dev: true + + /eslint-plugin-local@1.0.0: + resolution: {integrity: sha512-bcwcQnKL/Iw5Vi/F2lG1he5oKD2OGjhsLmrcctkWrWq5TujgiaYb0cj3pZgr3XI54inNVnneOFdAx1daLoYLJQ==} + dev: true + + /eslint-plugin-no-null@1.0.2(eslint@8.22.0): + resolution: {integrity: sha512-uRDiz88zCO/2rzGfgG15DBjNsgwWtWiSo4Ezy7zzajUgpnFIqd1TjepKeRmJZHEfBGu58o2a8S0D7vglvvhkVA==} + engines: {node: '>=5.0.0'} + peerDependencies: + eslint: '>=3.0.0' + dependencies: + eslint: 8.22.0 + dev: true + + /eslint-plugin-simple-import-sort@10.0.0(eslint@8.22.0): + resolution: {integrity: sha512-AeTvO9UCMSNzIHRkg8S6c3RPy5YEwKWSQPx3DYghLedo2ZQxowPFLGDN1AZ2evfg6r6mjBSZSLxLFsWSu3acsw==} + peerDependencies: + eslint: '>=5.0.0' + dependencies: + eslint: 8.22.0 + dev: true + + /eslint-scope@5.1.1: + resolution: {integrity: sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==} + engines: {node: '>=8.0.0'} + dependencies: + esrecurse: 4.3.0 + estraverse: 4.3.0 + dev: true + + /eslint-scope@7.2.2: + resolution: {integrity: sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + dependencies: + esrecurse: 4.3.0 + estraverse: 5.3.0 + dev: true + + /eslint-utils@3.0.0(eslint@8.22.0): + resolution: {integrity: sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA==} + engines: {node: ^10.0.0 || ^12.0.0 || >= 14.0.0} + peerDependencies: + eslint: '>=5' + dependencies: + eslint: 8.22.0 + eslint-visitor-keys: 2.1.0 + dev: true + + /eslint-visitor-keys@2.1.0: + resolution: {integrity: sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw==} + engines: {node: '>=10'} + dev: true + + /eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + dev: true + + /eslint@8.22.0: + resolution: {integrity: sha512-ci4t0sz6vSRKdmkOGmprBo6fmI4PrphDFMy5JEq/fNS0gQkJM3rLmrqcp8ipMcdobH3KtUP40KniAE9W19S4wA==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + hasBin: true + dependencies: + '@eslint/eslintrc': 1.4.1 + '@humanwhocodes/config-array': 0.10.7 + '@humanwhocodes/gitignore-to-minimatch': 1.0.2 + ajv: 6.12.6 + chalk: 4.1.2 + cross-spawn: 7.0.3 + debug: 4.3.4(supports-color@8.1.1) + doctrine: 3.0.0 + escape-string-regexp: 4.0.0 + eslint-scope: 7.2.2 + eslint-utils: 3.0.0(eslint@8.22.0) + eslint-visitor-keys: 3.4.3 + espree: 9.6.1 + esquery: 1.5.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 6.0.1 + find-up: 5.0.0 + functional-red-black-tree: 1.0.1 + glob-parent: 6.0.2 + globals: 13.23.0 + globby: 11.1.0 + grapheme-splitter: 1.0.4 + ignore: 5.2.4 + import-fresh: 3.3.0 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + js-yaml: 4.1.0 + json-stable-stringify-without-jsonify: 1.0.1 + levn: 0.4.1 + lodash.merge: 4.6.2 + minimatch: 3.1.2 + natural-compare: 1.4.0 + optionator: 0.9.3 + regexpp: 3.2.0 + strip-ansi: 6.0.1 + strip-json-comments: 3.1.1 + text-table: 0.2.0 + v8-compile-cache: 2.4.0 + transitivePeerDependencies: + - supports-color + dev: true + + /espree@9.6.1: + resolution: {integrity: sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + dependencies: + acorn: 8.10.0 + acorn-jsx: 5.3.2(acorn@8.10.0) + eslint-visitor-keys: 3.4.3 + dev: true + + /esquery@1.5.0: + resolution: {integrity: sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==} + engines: {node: '>=0.10'} + dependencies: + estraverse: 5.3.0 + dev: true + + /esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + dependencies: + estraverse: 5.3.0 + dev: true + + /estraverse@4.3.0: + resolution: {integrity: sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==} + engines: {node: '>=4.0'} + dev: true + + /estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + dev: true + + /esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + dev: true + + /fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + dev: true + + /fast-glob@3.3.1: + resolution: {integrity: sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==} + engines: {node: '>=8.6.0'} + dependencies: + '@nodelib/fs.stat': 2.0.5 + '@nodelib/fs.walk': 1.2.8 + glob-parent: 5.1.2 + merge2: 1.4.1 + micromatch: 4.0.5 + dev: true + + /fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + dev: true + + /fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + dev: true + + /fast-xml-parser@4.0.11: + resolution: {integrity: sha512-4aUg3aNRR/WjQAcpceODG1C3x3lFANXRo8+1biqfieHmg9pyMt7qB4lQV/Ta6sJCTbA5vfD8fnA8S54JATiFUA==} + hasBin: true + dependencies: + strnum: 1.0.5 + dev: true + + /fastest-levenshtein@1.0.16: + resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==} + engines: {node: '>= 4.9.1'} + dev: true + + /fastq@1.15.0: + resolution: {integrity: sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw==} + dependencies: + reusify: 1.0.4 + dev: true + + /fetch-blob@3.2.0: + resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==} + engines: {node: ^12.20 || >= 14.13} + dependencies: + node-domexception: 1.0.0 + web-streams-polyfill: 3.2.1 + dev: true + + /file-entry-cache@6.0.1: + resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==} + engines: {node: ^10.12.0 || >=12.0.0} + dependencies: + flat-cache: 3.1.1 + dev: true + + /fill-range@7.0.1: + resolution: {integrity: sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==} + engines: {node: '>=8'} + dependencies: + to-regex-range: 5.0.1 + dev: true + + /find-replace@3.0.0: + resolution: {integrity: sha512-6Tb2myMioCAgv5kfvP5/PkZZ/ntTpVK39fHY7WkWBgvbeE+VHd/tZuZ4mrC+bxh4cfOZeYKVPaJIZtZXV7GNCQ==} + engines: {node: '>=4.0.0'} + dependencies: + array-back: 3.1.0 + dev: true + + /find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + dev: true + + /flat-cache@3.1.1: + resolution: {integrity: sha512-/qM2b3LUIaIgviBQovTLvijfyOQXPtSRnRK26ksj2J7rzPIecePUIpJsZ4T02Qg+xiAEKIs5K8dsHEd+VaKa/Q==} + engines: {node: '>=12.0.0'} + dependencies: + flatted: 3.2.9 + keyv: 4.5.4 + rimraf: 3.0.2 + dev: true + + /flat@5.0.2: + resolution: {integrity: sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==} + hasBin: true + dev: true + + /flatted@3.2.9: + resolution: {integrity: sha512-36yxDn5H7OFZQla0/jFJmbIKTdZAQHngCedGxiMmpNfEZM0sdEeT+WczLQrjK6D7o2aiyLYDnkw0R3JK0Qv1RQ==} + dev: true + + /foreground-child@2.0.0: + resolution: {integrity: sha512-dCIq9FpEcyQyXKCkyzmlPTFNgrCzPudOe+mhvJU5zAtlBnGVy2yKxtfsxK2tQBThwq225jcvBjpw1Gr40uzZCA==} + engines: {node: '>=8.0.0'} + dependencies: + cross-spawn: 7.0.3 + signal-exit: 3.0.7 + dev: true + + /formdata-polyfill@4.0.10: + resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==} + engines: {node: '>=12.20.0'} + dependencies: + fetch-blob: 3.2.0 + dev: true + + /fs.realpath@1.0.0: + resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} + dev: true + + /fsevents@2.3.2: + resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + requiresBuild: true + dev: true + optional: true + + /function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + dev: true + + /functional-red-black-tree@1.0.1: + resolution: {integrity: sha512-dsKNQNdj6xA3T+QlADDA7mOSlX0qiMINjn0cgr+eGHGsbSHzTabcIogz2+p/iqP1Xs6EP/sS2SbqH+brGTbq0g==} + dev: true + + /get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + dev: true + + /get-func-name@2.0.2: + resolution: {integrity: sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==} + dev: true + + /get-intrinsic@1.2.2: + resolution: {integrity: sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==} + dependencies: + function-bind: 1.1.2 + has-proto: 1.0.1 + has-symbols: 1.0.3 + hasown: 2.0.0 + dev: true + + /glob-parent@5.1.2: + resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} + engines: {node: '>= 6'} + dependencies: + is-glob: 4.0.3 + dev: true + + /glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + dependencies: + is-glob: 4.0.3 + dev: true + + /glob@7.2.0: + resolution: {integrity: sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==} + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 3.1.2 + once: 1.4.0 + path-is-absolute: 1.0.1 + dev: true + + /glob@7.2.3: + resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 3.1.2 + once: 1.4.0 + path-is-absolute: 1.0.1 + dev: true + + /glob@8.1.0: + resolution: {integrity: sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==} + engines: {node: '>=12'} + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 5.1.6 + once: 1.4.0 + dev: true + + /globals@13.23.0: + resolution: {integrity: sha512-XAmF0RjlrjY23MA51q3HltdlGxUpXPvg0GioKiD9X6HD28iMjo2dKC8Vqwm7lne4GNr78+RHTfliktR6ZH09wA==} + engines: {node: '>=8'} + dependencies: + type-fest: 0.20.2 + dev: true + + /globby@11.1.0: + resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==} + engines: {node: '>=10'} + dependencies: + array-union: 2.1.0 + dir-glob: 3.0.1 + fast-glob: 3.3.1 + ignore: 5.2.4 + merge2: 1.4.1 + slash: 3.0.0 + dev: true + + /gopd@1.0.1: + resolution: {integrity: sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==} + dependencies: + get-intrinsic: 1.2.2 + dev: true + + /grapheme-splitter@1.0.4: + resolution: {integrity: sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==} + dev: true + + /graphemer@1.4.0: + resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} + dev: true + + /has-flag@3.0.0: + resolution: {integrity: sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==} + engines: {node: '>=4'} + dev: true + + /has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + dev: true + + /has-property-descriptors@1.0.1: + resolution: {integrity: sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==} + dependencies: + get-intrinsic: 1.2.2 + dev: true + + /has-proto@1.0.1: + resolution: {integrity: sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==} + engines: {node: '>= 0.4'} + dev: true + + /has-symbols@1.0.3: + resolution: {integrity: sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==} + engines: {node: '>= 0.4'} + dev: true + + /hasown@2.0.0: + resolution: {integrity: sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==} + engines: {node: '>= 0.4'} + dependencies: + function-bind: 1.1.2 + dev: true + + /he@1.2.0: + resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==} + hasBin: true + dev: true + + /hereby@1.6.4: + resolution: {integrity: sha512-QN79Mrr+xsGLgiEk2htGf5qP+mIHlan/yuM+tLeDx0BeWmmwo6fvy+Pl9QxYwXRVTrDKC0PRzvqF6hIF9dKCtw==} + engines: {node: '>= 12.20'} + hasBin: true + dependencies: + command-line-args: 5.2.1 + command-line-usage: 6.1.3 + fastest-levenshtein: 1.0.16 + foreground-child: 2.0.0 + import-meta-resolve: 2.2.2 + picocolors: 1.0.0 + pretty-ms: 8.0.0 + dev: true + + /html-escaper@2.0.2: + resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==} + dev: true + + /ignore@5.2.4: + resolution: {integrity: sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==} + engines: {node: '>= 4'} + dev: true + + /import-fresh@3.3.0: + resolution: {integrity: sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==} + engines: {node: '>=6'} + dependencies: + parent-module: 1.0.1 + resolve-from: 4.0.0 + dev: true + + /import-meta-resolve@2.2.2: + resolution: {integrity: sha512-f8KcQ1D80V7RnqVm+/lirO9zkOxjGxhaTC1IPrBGd3MEfNgmNG67tSUO9gTi2F3Blr2Az6g1vocaxzkVnWl9MA==} + dev: true + + /imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + dev: true + + /inflight@1.0.6: + resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} + dependencies: + once: 1.4.0 + wrappy: 1.0.2 + dev: true + + /inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + dev: true + + /irregular-plurals@3.5.0: + resolution: {integrity: sha512-1ANGLZ+Nkv1ptFb2pa8oG8Lem4krflKuX/gINiHJHjJUKaJHk/SXk5x6K3J+39/p0h1RQ2saROclJJ+QLvETCQ==} + engines: {node: '>=8'} + dev: true + + /is-binary-path@2.1.0: + resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} + engines: {node: '>=8'} + dependencies: + binary-extensions: 2.2.0 + dev: true + + /is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + dev: true + + /is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + dev: true + + /is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + dependencies: + is-extglob: 2.1.1 + dev: true + + /is-number@7.0.0: + resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} + engines: {node: '>=0.12.0'} + dev: true + + /is-plain-obj@2.1.0: + resolution: {integrity: sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==} + engines: {node: '>=8'} + dev: true + + /is-plain-object@5.0.0: + resolution: {integrity: sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==} + engines: {node: '>=0.10.0'} + dev: true + + /is-unicode-supported@0.1.0: + resolution: {integrity: sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==} + engines: {node: '>=10'} + dev: true + + /isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + dev: true + + /istanbul-lib-coverage@3.2.0: + resolution: {integrity: sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==} + engines: {node: '>=8'} + dev: true + + /istanbul-lib-report@3.0.1: + resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==} + engines: {node: '>=10'} + dependencies: + istanbul-lib-coverage: 3.2.0 + make-dir: 4.0.0 + supports-color: 7.2.0 + dev: true + + /istanbul-reports@3.1.6: + resolution: {integrity: sha512-TLgnMkKg3iTDsQ9PbPTdpfAK2DzjF9mqUG7RMgcQl8oFjad8ob4laGxv5XV5U9MAfx8D6tSJiUyuAwzLicaxlg==} + engines: {node: '>=8'} + dependencies: + html-escaper: 2.0.2 + istanbul-lib-report: 3.0.1 + dev: true + + /js-yaml@4.1.0: + resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} + hasBin: true + dependencies: + argparse: 2.0.1 + dev: true + + /json-buffer@3.0.1: + resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + dev: true + + /json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + dev: true + + /json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + dev: true + + /jsonc-parser@3.2.0: + resolution: {integrity: sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==} + dev: true + + /keyv@4.5.4: + resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + dependencies: + json-buffer: 3.0.1 + dev: true + + /levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + dev: true + + /locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + dependencies: + p-locate: 5.0.0 + dev: true + + /lodash.camelcase@4.3.0: + resolution: {integrity: sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==} + dev: true + + /lodash.merge@4.6.2: + resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} + dev: true + + /log-symbols@4.1.0: + resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==} + engines: {node: '>=10'} + dependencies: + chalk: 4.1.2 + is-unicode-supported: 0.1.0 + dev: true + + /loupe@2.3.7: + resolution: {integrity: sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==} + dependencies: + get-func-name: 2.0.2 + dev: true + + /lru-cache@6.0.0: + resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} + engines: {node: '>=10'} + dependencies: + yallist: 4.0.0 + dev: true + + /make-dir@4.0.0: + resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} + engines: {node: '>=10'} + dependencies: + semver: 7.5.4 + dev: true + + /merge2@1.4.1: + resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} + engines: {node: '>= 8'} + dev: true + + /micromatch@4.0.5: + resolution: {integrity: sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==} + engines: {node: '>=8.6'} + dependencies: + braces: 3.0.2 + picomatch: 2.3.1 + dev: true + + /minimatch@3.1.2: + resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==} + dependencies: + brace-expansion: 1.1.11 + dev: true + + /minimatch@5.0.1: + resolution: {integrity: sha512-nLDxIFRyhDblz3qMuq+SoRZED4+miJ/G+tdDrjkkkRnjAsBexeGpgjLEQ0blJy7rHhR2b93rhQY4SvyWu9v03g==} + engines: {node: '>=10'} + dependencies: + brace-expansion: 2.0.1 + dev: true + + /minimatch@5.1.6: + resolution: {integrity: sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==} + engines: {node: '>=10'} + dependencies: + brace-expansion: 2.0.1 + dev: true + + /minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + dev: true + + /mocha-fivemat-progress-reporter@0.1.0: + resolution: {integrity: sha512-nCf6dmCEHObJ8BBrcjW+UHYvVtHEL+FliYR/Mfc/v7dKenNmBQ0ZSuvlICgsyQy9Tt581ldvh+SReS4qp4LrQw==} + dev: true + + /mocha@10.2.0: + resolution: {integrity: sha512-IDY7fl/BecMwFHzoqF2sg/SHHANeBoMMXFlS9r0OXKDssYE1M5O43wUY/9BVPeIvfH2zmEbBfseqN9gBQZzXkg==} + engines: {node: '>= 14.0.0'} + hasBin: true + dependencies: + ansi-colors: 4.1.1 + browser-stdout: 1.3.1 + chokidar: 3.5.3 + debug: 4.3.4(supports-color@8.1.1) + diff: 5.0.0 + escape-string-regexp: 4.0.0 + find-up: 5.0.0 + glob: 7.2.0 + he: 1.2.0 + js-yaml: 4.1.0 + log-symbols: 4.1.0 + minimatch: 5.0.1 + ms: 2.1.3 + nanoid: 3.3.3 + serialize-javascript: 6.0.0 + strip-json-comments: 3.1.1 + supports-color: 8.1.1 + workerpool: 6.2.1 + yargs: 16.2.0 + yargs-parser: 20.2.4 + yargs-unparser: 2.0.0 + dev: true + + /ms@2.1.2: + resolution: {integrity: sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==} + dev: true + + /ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + dev: true + + /nanoid@3.3.3: + resolution: {integrity: sha512-p1sjXuopFs0xg+fPASzQ28agW1oHD7xDsd9Xkf3T15H3c/cifrFHVwrh74PdoklAPi+i7MdRsE47vm2r6JoB+w==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + dev: true + + /natural-compare-lite@1.4.0: + resolution: {integrity: sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g==} + dev: true + + /natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + dev: true + + /node-domexception@1.0.0: + resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==} + engines: {node: '>=10.5.0'} + dev: true + + /node-fetch@2.7.0: + resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==} + engines: {node: 4.x || >=6.0.0} + peerDependencies: + encoding: ^0.1.0 + peerDependenciesMeta: + encoding: + optional: true + dependencies: + whatwg-url: 5.0.0 + dev: true + + /node-fetch@3.2.10: + resolution: {integrity: sha512-MhuzNwdURnZ1Cp4XTazr69K0BTizsBroX7Zx3UgDSVcZYKF/6p0CBe4EUb/hLqmzVhl0UpYfgRljQ4yxE+iCxA==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + dependencies: + data-uri-to-buffer: 4.0.1 + fetch-blob: 3.2.0 + formdata-polyfill: 4.0.10 + dev: true + + /normalize-path@3.0.0: + resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} + engines: {node: '>=0.10.0'} + dev: true + + /object-inspect@1.13.1: + resolution: {integrity: sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==} + dev: true + + /once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + dependencies: + wrappy: 1.0.2 + dev: true + + /optionator@0.9.3: + resolution: {integrity: sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg==} + engines: {node: '>= 0.8.0'} + dependencies: + '@aashutoshrathi/word-wrap': 1.2.6 + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + dev: true + + /p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + dependencies: + yocto-queue: 0.1.0 + dev: true + + /p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + dependencies: + p-limit: 3.1.0 + dev: true + + /parent-module@1.0.1: + resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} + engines: {node: '>=6'} + dependencies: + callsites: 3.1.0 + dev: true + + /parse-ms@3.0.0: + resolution: {integrity: sha512-Tpb8Z7r7XbbtBTrM9UhpkzzaMrqA2VXMT3YChzYltwV3P3pM6t8wl7TvpMnSTosz1aQAdVib7kdoys7vYOPerw==} + engines: {node: '>=12'} + dev: true + + /path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + dev: true + + /path-is-absolute@1.0.1: + resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} + engines: {node: '>=0.10.0'} + dev: true + + /path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + dev: true + + /path-type@4.0.0: + resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==} + engines: {node: '>=8'} + dev: true + + /pathval@1.1.1: + resolution: {integrity: sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==} + dev: true + + /picocolors@1.0.0: + resolution: {integrity: sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==} + dev: true + + /picomatch@2.3.1: + resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} + engines: {node: '>=8.6'} + dev: true + + /playwright-core@1.38.0: + resolution: {integrity: sha512-f8z1y8J9zvmHoEhKgspmCvOExF2XdcxMW8jNRuX4vkQFrzV4MlZ55iwb5QeyiFQgOFCUolXiRHgpjSEnqvO48g==} + engines: {node: '>=16'} + hasBin: true + dev: true + + /playwright@1.38.0: + resolution: {integrity: sha512-fJGw+HO0YY+fU/F1N57DMO+TmXHTrmr905J05zwAQE9xkuwP/QLDk63rVhmyxh03dYnEhnRbsdbH9B0UVVRB3A==} + engines: {node: '>=16'} + hasBin: true + dependencies: + playwright-core: 1.38.0 + optionalDependencies: + fsevents: 2.3.2 + dev: true + + /plur@4.0.0: + resolution: {integrity: sha512-4UGewrYgqDFw9vV6zNV+ADmPAUAfJPKtGvb/VdpQAx25X5f3xXdGdyOEVFwkl8Hl/tl7+xbeHqSEM+D5/TirUg==} + engines: {node: '>=10'} + dependencies: + irregular-plurals: 3.5.0 + dev: true + + /prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + dev: true + + /pretty-ms@8.0.0: + resolution: {integrity: sha512-ASJqOugUF1bbzI35STMBUpZqdfYKlJugy6JBziGi2EE+AL5JPJGSzvpeVXojxrr0ViUYoToUjb5kjSEGf7Y83Q==} + engines: {node: '>=14.16'} + dependencies: + parse-ms: 3.0.0 + dev: true + + /punycode@2.3.0: + resolution: {integrity: sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==} + engines: {node: '>=6'} + dev: true + + /qs@6.11.2: + resolution: {integrity: sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==} + engines: {node: '>=0.6'} + dependencies: + side-channel: 1.0.4 + dev: true + + /queue-microtask@1.2.3: + resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} + dev: true + + /randombytes@2.1.0: + resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==} + dependencies: + safe-buffer: 5.2.1 + dev: true + + /readdirp@3.6.0: + resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} + engines: {node: '>=8.10.0'} + dependencies: + picomatch: 2.3.1 + dev: true + + /reduce-flatten@2.0.0: + resolution: {integrity: sha512-EJ4UNY/U1t2P/2k6oqotuX2Cc3T6nxJwsM0N0asT7dhrtH1ltUxDn4NalSYmPE2rCkVpcf/X6R0wDwcFpzhd4w==} + engines: {node: '>=6'} + dev: true + + /regexpp@3.2.0: + resolution: {integrity: sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==} + engines: {node: '>=8'} + dev: true + + /require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + dev: true + + /resolve-from@4.0.0: + resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} + engines: {node: '>=4'} + dev: true + + /reusify@1.0.4: + resolution: {integrity: sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==} + engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + dev: true + + /rimraf@3.0.2: + resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==} + hasBin: true + dependencies: + glob: 7.2.3 + dev: true + + /run-parallel@1.2.0: + resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} + dependencies: + queue-microtask: 1.2.3 + dev: true + + /safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + dev: true + + /semver@7.5.4: + resolution: {integrity: sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==} + engines: {node: '>=10'} + hasBin: true + dependencies: + lru-cache: 6.0.0 + dev: true + + /serialize-javascript@6.0.0: + resolution: {integrity: sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==} + dependencies: + randombytes: 2.1.0 + dev: true + + /set-function-length@1.1.1: + resolution: {integrity: sha512-VoaqjbBJKiWtg4yRcKBQ7g7wnGnLV3M8oLvVWwOk2PdYY6PEFegR1vezXR0tw6fZGF9csVakIRjrJiy2veSBFQ==} + engines: {node: '>= 0.4'} + dependencies: + define-data-property: 1.1.1 + get-intrinsic: 1.2.2 + gopd: 1.0.1 + has-property-descriptors: 1.0.1 + dev: true + + /shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + dependencies: + shebang-regex: 3.0.0 + dev: true + + /shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + dev: true + + /side-channel@1.0.4: + resolution: {integrity: sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==} + dependencies: + call-bind: 1.0.5 + get-intrinsic: 1.2.2 + object-inspect: 1.13.1 + dev: true + + /signal-exit@3.0.7: + resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} + dev: true + + /slash@3.0.0: + resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} + engines: {node: '>=8'} + dev: true + + /source-map-support@0.5.21: + resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} + dependencies: + buffer-from: 1.1.2 + source-map: 0.6.1 + dev: true + + /source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + dev: true + + /string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + dev: true + + /strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + dependencies: + ansi-regex: 5.0.1 + dev: true + + /strip-json-comments@3.1.1: + resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} + engines: {node: '>=8'} + dev: true + + /strnum@1.0.5: + resolution: {integrity: sha512-J8bbNyKKXl5qYcR36TIO8W3mVGVHrmmxsd5PAItGkmyzwJvybiw2IVq5nqd0i4LSNSkB/sx9VHllbfFdr9k1JA==} + dev: true + + /supports-color@5.5.0: + resolution: {integrity: sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==} + engines: {node: '>=4'} + dependencies: + has-flag: 3.0.0 + dev: true + + /supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + dependencies: + has-flag: 4.0.0 + dev: true + + /supports-color@8.1.1: + resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==} + engines: {node: '>=10'} + dependencies: + has-flag: 4.0.0 + dev: true + + /table-layout@1.0.2: + resolution: {integrity: sha512-qd/R7n5rQTRFi+Zf2sk5XVVd9UQl6ZkduPFC3S7WEGJAmetDTjY3qPN50eSKzwuzEyQKy5TN2TiZdkIjos2L6A==} + engines: {node: '>=8.0.0'} + dependencies: + array-back: 4.0.2 + deep-extend: 0.6.0 + typical: 5.2.0 + wordwrapjs: 4.0.1 + dev: true + + /test-exclude@6.0.0: + resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==} + engines: {node: '>=8'} + dependencies: + '@istanbuljs/schema': 0.1.3 + glob: 7.2.3 + minimatch: 3.1.2 + dev: true + + /text-table@0.2.0: + resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==} + dev: true + + /to-regex-range@5.0.1: + resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} + engines: {node: '>=8.0'} + dependencies: + is-number: 7.0.0 + dev: true + + /tr46@0.0.3: + resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} + dev: true + + /ts-api-utils@1.0.3(typescript@5.0.2): + resolution: {integrity: sha512-wNMeqtMz5NtwpT/UZGY5alT+VoKdSsOOP/kqHFcUW1P/VRhH2wJ48+DN2WwUliNbQ976ETwDL0Ifd2VVvgonvg==} + engines: {node: '>=16.13.0'} + peerDependencies: + typescript: '>=4.2.0' + dependencies: + typescript: 5.0.2 + dev: true + + /tslib@2.5.0: + resolution: {integrity: sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg==} + dev: true + + /tunnel@0.0.6: + resolution: {integrity: sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==} + engines: {node: '>=0.6.11 <=0.7.0 || >=0.7.3'} + dev: true + + /type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + dependencies: + prelude-ls: 1.2.1 + dev: true + + /type-detect@4.0.8: + resolution: {integrity: sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==} + engines: {node: '>=4'} + dev: true + + /type-fest@0.20.2: + resolution: {integrity: sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==} + engines: {node: '>=10'} + dev: true + + /typed-rest-client@1.8.11: + resolution: {integrity: sha512-5UvfMpd1oelmUPRbbaVnq+rHP7ng2cE4qoQkQeAqxRL6PklkxsM0g32/HL0yfvruK6ojQ5x8EE+HF4YV6DtuCA==} + dependencies: + qs: 6.11.2 + tunnel: 0.0.6 + underscore: 1.13.6 + dev: true + + /typescript@5.0.2: + resolution: {integrity: sha512-wVORMBGO/FAs/++blGNeAVdbNKtIh1rbBL2EyQ1+J9lClJ93KiiKe8PmFIVdXhHcyv44SL9oglmfeSsndo0jRw==} + engines: {node: '>=12.20'} + hasBin: true + dev: true + + /typical@4.0.0: + resolution: {integrity: sha512-VAH4IvQ7BDFYglMd7BPRDfLgxZZX4O4TFcRDA6EN5X7erNJJq+McIEp8np9aVtxrCJ6qx4GTYVfOWNjcqwZgRw==} + engines: {node: '>=8'} + dev: true + + /typical@5.2.0: + resolution: {integrity: sha512-dvdQgNDNJo+8B2uBQoqdb11eUCE1JQXhvjC/CZtgvZseVd5TYMXnq0+vuUemXbd/Se29cTaUuPX3YIc2xgbvIg==} + engines: {node: '>=8'} + dev: true + + /underscore@1.13.6: + resolution: {integrity: sha512-+A5Sja4HP1M08MaXya7p5LvjuM7K6q/2EaC0+iovj/wOcMsTzMvDFbasi/oSapiwOlt252IqsKqPjCl7huKS0A==} + dev: true + + /undici-types@5.25.3: + resolution: {integrity: sha512-Ga1jfYwRn7+cP9v8auvEXN1rX3sWqlayd4HP7OKk4mZWylEmu3KzXDUGrQUN6Ol7qo1gPvB2e5gX6udnyEPgdA==} + dev: true + + /undici-types@5.26.5: + resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==} + dev: true + + /universal-user-agent@6.0.0: + resolution: {integrity: sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==} + dev: true + + /uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + dependencies: + punycode: 2.3.0 + dev: true + + /v8-compile-cache@2.4.0: + resolution: {integrity: sha512-ocyWc3bAHBB/guyqJQVI5o4BZkPhznPYUG2ea80Gond/BgNWpap8TOmLSeeQG7bnh2KMISxskdADG59j7zruhw==} + dev: true + + /v8-to-istanbul@9.1.3: + resolution: {integrity: sha512-9lDD+EVI2fjFsMWXc6dy5JJzBsVTcQ2fVkfBvncZ6xJWG9wtBhOldG+mHkSL0+V1K/xgZz0JDO5UT5hFwHUghg==} + engines: {node: '>=10.12.0'} + dependencies: + '@jridgewell/trace-mapping': 0.3.20 + '@types/istanbul-lib-coverage': 2.0.5 + convert-source-map: 2.0.0 + dev: true + + /web-streams-polyfill@3.2.1: + resolution: {integrity: sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==} + engines: {node: '>= 8'} + dev: true + + /webidl-conversions@3.0.1: + resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} + dev: true + + /whatwg-url@5.0.0: + resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} + dependencies: + tr46: 0.0.3 + webidl-conversions: 3.0.1 + dev: true + + /which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + dependencies: + isexe: 2.0.0 + dev: true + + /wordwrapjs@4.0.1: + resolution: {integrity: sha512-kKlNACbvHrkpIw6oPeYDSmdCTu2hdMHoyXLTcUKala++lx5Y+wjJ/e474Jqv5abnVmwxw08DiTuHmw69lJGksA==} + engines: {node: '>=8.0.0'} + dependencies: + reduce-flatten: 2.0.0 + typical: 5.2.0 + dev: true + + /workerpool@6.2.1: + resolution: {integrity: sha512-ILEIE97kDZvF9Wb9f6h5aXK4swSlKGUcOEGiIYb2OOu/IrDU9iwj0fD//SsA6E5ibwJxpEvhullJY4Sl4GcpAw==} + dev: true + + /wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + dev: true + + /wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + dev: true + + /y18n@5.0.8: + resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} + engines: {node: '>=10'} + dev: true + + /yallist@4.0.0: + resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} + dev: true + + /yargs-parser@20.2.4: + resolution: {integrity: sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==} + engines: {node: '>=10'} + dev: true + + /yargs-parser@20.2.9: + resolution: {integrity: sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==} + engines: {node: '>=10'} + dev: true + + /yargs-unparser@2.0.0: + resolution: {integrity: sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==} + engines: {node: '>=10'} + dependencies: + camelcase: 6.3.0 + decamelize: 4.0.0 + flat: 5.0.2 + is-plain-obj: 2.1.0 + dev: true + + /yargs@16.2.0: + resolution: {integrity: sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==} + engines: {node: '>=10'} + dependencies: + cliui: 7.0.4 + escalade: 3.1.1 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 20.2.9 + dev: true + + /yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} + dev: true diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index a490f335a8a4d..e72f34e2d3e7e 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -5,7 +5,6 @@ import { append, appendIfUnique, ArrayBindingElement, - ArrayLiteralExpression, ArrowFunction, AssignmentDeclarationKind, BinaryExpression, @@ -53,7 +52,6 @@ import { DoStatement, DynamicNamedDeclaration, ElementAccessChain, - ElementAccessExpression, EntityNameExpression, EnumDeclaration, escapeLeadingUnderscores, @@ -227,8 +225,6 @@ import { JSDocCallbackTag, JSDocClassTag, JSDocEnumTag, - JSDocFunctionType, - JSDocOverloadTag, JSDocParameterTag, JSDocPropertyLikeTag, JSDocSignature, @@ -259,7 +255,6 @@ import { ObjectLiteralExpression, OptionalChain, ParameterDeclaration, - ParenthesizedExpression, Pattern, PatternAmbientModule, perfLogger, @@ -271,7 +266,6 @@ import { PropertyAccessExpression, PropertyDeclaration, PropertySignature, - QualifiedName, removeFileExtension, ReturnStatement, ScriptTarget, @@ -287,7 +281,6 @@ import { sliceAfter, some, SourceFile, - SpreadElement, Statement, StringLiteral, SuperExpression, @@ -307,7 +300,6 @@ import { tryParsePattern, TryStatement, TypeLiteralNode, - TypeOfExpression, TypeParameterDeclaration, unescapeLeadingUnderscores, unreachableCodeIsError, @@ -363,7 +355,7 @@ function getModuleInstanceStateWorker(node: Node, visited: Map void { // unless it is a well known Symbol. function getDeclarationName(node: Declaration): __String | undefined { if (node.kind === SyntaxKind.ExportAssignment) { - return (node as ExportAssignment).isExportEquals ? InternalSymbolName.ExportEquals : InternalSymbolName.Default; + return node.isExportEquals ? InternalSymbolName.ExportEquals : InternalSymbolName.Default; } const name = getNameOfDeclaration(node); if (name) { if (isAmbientModule(node)) { const moduleName = getTextOfIdentifierOrLiteral(name as Identifier | StringLiteral); - return (isGlobalScopeAugmentation(node as ModuleDeclaration) ? "__global" : `"${moduleName}"`) as __String; + return (isGlobalScopeAugmentation(node) ? "__global" : `"${moduleName}"`) as __String; } if (name.kind === SyntaxKind.ComputedPropertyName) { const nameExpression = name.expression; @@ -716,7 +708,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { // module.exports = ... return InternalSymbolName.ExportEquals; case SyntaxKind.BinaryExpression: - if (getAssignmentDeclarationKind(node as BinaryExpression) === AssignmentDeclarationKind.ModuleExports) { + if (getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports) { // module.exports = ... return InternalSymbolName.ExportEquals; } @@ -728,8 +720,8 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { // Parameters with names are handled at the top of this function. Parameters // without names can only come from JSDocFunctionTypes. Debug.assert(node.parent.kind === SyntaxKind.JSDocFunctionType, "Impossible parameter parent kind", () => `parent is: ${Debug.formatSyntaxKind(node.parent.kind)}, expected JSDocFunctionType`); - const functionType = node.parent as JSDocFunctionType; - const index = functionType.parameters.indexOf(node as ParameterDeclaration); + const functionType = node.parent; + const index = functionType.parameters.indexOf(node); return "arg" + index as __String; } } @@ -838,7 +830,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) if ( symbol.declarations && symbol.declarations.length && - (node.kind === SyntaxKind.ExportAssignment && !(node as ExportAssignment).isExportEquals) + (node.kind === SyntaxKind.ExportAssignment && !node.isExportEquals) ) { message = Diagnostics.A_module_cannot_have_multiple_default_exports; messageNeedsName = false; @@ -1099,52 +1091,52 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { } switch (node.kind) { case SyntaxKind.WhileStatement: - bindWhileStatement(node as WhileStatement); + bindWhileStatement(node); break; case SyntaxKind.DoStatement: - bindDoStatement(node as DoStatement); + bindDoStatement(node); break; case SyntaxKind.ForStatement: - bindForStatement(node as ForStatement); + bindForStatement(node); break; case SyntaxKind.ForInStatement: case SyntaxKind.ForOfStatement: - bindForInOrForOfStatement(node as ForInOrOfStatement); + bindForInOrForOfStatement(node); break; case SyntaxKind.IfStatement: - bindIfStatement(node as IfStatement); + bindIfStatement(node); break; case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: - bindReturnOrThrow(node as ReturnStatement | ThrowStatement); + bindReturnOrThrow(node); break; case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: - bindBreakOrContinueStatement(node as BreakOrContinueStatement); + bindBreakOrContinueStatement(node); break; case SyntaxKind.TryStatement: - bindTryStatement(node as TryStatement); + bindTryStatement(node); break; case SyntaxKind.SwitchStatement: - bindSwitchStatement(node as SwitchStatement); + bindSwitchStatement(node); break; case SyntaxKind.CaseBlock: - bindCaseBlock(node as CaseBlock); + bindCaseBlock(node); break; case SyntaxKind.CaseClause: - bindCaseClause(node as CaseClause); + bindCaseClause(node); break; case SyntaxKind.ExpressionStatement: - bindExpressionStatement(node as ExpressionStatement); + bindExpressionStatement(node); break; case SyntaxKind.LabeledStatement: - bindLabeledStatement(node as LabeledStatement); + bindLabeledStatement(node); break; case SyntaxKind.PrefixUnaryExpression: - bindPrefixUnaryExpressionFlow(node as PrefixUnaryExpression); + bindPrefixUnaryExpressionFlow(node); break; case SyntaxKind.PostfixUnaryExpression: - bindPostfixUnaryExpressionFlow(node as PostfixUnaryExpression); + bindPostfixUnaryExpressionFlow(node); break; case SyntaxKind.BinaryExpression: if (isDestructuringAssignment(node)) { @@ -1154,47 +1146,47 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { bindDestructuringAssignmentFlow(node); return; } - bindBinaryExpressionFlow(node as BinaryExpression); + bindBinaryExpressionFlow(node); break; case SyntaxKind.DeleteExpression: - bindDeleteExpressionFlow(node as DeleteExpression); + bindDeleteExpressionFlow(node); break; case SyntaxKind.ConditionalExpression: - bindConditionalExpressionFlow(node as ConditionalExpression); + bindConditionalExpressionFlow(node); break; case SyntaxKind.VariableDeclaration: - bindVariableDeclarationFlow(node as VariableDeclaration); + bindVariableDeclarationFlow(node); break; case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: - bindAccessExpressionFlow(node as AccessExpression); + bindAccessExpressionFlow(node); break; case SyntaxKind.CallExpression: - bindCallExpressionFlow(node as CallExpression); + bindCallExpressionFlow(node); break; case SyntaxKind.NonNullExpression: - bindNonNullExpressionFlow(node as NonNullExpression); + bindNonNullExpressionFlow(node); break; case SyntaxKind.JSDocTypedefTag: case SyntaxKind.JSDocCallbackTag: case SyntaxKind.JSDocEnumTag: - bindJSDocTypeAlias(node as JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag); + bindJSDocTypeAlias(node); break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case SyntaxKind.SourceFile: { - bindEachFunctionsFirst((node as SourceFile).statements); - bind((node as SourceFile).endOfFileToken); + bindEachFunctionsFirst(node.statements); + bind(node.endOfFileToken); break; } case SyntaxKind.Block: case SyntaxKind.ModuleBlock: - bindEachFunctionsFirst((node as Block).statements); + bindEachFunctionsFirst(node.statements); break; case SyntaxKind.BindingElement: - bindBindingElementFlow(node as BindingElement); + bindBindingElementFlow(node); break; case SyntaxKind.Parameter: - bindParameterFlow(node as ParameterDeclaration); + bindParameterFlow(node); break; case SyntaxKind.ObjectLiteralExpression: case SyntaxKind.ArrayLiteralExpression: @@ -1221,16 +1213,16 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { case SyntaxKind.ElementAccessExpression: return containsNarrowableReference(expr); case SyntaxKind.CallExpression: - return hasNarrowableArgument(expr as CallExpression); + return hasNarrowableArgument(expr); case SyntaxKind.ParenthesizedExpression: case SyntaxKind.NonNullExpression: - return isNarrowingExpression((expr as ParenthesizedExpression | NonNullExpression).expression); + return isNarrowingExpression(expr.expression); case SyntaxKind.BinaryExpression: - return isNarrowingBinaryExpression(expr as BinaryExpression); + return isNarrowingBinaryExpression(expr); case SyntaxKind.PrefixUnaryExpression: - return (expr as PrefixUnaryExpression).operator === SyntaxKind.ExclamationToken && isNarrowingExpression((expr as PrefixUnaryExpression).operand); + return expr.operator === SyntaxKind.ExclamationToken && isNarrowingExpression(expr.operand); case SyntaxKind.TypeOfExpression: - return isNarrowingExpression((expr as TypeOfExpression).expression); + return isNarrowingExpression(expr.expression); } return false; } @@ -1295,13 +1287,13 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { function isNarrowableOperand(expr: Expression): boolean { switch (expr.kind) { case SyntaxKind.ParenthesizedExpression: - return isNarrowableOperand((expr as ParenthesizedExpression).expression); + return isNarrowableOperand(expr.expression); case SyntaxKind.BinaryExpression: - switch ((expr as BinaryExpression).operatorToken.kind) { + switch (expr.operatorToken.kind) { case SyntaxKind.EqualsToken: - return isNarrowableOperand((expr as BinaryExpression).left); + return isNarrowableOperand(expr.left); case SyntaxKind.CommaToken: - return isNarrowableOperand((expr as BinaryExpression).right); + return isNarrowableOperand(expr.right); } } return containsNarrowableReference(expr); @@ -1399,10 +1391,10 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { function isLogicalExpression(node: Node) { while (true) { if (node.kind === SyntaxKind.ParenthesizedExpression) { - node = (node as ParenthesizedExpression).expression; + node = node.expression; } - else if (node.kind === SyntaxKind.PrefixUnaryExpression && (node as PrefixUnaryExpression).operator === SyntaxKind.ExclamationToken) { - node = (node as PrefixUnaryExpression).operand; + else if (node.kind === SyntaxKind.PrefixUnaryExpression && node.operator === SyntaxKind.ExclamationToken) { + node = node.operand; } else { return isLogicalOrCoalescingBinaryExpression(node); @@ -1720,7 +1712,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { // A top level or comma expression call expression with a dotted function name and at least one argument // is potentially an assertion and is therefore included in the control flow. if (node.kind === SyntaxKind.CallExpression) { - const call = node as CallExpression; + const call = node; if (call.expression.kind !== SyntaxKind.SuperKeyword && isDottedName(call.expression)) { currentFlow = createFlowCall(currentFlow, call); } @@ -1747,8 +1739,8 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { } function bindDestructuringTargetFlow(node: Expression) { - if (node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { - bindAssignmentTargetFlow((node as BinaryExpression).left); + if (node.kind === SyntaxKind.BinaryExpression && node.operatorToken.kind === SyntaxKind.EqualsToken) { + bindAssignmentTargetFlow(node.left); } else { bindAssignmentTargetFlow(node); @@ -1760,9 +1752,9 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { currentFlow = createFlowMutation(FlowFlags.Assignment, currentFlow, node); } else if (node.kind === SyntaxKind.ArrayLiteralExpression) { - for (const e of (node as ArrayLiteralExpression).elements) { + for (const e of node.elements) { if (e.kind === SyntaxKind.SpreadElement) { - bindAssignmentTargetFlow((e as SpreadElement).expression); + bindAssignmentTargetFlow(e.expression); } else { bindDestructuringTargetFlow(e); @@ -1770,7 +1762,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { } } else if (node.kind === SyntaxKind.ObjectLiteralExpression) { - for (const p of (node as ObjectLiteralExpression).properties) { + for (const p of node.properties) { if (p.kind === SyntaxKind.PropertyAssignment) { bindDestructuringTargetFlow(p.initializer); } @@ -1931,7 +1923,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) { - const elementAccess = node.left as ElementAccessExpression; + const elementAccess = node.left; if (isNarrowableOperand(elementAccess.expression)) { currentFlow = createFlowMutation(FlowFlags.ArrayMutation, currentFlow, node); } @@ -2524,13 +2516,17 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { } } - function isEvalOrArgumentsIdentifier(node: Node): boolean { + type EvalOrArgumentsIdentifier = Identifier & { + escapedText: "arguments" | "eval"; + }; + + function isEvalOrArgumentsIdentifier(node: Node): node is EvalOrArgumentsIdentifier { return isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments"); } function checkStrictModeEvalOrArguments(contextNode: Node, name: Node | undefined) { if (name && name.kind === SyntaxKind.Identifier) { - const identifier = name as Identifier; + const identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. @@ -2756,7 +2752,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { while (parentNode && !isJSDocTypeAlias(parentNode)) { parentNode = parentNode.parent; } - bindBlockScopedDeclaration(parentNode as Declaration, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); + bindBlockScopedDeclaration(parentNode, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); break; } // falls through @@ -2769,7 +2765,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { return checkContextualIdentifier(node as Identifier); case SyntaxKind.QualifiedName: if (currentFlow && isPartOfTypeQuery(node)) { - (node as QualifiedName).flowNode = currentFlow; + node.flowNode = currentFlow; } break; case SyntaxKind.MetaProperty: @@ -2777,10 +2773,10 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { (node as MetaProperty | SuperExpression).flowNode = currentFlow; break; case SyntaxKind.PrivateIdentifier: - return checkPrivateIdentifier(node as PrivateIdentifier); + return checkPrivateIdentifier(node); case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: - const expr = node as PropertyAccessExpression | ElementAccessExpression; + const expr = node; if (currentFlow && isNarrowableReference(expr)) { expr.flowNode = currentFlow; } @@ -2797,7 +2793,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { } break; case SyntaxKind.BinaryExpression: - const specialKind = getAssignmentDeclarationKind(node as BinaryExpression); + const specialKind = getAssignmentDeclarationKind(node); switch (specialKind) { case AssignmentDeclarationKind.ExportsProperty: bindExportsPropertyAssignment(node as BindableStaticPropertyAssignmentExpression); @@ -2812,10 +2808,10 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { bindPrototypeAssignment(node as BindableStaticPropertyAssignmentExpression); break; case AssignmentDeclarationKind.ThisProperty: - bindThisPropertyAssignment(node as BindablePropertyAssignmentExpression); + bindThisPropertyAssignment(node as BindableStaticPropertyAssignmentExpression); break; case AssignmentDeclarationKind.Property: - const expression = ((node as BinaryExpression).left as AccessExpression).expression; + const expression = (node.left as AccessExpression).expression; if (isInJSFile(node) && isIdentifier(expression)) { const symbol = lookupSymbolForName(blockScopeContainer, expression.escapedText); if (isThisInitializedDeclaration(symbol?.valueDeclaration)) { @@ -2831,61 +2827,61 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { default: Debug.fail("Unknown binary expression special property assignment kind"); } - return checkStrictModeBinaryExpression(node as BinaryExpression); + return checkStrictModeBinaryExpression(node); case SyntaxKind.CatchClause: - return checkStrictModeCatchClause(node as CatchClause); + return checkStrictModeCatchClause(node); case SyntaxKind.DeleteExpression: - return checkStrictModeDeleteExpression(node as DeleteExpression); + return checkStrictModeDeleteExpression(node); case SyntaxKind.PostfixUnaryExpression: - return checkStrictModePostfixUnaryExpression(node as PostfixUnaryExpression); + return checkStrictModePostfixUnaryExpression(node); case SyntaxKind.PrefixUnaryExpression: - return checkStrictModePrefixUnaryExpression(node as PrefixUnaryExpression); + return checkStrictModePrefixUnaryExpression(node); case SyntaxKind.WithStatement: - return checkStrictModeWithStatement(node as WithStatement); + return checkStrictModeWithStatement(node); case SyntaxKind.LabeledStatement: - return checkStrictModeLabeledStatement(node as LabeledStatement); + return checkStrictModeLabeledStatement(node); case SyntaxKind.ThisType: seenThisKeyword = true; return; case SyntaxKind.TypePredicate: break; // Binding the children will handle everything case SyntaxKind.TypeParameter: - return bindTypeParameter(node as TypeParameterDeclaration); + return bindTypeParameter(node); case SyntaxKind.Parameter: - return bindParameter(node as ParameterDeclaration); + return bindParameter(node); case SyntaxKind.VariableDeclaration: - return bindVariableDeclarationOrBindingElement(node as VariableDeclaration); + return bindVariableDeclarationOrBindingElement(node); case SyntaxKind.BindingElement: - (node as BindingElement).flowNode = currentFlow; - return bindVariableDeclarationOrBindingElement(node as BindingElement); + node.flowNode = currentFlow; + return bindVariableDeclarationOrBindingElement(node); case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - return bindPropertyWorker(node as PropertyDeclaration | PropertySignature); + return bindPropertyWorker(node); case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: - return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.Property, SymbolFlags.PropertyExcludes); + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); case SyntaxKind.EnumMember: - return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes); + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes); case SyntaxKind.CallSignature: case SyntaxKind.ConstructSignature: case SyntaxKind.IndexSignature: - return declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Signature, SymbolFlags.None); + return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Signature, SymbolFlags.None); case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: // If this is an ObjectLiteralExpression method, then it sits in the same space // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.Method | ((node as MethodDeclaration).questionToken ? SymbolFlags.Optional : SymbolFlags.None), isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes); + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Method | (node.questionToken ? SymbolFlags.Optional : SymbolFlags.None), isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes); case SyntaxKind.FunctionDeclaration: - return bindFunctionDeclaration(node as FunctionDeclaration); + return bindFunctionDeclaration(node); case SyntaxKind.Constructor: - return declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Constructor, /*symbolExcludes:*/ SymbolFlags.None); + return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Constructor, /*symbolExcludes:*/ SymbolFlags.None); case SyntaxKind.GetAccessor: - return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.GetAccessor, SymbolFlags.GetAccessorExcludes); + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.GetAccessor, SymbolFlags.GetAccessorExcludes); case SyntaxKind.SetAccessor: - return bindPropertyOrMethodOrAccessor(node as Declaration, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes); + return bindPropertyOrMethodOrAccessor(node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes); case SyntaxKind.FunctionType: case SyntaxKind.JSDocFunctionType: case SyntaxKind.JSDocSignature: @@ -2894,17 +2890,17 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { case SyntaxKind.TypeLiteral: case SyntaxKind.JSDocTypeLiteral: case SyntaxKind.MappedType: - return bindAnonymousTypeWorker(node as TypeLiteralNode | MappedTypeNode | JSDocTypeLiteral); + return bindAnonymousTypeWorker(node); case SyntaxKind.JSDocClassTag: - return bindJSDocClassTag(node as JSDocClassTag); + return bindJSDocClassTag(node); case SyntaxKind.ObjectLiteralExpression: - return bindObjectLiteralExpression(node as ObjectLiteralExpression); + return bindObjectLiteralExpression(node); case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - return bindFunctionExpression(node as FunctionExpression | ArrowFunction); + return bindFunctionExpression(node); case SyntaxKind.CallExpression: - const assignmentKind = getAssignmentDeclarationKind(node as CallExpression); + const assignmentKind = getAssignmentDeclarationKind(node); switch (assignmentKind) { case AssignmentDeclarationKind.ObjectDefinePropertyValue: return bindObjectDefinePropertyAssignment(node as BindableObjectDefinePropertyCall); @@ -2918,7 +2914,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { return Debug.fail("Unknown call expression assignment declaration kind"); } if (isInJSFile(node)) { - bindCallExpression(node as CallExpression); + bindCallExpression(node); } break; @@ -2929,35 +2925,35 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { inStrictMode = true; return bindClassLikeDeclaration(node as ClassLikeDeclaration); case SyntaxKind.InterfaceDeclaration: - return bindBlockScopedDeclaration(node as Declaration, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes); + return bindBlockScopedDeclaration(node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes); case SyntaxKind.TypeAliasDeclaration: - return bindBlockScopedDeclaration(node as Declaration, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); + return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); case SyntaxKind.EnumDeclaration: - return bindEnumDeclaration(node as EnumDeclaration); + return bindEnumDeclaration(node); case SyntaxKind.ModuleDeclaration: - return bindModuleDeclaration(node as ModuleDeclaration); + return bindModuleDeclaration(node); // Jsx-attributes case SyntaxKind.JsxAttributes: - return bindJsxAttributes(node as JsxAttributes); + return bindJsxAttributes(node); case SyntaxKind.JsxAttribute: - return bindJsxAttribute(node as JsxAttribute, SymbolFlags.Property, SymbolFlags.PropertyExcludes); + return bindJsxAttribute(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); // Imports and exports case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.NamespaceImport: case SyntaxKind.ImportSpecifier: case SyntaxKind.ExportSpecifier: - return declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Alias, SymbolFlags.AliasExcludes); + return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); case SyntaxKind.NamespaceExportDeclaration: - return bindNamespaceExportDeclaration(node as NamespaceExportDeclaration); + return bindNamespaceExportDeclaration(node); case SyntaxKind.ImportClause: - return bindImportClause(node as ImportClause); + return bindImportClause(node); case SyntaxKind.ExportDeclaration: - return bindExportDeclaration(node as ExportDeclaration); + return bindExportDeclaration(node); case SyntaxKind.ExportAssignment: - return bindExportAssignment(node as ExportAssignment); + return bindExportAssignment(node); case SyntaxKind.SourceFile: - updateStrictModeStatementList((node as SourceFile).statements); + updateStrictModeStatementList(node.statements); return bindSourceFileIfExternalModule(); case SyntaxKind.Block: if (!isFunctionLikeOrClassStaticBlockDeclaration(node.parent)) { @@ -2965,11 +2961,11 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { } // falls through case SyntaxKind.ModuleBlock: - return updateStrictModeStatementList((node as Block | ModuleBlock).statements); + return updateStrictModeStatementList(node.statements); case SyntaxKind.JSDocParameterTag: if (node.parent.kind === SyntaxKind.JSDocSignature) { - return bindParameter(node as JSDocParameterTag); + return bindParameter(node); } if (node.parent.kind !== SyntaxKind.JSDocTypeLiteral) { break; @@ -2984,9 +2980,9 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { case SyntaxKind.JSDocTypedefTag: case SyntaxKind.JSDocCallbackTag: case SyntaxKind.JSDocEnumTag: - return (delayedTypeAliases || (delayedTypeAliases = [])).push(node as JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag); + return (delayedTypeAliases || (delayedTypeAliases = [])).push(node); case SyntaxKind.JSDocOverloadTag: - return bind((node as JSDocOverloadTag).typeExpression); + return bind(node.typeExpression); } } @@ -2998,7 +2994,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { } function bindAnonymousTypeWorker(node: TypeLiteralNode | MappedTypeNode | JSDocTypeLiteral) { - return bindAnonymousDeclaration(node as Declaration, SymbolFlags.TypeLiteral, InternalSymbolName.Type); + return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, InternalSymbolName.Type); } function bindSourceFileIfExternalModule() { @@ -3233,7 +3229,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { } function bindDynamicallyNamedThisPropertyAssignment(node: BinaryExpression | DynamicNamedDeclaration, symbol: Symbol, symbolTable: SymbolTable) { - declareSymbol(symbolTable, symbol, node, SymbolFlags.Property, SymbolFlags.None, /*isReplaceableByMethod*/ true, /*isComputedName*/ true); + declareSymbol(symbolTable, symbol, node as Declaration, SymbolFlags.Property, SymbolFlags.None, /*isReplaceableByMethod*/ true, /*isComputedName*/ true); addLateBoundAssignmentDeclarationToSymbol(node, symbol); } @@ -3555,7 +3551,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { !getJSDocTypeTag(node) && !(getCombinedModifierFlags(node) & ModifierFlags.Export) ) { - declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Alias, SymbolFlags.AliasExcludes); + declareSymbolAndAddToSymbolTable(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); } else if (isBlockOrCatchScoped(node)) { bindBlockScopedDeclaration(node, SymbolFlags.BlockScopedVariable, SymbolFlags.BlockScopedVariableExcludes); @@ -3699,7 +3695,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void { // report error on class declarations node.kind === SyntaxKind.ClassDeclaration || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === SyntaxKind.ModuleDeclaration && shouldReportErrorOnModuleDeclaration(node as ModuleDeclaration)); + (node.kind === SyntaxKind.ModuleDeclaration && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; @@ -3754,7 +3750,7 @@ function isPurelyTypeDeclaration(s: Statement): boolean { case SyntaxKind.TypeAliasDeclaration: return true; case SyntaxKind.ModuleDeclaration: - return getModuleInstanceState(s as ModuleDeclaration) !== ModuleInstanceState.Instantiated; + return getModuleInstanceState(s) !== ModuleInstanceState.Instantiated; case SyntaxKind.EnumDeclaration: return hasSyntacticModifier(s, ModifierFlags.Const); default: @@ -3838,7 +3834,7 @@ export function getContainerFlags(node: Node): ContainerFlags { case SyntaxKind.ModuleBlock: return ContainerFlags.IsControlFlowContainer; case SyntaxKind.PropertyDeclaration: - return (node as PropertyDeclaration).initializer ? ContainerFlags.IsControlFlowContainer : 0; + return node.initializer ? ContainerFlags.IsControlFlowContainer : 0; case SyntaxKind.CatchClause: case SyntaxKind.ForStatement: diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 4cd242f264b1a..f6b8cff65db9f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -810,7 +810,7 @@ import { LabeledStatement, last, lastOrUndefined, - LateBoundBinaryExpressionDeclaration, + LateBoundBinaryExpressionDeclarationBase, LateBoundDeclaration, LateBoundName, LateVisibilityPaintedStatement, @@ -853,6 +853,7 @@ import { NewExpression, Node, NodeArray, + NodeBase, NodeBuilderFlags, nodeCanBeDecorated, NodeCheckFlags, @@ -1370,7 +1371,7 @@ function NodeLinks(this: NodeLinks) { } /** @internal */ -export function getNodeId(node: Node): number { +export function getNodeId(node: NodeBase): number { if (!node.id) { node.id = nextNodeId; nextNodeId++; @@ -2742,7 +2743,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function isGlobalSourceFile(node: Node) { - return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(node as SourceFile); + return node.kind === SyntaxKind.SourceFile && !isExternalOrCommonJsModule(node); } function getSymbol(symbols: SymbolTable, name: __String, meaning: SymbolFlags): Symbol | undefined { @@ -2827,7 +2828,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } else if (declaration.kind === SyntaxKind.VariableDeclaration) { // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a) - return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration as VariableDeclaration, usage); + return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage); } else if (isClassDeclaration(declaration)) { // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} }) @@ -2858,7 +2859,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return true; } // When resolving symbols for exports, the `usage` location passed in can be the export site directly - if (usage.kind === SyntaxKind.ExportAssignment && (usage as ExportAssignment).isExportEquals) { + if (usage.kind === SyntaxKind.ExportAssignment && usage.isExportEquals) { return true; } @@ -3026,7 +3027,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (hasStaticModifier(node)) { return !emitStandardClassFields; } - return requiresScopeChangeWorker((node as PropertyDeclaration).name); + return requiresScopeChangeWorker(node.name); default: // null coalesce and optional chain pre-es2020 produce temporary variables if (isNullishCoalesce(node) || isOptionalChain(node)) { @@ -3145,7 +3146,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if (location.kind === SyntaxKind.ConditionalType) { // A type parameter declared using 'infer T' in a conditional type is visible only in // the true branch of the conditional type. - useResult = lastLocation === (location as ConditionalTypeNode).trueType; + useResult = lastLocation === location.trueType; } if (useResult) { @@ -3159,11 +3160,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { case SyntaxKind.SourceFile: - if (!isExternalOrCommonJsModule(location as SourceFile)) break; + if (!isExternalOrCommonJsModule(location)) break; isInExternalModule = true; // falls through case SyntaxKind.ModuleDeclaration: - const moduleExports = getSymbolOfDeclaration(location as SourceFile | ModuleDeclaration)?.exports || emptySymbols; + const moduleExports = getSymbolOfDeclaration(location)?.exports || emptySymbols; if (location.kind === SyntaxKind.SourceFile || (isModuleDeclaration(location) && location.flags & NodeFlags.Ambient && !isGlobalScopeAugmentation(location))) { // It's an external module. First see if the module has an export default and if the local // name of that export default matches. @@ -3207,7 +3208,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } break; case SyntaxKind.EnumDeclaration: - if (result = lookup(getSymbolOfDeclaration(location as EnumDeclaration)?.exports || emptySymbols, name, meaning & SymbolFlags.EnumMember)) { + if (result = lookup(getSymbolOfDeclaration(location)?.exports || emptySymbols, name, meaning & SymbolFlags.EnumMember)) { if (nameNotFoundMessage && getIsolatedModules(compilerOptions) && !(location.flags & NodeFlags.Ambient) && getSourceFileOfNode(location) !== getSourceFileOfNode(result.valueDeclaration)) { error( errorLocation, @@ -3228,7 +3229,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. if (!isStatic(location)) { - const ctor = findConstructorDeclaration(location.parent as ClassLikeDeclaration); + const ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (lookup(ctor.locals, name, meaning & SymbolFlags.Value)) { // Remember the property node, it will be used later to report appropriate error @@ -3271,7 +3272,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { break; case SyntaxKind.ExpressionWithTypeArguments: // The type parameters of a class are not in scope in the base class expression. - if (lastLocation === (location as ExpressionWithTypeArguments).expression && (location.parent as HeritageClause).token === SyntaxKind.ExtendsKeyword) { + if (lastLocation === location.expression && (location.parent as HeritageClause).token === SyntaxKind.ExtendsKeyword) { const container = location.parent.parent; if (isClassLike(container) && (result = lookup(getSymbolOfDeclaration(container).members!, name, meaning & SymbolFlags.Type))) { if (nameNotFoundMessage) { @@ -3293,7 +3294,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { grandparent = location.parent.parent; if (isClassLike(grandparent) || grandparent.kind === SyntaxKind.InterfaceDeclaration) { // A reference to this grandparent's type parameters would be an error - if (result = lookup(getSymbolOfDeclaration(grandparent as ClassLikeDeclaration | InterfaceDeclaration).members!, name, meaning & SymbolFlags.Type)) { + if (result = lookup(getSymbolOfDeclaration(grandparent).members!, name, meaning & SymbolFlags.Type)) { if (nameNotFoundMessage) { error(errorLocation, Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); } @@ -3325,9 +3326,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (meaning & SymbolFlags.Function) { - const functionName = (location as FunctionExpression).name; + const functionName = location.name; if (functionName && name === functionName.escapedText) { - result = (location as FunctionExpression).symbol; + result = location.symbol; break loop; } } @@ -3373,32 +3374,32 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.Parameter: if ( lastLocation && ( - lastLocation === (location as ParameterDeclaration).initializer || - lastLocation === (location as ParameterDeclaration).name && isBindingPattern(lastLocation) + lastLocation === location.initializer || + lastLocation === location.name && isBindingPattern(lastLocation) ) ) { if (!associatedDeclarationForContainingInitializerOrBindingName) { - associatedDeclarationForContainingInitializerOrBindingName = location as ParameterDeclaration; + associatedDeclarationForContainingInitializerOrBindingName = location; } } break; case SyntaxKind.BindingElement: if ( lastLocation && ( - lastLocation === (location as BindingElement).initializer || - lastLocation === (location as BindingElement).name && isBindingPattern(lastLocation) + lastLocation === location.initializer || + lastLocation === location.name && isBindingPattern(lastLocation) ) ) { - if (isParameterDeclaration(location as BindingElement) && !associatedDeclarationForContainingInitializerOrBindingName) { - associatedDeclarationForContainingInitializerOrBindingName = location as BindingElement; + if (isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) { + associatedDeclarationForContainingInitializerOrBindingName = location; } } break; case SyntaxKind.InferType: if (meaning & SymbolFlags.TypeParameter) { - const parameterName = (location as InferTypeNode).typeParameter.name; + const parameterName = location.typeParameter.name; if (parameterName && name === parameterName.escapedText) { - result = (location as InferTypeNode).typeParameter.symbol; + result = location.typeParameter.symbol; break loop; } } @@ -3407,8 +3408,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // External module export bindings shouldn't be resolved to local symbols. if ( lastLocation && - lastLocation === (location as ExportSpecifier).propertyName && - (location as ExportSpecifier).parent.parent.moduleSpecifier + lastLocation === location.propertyName && + location.parent.parent.moduleSpecifier ) { location = location.parent.parent.parent; } @@ -3619,11 +3620,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { (location.kind === SyntaxKind.PropertyDeclaration && !isStatic(location)) ) && (!lastLocation || lastLocation !== (location as SignatureDeclaration | PropertyDeclaration).name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred } - if (lastLocation && lastLocation === (location as FunctionExpression | ArrowFunction).name) { + if (lastLocation && lastLocation === location.name) { return false; } // generator functions and async functions are not inlined in control flow when immediately invoked - if ((location as FunctionExpression | ArrowFunction).asteriskToken || hasSyntacticModifier(location, ModifierFlags.Async)) { + if (location.asteriskToken || hasSyntacticModifier(location, ModifierFlags.Async)) { return true; } return !getImmediatelyInvokedFunctionExpression(location); @@ -3725,8 +3726,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.PropertyAccessExpression: return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined; case SyntaxKind.ExpressionWithTypeArguments: - if (isEntityNameExpression((node as ExpressionWithTypeArguments).expression)) { - return (node as ExpressionWithTypeArguments).expression as EntityNameExpression; + if (isEntityNameExpression(node.expression)) { + return node.expression; } // falls through default: @@ -3916,13 +3917,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getAnyImportSyntax(node: Node): AnyImportSyntax | undefined { switch (node.kind) { case SyntaxKind.ImportEqualsDeclaration: - return node as ImportEqualsDeclaration; + return node; case SyntaxKind.ImportClause: - return (node as ImportClause).parent; + return node.parent; case SyntaxKind.NamespaceImport: - return (node as NamespaceImport).parent.parent; + return node.parent.parent; case SyntaxKind.ImportSpecifier: - return (node as ImportSpecifier).parent.parent.parent; + return node.parent.parent.parent; default: return undefined; } @@ -3950,12 +3951,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isAliasSymbolDeclaration(node: Node): boolean { return node.kind === SyntaxKind.ImportEqualsDeclaration || node.kind === SyntaxKind.NamespaceExportDeclaration - || node.kind === SyntaxKind.ImportClause && !!(node as ImportClause).name + || node.kind === SyntaxKind.ImportClause && !!node.name || node.kind === SyntaxKind.NamespaceImport || node.kind === SyntaxKind.NamespaceExport || node.kind === SyntaxKind.ImportSpecifier || node.kind === SyntaxKind.ExportSpecifier - || node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node as ExportAssignment) + || node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) || isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports && exportAssignmentIsAlias(node) || isAccessExpression(node) && isBinaryExpression(node.parent) @@ -3963,7 +3964,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { && node.parent.operatorToken.kind === SyntaxKind.EqualsToken && isAliasableOrJsExpression(node.parent.right) || node.kind === SyntaxKind.ShorthandPropertyAssignment - || node.kind === SyntaxKind.PropertyAssignment && isAliasableOrJsExpression((node as PropertyAssignment).initializer) + || node.kind === SyntaxKind.PropertyAssignment && isAliasableOrJsExpression(node.initializer) || node.kind === SyntaxKind.VariableDeclaration && isVariableDeclarationInitializedToBareOrAccessedRequire(node) || node.kind === SyntaxKind.BindingElement && isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); } @@ -4447,27 +4448,27 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { switch (node.kind) { case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.VariableDeclaration: - return getTargetOfImportEqualsDeclaration(node as ImportEqualsDeclaration | VariableDeclaration, dontRecursivelyResolve); + return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve); case SyntaxKind.ImportClause: - return getTargetOfImportClause(node as ImportClause, dontRecursivelyResolve); + return getTargetOfImportClause(node, dontRecursivelyResolve); case SyntaxKind.NamespaceImport: - return getTargetOfNamespaceImport(node as NamespaceImport, dontRecursivelyResolve); + return getTargetOfNamespaceImport(node, dontRecursivelyResolve); case SyntaxKind.NamespaceExport: - return getTargetOfNamespaceExport(node as NamespaceExport, dontRecursivelyResolve); + return getTargetOfNamespaceExport(node, dontRecursivelyResolve); case SyntaxKind.ImportSpecifier: case SyntaxKind.BindingElement: - return getTargetOfImportSpecifier(node as ImportSpecifier | BindingElement, dontRecursivelyResolve); + return getTargetOfImportSpecifier(node, dontRecursivelyResolve); case SyntaxKind.ExportSpecifier: - return getTargetOfExportSpecifier(node as ExportSpecifier, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, dontRecursivelyResolve); + return getTargetOfExportSpecifier(node, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, dontRecursivelyResolve); case SyntaxKind.ExportAssignment: case SyntaxKind.BinaryExpression: - return getTargetOfExportAssignment(node as ExportAssignment | BinaryExpression, dontRecursivelyResolve); + return getTargetOfExportAssignment(node, dontRecursivelyResolve); case SyntaxKind.NamespaceExportDeclaration: - return getTargetOfNamespaceExportDeclaration(node as NamespaceExportDeclaration, dontRecursivelyResolve); + return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve); case SyntaxKind.ShorthandPropertyAssignment: - return resolveEntityName((node as ShorthandPropertyAssignment).name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, /*ignoreErrors*/ true, dontRecursivelyResolve); + return resolveEntityName(node.name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, /*ignoreErrors*/ true, dontRecursivelyResolve); case SyntaxKind.PropertyAssignment: - return getTargetOfAliasLikeExpression((node as PropertyAssignment).initializer, dontRecursivelyResolve); + return getTargetOfAliasLikeExpression(node.initializer, dontRecursivelyResolve); case SyntaxKind.ElementAccessExpression: case SyntaxKind.PropertyAccessExpression: return getTargetOfAccessExpression(node as AccessExpression, dontRecursivelyResolve); @@ -5693,8 +5694,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function findConstructorDeclaration(node: ClassLikeDeclaration): ConstructorDeclaration | undefined { const members = node.members; for (const member of members) { - if (member.kind === SyntaxKind.Constructor && nodeIsPresent((member as ConstructorDeclaration).body)) { - return member as ConstructorDeclaration; + if (member.kind === SyntaxKind.Constructor && nodeIsPresent(member.body)) { + return member; } } } @@ -5829,7 +5830,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } switch (location.kind) { case SyntaxKind.SourceFile: - if (!isExternalOrCommonJsModule(location as SourceFile)) { + if (!isExternalOrCommonJsModule(location)) { break; } // falls through @@ -6160,11 +6161,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function hasExternalModuleSymbol(declaration: Node) { - return isAmbientModule(declaration) || (declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration as SourceFile)); + return isAmbientModule(declaration) || (declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration)); } function hasNonGlobalAugmentationExternalModuleSymbol(declaration: Node) { - return isModuleWithStringLiteralName(declaration) || (declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration as SourceFile)); + return isModuleWithStringLiteralName(declaration) || (declaration.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(declaration)); } function hasVisibleDeclarations(symbol: Symbol, shouldComputeAliasToMakeVisible: boolean): SymbolVisibilityResult | undefined { @@ -9498,7 +9499,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (node.parent?.parent?.kind === SyntaxKind.VariableDeclaration) { // const { SomeClass } = require('./lib'); const specifier = getSpecifierForModuleSymbol(target.parent || target, context); // './lib' - const { propertyName } = node as BindingElement; + const { propertyName } = node; addResult( factory.createImportDeclaration( /*modifiers*/ undefined, @@ -9532,9 +9533,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { break; case SyntaxKind.VariableDeclaration: // commonjs require: const x = require('y') - if (isPropertyAccessExpression((node as VariableDeclaration).initializer!)) { + if (isPropertyAccessExpression(node.initializer!)) { // const x = require('y').z - const initializer = (node as VariableDeclaration).initializer! as PropertyAccessExpression; // require('y').z + const initializer = node.initializer; // require('y').z const uniqueName = factory.createUniqueName(localName); // _x const specifier = getSpecifierForModuleSymbol(target.parent || target, context); // 'y' // import _x = require('y'); @@ -9586,17 +9587,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // export as namespace foo // TODO: Not part of a file's local or export symbol tables // Is bound into file.symbol.globalExports instead, which we don't currently traverse - addResult(factory.createNamespaceExportDeclaration(idText((node as NamespaceExportDeclaration).name)), ModifierFlags.None); + addResult(factory.createNamespaceExportDeclaration(idText(node.name)), ModifierFlags.None); break; case SyntaxKind.ImportClause: { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); // generate specifier (even though we're reusing and existing one) for ambient module reference include side effects - const specifier = bundled ? factory.createStringLiteral(generatedSpecifier) : (node as ImportClause).parent.moduleSpecifier; + const specifier = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.moduleSpecifier; addResult( factory.createImportDeclaration( /*modifiers*/ undefined, factory.createImportClause(/*isTypeOnly*/ false, factory.createIdentifier(localName), /*namedBindings*/ undefined), specifier, - (node as ImportClause).parent.attributes, + node.parent.attributes, ), ModifierFlags.None, ); @@ -9604,7 +9605,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } case SyntaxKind.NamespaceImport: { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); // generate specifier (even though we're reusing and existing one) for ambient module reference include side effects - const specifier = bundled ? factory.createStringLiteral(generatedSpecifier) : (node as NamespaceImport).parent.parent.moduleSpecifier; + const specifier = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.moduleSpecifier; addResult( factory.createImportDeclaration( /*modifiers*/ undefined, @@ -9629,7 +9630,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { break; case SyntaxKind.ImportSpecifier: { const generatedSpecifier = getSpecifierForModuleSymbol(target.parent || target, context); // generate specifier (even though we're reusing and existing one) for ambient module reference include side effects - const specifier = bundled ? factory.createStringLiteral(generatedSpecifier) : (node as ImportSpecifier).parent.parent.parent.moduleSpecifier; + const specifier = bundled ? factory.createStringLiteral(generatedSpecifier) : node.parent.parent.parent.moduleSpecifier; addResult( factory.createImportDeclaration( /*modifiers*/ undefined, @@ -9645,7 +9646,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { ]), ), specifier, - (node as ImportSpecifier).parent.parent.parent.attributes, + node.parent.parent.parent.attributes, ), ModifierFlags.None, ); @@ -9654,7 +9655,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.ExportSpecifier: // does not use localName because the symbol name in this case refers to the name in the exports table, // which we must exactly preserve - const specifier = (node.parent.parent as ExportDeclaration).moduleSpecifier; + const specifier = node.parent.parent.moduleSpecifier; // targetName is only used when the target is local, as otherwise the target is an alias that points at // another file serializeExportSpecifier( @@ -9891,7 +9892,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (p.flags & SymbolFlags.SetAccessor) { const setter = p.declarations && forEach(p.declarations, d => { if (d.kind === SyntaxKind.SetAccessor) { - return d as SetAccessorDeclaration; + return d; } if (isCallExpression(d) && isBindableObjectDefinePropertyCall(d)) { return forEach(d.arguments[2].properties, propDecl => { @@ -10298,7 +10299,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway } if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { - return declarationNameToString((declaration.parent as VariableDeclaration).name); + return declarationNameToString(declaration.parent.name); } switch (declaration.kind) { case SyntaxKind.ClassExpression: @@ -10314,7 +10315,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return name !== undefined ? name : symbolName(symbol); } - function isDeclarationVisible(node: Node): boolean { + function isDeclarationVisible(node: NodeBase): boolean { if (node) { const links = getNodeLinks(node); if (links.isVisible === undefined) { @@ -10429,7 +10430,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { exportSymbol = resolveName(node, node.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false); } else if (node.parent.kind === SyntaxKind.ExportSpecifier) { - exportSymbol = getTargetOfExportSpecifier(node.parent as ExportSpecifier, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); + exportSymbol = getTargetOfExportSpecifier(node.parent, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); } let result: Node[] | undefined; let visited: Set | undefined; @@ -10718,10 +10719,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getDestructuringPropertyName(node: BindingElement | PropertyAssignment | ShorthandPropertyAssignment | Expression) { const parent = node.parent; if (node.kind === SyntaxKind.BindingElement && parent.kind === SyntaxKind.ObjectBindingPattern) { - return getLiteralPropertyNameText((node as BindingElement).propertyName || (node as BindingElement).name as Identifier); + return getLiteralPropertyNameText(node.propertyName || node.name as Identifier); } if (node.kind === SyntaxKind.PropertyAssignment || node.kind === SyntaxKind.ShorthandPropertyAssignment) { - return getLiteralPropertyNameText((node as PropertyAssignment | ShorthandPropertyAssignment).name); + return getLiteralPropertyNameText(node.name); } return "" + ((parent as BindingPattern | ArrayLiteralExpression).elements as NodeArray).indexOf(node); } @@ -10823,12 +10824,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isNullOrUndefined(node: Expression) { const expr = skipParentheses(node, /*excludeJSDocTypeAssertions*/ true); - return expr.kind === SyntaxKind.NullKeyword || expr.kind === SyntaxKind.Identifier && getResolvedSymbol(expr as Identifier) === undefinedSymbol; + return expr.kind === SyntaxKind.NullKeyword || expr.kind === SyntaxKind.Identifier && getResolvedSymbol(expr) === undefinedSymbol; } function isEmptyArrayLiteral(node: Expression) { const expr = skipParentheses(node, /*excludeJSDocTypeAssertions*/ true); - return expr.kind === SyntaxKind.ArrayLiteralExpression && (expr as ArrayLiteralExpression).elements.length === 0; + return expr.kind === SyntaxKind.ArrayLiteralExpression && expr.elements.length === 0; } function addOptionality(type: Type, isProperty = false, isOptional = true): Type { @@ -10981,7 +10982,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && every(symbol.declarations, declaration => isBinaryExpression(declaration) && isPossiblyAliasedThisProperty(declaration) && - (declaration.left.kind !== SyntaxKind.ElementAccessExpression || isStringOrNumericLiteralLike((declaration.left as ElementAccessExpression).argumentExpression)) && + (declaration.left.kind !== SyntaxKind.ElementAccessExpression || isStringOrNumericLiteralLike(declaration.left.argumentExpression)) && !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration)); } return links.isConstructorDeclaredProperty; @@ -11565,7 +11566,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } let type: Type; if (declaration.kind === SyntaxKind.ExportAssignment) { - type = widenTypeForVariableLikeDeclaration(tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionCached((declaration as ExportAssignment).expression), declaration); + type = widenTypeForVariableLikeDeclaration(tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionCached(declaration.expression), declaration); } else if ( isBinaryExpression(declaration) || @@ -12010,10 +12011,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.ConditionalType: { const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); if (node.kind === SyntaxKind.MappedType) { - return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration((node as MappedTypeNode).typeParameter))); + return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))); } else if (node.kind === SyntaxKind.ConditionalType) { - return concatenate(outerTypeParameters, getInferTypeParameters(node as ConditionalTypeNode)); + return concatenate(outerTypeParameters, getInferTypeParameters(node)); } const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node as DeclarationWithTypeParameters)); const thisType = includeThisTypes && @@ -12022,15 +12023,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return thisType ? append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } case SyntaxKind.JSDocParameterTag: - const paramSymbol = getParameterSymbolFromJSDoc(node as JSDocParameterTag); + const paramSymbol = getParameterSymbolFromJSDoc(node); if (paramSymbol) { node = paramSymbol.valueDeclaration!; } break; case SyntaxKind.JSDoc: { const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - return (node as JSDoc).tags - ? appendTypeParameters(outerTypeParameters, flatMap((node as JSDoc).tags, t => isJSDocTemplateTag(t) ? t.typeParameters : undefined)) + return node.tags + ? appendTypeParameters(outerTypeParameters, flatMap(node.tags, t => isJSDocTemplateTag(t) ? t.typeParameters : undefined)) : outerTypeParameters; } } @@ -12048,7 +12049,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (decl.kind !== SyntaxKind.VariableDeclaration) { return false; } - const initializer = (decl as VariableDeclaration).initializer; + const initializer = decl.initializer; return !!initializer && (initializer.kind === SyntaxKind.FunctionExpression || initializer.kind === SyntaxKind.ArrowFunction); })!; Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); @@ -12328,8 +12329,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; if (type.symbol.declarations) { for (const declaration of type.symbol.declarations) { - if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(declaration as InterfaceDeclaration)) { - for (const node of getInterfaceBaseTypeNodes(declaration as InterfaceDeclaration)!) { + if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(declaration)) { + for (const node of getInterfaceBaseTypeNodes(declaration)!) { const baseType = getReducedType(getTypeFromTypeNode(node)); if (!isErrorType(baseType)) { if (isValidBaseType(baseType)) { @@ -12371,7 +12372,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (declaration.flags & NodeFlags.ContainsThis) { return false; } - const baseTypeNodes = getInterfaceBaseTypeNodes(declaration as InterfaceDeclaration); + const baseTypeNodes = getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { for (const node of baseTypeNodes) { if (isEntityNameExpression(node.expression)) { @@ -12473,7 +12474,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (symbol.declarations) { for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.EnumDeclaration) { - for (const member of (declaration as EnumDeclaration).members) { + for (const member of declaration.members) { if (hasBindableName(member)) { const memberSymbol = getSymbolOfDeclaration(member); const value = getEnumMemberValue(member); @@ -12579,9 +12580,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.LiteralType: return true; case SyntaxKind.ArrayType: - return isThislessType((node as ArrayTypeNode).elementType); + return isThislessType(node.elementType); case SyntaxKind.TypeReference: - return !(node as TypeReferenceNode).typeArguments || (node as TypeReferenceNode).typeArguments!.every(isThislessType); + return !node.typeArguments || node.typeArguments.every(isThislessType); } return false; } @@ -12718,7 +12719,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { /** * Indicates whether a declaration has a late-bindable dynamic name. */ - function hasLateBindableName(node: Declaration): node is LateBoundDeclaration | LateBoundBinaryExpressionDeclaration { + function hasLateBindableName(node: Declaration): node is LateBoundDeclaration | LateBoundBinaryExpressionDeclarationBase { const name = getNameOfDeclaration(node); return !!name && isLateBindableName(name); } @@ -12787,7 +12788,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { * @param lateSymbols The late-bound symbols of the parent. * @param decl The member to bind. */ - function lateBindMember(parent: Symbol, earlySymbols: SymbolTable | undefined, lateSymbols: Map<__String, TransientSymbol>, decl: LateBoundDeclaration | LateBoundBinaryExpressionDeclaration) { + function lateBindMember(parent: Symbol, earlySymbols: SymbolTable | undefined, lateSymbols: Map<__String, TransientSymbol>, decl: LateBoundDeclaration | LateBoundBinaryExpressionDeclarationBase) { Debug.assert(!!decl.symbol, "The member is expected to have a symbol."); const links = getNodeLinks(decl); if (!links.resolvedSymbol) { @@ -13778,7 +13779,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isMappedTypeWithKeyofConstraintDeclaration(type: MappedType) { const constraintDeclaration = getConstraintDeclarationForMappedType(type)!; // TODO: GH#18217 return constraintDeclaration.kind === SyntaxKind.TypeOperator && - (constraintDeclaration as TypeOperatorNode).operator === SyntaxKind.KeyOfKeyword; + constraintDeclaration.operator === SyntaxKind.KeyOfKeyword; } function getModifiersTypeFromMappedType(type: MappedType) { @@ -15097,7 +15098,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!node) return false; switch (node.kind) { case SyntaxKind.Identifier: - return (node as Identifier).escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node as Identifier) === argumentsSymbol; + return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; case SyntaxKind.PropertyDeclaration: case SyntaxKind.MethodDeclaration: @@ -15108,10 +15109,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: - return traverse((node as PropertyAccessExpression | ElementAccessExpression).expression); + return traverse(node.expression); case SyntaxKind.PropertyAssignment: - return traverse((node as PropertyAssignment).initializer); + return traverse(node.initializer); default: return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && !!forEachChild(node, traverse); @@ -15476,10 +15477,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // present, we form an intersection of the inferred constraint types. const [childTypeParameter = declaration.parent, grandParent] = walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent); if (grandParent.kind === SyntaxKind.TypeReference && !omitTypeReferences) { - const typeReference = grandParent as TypeReferenceNode; + const typeReference = grandParent; const typeParameters = getTypeParametersForTypeReferenceOrImport(typeReference); if (typeParameters) { - const index = typeReference.typeArguments!.indexOf(childTypeParameter as TypeNode); + const index = typeReference.typeArguments!.indexOf(childTypeParameter); if (index < typeParameters.length) { const declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]); if (declaredConstraint) { @@ -15506,9 +15507,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type // or a named rest tuple element, we infer an 'unknown[]' constraint. else if ( - grandParent.kind === SyntaxKind.Parameter && (grandParent as ParameterDeclaration).dotDotDotToken || + grandParent.kind === SyntaxKind.Parameter && grandParent.dotDotDotToken || grandParent.kind === SyntaxKind.RestType || - grandParent.kind === SyntaxKind.NamedTupleMember && (grandParent as NamedTupleMember).dotDotDotToken + grandParent.kind === SyntaxKind.NamedTupleMember && grandParent.dotDotDotToken ) { inferences = append(inferences, createArrayType(unknownType)); } @@ -15526,12 +15527,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // clause of a conditional whose check type is also a mapped type, give it a constraint equal to the template // of the check type's mapped type else if ( - grandParent.kind === SyntaxKind.MappedType && (grandParent as MappedTypeNode).type && - skipParentheses((grandParent as MappedTypeNode).type!) === declaration.parent && grandParent.parent.kind === SyntaxKind.ConditionalType && - (grandParent.parent as ConditionalTypeNode).extendsType === grandParent && (grandParent.parent as ConditionalTypeNode).checkType.kind === SyntaxKind.MappedType && - ((grandParent.parent as ConditionalTypeNode).checkType as MappedTypeNode).type + grandParent.kind === SyntaxKind.MappedType && grandParent.type && + skipParentheses(grandParent.type) === declaration.parent && grandParent.parent.kind === SyntaxKind.ConditionalType && + grandParent.parent.extendsType === grandParent && grandParent.parent.checkType.kind === SyntaxKind.MappedType && + grandParent.parent.checkType.type ) { - const checkMappedType = (grandParent.parent as ConditionalTypeNode).checkType as MappedTypeNode; + const checkMappedType = grandParent.parent.checkType; const nodeType = getTypeFromTypeNode(checkMappedType.type!); inferences = append(inferences, instantiateType(nodeType, makeUnaryTypeMapper(getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(checkMappedType.typeParameter)), checkMappedType.typeParameter.constraint ? getTypeFromTypeNode(checkMappedType.typeParameter.constraint) : keyofConstraintType))); } @@ -15716,8 +15717,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return errorType; } } - if (node.kind === SyntaxKind.TypeReference && isDeferredTypeReferenceNode(node as TypeReferenceNode, length(node.typeArguments) !== typeParameters.length)) { - return createDeferredTypeReference(type as GenericType, node as TypeReferenceNode, /*mapper*/ undefined); + if (node.kind === SyntaxKind.TypeReference && isDeferredTypeReferenceNode(node, length(node.typeArguments) !== typeParameters.length)) { + return createDeferredTypeReference(type as GenericType, node, /*mapper*/ undefined); } // In a type reference, the outer type parameters of the referenced class or interface are automatically // supplied as type arguments and the type reference only specifies arguments for the local type parameters @@ -15902,7 +15903,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const valueType = getTypeOfSymbol(symbol); let typeType = valueType; if (symbol.valueDeclaration) { - const isImportTypeWithQualifier = node.kind === SyntaxKind.ImportType && (node as ImportTypeNode).qualifier; + const isImportTypeWithQualifier = node.kind === SyntaxKind.ImportType && node.qualifier; // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL} if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) { typeType = getTypeReferenceType(node, valueType.symbol); @@ -15934,7 +15935,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function isUnaryTupleTypeNode(node: TypeNode) { - return node.kind === SyntaxKind.TupleType && (node as TupleTypeNode).elements.length === 1; + return node.kind === SyntaxKind.TupleType && node.elements.length === 1; } function getImpliedConstraint(type: Type, checkNode: TypeNode, extendsNode: TypeNode): Type | undefined { @@ -16368,10 +16369,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.OptionalType: return ElementFlags.Optional; case SyntaxKind.RestType: - return getRestTypeElementFlags(node as RestTypeNode); + return getRestTypeElementFlags(node); case SyntaxKind.NamedTupleMember: - return (node as NamedTupleMember).questionToken ? ElementFlags.Optional : - (node as NamedTupleMember).dotDotDotToken ? getRestTypeElementFlags(node as NamedTupleMember) : + return node.questionToken ? ElementFlags.Optional : + node.dotDotDotToken ? getRestTypeElementFlags(node) : ElementFlags.Required; default: return ElementFlags.Required; @@ -16438,7 +16439,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.TypeQuery: return true; case SyntaxKind.TypeOperator: - return (node as TypeOperatorNode).operator !== SyntaxKind.UniqueKeyword && mayResolveTypeAlias((node as TypeOperatorNode).type); + return node.operator !== SyntaxKind.UniqueKeyword && mayResolveTypeAlias(node.type); case SyntaxKind.ParenthesizedType: case SyntaxKind.OptionalType: case SyntaxKind.NamedTupleMember: @@ -16448,15 +16449,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.JSDocTypeExpression: return mayResolveTypeAlias((node as ParenthesizedTypeNode | OptionalTypeNode | JSDocTypeReferencingNode | NamedTupleMember).type); case SyntaxKind.RestType: - return (node as RestTypeNode).type.kind !== SyntaxKind.ArrayType || mayResolveTypeAlias(((node as RestTypeNode).type as ArrayTypeNode).elementType); + return node.type.kind !== SyntaxKind.ArrayType || mayResolveTypeAlias(node.type.elementType); case SyntaxKind.UnionType: case SyntaxKind.IntersectionType: return some((node as UnionOrIntersectionTypeNode).types, mayResolveTypeAlias); case SyntaxKind.IndexedAccessType: - return mayResolveTypeAlias((node as IndexedAccessTypeNode).objectType) || mayResolveTypeAlias((node as IndexedAccessTypeNode).indexType); + return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType); case SyntaxKind.ConditionalType: - return mayResolveTypeAlias((node as ConditionalTypeNode).checkType) || mayResolveTypeAlias((node as ConditionalTypeNode).extendsType) || - mayResolveTypeAlias((node as ConditionalTypeNode).trueType) || mayResolveTypeAlias((node as ConditionalTypeNode).falseType); + return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) || + mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType); } return false; } @@ -18884,7 +18885,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { !isStatic(container) && (!isConstructorDeclaration(container) || isNodeDescendantOf(node, container.body)) ) { - return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(parent as ClassLikeDeclaration | InterfaceDeclaration)).thisType!; + return getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(parent)).thisType!; } } @@ -18921,17 +18922,17 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getArrayElementTypeNode(node: TypeNode): TypeNode | undefined { switch (node.kind) { case SyntaxKind.ParenthesizedType: - return getArrayElementTypeNode((node as ParenthesizedTypeNode).type); + return getArrayElementTypeNode(node.type); case SyntaxKind.TupleType: - if ((node as TupleTypeNode).elements.length === 1) { - node = (node as TupleTypeNode).elements[0]; - if (node.kind === SyntaxKind.RestType || node.kind === SyntaxKind.NamedTupleMember && (node as NamedTupleMember).dotDotDotToken) { - return getArrayElementTypeNode((node as RestTypeNode | NamedTupleMember).type); + if (node.elements.length === 1) { + node = node.elements[0]; + if (node.kind === SyntaxKind.RestType || node.kind === SyntaxKind.NamedTupleMember && node.dotDotDotToken) { + return getArrayElementTypeNode(node.type); } } break; case SyntaxKind.ArrayType: - return (node as ArrayTypeNode).elementType; + return node.elementType; } return undefined; } @@ -18982,38 +18983,38 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // TODO(rbuckton): `ThisKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service and because of `isPartOfTypeNode`. return getTypeFromThisTypeNode(node as ThisExpression | ThisTypeNode); case SyntaxKind.LiteralType: - return getTypeFromLiteralTypeNode(node as LiteralTypeNode); + return getTypeFromLiteralTypeNode(node); case SyntaxKind.TypeReference: - return getTypeFromTypeReference(node as TypeReferenceNode); + return getTypeFromTypeReference(node); case SyntaxKind.TypePredicate: - return (node as TypePredicateNode).assertsModifier ? voidType : booleanType; + return node.assertsModifier ? voidType : booleanType; case SyntaxKind.ExpressionWithTypeArguments: return getTypeFromTypeReference(node as ExpressionWithTypeArguments); case SyntaxKind.TypeQuery: - return getTypeFromTypeQueryNode(node as TypeQueryNode); + return getTypeFromTypeQueryNode(node); case SyntaxKind.ArrayType: case SyntaxKind.TupleType: - return getTypeFromArrayOrTupleTypeNode(node as ArrayTypeNode | TupleTypeNode); + return getTypeFromArrayOrTupleTypeNode(node); case SyntaxKind.OptionalType: - return getTypeFromOptionalTypeNode(node as OptionalTypeNode); + return getTypeFromOptionalTypeNode(node); case SyntaxKind.UnionType: - return getTypeFromUnionTypeNode(node as UnionTypeNode); + return getTypeFromUnionTypeNode(node); case SyntaxKind.IntersectionType: - return getTypeFromIntersectionTypeNode(node as IntersectionTypeNode); + return getTypeFromIntersectionTypeNode(node); case SyntaxKind.JSDocNullableType: - return getTypeFromJSDocNullableTypeNode(node as JSDocNullableType); + return getTypeFromJSDocNullableTypeNode(node); case SyntaxKind.JSDocOptionalType: - return addOptionality(getTypeFromTypeNode((node as JSDocOptionalType).type)); + return addOptionality(getTypeFromTypeNode(node.type)); case SyntaxKind.NamedTupleMember: - return getTypeFromNamedTupleTypeNode(node as NamedTupleMember); + return getTypeFromNamedTupleTypeNode(node); case SyntaxKind.ParenthesizedType: case SyntaxKind.JSDocNonNullableType: case SyntaxKind.JSDocTypeExpression: return getTypeFromTypeNode((node as ParenthesizedTypeNode | JSDocTypeReferencingNode | JSDocTypeExpression | NamedTupleMember).type); case SyntaxKind.RestType: - return getTypeFromRestTypeNode(node as RestTypeNode); + return getTypeFromRestTypeNode(node); case SyntaxKind.JSDocVariadicType: - return getTypeFromJSDocVariadicType(node as JSDocVariadicType); + return getTypeFromJSDocVariadicType(node); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.TypeLiteral: @@ -19022,19 +19023,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.JSDocSignature: return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node as TypeLiteralNode | FunctionOrConstructorTypeNode | JSDocTypeLiteral | JSDocFunctionType | JSDocSignature); case SyntaxKind.TypeOperator: - return getTypeFromTypeOperatorNode(node as TypeOperatorNode); + return getTypeFromTypeOperatorNode(node); case SyntaxKind.IndexedAccessType: - return getTypeFromIndexedAccessTypeNode(node as IndexedAccessTypeNode); + return getTypeFromIndexedAccessTypeNode(node); case SyntaxKind.MappedType: - return getTypeFromMappedTypeNode(node as MappedTypeNode); + return getTypeFromMappedTypeNode(node); case SyntaxKind.ConditionalType: - return getTypeFromConditionalTypeNode(node as ConditionalTypeNode); + return getTypeFromConditionalTypeNode(node); case SyntaxKind.InferType: - return getTypeFromInferTypeNode(node as InferTypeNode); + return getTypeFromInferTypeNode(node); case SyntaxKind.TemplateLiteralType: - return getTypeFromTemplateTypeNode(node as TemplateLiteralTypeNode); + return getTypeFromTemplateTypeNode(node); case SyntaxKind.ImportType: - return getTypeFromImportTypeNode(node as ImportTypeNode); + return getTypeFromImportTypeNode(node); // This function assumes that an identifier, qualified name, or property access expression is a type expression // Callers should first ensure this by calling `isPartOfTypeNode` // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. @@ -19321,7 +19322,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) { const container = tp.symbol.declarations[0].parent; for (let n = node; n !== container; n = n.parent) { - if (!n || n.kind === SyntaxKind.Block || n.kind === SyntaxKind.ConditionalType && forEachChild((n as ConditionalTypeNode).extendsType, containsReference)) { + if (!n || n.kind === SyntaxKind.Block || n.kind === SyntaxKind.ConditionalType && forEachChild(n.extendsType, containsReference)) { return true; } } @@ -19336,7 +19337,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return !tp.isThisType && isPartOfTypeNode(node) && maybeTypeParameterReference(node) && getTypeFromTypeNodeWorker(node as TypeNode) === tp; // use worker because we're looking for === equality case SyntaxKind.TypeQuery: - const entityName = (node as TypeQueryNode).exprName; + const entityName = node.exprName; const firstIdentifier = getFirstIdentifier(entityName); if (!isThisIdentifier(firstIdentifier)) { // Don't attempt to analyze typeof this.xxx const firstIdentifierSymbol = getResolvedSymbol(firstIdentifier); @@ -19346,7 +19347,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { undefined; // Type parameter's declaration was unrecognized, e.g. comes from JSDoc annotation. if (firstIdentifierSymbol.declarations && tpScope) { return some(firstIdentifierSymbol.declarations, idDecl => isNodeDescendantOf(idDecl, tpScope)) || - some((node as TypeQueryNode).typeArguments, containsReference); + some(node.typeArguments, containsReference); } } return true; @@ -19667,32 +19668,33 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: case SyntaxKind.MethodDeclaration: - case SyntaxKind.FunctionDeclaration: // Function declarations can have context when annotated with a jsdoc @type - return isContextSensitiveFunctionLikeDeclaration(node as FunctionExpression | ArrowFunction | MethodDeclaration); + // @ts-expect-error -- Function declarations can have context when annotated with a jsdoc @type + case SyntaxKind.FunctionDeclaration: + return isContextSensitiveFunctionLikeDeclaration(node); case SyntaxKind.ObjectLiteralExpression: - return some((node as ObjectLiteralExpression).properties, isContextSensitive); + return some(node.properties, isContextSensitive); case SyntaxKind.ArrayLiteralExpression: - return some((node as ArrayLiteralExpression).elements, isContextSensitive); + return some(node.elements, isContextSensitive); case SyntaxKind.ConditionalExpression: - return isContextSensitive((node as ConditionalExpression).whenTrue) || - isContextSensitive((node as ConditionalExpression).whenFalse); + return isContextSensitive(node.whenTrue) || + isContextSensitive(node.whenFalse); case SyntaxKind.BinaryExpression: - return ((node as BinaryExpression).operatorToken.kind === SyntaxKind.BarBarToken || (node as BinaryExpression).operatorToken.kind === SyntaxKind.QuestionQuestionToken) && - (isContextSensitive((node as BinaryExpression).left) || isContextSensitive((node as BinaryExpression).right)); + return (node.operatorToken.kind === SyntaxKind.BarBarToken || node.operatorToken.kind === SyntaxKind.QuestionQuestionToken) && + (isContextSensitive(node.left) || isContextSensitive(node.right)); case SyntaxKind.PropertyAssignment: - return isContextSensitive((node as PropertyAssignment).initializer); + return isContextSensitive(node.initializer); case SyntaxKind.ParenthesizedExpression: - return isContextSensitive((node as ParenthesizedExpression).expression); + return isContextSensitive(node.expression); case SyntaxKind.JsxAttributes: - return some((node as JsxAttributes).properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive); + return some(node.properties, isContextSensitive) || isJsxOpeningElement(node.parent) && some(node.parent.parent.children, isContextSensitive); case SyntaxKind.JsxAttribute: { // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive. - const { initializer } = node as JsxAttribute; + const { initializer } = node; return !!initializer && isContextSensitive(initializer); } case SyntaxKind.JsxExpression: { // It is possible to that node.expression is undefined (e.g
) - const { expression } = node as JsxExpression; + const { expression } = node; return !!expression && isContextSensitive(expression); } } @@ -19711,7 +19713,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (node.body.kind !== SyntaxKind.Block) { return isContextSensitive(node.body); } - return !!forEachReturnStatement(node.body as Block, statement => !!statement.expression && isContextSensitive(statement.expression)); + return !!forEachReturnStatement(node.body, statement => !!statement.expression && isContextSensitive(statement.expression)); } function isContextSensitiveFunctionOrObjectLiteralMethod(func: Node): func is FunctionExpression | ArrowFunction | MethodDeclaration { @@ -19864,22 +19866,22 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // fallthrough case SyntaxKind.JsxExpression: case SyntaxKind.ParenthesizedExpression: - return elaborateError((node as AsExpression | ParenthesizedExpression | JsxExpression).expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); + return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); case SyntaxKind.BinaryExpression: - switch ((node as BinaryExpression).operatorToken.kind) { + switch (node.operatorToken.kind) { case SyntaxKind.EqualsToken: case SyntaxKind.CommaToken: - return elaborateError((node as BinaryExpression).right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); + return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); } break; case SyntaxKind.ObjectLiteralExpression: - return elaborateObjectLiteral(node as ObjectLiteralExpression, source, target, relation, containingMessageChain, errorOutputContainer); + return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); case SyntaxKind.ArrayLiteralExpression: - return elaborateArrayLiteral(node as ArrayLiteralExpression, source, target, relation, containingMessageChain, errorOutputContainer); + return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer); case SyntaxKind.JsxAttributes: - return elaborateJsxComponents(node as JsxAttributes, source, target, relation, containingMessageChain, errorOutputContainer); + return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer); case SyntaxKind.ArrowFunction: - return elaborateArrowFunction(node as ArrowFunction, source, target, relation, containingMessageChain, errorOutputContainer); + return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer); } return false; } @@ -24447,7 +24449,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { diagnostic = noImplicitAny ? Diagnostics.Member_0_implicitly_has_an_1_type : Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; case SyntaxKind.Parameter: - const param = declaration as ParameterDeclaration; + const param = declaration; if (isIdentifier(param.name)) { const originalKeywordKind = identifierToKeywordKind(param.name); if ( @@ -24462,7 +24464,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return; } } - diagnostic = (declaration as ParameterDeclaration).dotDotDotToken ? + diagnostic = declaration.dotDotDotToken ? noImplicitAny ? Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? Diagnostics.Parameter_0_implicitly_has_an_1_type : Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage; break; @@ -24632,7 +24634,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (context.intraExpressionInferenceSites) { for (const { node, type } of context.intraExpressionInferenceSites) { const contextualType = node.kind === SyntaxKind.MethodDeclaration ? - getContextualTypeForObjectLiteralMethod(node as MethodDeclaration, ContextFlags.NoConstraints) : + getContextualTypeForObjectLiteralMethod(node, ContextFlags.NoConstraints) : getContextualType(node, ContextFlags.NoConstraints); if (contextualType) { inferTypes(context.inferences, type, contextualType); @@ -26014,7 +26016,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { switch (node.kind) { case SyntaxKind.Identifier: if (!isThisInTypeQuery(node)) { - const symbol = getResolvedSymbol(node as Identifier); + const symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? `${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}|${getSymbolId(symbol)}` : undefined; } // falls through @@ -26022,10 +26024,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return `0|${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}`; case SyntaxKind.NonNullExpression: case SyntaxKind.ParenthesizedExpression: - return getFlowCacheKey((node as NonNullExpression | ParenthesizedExpression).expression, declaredType, initialType, flowContainer); + return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer); case SyntaxKind.QualifiedName: - const left = getFlowCacheKey((node as QualifiedName).left, declaredType, initialType, flowContainer); - return left && left + "." + (node as QualifiedName).right.escapedText; + const left = getFlowCacheKey(node.left, declaredType, initialType, flowContainer); + return left && left + "." + node.right.escapedText; case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: const propName = getAccessedPropertyName(node as AccessExpression); @@ -26050,7 +26052,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { switch (target.kind) { case SyntaxKind.ParenthesizedExpression: case SyntaxKind.NonNullExpression: - return isMatchingReference(source, (target as NonNullExpression | ParenthesizedExpression).expression); + return isMatchingReference(source, target.expression); case SyntaxKind.BinaryExpression: return (isAssignmentExpression(target) && isMatchingReference(source, target.left)) || (isBinaryExpression(target) && target.operatorToken.kind === SyntaxKind.CommaToken && isMatchingReference(source, target.right)); @@ -26058,13 +26060,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { switch (source.kind) { case SyntaxKind.MetaProperty: return target.kind === SyntaxKind.MetaProperty - && (source as MetaProperty).keywordToken === (target as MetaProperty).keywordToken - && (source as MetaProperty).name.escapedText === (target as MetaProperty).name.escapedText; + && source.keywordToken === target.keywordToken + && source.name.escapedText === target.name.escapedText; case SyntaxKind.Identifier: case SyntaxKind.PrivateIdentifier: return isThisInTypeQuery(source) ? target.kind === SyntaxKind.ThisKeyword : - target.kind === SyntaxKind.Identifier && getResolvedSymbol(source as Identifier) === getResolvedSymbol(target as Identifier) || + target.kind === SyntaxKind.Identifier && getResolvedSymbol(source as Identifier) === getResolvedSymbol(target) || (isVariableDeclaration(target) || isBindingElement(target)) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source as Identifier)) === getSymbolOfDeclaration(target); case SyntaxKind.ThisKeyword: @@ -26073,7 +26075,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return target.kind === SyntaxKind.SuperKeyword; case SyntaxKind.NonNullExpression: case SyntaxKind.ParenthesizedExpression: - return isMatchingReference((source as NonNullExpression | ParenthesizedExpression).expression, target); + return isMatchingReference(source.expression, target); case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: const sourcePropertyName = getAccessedPropertyName(source as AccessExpression); @@ -26082,8 +26084,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isMatchingReference((source as AccessExpression).expression, (target as AccessExpression).expression); case SyntaxKind.QualifiedName: return isAccessExpression(target) && - (source as QualifiedName).right.escapedText === getAccessedPropertyName(target) && - isMatchingReference((source as QualifiedName).left, target.expression); + source.right.escapedText === getAccessedPropertyName(target) && + isMatchingReference(source.left, target.expression); case SyntaxKind.BinaryExpression: return (isBinaryExpression(source) && source.operatorToken.kind === SyntaxKind.CommaToken && isMatchingReference(source.right, target)); } @@ -26548,19 +26550,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.ForInStatement: return stringType; case SyntaxKind.ForOfStatement: - return checkRightHandSideOfForOf(parent as ForOfStatement) || errorType; + return checkRightHandSideOfForOf(parent) || errorType; case SyntaxKind.BinaryExpression: - return getAssignedTypeOfBinaryExpression(parent as BinaryExpression); + return getAssignedTypeOfBinaryExpression(parent); case SyntaxKind.DeleteExpression: return undefinedType; case SyntaxKind.ArrayLiteralExpression: - return getAssignedTypeOfArrayLiteralElement(parent as ArrayLiteralExpression, node); + return getAssignedTypeOfArrayLiteralElement(parent, node); case SyntaxKind.SpreadElement: - return getAssignedTypeOfSpreadExpression(parent as SpreadElement); + return getAssignedTypeOfSpreadExpression(parent); case SyntaxKind.PropertyAssignment: - return getAssignedTypeOfPropertyAssignment(parent as PropertyAssignment); + return getAssignedTypeOfPropertyAssignment(parent); case SyntaxKind.ShorthandPropertyAssignment: - return getAssignedTypeOfShorthandPropertyAssignment(parent as ShorthandPropertyAssignment); + return getAssignedTypeOfShorthandPropertyAssignment(parent); } return errorType; } @@ -26604,25 +26606,25 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function isEmptyArrayAssignment(node: VariableDeclaration | BindingElement | Expression) { - return node.kind === SyntaxKind.VariableDeclaration && (node as VariableDeclaration).initializer && - isEmptyArrayLiteral((node as VariableDeclaration).initializer!) || + return node.kind === SyntaxKind.VariableDeclaration && node.initializer && + isEmptyArrayLiteral(node.initializer) || node.kind !== SyntaxKind.BindingElement && node.parent.kind === SyntaxKind.BinaryExpression && - isEmptyArrayLiteral((node.parent as BinaryExpression).right); + isEmptyArrayLiteral(node.parent.right); } function getReferenceCandidate(node: Expression): Expression { switch (node.kind) { case SyntaxKind.ParenthesizedExpression: - return getReferenceCandidate((node as ParenthesizedExpression).expression); + return getReferenceCandidate(node.expression); case SyntaxKind.BinaryExpression: - switch ((node as BinaryExpression).operatorToken.kind) { + switch (node.operatorToken.kind) { case SyntaxKind.EqualsToken: case SyntaxKind.BarBarEqualsToken: case SyntaxKind.AmpersandAmpersandEqualsToken: case SyntaxKind.QuestionQuestionEqualsToken: - return getReferenceCandidate((node as BinaryExpression).left); + return getReferenceCandidate(node.left); case SyntaxKind.CommaToken: - return getReferenceCandidate((node as BinaryExpression).right); + return getReferenceCandidate(node.right); } } return node; @@ -26890,8 +26892,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const isElementAssignment = parent.kind === SyntaxKind.ElementAccessExpression && (parent as ElementAccessExpression).expression === root && parent.parent.kind === SyntaxKind.BinaryExpression && - (parent.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken && - (parent.parent as BinaryExpression).left === parent && + parent.parent.operatorToken.kind === SyntaxKind.EqualsToken && + parent.parent.left === parent && !isAssignmentTarget(parent.parent) && isTypeAssignableToKind(getTypeOfExpression((parent as ElementAccessExpression).argumentExpression), TypeFlags.NumberLike); return isLengthPushOrUnshift || isElementAssignment; @@ -26943,16 +26945,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!(node.flags & NodeFlags.InWithStatement)) { switch (node.kind) { case SyntaxKind.Identifier: - const symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node as Identifier)); + const symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node)); return getExplicitTypeOfSymbol(symbol, diagnostic); case SyntaxKind.ThisKeyword: return getExplicitThisType(node); case SyntaxKind.SuperKeyword: return checkSuperExpression(node); case SyntaxKind.PropertyAccessExpression: { - const type = getTypeOfDottedName((node as PropertyAccessExpression).expression, diagnostic); + const type = getTypeOfDottedName(node.expression, diagnostic); if (type) { - const name = (node as PropertyAccessExpression).name; + const name = node.name; let prop: Symbol | undefined; if (isPrivateIdentifier(name)) { if (!type.symbol) { @@ -26968,7 +26970,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return undefined; } case SyntaxKind.ParenthesizedExpression: - return getTypeOfDottedName((node as ParenthesizedExpression).expression, diagnostic); + return getTypeOfDottedName(node.expression, diagnostic); } } } @@ -27039,8 +27041,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isFalseExpression(expr: Expression): boolean { const node = skipParentheses(expr, /*excludeJSDocTypeAssertions*/ true); return node.kind === SyntaxKind.FalseKeyword || node.kind === SyntaxKind.BinaryExpression && ( - (node as BinaryExpression).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken && (isFalseExpression((node as BinaryExpression).left) || isFalseExpression((node as BinaryExpression).right)) || - (node as BinaryExpression).operatorToken.kind === SyntaxKind.BarBarToken && isFalseExpression((node as BinaryExpression).left) && isFalseExpression((node as BinaryExpression).right) + node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === SyntaxKind.BarBarToken && isFalseExpression(node.left) && isFalseExpression(node.right) ); } @@ -27164,7 +27166,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return true; case SyntaxKind.Identifier: if (!isThisInTypeQuery(node)) { - const symbol = getResolvedSymbol(node as Identifier); + const symbol = getResolvedSymbol(node); return isConstantVariable(symbol) || isParameterOrCatchClauseVariable(symbol) && !isSymbolAssigned(symbol); } break; @@ -27313,7 +27315,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const node = flow.node; return getNarrowableTypeForReference( node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement ? - getInitialType(node as VariableDeclaration | BindingElement) : + getInitialType(node) : getAssignedType(node), reference, ); @@ -27380,11 +27382,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return unreachableNeverType; } if (node.kind === SyntaxKind.BinaryExpression) { - if ((node as BinaryExpression).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) { - return narrowTypeByAssertion(narrowTypeByAssertion(type, (node as BinaryExpression).left), (node as BinaryExpression).right); + if (node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) { + return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); } - if ((node as BinaryExpression).operatorToken.kind === SyntaxKind.BarBarToken) { - return getUnionType([narrowTypeByAssertion(type, (node as BinaryExpression).left), narrowTypeByAssertion(type, (node as BinaryExpression).right)]); + if (node.operatorToken.kind === SyntaxKind.BarBarToken) { + return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]); } } return narrowType(type, node, /*assumeTrue*/ true); @@ -27469,7 +27471,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (expr.kind === SyntaxKind.TypeOfExpression && isMatchingReference(reference, (expr as TypeOfExpression).expression)) { + else if (expr.kind === SyntaxKind.TypeOfExpression && isMatchingReference(reference, expr.expression)) { type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } else if (expr.kind === SyntaxKind.TrueKeyword) { @@ -27480,7 +27482,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (optionalChainContainsReference(expr, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, t => !(t.flags & (TypeFlags.Undefined | TypeFlags.Never))); } - else if (expr.kind === SyntaxKind.TypeOfExpression && optionalChainContainsReference((expr as TypeOfExpression).expression, reference)) { + else if (expr.kind === SyntaxKind.TypeOfExpression && optionalChainContainsReference(expr.expression, reference)) { type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, t => !(t.flags & TypeFlags.Never || t.flags & TypeFlags.StringLiteral && (t as StringLiteralType).value === "undefined")); } } @@ -27812,10 +27814,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const left = getReferenceCandidate(expr.left); const right = getReferenceCandidate(expr.right); if (left.kind === SyntaxKind.TypeOfExpression && isStringLiteralLike(right)) { - return narrowTypeByTypeof(type, left as TypeOfExpression, operator, right, assumeTrue); + return narrowTypeByTypeof(type, left, operator, right, assumeTrue); } if (right.kind === SyntaxKind.TypeOfExpression && isStringLiteralLike(left)) { - return narrowTypeByTypeof(type, right as TypeOfExpression, operator, left, assumeTrue); + return narrowTypeByTypeof(type, right, operator, left, assumeTrue); } if (isMatchingReference(reference, left)) { return narrowTypeByEquality(type, operator, right, assumeTrue); @@ -28343,7 +28345,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // When narrowing a reference to a const variable, non-assigned parameter, or readonly property, we inline // up to five levels of aliased conditional expressions that are themselves declared as const variables. if (!isMatchingReference(reference, expr) && inlineLevel < 5) { - const symbol = getResolvedSymbol(expr as Identifier); + const symbol = getResolvedSymbol(expr); if (isConstantVariable(symbol)) { const declaration = symbol.valueDeclaration; if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isConstantReference(reference)) { @@ -28361,15 +28363,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.ElementAccessExpression: return narrowTypeByTruthiness(type, expr, assumeTrue); case SyntaxKind.CallExpression: - return narrowTypeByCallExpression(type, expr as CallExpression, assumeTrue); + return narrowTypeByCallExpression(type, expr, assumeTrue); case SyntaxKind.ParenthesizedExpression: case SyntaxKind.NonNullExpression: - return narrowType(type, (expr as ParenthesizedExpression | NonNullExpression).expression, assumeTrue); + return narrowType(type, expr.expression, assumeTrue); case SyntaxKind.BinaryExpression: - return narrowTypeByBinaryExpression(type, expr as BinaryExpression, assumeTrue); + return narrowTypeByBinaryExpression(type, expr, assumeTrue); case SyntaxKind.PrefixUnaryExpression: - if ((expr as PrefixUnaryExpression).operator === SyntaxKind.ExclamationToken) { - return narrowType(type, (expr as PrefixUnaryExpression).operand, !assumeTrue); + if (expr.operator === SyntaxKind.ExclamationToken) { + return narrowType(type, expr.operand, !assumeTrue); } break; } @@ -28402,7 +28404,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isExpressionNode(location) && (!isAssignmentTarget(location) || isWriteAccess(location))) { const type = removeOptionalTypeMarker( isWriteAccess(location) && location.kind === SyntaxKind.PropertyAccessExpression ? - checkPropertyAccessExpression(location as PropertyAccessExpression, /*checkMode*/ undefined, /*writeOnly*/ true) : + checkPropertyAccessExpression(location, /*checkMode*/ undefined, /*writeOnly*/ true) : getTypeOfExpression(location as Expression), ); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { @@ -28452,7 +28454,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function markNodeAssignments(node: Node) { if (node.kind === SyntaxKind.Identifier) { if (isAssignmentTarget(node)) { - const symbol = getResolvedSymbol(node as Identifier); + const symbol = getResolvedSymbol(node); if (isParameterOrCatchClauseVariable(symbol)) { symbol.isAssigned = true; } @@ -28825,7 +28827,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Void)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === SyntaxKind.ExportSpecifier) || node.parent.kind === SyntaxKind.NonNullExpression || - declaration.kind === SyntaxKind.VariableDeclaration && (declaration as VariableDeclaration).exclamationToken || + declaration.kind === SyntaxKind.VariableDeclaration && declaration.exclamationToken || declaration.flags & NodeFlags.Ambient; const initialType = isAutomaticTypeInNonNull ? undefinedType : assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration as VariableLikeDeclaration) : type) : @@ -28975,7 +28977,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isAssigned = true; } else if ((current.parent.kind === SyntaxKind.PrefixUnaryExpression || current.parent.kind === SyntaxKind.PostfixUnaryExpression)) { - const expr = current.parent as PrefixUnaryExpression | PostfixUnaryExpression; + const expr = current.parent; isAssigned = expr.operator === SyntaxKind.PlusPlusToken || expr.operator === SyntaxKind.MinusMinusToken; } @@ -29482,7 +29484,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return (func.kind === SyntaxKind.MethodDeclaration || func.kind === SyntaxKind.GetAccessor || func.kind === SyntaxKind.SetAccessor) && func.parent.kind === SyntaxKind.ObjectLiteralExpression ? func.parent : - func.kind === SyntaxKind.FunctionExpression && func.parent.kind === SyntaxKind.PropertyAssignment ? func.parent.parent as ObjectLiteralExpression : + func.kind === SyntaxKind.FunctionExpression && func.parent.kind === SyntaxKind.PropertyAssignment ? func.parent.parent : undefined; } @@ -29507,7 +29509,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (literal.parent.kind !== SyntaxKind.PropertyAssignment) { break; } - literal = literal.parent.parent as ObjectLiteralExpression; + literal = literal.parent.parent; type = getApparentTypeOfContextualType(literal, /*contextFlags*/ undefined); } } @@ -29799,7 +29801,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getContextualTypeForSubstitutionExpression(template: TemplateExpression, substitutionExpression: Expression) { if (template.parent.kind === SyntaxKind.TaggedTemplateExpression) { - return getContextualTypeForArgument(template.parent as TaggedTemplateExpression, substitutionExpression); + return getContextualTypeForArgument(template.parent, substitutionExpression); } return undefined; @@ -30154,9 +30156,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return true; case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ParenthesizedExpression: - return isPossiblyDiscriminantValue((node as PropertyAccessExpression | ParenthesizedExpression).expression); + return isPossiblyDiscriminantValue(node.expression); case SyntaxKind.JsxExpression: - return !(node as JsxExpression).expression || isPossiblyDiscriminantValue((node as JsxExpression).expression!); + return !node.expression || isPossiblyDiscriminantValue(node.expression); } return false; } @@ -30322,14 +30324,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.ReturnStatement: return getContextualTypeForReturnExpression(node, contextFlags); case SyntaxKind.YieldExpression: - return getContextualTypeForYieldOperand(parent as YieldExpression, contextFlags); + return getContextualTypeForYieldOperand(parent, contextFlags); case SyntaxKind.AwaitExpression: - return getContextualTypeForAwaitOperand(parent as AwaitExpression, contextFlags); + return getContextualTypeForAwaitOperand(parent, contextFlags); case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: return getContextualTypeForArgument(parent as CallExpression | NewExpression | Decorator, node); case SyntaxKind.Decorator: - return getContextualTypeForDecorator(parent as Decorator); + return getContextualTypeForDecorator(parent); case SyntaxKind.TypeAssertionExpression: case SyntaxKind.AsExpression: return isConstTypeReference((parent as AssertionExpression).type) ? getContextualType(parent as AssertionExpression, contextFlags) : getTypeFromTypeNode((parent as AssertionExpression).type); @@ -30337,11 +30339,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getContextualTypeForBinaryOperand(node, contextFlags); case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: - return getContextualTypeForObjectLiteralElement(parent as PropertyAssignment | ShorthandPropertyAssignment, contextFlags); + return getContextualTypeForObjectLiteralElement(parent, contextFlags); case SyntaxKind.SpreadAssignment: - return getContextualType(parent.parent as ObjectLiteralExpression, contextFlags); + return getContextualType(parent.parent, contextFlags); case SyntaxKind.ArrayLiteralExpression: { - const arrayLiteral = parent as ArrayLiteralExpression; + const arrayLiteral = parent; const type = getApparentTypeOfContextualType(arrayLiteral, contextFlags); const elementIndex = indexOfNode(arrayLiteral.elements, node); const spreadIndices = getNodeLinks(arrayLiteral).spreadIndices ??= getSpreadIndices(arrayLiteral.elements); @@ -30351,7 +30353,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getContextualTypeForConditionalOperand(node, contextFlags); case SyntaxKind.TemplateSpan: Debug.assert(parent.parent.kind === SyntaxKind.TemplateExpression); - return getContextualTypeForSubstitutionExpression(parent.parent as TemplateExpression, node); + return getContextualTypeForSubstitutionExpression(parent.parent, node); case SyntaxKind.ParenthesizedExpression: { if (isInJSFile(parent)) { if (isJSDocSatisfiesExpression(parent)) { @@ -30363,19 +30365,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getTypeFromTypeNode(typeTag.typeExpression.type); } } - return getContextualType(parent as ParenthesizedExpression, contextFlags); + return getContextualType(parent, contextFlags); } case SyntaxKind.NonNullExpression: - return getContextualType(parent as NonNullExpression, contextFlags); + return getContextualType(parent, contextFlags); case SyntaxKind.SatisfiesExpression: - return getTypeFromTypeNode((parent as SatisfiesExpression).type); + return getTypeFromTypeNode(parent.type); case SyntaxKind.ExportAssignment: - return tryGetTypeFromEffectiveTypeNode(parent as ExportAssignment); + return tryGetTypeFromEffectiveTypeNode(parent); case SyntaxKind.JsxExpression: - return getContextualTypeForJsxExpression(parent as JsxExpression, contextFlags); + return getContextualTypeForJsxExpression(parent, contextFlags); case SyntaxKind.JsxAttribute: case SyntaxKind.JsxSpreadAttribute: - return getContextualTypeForJsxAttribute(parent as JsxAttribute | JsxSpreadAttribute, contextFlags); + return getContextualTypeForJsxAttribute(parent, contextFlags); case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxSelfClosingElement: return getContextualJsxElementAttributesType(parent as JsxOpeningLikeElement, contextFlags); @@ -30747,8 +30749,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function hasDefaultValue(node: BindingElement | Expression): boolean { - return (node.kind === SyntaxKind.BindingElement && !!(node as BindingElement).initializer) || - (node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken); + return (node.kind === SyntaxKind.BindingElement && !!node.initializer) || + (node.kind === SyntaxKind.BinaryExpression && node.operatorToken.kind === SyntaxKind.EqualsToken); } function isSpreadIntoCallOrNew(node: ArrayLiteralExpression) { @@ -30773,7 +30775,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (languageVersion < ScriptTarget.ES2015) { checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? ExternalEmitHelpers.SpreadIncludes : ExternalEmitHelpers.SpreadArray); } - const spreadType = checkExpression((e as SpreadElement).expression, checkMode, forceTuple); + const spreadType = checkExpression(e.expression, checkMode, forceTuple); if (isArrayLikeType(spreadType)) { elementTypes.push(spreadType); elementFlags.push(ElementFlags.Variadic); @@ -30798,7 +30800,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { elementFlags.push(ElementFlags.Rest); } else { - elementTypes.push(checkIteratedTypeOrElementType(IterationUse.Spread, spreadType, undefinedType, (e as SpreadElement).expression)); + elementTypes.push(checkIteratedTypeOrElementType(IterationUse.Spread, spreadType, undefinedType, e.expression)); elementFlags.push(ElementFlags.Rest); } } @@ -31342,7 +31344,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } // Handle children attribute - const parent = openingLikeElement.parent.kind === SyntaxKind.JsxElement ? openingLikeElement.parent as JsxElement : undefined; + const parent = openingLikeElement.parent.kind === SyntaxKind.JsxElement ? openingLikeElement.parent : undefined; // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement if (parent && parent.openingElement === openingLikeElement && getSemanticJsxChildren(parent.children).length > 0) { const childrenTypes: Type[] = checkJsxChildren(parent, checkMode); @@ -32963,13 +32965,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getForInVariableSymbol(node: ForInStatement): Symbol | undefined { const initializer = node.initializer; if (initializer.kind === SyntaxKind.VariableDeclarationList) { - const variable = (initializer as VariableDeclarationList).declarations[0]; + const variable = initializer.declarations[0]; if (variable && !isBindingPattern(variable.name)) { return getSymbolOfDeclaration(variable); } } else if (initializer.kind === SyntaxKind.Identifier) { - return getResolvedSymbol(initializer as Identifier); + return getResolvedSymbol(initializer); } return undefined; } @@ -32988,16 +32990,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isForInVariableForNumericPropertyNames(expr: Expression) { const e = skipParentheses(expr); if (e.kind === SyntaxKind.Identifier) { - const symbol = getResolvedSymbol(e as Identifier); + const symbol = getResolvedSymbol(e); if (symbol.flags & SymbolFlags.Variable) { let child: Node = expr; let node = expr.parent; while (node) { if ( node.kind === SyntaxKind.ForInStatement && - child === (node as ForInStatement).statement && - getForInVariableSymbol(node as ForInStatement) === symbol && - hasNumericPropertyNames(getTypeOfExpression((node as ForInStatement).expression)) + child === node.statement && + getForInVariableSymbol(node) === symbol && + hasNumericPropertyNames(getTypeOfExpression(node.expression)) ) { return true; } @@ -33130,7 +33132,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function isSpreadArgument(arg: Expression | undefined): arg is Expression { - return !!arg && (arg.kind === SyntaxKind.SpreadElement || arg.kind === SyntaxKind.SyntheticExpression && (arg as SyntheticExpression).isSpread); + return !!arg && (arg.kind === SyntaxKind.SpreadElement || arg.kind === SyntaxKind.SyntheticExpression && arg.isSpread); } function getSpreadArgumentIndex(args: readonly Expression[]): number { @@ -33401,14 +33403,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isSpreadArgument(arg)) { // We are inferring from a spread expression in the last argument position, i.e. both the parameter // and the argument are ...x forms. - const spreadType = arg.kind === SyntaxKind.SyntheticExpression ? (arg as SyntheticExpression).type : + const spreadType = arg.kind === SyntaxKind.SyntheticExpression ? arg.type : checkExpressionWithContextualType((arg as SpreadElement).expression, restType, context, checkMode); if (isArrayLikeType(spreadType)) { return getMutableArrayOrTupleType(spreadType); } - return createArrayType(checkIteratedTypeOrElementType(IterationUse.Spread, spreadType, undefinedType, arg.kind === SyntaxKind.SpreadElement ? (arg as SpreadElement).expression : arg), inConstContext); + return createArrayType(checkIteratedTypeOrElementType(IterationUse.Spread, spreadType, undefinedType, arg.kind === SyntaxKind.SpreadElement ? arg.expression : arg), inConstContext); } } const types = []; @@ -33417,13 +33419,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { for (let i = index; i < argCount; i++) { const arg = args[i]; if (isSpreadArgument(arg)) { - const spreadType = arg.kind === SyntaxKind.SyntheticExpression ? (arg as SyntheticExpression).type : checkExpression((arg as SpreadElement).expression); + const spreadType = arg.kind === SyntaxKind.SyntheticExpression ? arg.type : checkExpression((arg as SpreadElement).expression); if (isArrayLikeType(spreadType)) { types.push(spreadType); flags.push(ElementFlags.Variadic); } else { - types.push(checkIteratedTypeOrElementType(IterationUse.Spread, spreadType, undefinedType, arg.kind === SyntaxKind.SpreadElement ? (arg as SpreadElement).expression : arg)); + types.push(checkIteratedTypeOrElementType(IterationUse.Spread, spreadType, undefinedType, arg.kind === SyntaxKind.SpreadElement ? arg.expression : arg)); flags.push(ElementFlags.Rest); } } @@ -33436,8 +33438,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType)); flags.push(ElementFlags.Required); } - if (arg.kind === SyntaxKind.SyntheticExpression && (arg as SyntheticExpression).tupleNameSource) { - names.push((arg as SyntheticExpression).tupleNameSource!); + if (arg.kind === SyntaxKind.SyntheticExpression && arg.tupleNameSource) { + names.push(arg.tupleNameSource); } else { names.push(undefined); @@ -33738,7 +33740,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { for (let i = spreadIndex; i < args.length; i++) { const arg = args[i]; // We can call checkExpressionCached because spread expressions never have a contextual type. - const spreadType = arg.kind === SyntaxKind.SpreadElement && (flowLoopCount ? checkExpression((arg as SpreadElement).expression) : checkExpressionCached((arg as SpreadElement).expression)); + const spreadType = arg.kind === SyntaxKind.SpreadElement && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { forEach(getElementTypes(spreadType), (t, i) => { const flags = spreadType.target.elementFlags[i]; @@ -35272,18 +35274,18 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.CallExpression: case SyntaxKind.Decorator: case SyntaxKind.NewExpression: - return getDeprecatedSuggestionNode((node as Decorator | CallExpression | NewExpression).expression); + return getDeprecatedSuggestionNode(node.expression); case SyntaxKind.TaggedTemplateExpression: - return getDeprecatedSuggestionNode((node as TaggedTemplateExpression).tag); + return getDeprecatedSuggestionNode(node.tag); case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxSelfClosingElement: return getDeprecatedSuggestionNode((node as JsxOpeningLikeElement).tagName); case SyntaxKind.ElementAccessExpression: - return (node as ElementAccessExpression).argumentExpression; + return node.argumentExpression; case SyntaxKind.PropertyAccessExpression: - return (node as PropertyAccessExpression).name; + return node.name; case SyntaxKind.TypeReference: - const typeReference = node as TypeReferenceNode; + const typeReference = node; return isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference; default: return node; @@ -35457,15 +35459,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.TemplateExpression: return true; case SyntaxKind.ParenthesizedExpression: - return isValidConstAssertionArgument((node as ParenthesizedExpression).expression); + return isValidConstAssertionArgument(node.expression); case SyntaxKind.PrefixUnaryExpression: - const op = (node as PrefixUnaryExpression).operator; - const arg = (node as PrefixUnaryExpression).operand; + const op = node.operator; + const arg = node.operand; return op === SyntaxKind.MinusToken && (arg.kind === SyntaxKind.NumericLiteral || arg.kind === SyntaxKind.BigIntLiteral) || op === SyntaxKind.PlusToken && arg.kind === SyntaxKind.NumericLiteral; case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: - const expr = skipParentheses((node as PropertyAccessExpression | ElementAccessExpression).expression); + const expr = skipParentheses(node.expression); const symbol = isEntityNameExpression(expr) ? resolveEntityName(expr, SymbolFlags.Value, /*ignoreErrors*/ true) : undefined; return !!(symbol && symbol.flags & SymbolFlags.Enum); } @@ -35539,7 +35541,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { forEach(node.typeArguments, checkSourceElement); if (node.kind === SyntaxKind.ExpressionWithTypeArguments) { const parent = walkUpParenthesizedExpressions(node.parent); - if (parent.kind === SyntaxKind.BinaryExpression && (parent as BinaryExpression).operatorToken.kind === SyntaxKind.InstanceOfKeyword && isNodeDescendantOf(node, (parent as BinaryExpression).right)) { + if (parent.kind === SyntaxKind.BinaryExpression && parent.operatorToken.kind === SyntaxKind.InstanceOfKeyword && isNodeDescendantOf(node, parent.right)) { error(node, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression); } } @@ -36664,7 +36666,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!witnesses) { return false; } - const operandConstraint = getBaseConstraintOrType(checkExpressionCached((node.expression as TypeOfExpression).expression)); + const operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression)); // Get the not-equal flags for all handled cases. const notEqualFacts = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses); if (operandConstraint.flags & TypeFlags.AnyOrUnknown) { @@ -36702,12 +36704,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Bare calls to this same function don't contribute to inference // and `return await` is also safe to unwrap here if (functionFlags & FunctionFlags.Async && expr.kind === SyntaxKind.AwaitExpression) { - expr = skipParentheses((expr as AwaitExpression).expression, /*excludeJSDocTypeAssertions*/ true); + expr = skipParentheses(expr.expression, /*excludeJSDocTypeAssertions*/ true); } if ( expr.kind === SyntaxKind.CallExpression && - (expr as CallExpression).expression.kind === SyntaxKind.Identifier && - checkExpressionCached((expr as CallExpression).expression).symbol === func.symbol + expr.expression.kind === SyntaxKind.Identifier && + checkExpressionCached(expr.expression).symbol === func.symbol ) { hasReturnOfTypeNever = true; return; @@ -37211,16 +37213,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.NumericLiteral: switch (node.operator) { case SyntaxKind.MinusToken: - return getFreshTypeOfLiteralType(getNumberLiteralType(-(node.operand as NumericLiteral).text)); + return getFreshTypeOfLiteralType(getNumberLiteralType(-node.operand.text)); case SyntaxKind.PlusToken: - return getFreshTypeOfLiteralType(getNumberLiteralType(+(node.operand as NumericLiteral).text)); + return getFreshTypeOfLiteralType(getNumberLiteralType(+node.operand.text)); } break; case SyntaxKind.BigIntLiteral: if (node.operator === SyntaxKind.MinusToken) { return getFreshTypeOfLiteralType(getBigIntLiteralType({ negative: true, - base10Value: parsePseudoBigInt((node.operand as BigIntLiteral).text), + base10Value: parsePseudoBigInt(node.operand.text), })); } } @@ -37538,9 +37540,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { error(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { - const restExpression = (element as SpreadElement).expression; - if (restExpression.kind === SyntaxKind.BinaryExpression && (restExpression as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { - error((restExpression as BinaryExpression).operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); + const restExpression = element.expression; + if (restExpression.kind === SyntaxKind.BinaryExpression && restExpression.operatorToken.kind === SyntaxKind.EqualsToken) { + error(restExpression.operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); } else { checkGrammarForDisallowedTrailingComma(node.elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); @@ -37557,7 +37559,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkDestructuringAssignment(exprOrAssignment: Expression | ShorthandPropertyAssignment, sourceType: Type, checkMode?: CheckMode, rightIsThis?: boolean): Type { let target: Expression; if (exprOrAssignment.kind === SyntaxKind.ShorthandPropertyAssignment) { - const prop = exprOrAssignment as ShorthandPropertyAssignment; + const prop = exprOrAssignment; if (prop.objectAssignmentInitializer) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. @@ -37569,25 +37571,25 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } checkBinaryLikeExpression(prop.name, prop.equalsToken!, prop.objectAssignmentInitializer, checkMode); } - target = (exprOrAssignment as ShorthandPropertyAssignment).name; + target = exprOrAssignment.name; } else { target = exprOrAssignment; } - if (target.kind === SyntaxKind.BinaryExpression && (target as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { - checkBinaryExpression(target as BinaryExpression, checkMode); - target = (target as BinaryExpression).left; + if (target.kind === SyntaxKind.BinaryExpression && target.operatorToken.kind === SyntaxKind.EqualsToken) { + checkBinaryExpression(target, checkMode); + target = target.left; // A default value is specified, so remove undefined from the final type. if (strictNullChecks) { sourceType = getTypeWithFacts(sourceType, TypeFacts.NEUndefined); } } if (target.kind === SyntaxKind.ObjectLiteralExpression) { - return checkObjectLiteralAssignment(target as ObjectLiteralExpression, sourceType, rightIsThis); + return checkObjectLiteralAssignment(target, sourceType, rightIsThis); } if (target.kind === SyntaxKind.ArrayLiteralExpression) { - return checkArrayLiteralAssignment(target as ArrayLiteralExpression, sourceType, checkMode); + return checkArrayLiteralAssignment(target, sourceType, checkMode); } return checkReferenceAssignment(target, sourceType, checkMode); } @@ -37644,15 +37646,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return true; case SyntaxKind.ConditionalExpression: - return isSideEffectFree((node as ConditionalExpression).whenTrue) && - isSideEffectFree((node as ConditionalExpression).whenFalse); + return isSideEffectFree(node.whenTrue) && + isSideEffectFree(node.whenFalse); case SyntaxKind.BinaryExpression: - if (isAssignmentOperator((node as BinaryExpression).operatorToken.kind)) { + if (isAssignmentOperator(node.operatorToken.kind)) { return false; } - return isSideEffectFree((node as BinaryExpression).left) && - isSideEffectFree((node as BinaryExpression).right); + return isSideEffectFree(node.left) && + isSideEffectFree(node.right); case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.PostfixUnaryExpression: @@ -38175,7 +38177,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // getters can be a subtype of setters, so to check for assignability we use the setter's type instead if (isCompoundAssignment(operatorToken.kind) && left.kind === SyntaxKind.PropertyAccessExpression) { - assigneeType = checkPropertyAccessExpression(left as PropertyAccessExpression, /*checkMode*/ undefined, /*writeOnly*/ true); + assigneeType = checkPropertyAccessExpression(left, /*checkMode*/ undefined, /*writeOnly*/ true); } // TypeScript 1.0 spec (April 2014): 4.17 @@ -38841,10 +38843,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - const ok = (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent as PropertyAccessExpression).expression === node) || - (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent as ElementAccessExpression).expression === node) || + const ok = (node.parent.kind === SyntaxKind.PropertyAccessExpression && node.parent.expression === node) || + (node.parent.kind === SyntaxKind.ElementAccessExpression && node.parent.expression === node) || ((node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName) && isInRightSideOfImportOrExportAssignment(node as Identifier) || - (node.parent.kind === SyntaxKind.TypeQuery && (node.parent as TypeQueryNode).exprName === node)) || + (node.parent.kind === SyntaxKind.TypeQuery && node.parent.exprName === node)) || (node.parent.kind === SyntaxKind.ExportSpecifier); // We allow reexporting const enums if (!ok) { @@ -38886,9 +38888,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } switch (kind) { case SyntaxKind.Identifier: - return checkIdentifier(node as Identifier, checkMode); + return checkIdentifier(node, checkMode); case SyntaxKind.PrivateIdentifier: - return checkPrivateIdentifierExpression(node as PrivateIdentifier); + return checkPrivateIdentifierExpression(node); case SyntaxKind.ThisKeyword: return checkThisExpression(node); case SyntaxKind.SuperKeyword: @@ -38899,100 +38901,100 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.StringLiteral: return hasSkipDirectInferenceFlag(node) ? blockedStringType : - getFreshTypeOfLiteralType(getStringLiteralType((node as StringLiteralLike).text)); + getFreshTypeOfLiteralType(getStringLiteralType(node.text)); case SyntaxKind.NumericLiteral: { - checkGrammarNumericLiteral(node as NumericLiteral); - const value = +(node as NumericLiteral).text; + checkGrammarNumericLiteral(node); + const value = +node.text; if (!isFinite(value)) { return numberType; } return getFreshTypeOfLiteralType(getNumberLiteralType(value)); } case SyntaxKind.BigIntLiteral: - checkGrammarBigIntLiteral(node as BigIntLiteral); + checkGrammarBigIntLiteral(node); return getFreshTypeOfLiteralType(getBigIntLiteralType({ negative: false, - base10Value: parsePseudoBigInt((node as BigIntLiteral).text), + base10Value: parsePseudoBigInt(node.text), })); case SyntaxKind.TrueKeyword: return trueType; case SyntaxKind.FalseKeyword: return falseType; case SyntaxKind.TemplateExpression: - return checkTemplateExpression(node as TemplateExpression); + return checkTemplateExpression(node); case SyntaxKind.RegularExpressionLiteral: return globalRegExpType; case SyntaxKind.ArrayLiteralExpression: - return checkArrayLiteral(node as ArrayLiteralExpression, checkMode, forceTuple); + return checkArrayLiteral(node, checkMode, forceTuple); case SyntaxKind.ObjectLiteralExpression: - return checkObjectLiteral(node as ObjectLiteralExpression, checkMode); + return checkObjectLiteral(node, checkMode); case SyntaxKind.PropertyAccessExpression: - return checkPropertyAccessExpression(node as PropertyAccessExpression, checkMode); + return checkPropertyAccessExpression(node, checkMode); case SyntaxKind.QualifiedName: - return checkQualifiedName(node as QualifiedName, checkMode); + return checkQualifiedName(node, checkMode); case SyntaxKind.ElementAccessExpression: - return checkIndexedAccess(node as ElementAccessExpression, checkMode); + return checkIndexedAccess(node, checkMode); case SyntaxKind.CallExpression: - if ((node as CallExpression).expression.kind === SyntaxKind.ImportKeyword) { - return checkImportCallExpression(node as ImportCall); + if (node.expression.kind === SyntaxKind.ImportKeyword) { + return checkImportCallExpression(node); } // falls through case SyntaxKind.NewExpression: - return checkCallExpression(node as CallExpression, checkMode); + return checkCallExpression(node, checkMode); case SyntaxKind.TaggedTemplateExpression: - return checkTaggedTemplateExpression(node as TaggedTemplateExpression); + return checkTaggedTemplateExpression(node); case SyntaxKind.ParenthesizedExpression: - return checkParenthesizedExpression(node as ParenthesizedExpression, checkMode); + return checkParenthesizedExpression(node, checkMode); case SyntaxKind.ClassExpression: - return checkClassExpression(node as ClassExpression); + return checkClassExpression(node); case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - return checkFunctionExpressionOrObjectLiteralMethod(node as FunctionExpression | ArrowFunction, checkMode); + return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode); case SyntaxKind.TypeOfExpression: - return checkTypeOfExpression(node as TypeOfExpression); + return checkTypeOfExpression(node); case SyntaxKind.TypeAssertionExpression: case SyntaxKind.AsExpression: - return checkAssertion(node as AssertionExpression, checkMode); + return checkAssertion(node, checkMode); case SyntaxKind.NonNullExpression: - return checkNonNullAssertion(node as NonNullExpression); + return checkNonNullAssertion(node); case SyntaxKind.ExpressionWithTypeArguments: - return checkExpressionWithTypeArguments(node as ExpressionWithTypeArguments); + return checkExpressionWithTypeArguments(node); case SyntaxKind.SatisfiesExpression: - return checkSatisfiesExpression(node as SatisfiesExpression); + return checkSatisfiesExpression(node); case SyntaxKind.MetaProperty: - return checkMetaProperty(node as MetaProperty); + return checkMetaProperty(node); case SyntaxKind.DeleteExpression: - return checkDeleteExpression(node as DeleteExpression); + return checkDeleteExpression(node); case SyntaxKind.VoidExpression: - return checkVoidExpression(node as VoidExpression); + return checkVoidExpression(node); case SyntaxKind.AwaitExpression: - return checkAwaitExpression(node as AwaitExpression); + return checkAwaitExpression(node); case SyntaxKind.PrefixUnaryExpression: - return checkPrefixUnaryExpression(node as PrefixUnaryExpression); + return checkPrefixUnaryExpression(node); case SyntaxKind.PostfixUnaryExpression: - return checkPostfixUnaryExpression(node as PostfixUnaryExpression); + return checkPostfixUnaryExpression(node); case SyntaxKind.BinaryExpression: - return checkBinaryExpression(node as BinaryExpression, checkMode); + return checkBinaryExpression(node, checkMode); case SyntaxKind.ConditionalExpression: - return checkConditionalExpression(node as ConditionalExpression, checkMode); + return checkConditionalExpression(node, checkMode); case SyntaxKind.SpreadElement: - return checkSpreadExpression(node as SpreadElement, checkMode); + return checkSpreadExpression(node, checkMode); case SyntaxKind.OmittedExpression: return undefinedWideningType; case SyntaxKind.YieldExpression: - return checkYieldExpression(node as YieldExpression); + return checkYieldExpression(node); case SyntaxKind.SyntheticExpression: - return checkSyntheticExpression(node as SyntheticExpression); + return checkSyntheticExpression(node); case SyntaxKind.JsxExpression: - return checkJsxExpression(node as JsxExpression, checkMode); + return checkJsxExpression(node, checkMode); case SyntaxKind.JsxElement: - return checkJsxElement(node as JsxElement, checkMode); + return checkJsxElement(node, checkMode); case SyntaxKind.JsxSelfClosingElement: - return checkJsxSelfClosingElement(node as JsxSelfClosingElement, checkMode); + return checkJsxSelfClosingElement(node, checkMode); case SyntaxKind.JsxFragment: - return checkJsxFragment(node as JsxFragment); + return checkJsxFragment(node); case SyntaxKind.JsxAttributes: - return checkJsxAttributes(node as JsxAttributes, checkMode); + return checkJsxAttributes(node, checkMode); case SyntaxKind.JsxOpeningElement: Debug.fail("Shouldn't ever directly check a JsxOpeningElement"); } @@ -39296,7 +39298,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const privateIdentifiers = new Map<__String, DeclarationMeaning>(); for (const member of node.members) { if (member.kind === SyntaxKind.Constructor) { - for (const param of (member as ConstructorDeclaration).parameters) { + for (const param of member.parameters) { if (isParameterPropertyDeclaration(param, member) && !isBindingPattern(param.name)) { addName(instanceNames, param.name, param.name.escapedText, DeclarationMeaning.GetOrSetAccessor); } @@ -39408,7 +39410,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { for (const member of node.members) { if (member.kind === SyntaxKind.PropertySignature) { let memberName: string; - const name = member.name!; + const name = member.name; switch (name.kind) { case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: @@ -39571,7 +39573,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } return n.kind === SyntaxKind.PropertyDeclaration && !isStatic(n) && - !!(n as PropertyDeclaration).initializer; + !!n.initializer; } function checkConstructorDeclarationDiagnostics() { @@ -40381,7 +40383,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.JSDocEnumTag: return DeclarationSpaces.ExportType; case SyntaxKind.ModuleDeclaration: - return isAmbientModule(d as ModuleDeclaration) || getModuleInstanceState(d as ModuleDeclaration) !== ModuleInstanceState.NonInstantiated + return isAmbientModule(d) || getModuleInstanceState(d) !== ModuleInstanceState.NonInstantiated ? DeclarationSpaces.ExportNamespace | DeclarationSpaces.ExportValue : DeclarationSpaces.ExportNamespace; case SyntaxKind.ClassDeclaration: @@ -40392,7 +40394,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return DeclarationSpaces.ExportType | DeclarationSpaces.ExportValue | DeclarationSpaces.ExportNamespace; case SyntaxKind.ExportAssignment: case SyntaxKind.BinaryExpression: - const node = d as ExportAssignment | BinaryExpression; + const node = d; const expression = isExportAssignment(node) ? node.expression : node.right; // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values if (!isEntityNameExpression(expression)) { @@ -41034,14 +41036,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return getEntityNameForDecoratorMetadataFromTypeList((node as UnionOrIntersectionTypeNode).types); case SyntaxKind.ConditionalType: - return getEntityNameForDecoratorMetadataFromTypeList([(node as ConditionalTypeNode).trueType, (node as ConditionalTypeNode).falseType]); + return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]); case SyntaxKind.ParenthesizedType: case SyntaxKind.NamedTupleMember: return getEntityNameForDecoratorMetadata((node as ParenthesizedTypeNode).type); case SyntaxKind.TypeReference: - return (node as TypeReferenceNode).typeName; + return node.typeName; } } } @@ -41050,12 +41052,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { let commonEntityName: EntityName | undefined; for (let typeNode of types) { while (typeNode.kind === SyntaxKind.ParenthesizedType || typeNode.kind === SyntaxKind.NamedTupleMember) { - typeNode = (typeNode as ParenthesizedTypeNode | NamedTupleMember).type; // Skip parens if need be + typeNode = typeNode.type; // Skip parens if need be } if (typeNode.kind === SyntaxKind.NeverKeyword) { continue; // Always elide `never` from the union/intersection if possible } - if (!strictNullChecks && (typeNode.kind === SyntaxKind.LiteralType && (typeNode as LiteralTypeNode).literal.kind === SyntaxKind.NullKeyword || typeNode.kind === SyntaxKind.UndefinedKeyword)) { + if (!strictNullChecks && (typeNode.kind === SyntaxKind.LiteralType && typeNode.literal.kind === SyntaxKind.NullKeyword || typeNode.kind === SyntaxKind.UndefinedKeyword)) { continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks } const individualEntityName = getEntityNameForDecoratorMetadata(typeNode); @@ -41297,9 +41299,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getIdentifierFromEntityNameExpression(node: Expression): Identifier | PrivateIdentifier | undefined { switch (node.kind) { case SyntaxKind.Identifier: - return node as Identifier; + return node; case SyntaxKind.PropertyAccessExpression: - return (node as PropertyAccessExpression).name; + return node.name; default: return undefined; } @@ -41450,7 +41452,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function isIdentifierThatStartsWithUnderscore(node: Node) { - return isIdentifier(node) && idText(node).charCodeAt(0) === CharacterCodes._; + return isIdentifier(node) && idTextnode.charCodeAt(0) === CharacterCodes._; } function checkUnusedClassMembers(node: ClassDeclaration | ClassExpression, addDiagnostic: AddUnusedDiagnostic): void { @@ -41470,11 +41472,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { && (hasEffectiveModifier(member, ModifierFlags.Private) || isNamedDeclaration(member) && isPrivateIdentifier(member.name)) && !(member.flags & NodeFlags.Ambient) ) { - addDiagnostic(member, UnusedKind.Local, createDiagnosticForNode(member.name!, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); + addDiagnostic(member, UnusedKind.Local, createDiagnosticForNode(member.name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; case SyntaxKind.Constructor: - for (const parameter of (member as ConstructorDeclaration).parameters) { + for (const parameter of member.parameters) { if (!parameter.symbol.isReferenced && hasSyntacticModifier(parameter, ModifierFlags.Private)) { addDiagnostic(parameter, UnusedKind.Local, createDiagnosticForNode(parameter.name, Diagnostics.Property_0_is_declared_but_its_value_is_never_read, symbolName(parameter.symbol))); } @@ -41501,7 +41503,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function checkUnusedTypeParameters(node: ClassLikeDeclaration | SignatureDeclaration | InterfaceDeclaration | TypeAliasDeclaration, addDiagnostic: AddUnusedDiagnostic): void { // Only report errors on the last declaration for the type parameter container; // this ensures that all uses have been accounted for. - const declarations = getSymbolOfDeclaration(node).declarations; + const declarations = getSymbolOfDeclarationnode.declarations; if (!declarations || last(declarations) !== node) return; const typeParameters = getEffectiveTypeParameterDeclarations(node); @@ -41845,7 +41847,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent const parent = getDeclarationContainer(node); - if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent as SourceFile)) { + if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, declarationNameToString(name), declarationNameToString(name)); } @@ -41863,7 +41865,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent const parent = getDeclarationContainer(node); - if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent as SourceFile) && parent.flags & NodeFlags.HasAsyncFunctions) { + if (parent.kind === SyntaxKind.SourceFile && isExternalOrCommonJsModule(parent) && parent.flags & NodeFlags.HasAsyncFunctions) { // If the declaration happens to be in external module, report error that Promise is a reserved identifier. errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, declarationNameToString(name), declarationNameToString(name)); } @@ -42438,13 +42440,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { if (node.initializer && node.initializer.kind === SyntaxKind.VariableDeclarationList) { - checkGrammarVariableDeclarationList(node.initializer as VariableDeclarationList); + checkGrammarVariableDeclarationList(node.initializer); } } if (node.initializer) { if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { - checkVariableDeclarationList(node.initializer as VariableDeclarationList); + checkVariableDeclarationList(node.initializer); } else { checkExpression(node.initializer); @@ -42486,7 +42488,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. // Then check that the RHS is assignable to it. if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { - checkVariableDeclarationList(node.initializer as VariableDeclarationList); + checkVariableDeclarationList(node.initializer); } else { const varExpr = node.initializer; @@ -42534,11 +42536,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { - const variable = (node.initializer as VariableDeclarationList).declarations[0]; + const variable = node.initializer.declarations[0]; if (variable && isBindingPattern(variable.name)) { error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } - checkVariableDeclarationList(node.initializer as VariableDeclarationList); + checkVariableDeclarationList(node.initializer); } else { // In a 'for-in' statement of the form @@ -43553,7 +43555,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (isFunctionLike(current)) { return "quit"; } - if (current.kind === SyntaxKind.LabeledStatement && (current as LabeledStatement).label.escapedText === node.label.escapedText) { + if (current.kind === SyntaxKind.LabeledStatement && current.label.escapedText === node.label.escapedText) { grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNode(node.label)); return true; } @@ -43808,7 +43810,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { visit(root); function visit(node: Node) { if (node.kind === SyntaxKind.TypeReference) { - const type = getTypeFromTypeReference(node as TypeReferenceNode); + const type = getTypeFromTypeReference(node); if (type.flags & TypeFlags.TypeParameter) { for (let i = index; i < typeParameters.length; i++) { if (type.symbol === getSymbolOfDeclaration(typeParameters[i])) { @@ -44488,7 +44490,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, symbolToString(base), typeToString(baseType), typeToString(type)); } else if (useDefineForClassFields) { - const uninitialized = derived.declarations?.find(d => d.kind === SyntaxKind.PropertyDeclaration && !(d as PropertyDeclaration).initializer); + const uninitialized = derived.declarations?.find(d => d.kind === SyntaxKind.PropertyDeclaration && !d.initializer); if ( uninitialized && !(derived.flags & SymbolFlags.Transient) @@ -44631,8 +44633,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isPropertyWithoutInitializer(node: Node) { return node.kind === SyntaxKind.PropertyDeclaration && !hasAbstractModifier(node) && - !(node as PropertyDeclaration).exclamationToken && - !(node as PropertyDeclaration).initializer; + !node.exclamationToken && + !node.initializer; } function isPropertyInitializedInStaticBlocks(propName: Identifier | PrivateIdentifier, propType: Type, staticBlocks: readonly ClassStaticBlockDeclaration[], startPos: number, endPos: number) { @@ -44793,9 +44795,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function evaluate(expr: Expression, location?: Declaration): string | number | undefined { switch (expr.kind) { case SyntaxKind.PrefixUnaryExpression: - const value = evaluate((expr as PrefixUnaryExpression).operand, location); + const value = evaluate(expr.operand, location); if (typeof value === "number") { - switch ((expr as PrefixUnaryExpression).operator) { + switch (expr.operator) { case SyntaxKind.PlusToken: return value; case SyntaxKind.MinusToken: @@ -44806,10 +44808,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } break; case SyntaxKind.BinaryExpression: - const left = evaluate((expr as BinaryExpression).left, location); - const right = evaluate((expr as BinaryExpression).right, location); + const left = evaluate(expr.left, location); + const right = evaluate(expr.right, location); if (typeof left === "number" && typeof right === "number") { - switch ((expr as BinaryExpression).operatorToken.kind) { + switch (expr.operatorToken.kind) { case SyntaxKind.BarToken: return left | right; case SyntaxKind.AmpersandToken: @@ -44839,7 +44841,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if ( (typeof left === "string" || typeof left === "number") && (typeof right === "string" || typeof right === "number") && - (expr as BinaryExpression).operatorToken.kind === SyntaxKind.PlusToken + expr.operatorToken.kind === SyntaxKind.PlusToken ) { return "" + left + right; } @@ -44848,14 +44850,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case SyntaxKind.NoSubstitutionTemplateLiteral: return (expr as StringLiteralLike).text; case SyntaxKind.TemplateExpression: - return evaluateTemplateExpression(expr as TemplateExpression, location); + return evaluateTemplateExpression(expr, location); case SyntaxKind.NumericLiteral: - checkGrammarNumericLiteral(expr as NumericLiteral); - return +(expr as NumericLiteral).text; + checkGrammarNumericLiteral(expr); + return +expr.text; case SyntaxKind.ParenthesizedExpression: - return evaluate((expr as ParenthesizedExpression).expression, location); + return evaluate(expr.expression, location); case SyntaxKind.Identifier: { - const identifier = expr as Identifier; + const identifier = expr; if (isInfinityOrNaNString(identifier.escapedText) && (resolveEntityName(identifier, SymbolFlags.Value, /*ignoreErrors*/ true) === getGlobalSymbol(identifier.escapedText, SymbolFlags.Value, /*diagnostic*/ undefined))) { return +(identifier.escapedText); } @@ -44878,11 +44880,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } break; case SyntaxKind.ElementAccessExpression: - const root = (expr as ElementAccessExpression).expression; - if (isEntityNameExpression(root) && isStringLiteralLike((expr as ElementAccessExpression).argumentExpression)) { + const root = expr.expression; + if (isEntityNameExpression(root) && isStringLiteralLike(expr.argumentExpression)) { const rootSymbol = resolveEntityName(root, SymbolFlags.Value, /*ignoreErrors*/ true); if (rootSymbol && rootSymbol.flags & SymbolFlags.Enum) { - const name = escapeLeadingUnderscores(((expr as ElementAccessExpression).argumentExpression as StringLiteralLike).text); + const name = escapeLeadingUnderscores(expr.argumentExpression.text); const member = rootSymbol.exports!.get(name); if (member) { return location ? evaluateEnumMember(expr, member, location) : getEnumMemberValue(member.valueDeclaration as EnumMember); @@ -44960,7 +44962,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return false; } - const enumDeclaration = declaration as EnumDeclaration; + const enumDeclaration = declaration; if (!enumDeclaration.members.length) { return false; } @@ -45109,7 +45111,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // We can detect if augmentation was applied using following rules: // - augmentation for a global scope is always applied // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). - const checkBody = isGlobalAugmentation || (getSymbolOfDeclaration(node).flags & SymbolFlags.Transient); + const checkBody = isGlobalAugmentation || (getSymbolOfDeclarationnode.flags & SymbolFlags.Transient); if (checkBody && node.body) { for (const statement of node.body.statements) { checkModuleAugmentationElement(statement, isGlobalAugmentation); @@ -45142,7 +45144,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { switch (node.kind) { case SyntaxKind.VariableStatement: // error each individual name in variable statement instead of marking the entire variable statement - for (const decl of (node as VariableStatement).declarationList.declarations) { + for (const decl of node.declarationList.declarations) { checkModuleAugmentationElement(decl, isGlobalAugmentation); } break; @@ -45156,7 +45158,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { break; case SyntaxKind.BindingElement: case SyntaxKind.VariableDeclaration: - const name = (node as VariableDeclaration | BindingElement).name; + const name = node.name; if (isBindingPattern(name)) { for (const el of name.elements) { // mark individual names in binding pattern @@ -45713,7 +45715,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { (moduleKind === ModuleKind.CommonJS || getSourceFileOfNode(node).impliedNodeFormat === ModuleKind.CommonJS); if (node.expression.kind === SyntaxKind.Identifier) { - const id = node.expression as Identifier; + const id = node.expression; const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName(id, SymbolFlags.All, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node)); if (sym) { markAliasReferenced(sym, id); @@ -45875,13 +45877,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { switch (kind) { case SyntaxKind.TypeParameter: - return checkTypeParameter(node as TypeParameterDeclaration); + return checkTypeParameter(node); case SyntaxKind.Parameter: - return checkParameter(node as ParameterDeclaration); + return checkParameter(node); case SyntaxKind.PropertyDeclaration: - return checkPropertyDeclaration(node as PropertyDeclaration); + return checkPropertyDeclaration(node); case SyntaxKind.PropertySignature: - return checkPropertySignature(node as PropertySignature); + return checkPropertySignature(node); case SyntaxKind.ConstructorType: case SyntaxKind.FunctionType: case SyntaxKind.CallSignature: @@ -45890,69 +45892,69 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return checkSignatureDeclaration(node as SignatureDeclaration); case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - return checkMethodDeclaration(node as MethodDeclaration | MethodSignature); + return checkMethodDeclaration(node); case SyntaxKind.ClassStaticBlockDeclaration: - return checkClassStaticBlockDeclaration(node as ClassStaticBlockDeclaration); + return checkClassStaticBlockDeclaration(node); case SyntaxKind.Constructor: - return checkConstructorDeclaration(node as ConstructorDeclaration); + return checkConstructorDeclaration(node); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: return checkAccessorDeclaration(node as AccessorDeclaration); case SyntaxKind.TypeReference: - return checkTypeReferenceNode(node as TypeReferenceNode); + return checkTypeReferenceNode(node); case SyntaxKind.TypePredicate: - return checkTypePredicate(node as TypePredicateNode); + return checkTypePredicate(node); case SyntaxKind.TypeQuery: - return checkTypeQuery(node as TypeQueryNode); + return checkTypeQuery(node); case SyntaxKind.TypeLiteral: - return checkTypeLiteral(node as TypeLiteralNode); + return checkTypeLiteral(node); case SyntaxKind.ArrayType: - return checkArrayType(node as ArrayTypeNode); + return checkArrayType(node); case SyntaxKind.TupleType: - return checkTupleType(node as TupleTypeNode); + return checkTupleType(node); case SyntaxKind.UnionType: case SyntaxKind.IntersectionType: return checkUnionOrIntersectionType(node as UnionOrIntersectionTypeNode); case SyntaxKind.ParenthesizedType: case SyntaxKind.OptionalType: case SyntaxKind.RestType: - return checkSourceElement((node as ParenthesizedTypeNode | OptionalTypeNode | RestTypeNode).type); + return checkSourceElement(node.type); case SyntaxKind.ThisType: - return checkThisType(node as ThisTypeNode); + return checkThisType(node); case SyntaxKind.TypeOperator: - return checkTypeOperator(node as TypeOperatorNode); + return checkTypeOperator(node); case SyntaxKind.ConditionalType: - return checkConditionalType(node as ConditionalTypeNode); + return checkConditionalType(node); case SyntaxKind.InferType: - return checkInferType(node as InferTypeNode); + return checkInferType(node); case SyntaxKind.TemplateLiteralType: - return checkTemplateLiteralType(node as TemplateLiteralTypeNode); + return checkTemplateLiteralType(node); case SyntaxKind.ImportType: - return checkImportType(node as ImportTypeNode); + return checkImportType(node); case SyntaxKind.NamedTupleMember: - return checkNamedTupleMember(node as NamedTupleMember); + return checkNamedTupleMember(node); case SyntaxKind.JSDocAugmentsTag: - return checkJSDocAugmentsTag(node as JSDocAugmentsTag); + return checkJSDocAugmentsTag(node); case SyntaxKind.JSDocImplementsTag: - return checkJSDocImplementsTag(node as JSDocImplementsTag); + return checkJSDocImplementsTag(node); case SyntaxKind.JSDocTypedefTag: case SyntaxKind.JSDocCallbackTag: case SyntaxKind.JSDocEnumTag: return checkJSDocTypeAliasTag(node as JSDocTypedefTag); case SyntaxKind.JSDocTemplateTag: - return checkJSDocTemplateTag(node as JSDocTemplateTag); + return checkJSDocTemplateTag(node); case SyntaxKind.JSDocTypeTag: - return checkJSDocTypeTag(node as JSDocTypeTag); + return checkJSDocTypeTag(node); case SyntaxKind.JSDocLink: case SyntaxKind.JSDocLinkCode: case SyntaxKind.JSDocLinkPlain: - return checkJSDocLinkLikeTag(node as JSDocLink | JSDocLinkCode | JSDocLinkPlain); + return checkJSDocLinkLikeTag(node); case SyntaxKind.JSDocParameterTag: - return checkJSDocParameterTag(node as JSDocParameterTag); + return checkJSDocParameterTag(node); case SyntaxKind.JSDocPropertyTag: - return checkJSDocPropertyTag(node as JSDocPropertyTag); + return checkJSDocPropertyTag(node); case SyntaxKind.JSDocFunctionType: - checkJSDocFunctionType(node as JSDocFunctionType); + checkJSDocFunctionType(node); // falls through case SyntaxKind.JSDocNonNullableType: case SyntaxKind.JSDocNullableType: @@ -45963,78 +45965,78 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { forEachChild(node, checkSourceElement); return; case SyntaxKind.JSDocVariadicType: - checkJSDocVariadicType(node as JSDocVariadicType); + checkJSDocVariadicType(node); return; case SyntaxKind.JSDocTypeExpression: - return checkSourceElement((node as JSDocTypeExpression).type); + return checkSourceElement(node.type); case SyntaxKind.JSDocPublicTag: case SyntaxKind.JSDocProtectedTag: case SyntaxKind.JSDocPrivateTag: - return checkJSDocAccessibilityModifiers(node as JSDocPublicTag | JSDocProtectedTag | JSDocPrivateTag); + return checkJSDocAccessibilityModifiers(node); case SyntaxKind.JSDocSatisfiesTag: - return checkJSDocSatisfiesTag(node as JSDocSatisfiesTag); + return checkJSDocSatisfiesTag(node); case SyntaxKind.IndexedAccessType: - return checkIndexedAccessType(node as IndexedAccessTypeNode); + return checkIndexedAccessType(node); case SyntaxKind.MappedType: - return checkMappedType(node as MappedTypeNode); + return checkMappedType(node); case SyntaxKind.FunctionDeclaration: - return checkFunctionDeclaration(node as FunctionDeclaration); + return checkFunctionDeclaration(node); case SyntaxKind.Block: case SyntaxKind.ModuleBlock: return checkBlock(node as Block); case SyntaxKind.VariableStatement: - return checkVariableStatement(node as VariableStatement); + return checkVariableStatement(node); case SyntaxKind.ExpressionStatement: - return checkExpressionStatement(node as ExpressionStatement); + return checkExpressionStatement(node); case SyntaxKind.IfStatement: - return checkIfStatement(node as IfStatement); + return checkIfStatement(node); case SyntaxKind.DoStatement: - return checkDoStatement(node as DoStatement); + return checkDoStatement(node); case SyntaxKind.WhileStatement: - return checkWhileStatement(node as WhileStatement); + return checkWhileStatement(node); case SyntaxKind.ForStatement: - return checkForStatement(node as ForStatement); + return checkForStatement(node); case SyntaxKind.ForInStatement: - return checkForInStatement(node as ForInStatement); + return checkForInStatement(node); case SyntaxKind.ForOfStatement: - return checkForOfStatement(node as ForOfStatement); + return checkForOfStatement(node); case SyntaxKind.ContinueStatement: case SyntaxKind.BreakStatement: return checkBreakOrContinueStatement(node as BreakOrContinueStatement); case SyntaxKind.ReturnStatement: - return checkReturnStatement(node as ReturnStatement); + return checkReturnStatement(node); case SyntaxKind.WithStatement: - return checkWithStatement(node as WithStatement); + return checkWithStatement(node); case SyntaxKind.SwitchStatement: - return checkSwitchStatement(node as SwitchStatement); + return checkSwitchStatement(node); case SyntaxKind.LabeledStatement: - return checkLabeledStatement(node as LabeledStatement); + return checkLabeledStatement(node); case SyntaxKind.ThrowStatement: - return checkThrowStatement(node as ThrowStatement); + return checkThrowStatement(node); case SyntaxKind.TryStatement: - return checkTryStatement(node as TryStatement); + return checkTryStatement(node); case SyntaxKind.VariableDeclaration: - return checkVariableDeclaration(node as VariableDeclaration); + return checkVariableDeclaration(node); case SyntaxKind.BindingElement: - return checkBindingElement(node as BindingElement); + return checkBindingElement(node); case SyntaxKind.ClassDeclaration: - return checkClassDeclaration(node as ClassDeclaration); + return checkClassDeclaration(node); case SyntaxKind.InterfaceDeclaration: - return checkInterfaceDeclaration(node as InterfaceDeclaration); + return checkInterfaceDeclaration(node); case SyntaxKind.TypeAliasDeclaration: - return checkTypeAliasDeclaration(node as TypeAliasDeclaration); + return checkTypeAliasDeclaration(node); case SyntaxKind.EnumDeclaration: - return checkEnumDeclaration(node as EnumDeclaration); + return checkEnumDeclaration(node); case SyntaxKind.ModuleDeclaration: - return checkModuleDeclaration(node as ModuleDeclaration); + return checkModuleDeclaration(node); case SyntaxKind.ImportDeclaration: - return checkImportDeclaration(node as ImportDeclaration); + return checkImportDeclaration(node); case SyntaxKind.ImportEqualsDeclaration: - return checkImportEqualsDeclaration(node as ImportEqualsDeclaration); + return checkImportEqualsDeclaration(node); case SyntaxKind.ExportDeclaration: - return checkExportDeclaration(node as ExportDeclaration); + return checkExportDeclaration(node); case SyntaxKind.ExportAssignment: - return checkExportAssignment(node as ExportAssignment); + return checkExportAssignment(node); case SyntaxKind.EmptyStatement: case SyntaxKind.DebuggerStatement: checkGrammarStatementInAmbientContext(node); @@ -46204,16 +46206,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkAccessorDeclaration(node as AccessorDeclaration); break; case SyntaxKind.ClassExpression: - checkClassExpressionDeferred(node as ClassExpression); + checkClassExpressionDeferred(node); break; case SyntaxKind.TypeParameter: - checkTypeParameterDeferred(node as TypeParameterDeclaration); + checkTypeParameterDeferred(node); break; case SyntaxKind.JsxSelfClosingElement: - checkJsxSelfClosingElementDeferred(node as JsxSelfClosingElement); + checkJsxSelfClosingElementDeferred(node); break; case SyntaxKind.JsxElement: - checkJsxElementDeferred(node as JsxElement); + checkJsxElementDeferred(node); break; case SyntaxKind.TypeAssertionExpression: case SyntaxKind.AsExpression: @@ -46221,7 +46223,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkAssertionDeferred(node as AssertionExpression | JSDocTypeAssertion); break; case SyntaxKind.VoidExpression: - checkExpression((node as VoidExpression).expression); + checkExpression(node.expression); break; case SyntaxKind.BinaryExpression: if (isInstanceOfExpression(node)) { @@ -46433,18 +46435,18 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { switch (location.kind) { case SyntaxKind.SourceFile: - if (!isExternalModule(location as SourceFile)) break; + if (!isExternalModule(location)) break; // falls through case SyntaxKind.ModuleDeclaration: - copyLocallyVisibleExportSymbols(getSymbolOfDeclaration(location as ModuleDeclaration | SourceFile).exports!, meaning & SymbolFlags.ModuleMember); + copyLocallyVisibleExportSymbols(getSymbolOfDeclaration(location).exports!, meaning & SymbolFlags.ModuleMember); break; case SyntaxKind.EnumDeclaration: - copySymbols(getSymbolOfDeclaration(location as EnumDeclaration).exports!, meaning & SymbolFlags.EnumMember); + copySymbols(getSymbolOfDeclaration(location).exports!, meaning & SymbolFlags.EnumMember); break; case SyntaxKind.ClassExpression: - const className = (location as ClassExpression).name; + const className = location.name; if (className) { - copySymbol((location as ClassExpression).symbol, meaning); + copySymbol(location.symbol, meaning); } // this fall-through is necessary because we would like to handle @@ -46461,9 +46463,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } break; case SyntaxKind.FunctionExpression: - const funcName = (location as FunctionExpression).name; + const funcName = location.name; if (funcName) { - copySymbol((location as FunctionExpression).symbol, meaning); + copySymbol(location.symbol, meaning); } break; } @@ -46527,7 +46529,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // True if the given identifier is part of a type reference function isTypeReferenceIdentifier(node: EntityName): boolean { while (node.parent.kind === SyntaxKind.QualifiedName) { - node = node.parent as QualifiedName; + node = node.parent; } return node.parent.kind === SyntaxKind.TypeReference; @@ -46571,15 +46573,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide: EntityName): ImportEqualsDeclaration | ExportAssignment | undefined { while (nodeOnRightSide.parent.kind === SyntaxKind.QualifiedName) { - nodeOnRightSide = nodeOnRightSide.parent as QualifiedName; + nodeOnRightSide = nodeOnRightSide.parent; } if (nodeOnRightSide.parent.kind === SyntaxKind.ImportEqualsDeclaration) { - return (nodeOnRightSide.parent as ImportEqualsDeclaration).moduleReference === nodeOnRightSide ? nodeOnRightSide.parent as ImportEqualsDeclaration : undefined; + return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined; } if (nodeOnRightSide.parent.kind === SyntaxKind.ExportAssignment) { - return (nodeOnRightSide.parent as ExportAssignment).expression === nodeOnRightSide as Node ? nodeOnRightSide.parent as ExportAssignment : undefined; + return nodeOnRightSide.parent.expression === nodeOnRightSide as Node ? nodeOnRightSide.parent : undefined; } return undefined; @@ -46608,8 +46610,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node = parent; parent = parent.parent; } - if (parent && parent.kind === SyntaxKind.ImportType && (parent as ImportTypeNode).qualifier === node) { - return parent as ImportTypeNode; + if (parent && parent.kind === SyntaxKind.ImportType && parent.qualifier === node) { + return parent; } return undefined; } @@ -46639,7 +46641,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { name.parent === (name.parent.parent as BinaryExpression).left ) { // Check if this is a special property assignment - if (!isPrivateIdentifier(name) && !isJSDocMemberName(name) && !isThisPropertyAndThisTyped(name.parent as PropertyAccessExpression)) { + if (!isPrivateIdentifier(name) && !isJSDocMemberName(name) && !isThisPropertyAndThisTyped(name.parent)) { const specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name); if (specialPropertyAssignmentSymbol) { return specialPropertyAssignmentSymbol; @@ -46698,7 +46700,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (name.parent.kind === SyntaxKind.JSDocParameterTag) { - return getParameterSymbolFromJSDoc(name.parent as JSDocParameterTag); + return getParameterSymbolFromJSDoc(name.parent); } if (name.parent.kind === SyntaxKind.TypeParameter && name.parent.parent.kind === SyntaxKind.JSDocTemplateTag) { @@ -46855,8 +46857,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (node.kind === SyntaxKind.Identifier) { - if (isInRightSideOfImportOrExportAssignment(node as Identifier)) { - return getSymbolOfNameOrPropertyAccessExpression(node as Identifier); + if (isInRightSideOfImportOrExportAssignment(node)) { + return getSymbolOfNameOrPropertyAccessExpression(node); } else if ( parent.kind === SyntaxKind.BindingElement && @@ -46864,14 +46866,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { node === (parent as BindingElement).propertyName ) { const typeOfPattern = getTypeOfNode(grandParent); - const propertyDeclaration = getPropertyOfType(typeOfPattern, (node as Identifier).escapedText); + const propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText); if (propertyDeclaration) { return propertyDeclaration; } } else if (isMetaProperty(parent) && parent.name === node) { - if (parent.keywordToken === SyntaxKind.NewKeyword && idText(node as Identifier) === "target") { + if (parent.keywordToken === SyntaxKind.NewKeyword && idText(node) === "target") { // `target` in `new.target` return checkNewTargetMetaProperty(parent).symbol; } @@ -46879,7 +46881,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // we have a fake expression type made for other reasons already, whose transient `meta` // member should more exactly be the kind of (declarationless) symbol we want. // (See #44364 and #45031 for relevant implementation PRs) - if (parent.keywordToken === SyntaxKind.ImportKeyword && idText(node as Identifier) === "meta") { + if (parent.keywordToken === SyntaxKind.ImportKeyword && idText(node) === "meta") { return getGlobalImportMetaExpressionType().members!.get("meta" as __String); } // no other meta properties are valid syntax, thus no others should have symbols @@ -46999,7 +47001,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined { if (location && location.kind === SyntaxKind.ShorthandPropertyAssignment) { - return resolveEntityName((location as ShorthandPropertyAssignment).name, SymbolFlags.Value | SymbolFlags.Alias); + return resolveEntityName(location.name, SymbolFlags.Value | SymbolFlags.Alias); } return undefined; } @@ -47104,13 +47106,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // for ( { a } of elems) { // } if (expr.parent.kind === SyntaxKind.ForOfStatement) { - const iteratedType = checkRightHandSideOfForOf(expr.parent as ForOfStatement); + const iteratedType = checkRightHandSideOfForOf(expr.parent); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from "for" initializer // for ({a } = elems[0];.....) { } if (expr.parent.kind === SyntaxKind.BinaryExpression) { - const iteratedType = getTypeOfExpression((expr.parent as BinaryExpression).right); + const iteratedType = getTypeOfExpression(expr.parent.right); return checkDestructuringAssignment(expr, iteratedType || errorType); } // If this is from nested object binding pattern @@ -47294,7 +47296,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { if (parentSymbol.flags & SymbolFlags.ValueModule && parentSymbol.valueDeclaration?.kind === SyntaxKind.SourceFile) { - const symbolFile = parentSymbol.valueDeclaration as SourceFile; + const symbolFile = parentSymbol.valueDeclaration; const referenceFile = getSourceFileOfNode(node); // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined. const symbolIsUmdExport = symbolFile !== referenceFile; @@ -47411,22 +47413,22 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { Debug.assert(canCollectSymbolAliasAccessabilityData); switch (node.kind) { case SyntaxKind.ImportEqualsDeclaration: - return isAliasResolvedToValue(getSymbolOfDeclaration(node as ImportEqualsDeclaration)); + return isAliasResolvedToValue(getSymbolOfDeclaration(node)); case SyntaxKind.ImportClause: case SyntaxKind.NamespaceImport: case SyntaxKind.ImportSpecifier: case SyntaxKind.ExportSpecifier: - const symbol = getSymbolOfDeclaration(node as ImportClause | NamespaceImport | ImportSpecifier | ExportSpecifier); + const symbol = getSymbolOfDeclaration(node); return !!symbol && isAliasResolvedToValue(symbol, /*excludeTypeOnlyValues*/ true); case SyntaxKind.ExportDeclaration: - const exportClause = (node as ExportDeclaration).exportClause; + const exportClause = node.exportClause; return !!exportClause && ( isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration) ); case SyntaxKind.ExportAssignment: - return (node as ExportAssignment).expression && (node as ExportAssignment).expression.kind === SyntaxKind.Identifier ? - isAliasResolvedToValue(getSymbolOfDeclaration(node as ExportAssignment)) : + return node.expression && node.expression.kind === SyntaxKind.Identifier ? + isAliasResolvedToValue(getSymbolOfDeclaration(node)) : true; } return false; @@ -49110,8 +49112,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return false; } - const computedPropertyName = node as ComputedPropertyName; - if (computedPropertyName.expression.kind === SyntaxKind.BinaryExpression && (computedPropertyName.expression as BinaryExpression).operatorToken.kind === SyntaxKind.CommaToken) { + const computedPropertyName = node; + if (computedPropertyName.expression.kind === SyntaxKind.BinaryExpression && computedPropertyName.expression.operatorToken.kind === SyntaxKind.CommaToken) { return grammarErrorOnNode(computedPropertyName.expression, Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } return false; @@ -49358,7 +49360,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (forInOrOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList) { - const variableList = forInOrOfStatement.initializer as VariableDeclarationList; + const variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { const declarations = variableList.declarations; @@ -49476,7 +49478,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } switch (parent.kind) { case SyntaxKind.VariableDeclaration: - const decl = parent as VariableDeclaration; + const decl = parent; if (decl.name.kind !== SyntaxKind.Identifier) { return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name); } @@ -49484,7 +49486,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return grammarErrorOnNode(node, Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement); } if (!(decl.parent.flags & NodeFlags.Const)) { - return grammarErrorOnNode((parent as VariableDeclaration).name, Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); + return grammarErrorOnNode(parent.name, Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const); } break; @@ -49493,13 +49495,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { !isStatic(parent) || !hasEffectiveReadonlyModifier(parent) ) { - return grammarErrorOnNode((parent as PropertyDeclaration).name, Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); + return grammarErrorOnNode(parent.name, Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly); } break; case SyntaxKind.PropertySignature: if (!hasSyntacticModifier(parent, ModifierFlags.Readonly)) { - return grammarErrorOnNode((parent as PropertySignature).name, Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); + return grammarErrorOnNode(parent.name, Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly); } break; @@ -49579,11 +49581,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { switch (current.kind) { case SyntaxKind.LabeledStatement: - if (node.label && (current as LabeledStatement).label.escapedText === node.label.escapedText) { + if (node.label && current.label.escapedText === node.label.escapedText) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements const isMisplacedContinueLabel = node.kind === SyntaxKind.ContinueStatement - && !isIterationStatement((current as LabeledStatement).statement, /*lookInLabeledStatements*/ true); + && !isIterationStatement(current.statement, /*lookInLabeledStatements*/ true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); @@ -49645,14 +49647,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function isStringOrNumberLiteralExpression(expr: Expression) { return isStringOrNumericLiteralLike(expr) || - expr.kind === SyntaxKind.PrefixUnaryExpression && (expr as PrefixUnaryExpression).operator === SyntaxKind.MinusToken && - (expr as PrefixUnaryExpression).operand.kind === SyntaxKind.NumericLiteral; + expr.kind === SyntaxKind.PrefixUnaryExpression && expr.operator === SyntaxKind.MinusToken && + expr.operand.kind === SyntaxKind.NumericLiteral; } function isBigIntLiteralExpression(expr: Expression) { return expr.kind === SyntaxKind.BigIntLiteral || - expr.kind === SyntaxKind.PrefixUnaryExpression && (expr as PrefixUnaryExpression).operator === SyntaxKind.MinusToken && - (expr as PrefixUnaryExpression).operand.kind === SyntaxKind.BigIntLiteral; + expr.kind === SyntaxKind.PrefixUnaryExpression && expr.operator === SyntaxKind.MinusToken && + expr.operand.kind === SyntaxKind.BigIntLiteral; } function isSimpleLiteralEnumReference(expr: Expression) { @@ -50044,7 +50046,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Realism (size) checking // We should test against `getTextOfNode(node)` rather than `node.text`, because `node.text` for large numeric literals can contain "." // e.g. `node.text` for numeric literal `1100000000000000000000` is `1.1e21`. - const isFractional = getTextOfNode(node).includes("."); + const isFractional = getTextOfNodenode.includes("."); const isScientific = node.numericLiteralFlags & TokenFlags.Scientific; // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 463651bdb0049..29b39bb2a9c26 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -323,7 +323,7 @@ import { ModuleKind, ModuleReference, moveRangePastModifiers, - NamedDeclaration, + NamedDeclarationBase, NamedExports, NamedImports, NamedImportsOrExports, @@ -369,6 +369,7 @@ import { PropertyAssignment, PropertyDeclaration, PropertySignature, + PseudoLiteralToken, QualifiedName, rangeEndIsOnSameLineAsRangeStart, rangeEndPositionsAreOnSameLine, @@ -407,7 +408,6 @@ import { SpreadElement, stableSort, Statement, - StringLiteral, supportedJSExtensionsFlat, SwitchStatement, Symbol, @@ -967,7 +967,7 @@ export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFi function collectLinkedAliases(node: Node) { if (isExportAssignment(node)) { if (node.expression.kind === SyntaxKind.Identifier) { - resolver.collectLinkedAliases(node.expression as Identifier, /*setVisibility*/ true); + resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true); } return; } @@ -1482,11 +1482,11 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri } switch (node.kind) { case SyntaxKind.SourceFile: - return printFile(node as SourceFile); + return printFile(node); case SyntaxKind.Bundle: - return printBundle(node as Bundle); + return printBundle(node); case SyntaxKind.UnparsedSource: - return printUnparsedSource(node as UnparsedSource); + return printUnparsedSource(node); } writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); @@ -1858,218 +1858,218 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri case SyntaxKind.TemplateHead: case SyntaxKind.TemplateMiddle: case SyntaxKind.TemplateTail: - return emitLiteral(node as LiteralExpression, /*jsxAttributeEscape*/ false); + return emitLiteral(node, /*jsxAttributeEscape*/ false); // Identifiers case SyntaxKind.Identifier: - return emitIdentifier(node as Identifier); + return emitIdentifier(node); // PrivateIdentifiers case SyntaxKind.PrivateIdentifier: - return emitPrivateIdentifier(node as PrivateIdentifier); + return emitPrivateIdentifier(node); // Parse tree nodes // Names case SyntaxKind.QualifiedName: - return emitQualifiedName(node as QualifiedName); + return emitQualifiedName(node); case SyntaxKind.ComputedPropertyName: - return emitComputedPropertyName(node as ComputedPropertyName); + return emitComputedPropertyName(node); // Signature elements case SyntaxKind.TypeParameter: - return emitTypeParameter(node as TypeParameterDeclaration); + return emitTypeParameter(node); case SyntaxKind.Parameter: - return emitParameter(node as ParameterDeclaration); + return emitParameter(node); case SyntaxKind.Decorator: - return emitDecorator(node as Decorator); + return emitDecorator(node); // Type members case SyntaxKind.PropertySignature: - return emitPropertySignature(node as PropertySignature); + return emitPropertySignature(node); case SyntaxKind.PropertyDeclaration: - return emitPropertyDeclaration(node as PropertyDeclaration); + return emitPropertyDeclaration(node); case SyntaxKind.MethodSignature: - return emitMethodSignature(node as MethodSignature); + return emitMethodSignature(node); case SyntaxKind.MethodDeclaration: - return emitMethodDeclaration(node as MethodDeclaration); + return emitMethodDeclaration(node); case SyntaxKind.ClassStaticBlockDeclaration: - return emitClassStaticBlockDeclaration(node as ClassStaticBlockDeclaration); + return emitClassStaticBlockDeclaration(node); case SyntaxKind.Constructor: - return emitConstructor(node as ConstructorDeclaration); + return emitConstructor(node); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return emitAccessorDeclaration(node as AccessorDeclaration); + return emitAccessorDeclaration(node); case SyntaxKind.CallSignature: - return emitCallSignature(node as CallSignatureDeclaration); + return emitCallSignature(node); case SyntaxKind.ConstructSignature: - return emitConstructSignature(node as ConstructSignatureDeclaration); + return emitConstructSignature(node); case SyntaxKind.IndexSignature: - return emitIndexSignature(node as IndexSignatureDeclaration); + return emitIndexSignature(node); // Types case SyntaxKind.TypePredicate: - return emitTypePredicate(node as TypePredicateNode); + return emitTypePredicate(node); case SyntaxKind.TypeReference: - return emitTypeReference(node as TypeReferenceNode); + return emitTypeReference(node); case SyntaxKind.FunctionType: - return emitFunctionType(node as FunctionTypeNode); + return emitFunctionType(node); case SyntaxKind.ConstructorType: - return emitConstructorType(node as ConstructorTypeNode); + return emitConstructorType(node); case SyntaxKind.TypeQuery: - return emitTypeQuery(node as TypeQueryNode); + return emitTypeQuery(node); case SyntaxKind.TypeLiteral: - return emitTypeLiteral(node as TypeLiteralNode); + return emitTypeLiteral(node); case SyntaxKind.ArrayType: - return emitArrayType(node as ArrayTypeNode); + return emitArrayType(node); case SyntaxKind.TupleType: - return emitTupleType(node as TupleTypeNode); + return emitTupleType(node); case SyntaxKind.OptionalType: - return emitOptionalType(node as OptionalTypeNode); + return emitOptionalType(node); // SyntaxKind.RestType is handled below case SyntaxKind.UnionType: - return emitUnionType(node as UnionTypeNode); + return emitUnionType(node); case SyntaxKind.IntersectionType: - return emitIntersectionType(node as IntersectionTypeNode); + return emitIntersectionType(node); case SyntaxKind.ConditionalType: - return emitConditionalType(node as ConditionalTypeNode); + return emitConditionalType(node); case SyntaxKind.InferType: - return emitInferType(node as InferTypeNode); + return emitInferType(node); case SyntaxKind.ParenthesizedType: - return emitParenthesizedType(node as ParenthesizedTypeNode); + return emitParenthesizedType(node); case SyntaxKind.ExpressionWithTypeArguments: - return emitExpressionWithTypeArguments(node as ExpressionWithTypeArguments); + return emitExpressionWithTypeArguments(node); case SyntaxKind.ThisType: return emitThisType(); case SyntaxKind.TypeOperator: - return emitTypeOperator(node as TypeOperatorNode); + return emitTypeOperator(node); case SyntaxKind.IndexedAccessType: - return emitIndexedAccessType(node as IndexedAccessTypeNode); + return emitIndexedAccessType(node); case SyntaxKind.MappedType: - return emitMappedType(node as MappedTypeNode); + return emitMappedType(node); case SyntaxKind.LiteralType: - return emitLiteralType(node as LiteralTypeNode); + return emitLiteralType(node); case SyntaxKind.NamedTupleMember: - return emitNamedTupleMember(node as NamedTupleMember); + return emitNamedTupleMember(node); case SyntaxKind.TemplateLiteralType: - return emitTemplateType(node as TemplateLiteralTypeNode); + return emitTemplateType(node); case SyntaxKind.TemplateLiteralTypeSpan: - return emitTemplateTypeSpan(node as TemplateLiteralTypeSpan); + return emitTemplateTypeSpan(node); case SyntaxKind.ImportType: - return emitImportTypeNode(node as ImportTypeNode); + return emitImportTypeNode(node); // Binding patterns case SyntaxKind.ObjectBindingPattern: - return emitObjectBindingPattern(node as ObjectBindingPattern); + return emitObjectBindingPattern(node); case SyntaxKind.ArrayBindingPattern: - return emitArrayBindingPattern(node as ArrayBindingPattern); + return emitArrayBindingPattern(node); case SyntaxKind.BindingElement: - return emitBindingElement(node as BindingElement); + return emitBindingElement(node); // Misc case SyntaxKind.TemplateSpan: - return emitTemplateSpan(node as TemplateSpan); + return emitTemplateSpan(node); case SyntaxKind.SemicolonClassElement: return emitSemicolonClassElement(); // Statements case SyntaxKind.Block: - return emitBlock(node as Block); + return emitBlock(node); case SyntaxKind.VariableStatement: - return emitVariableStatement(node as VariableStatement); + return emitVariableStatement(node); case SyntaxKind.EmptyStatement: return emitEmptyStatement(/*isEmbeddedStatement*/ false); case SyntaxKind.ExpressionStatement: - return emitExpressionStatement(node as ExpressionStatement); + return emitExpressionStatement(node); case SyntaxKind.IfStatement: - return emitIfStatement(node as IfStatement); + return emitIfStatement(node); case SyntaxKind.DoStatement: - return emitDoStatement(node as DoStatement); + return emitDoStatement(node); case SyntaxKind.WhileStatement: - return emitWhileStatement(node as WhileStatement); + return emitWhileStatement(node); case SyntaxKind.ForStatement: - return emitForStatement(node as ForStatement); + return emitForStatement(node); case SyntaxKind.ForInStatement: - return emitForInStatement(node as ForInStatement); + return emitForInStatement(node); case SyntaxKind.ForOfStatement: - return emitForOfStatement(node as ForOfStatement); + return emitForOfStatement(node); case SyntaxKind.ContinueStatement: - return emitContinueStatement(node as ContinueStatement); + return emitContinueStatement(node); case SyntaxKind.BreakStatement: - return emitBreakStatement(node as BreakStatement); + return emitBreakStatement(node); case SyntaxKind.ReturnStatement: - return emitReturnStatement(node as ReturnStatement); + return emitReturnStatement(node); case SyntaxKind.WithStatement: - return emitWithStatement(node as WithStatement); + return emitWithStatement(node); case SyntaxKind.SwitchStatement: - return emitSwitchStatement(node as SwitchStatement); + return emitSwitchStatement(node); case SyntaxKind.LabeledStatement: - return emitLabeledStatement(node as LabeledStatement); + return emitLabeledStatement(node); case SyntaxKind.ThrowStatement: - return emitThrowStatement(node as ThrowStatement); + return emitThrowStatement(node); case SyntaxKind.TryStatement: - return emitTryStatement(node as TryStatement); + return emitTryStatement(node); case SyntaxKind.DebuggerStatement: - return emitDebuggerStatement(node as DebuggerStatement); + return emitDebuggerStatement(node); // Declarations case SyntaxKind.VariableDeclaration: - return emitVariableDeclaration(node as VariableDeclaration); + return emitVariableDeclaration(node); case SyntaxKind.VariableDeclarationList: - return emitVariableDeclarationList(node as VariableDeclarationList); + return emitVariableDeclarationList(node); case SyntaxKind.FunctionDeclaration: - return emitFunctionDeclaration(node as FunctionDeclaration); + return emitFunctionDeclaration(node); case SyntaxKind.ClassDeclaration: - return emitClassDeclaration(node as ClassDeclaration); + return emitClassDeclaration(node); case SyntaxKind.InterfaceDeclaration: - return emitInterfaceDeclaration(node as InterfaceDeclaration); + return emitInterfaceDeclaration(node); case SyntaxKind.TypeAliasDeclaration: - return emitTypeAliasDeclaration(node as TypeAliasDeclaration); + return emitTypeAliasDeclaration(node); case SyntaxKind.EnumDeclaration: - return emitEnumDeclaration(node as EnumDeclaration); + return emitEnumDeclaration(node); case SyntaxKind.ModuleDeclaration: - return emitModuleDeclaration(node as ModuleDeclaration); + return emitModuleDeclaration(node); case SyntaxKind.ModuleBlock: - return emitModuleBlock(node as ModuleBlock); + return emitModuleBlock(node); case SyntaxKind.CaseBlock: - return emitCaseBlock(node as CaseBlock); + return emitCaseBlock(node); case SyntaxKind.NamespaceExportDeclaration: - return emitNamespaceExportDeclaration(node as NamespaceExportDeclaration); + return emitNamespaceExportDeclaration(node); case SyntaxKind.ImportEqualsDeclaration: - return emitImportEqualsDeclaration(node as ImportEqualsDeclaration); + return emitImportEqualsDeclaration(node); case SyntaxKind.ImportDeclaration: - return emitImportDeclaration(node as ImportDeclaration); + return emitImportDeclaration(node); case SyntaxKind.ImportClause: - return emitImportClause(node as ImportClause); + return emitImportClause(node); case SyntaxKind.NamespaceImport: - return emitNamespaceImport(node as NamespaceImport); + return emitNamespaceImport(node); case SyntaxKind.NamespaceExport: - return emitNamespaceExport(node as NamespaceExport); + return emitNamespaceExport(node); case SyntaxKind.NamedImports: - return emitNamedImports(node as NamedImports); + return emitNamedImports(node); case SyntaxKind.ImportSpecifier: - return emitImportSpecifier(node as ImportSpecifier); + return emitImportSpecifier(node); case SyntaxKind.ExportAssignment: - return emitExportAssignment(node as ExportAssignment); + return emitExportAssignment(node); case SyntaxKind.ExportDeclaration: - return emitExportDeclaration(node as ExportDeclaration); + return emitExportDeclaration(node); case SyntaxKind.NamedExports: - return emitNamedExports(node as NamedExports); + return emitNamedExports(node); case SyntaxKind.ExportSpecifier: - return emitExportSpecifier(node as ExportSpecifier); + return emitExportSpecifier(node); case SyntaxKind.ImportAttributes: - return emitImportAttributes(node as ImportAttributes); + return emitImportAttributes(node); case SyntaxKind.ImportAttribute: - return emitImportAttribute(node as ImportAttribute); + return emitImportAttribute(node); case SyntaxKind.MissingDeclaration: return; // Module references case SyntaxKind.ExternalModuleReference: - return emitExternalModuleReference(node as ExternalModuleReference); + return emitExternalModuleReference(node); // JSX (non-expression) case SyntaxKind.JsxText: - return emitJsxText(node as JsxText); + return emitJsxText(node); case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxOpeningFragment: return emitJsxOpeningElementOrFragment(node as JsxOpeningElement); @@ -2077,37 +2077,37 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri case SyntaxKind.JsxClosingFragment: return emitJsxClosingElementOrFragment(node as JsxClosingElement); case SyntaxKind.JsxAttribute: - return emitJsxAttribute(node as JsxAttribute); + return emitJsxAttribute(node); case SyntaxKind.JsxAttributes: - return emitJsxAttributes(node as JsxAttributes); + return emitJsxAttributes(node); case SyntaxKind.JsxSpreadAttribute: - return emitJsxSpreadAttribute(node as JsxSpreadAttribute); + return emitJsxSpreadAttribute(node); case SyntaxKind.JsxExpression: - return emitJsxExpression(node as JsxExpression); + return emitJsxExpression(node); case SyntaxKind.JsxNamespacedName: - return emitJsxNamespacedName(node as JsxNamespacedName); + return emitJsxNamespacedName(node); // Clauses case SyntaxKind.CaseClause: - return emitCaseClause(node as CaseClause); + return emitCaseClause(node); case SyntaxKind.DefaultClause: - return emitDefaultClause(node as DefaultClause); + return emitDefaultClause(node); case SyntaxKind.HeritageClause: - return emitHeritageClause(node as HeritageClause); + return emitHeritageClause(node); case SyntaxKind.CatchClause: - return emitCatchClause(node as CatchClause); + return emitCatchClause(node); // Property assignments case SyntaxKind.PropertyAssignment: - return emitPropertyAssignment(node as PropertyAssignment); + return emitPropertyAssignment(node); case SyntaxKind.ShorthandPropertyAssignment: - return emitShorthandPropertyAssignment(node as ShorthandPropertyAssignment); + return emitShorthandPropertyAssignment(node); case SyntaxKind.SpreadAssignment: - return emitSpreadAssignment(node as SpreadAssignment); + return emitSpreadAssignment(node); // Enum case SyntaxKind.EnumMember: - return emitEnumMember(node as EnumMember); + return emitEnumMember(node); // Unparsed case SyntaxKind.UnparsedPrologue: @@ -2117,13 +2117,13 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri return emitUnparsedSourceOrPrepend(node as UnparsedSource); case SyntaxKind.UnparsedText: case SyntaxKind.UnparsedInternalText: - return emitUnparsedTextLike(node as UnparsedTextLike); + return emitUnparsedTextLike(node); case SyntaxKind.UnparsedSyntheticReference: - return emitUnparsedSyntheticReference(node as UnparsedSyntheticReference); + return emitUnparsedSyntheticReference(node); // Top-level nodes case SyntaxKind.SourceFile: - return emitSourceFile(node as SourceFile); + return emitSourceFile(node); case SyntaxKind.Bundle: return Debug.fail("Bundles should be printed using printBundle"); // SyntaxKind.UnparsedSource (handled above) @@ -2132,39 +2132,39 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri // JSDoc nodes (only used in codefixes currently) case SyntaxKind.JSDocTypeExpression: - return emitJSDocTypeExpression(node as JSDocTypeExpression); + return emitJSDocTypeExpression(node); case SyntaxKind.JSDocNameReference: - return emitJSDocNameReference(node as JSDocNameReference); + return emitJSDocNameReference(node); case SyntaxKind.JSDocAllType: return writePunctuation("*"); case SyntaxKind.JSDocUnknownType: return writePunctuation("?"); case SyntaxKind.JSDocNullableType: - return emitJSDocNullableType(node as JSDocNullableType); + return emitJSDocNullableType(node); case SyntaxKind.JSDocNonNullableType: - return emitJSDocNonNullableType(node as JSDocNonNullableType); + return emitJSDocNonNullableType(node); case SyntaxKind.JSDocOptionalType: - return emitJSDocOptionalType(node as JSDocOptionalType); + return emitJSDocOptionalType(node); case SyntaxKind.JSDocFunctionType: - return emitJSDocFunctionType(node as JSDocFunctionType); + return emitJSDocFunctionType(node); case SyntaxKind.RestType: case SyntaxKind.JSDocVariadicType: - return emitRestOrJSDocVariadicType(node as RestTypeNode | JSDocVariadicType); + return emitRestOrJSDocVariadicType(node); case SyntaxKind.JSDocNamepathType: return; case SyntaxKind.JSDoc: - return emitJSDoc(node as JSDoc); + return emitJSDoc(node); case SyntaxKind.JSDocTypeLiteral: - return emitJSDocTypeLiteral(node as JSDocTypeLiteral); + return emitJSDocTypeLiteral(node); case SyntaxKind.JSDocSignature: - return emitJSDocSignature(node as JSDocSignature); + return emitJSDocSignature(node); case SyntaxKind.JSDocTag: case SyntaxKind.JSDocClassTag: case SyntaxKind.JSDocOverrideTag: return emitJSDocSimpleTag(node as JSDocTag); case SyntaxKind.JSDocAugmentsTag: case SyntaxKind.JSDocImplementsTag: - return emitJSDocHeritageTag(node as JSDocImplementsTag | JSDocAugmentsTag); + return emitJSDocHeritageTag(node); case SyntaxKind.JSDocAuthorTag: case SyntaxKind.JSDocDeprecatedTag: return; @@ -2175,9 +2175,9 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri case SyntaxKind.JSDocReadonlyTag: return; case SyntaxKind.JSDocCallbackTag: - return emitJSDocCallbackTag(node as JSDocCallbackTag); + return emitJSDocCallbackTag(node); case SyntaxKind.JSDocOverloadTag: - return emitJSDocOverloadTag(node as JSDocOverloadTag); + return emitJSDocOverloadTag(node); // SyntaxKind.JSDocEnumTag (see below) case SyntaxKind.JSDocParameterTag: case SyntaxKind.JSDocPropertyTag: @@ -2190,11 +2190,11 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri case SyntaxKind.JSDocSatisfiesTag: return emitJSDocSimpleTypedTag(node as JSDocTypeTag | JSDocReturnTag | JSDocThisTag | JSDocTypeTag | JSDocThrowsTag | JSDocSatisfiesTag); case SyntaxKind.JSDocTemplateTag: - return emitJSDocTemplateTag(node as JSDocTemplateTag); + return emitJSDocTemplateTag(node); case SyntaxKind.JSDocTypedefTag: - return emitJSDocTypedefTag(node as JSDocTypedefTag); + return emitJSDocTypedefTag(node); case SyntaxKind.JSDocSeeTag: - return emitJSDocSeeTag(node as JSDocSeeTag); + return emitJSDocSeeTag(node); // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) // Transformation nodes @@ -2219,78 +2219,79 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri // Literals case SyntaxKind.NumericLiteral: case SyntaxKind.BigIntLiteral: - return emitNumericOrBigIntLiteral(node as NumericLiteral | BigIntLiteral); + node.kind; + return emitNumericOrBigIntLiteral(node); case SyntaxKind.StringLiteral: case SyntaxKind.RegularExpressionLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: - return emitLiteral(node as LiteralExpression, /*jsxAttributeEscape*/ false); + return emitLiteral(node, /*jsxAttributeEscape*/ false); // Identifiers case SyntaxKind.Identifier: - return emitIdentifier(node as Identifier); + return emitIdentifier(node); case SyntaxKind.PrivateIdentifier: - return emitPrivateIdentifier(node as PrivateIdentifier); + return emitPrivateIdentifier(node); // Expressions case SyntaxKind.ArrayLiteralExpression: - return emitArrayLiteralExpression(node as ArrayLiteralExpression); + return emitArrayLiteralExpression(node); case SyntaxKind.ObjectLiteralExpression: - return emitObjectLiteralExpression(node as ObjectLiteralExpression); + return emitObjectLiteralExpression(node); case SyntaxKind.PropertyAccessExpression: - return emitPropertyAccessExpression(node as PropertyAccessExpression); + return emitPropertyAccessExpression(node); case SyntaxKind.ElementAccessExpression: - return emitElementAccessExpression(node as ElementAccessExpression); + return emitElementAccessExpression(node); case SyntaxKind.CallExpression: - return emitCallExpression(node as CallExpression); + return emitCallExpression(node); case SyntaxKind.NewExpression: - return emitNewExpression(node as NewExpression); + return emitNewExpression(node); case SyntaxKind.TaggedTemplateExpression: - return emitTaggedTemplateExpression(node as TaggedTemplateExpression); + return emitTaggedTemplateExpression(node); case SyntaxKind.TypeAssertionExpression: - return emitTypeAssertionExpression(node as TypeAssertion); + return emitTypeAssertionExpression(node); case SyntaxKind.ParenthesizedExpression: - return emitParenthesizedExpression(node as ParenthesizedExpression); + return emitParenthesizedExpression(node); case SyntaxKind.FunctionExpression: - return emitFunctionExpression(node as FunctionExpression); + return emitFunctionExpression(node); case SyntaxKind.ArrowFunction: - return emitArrowFunction(node as ArrowFunction); + return emitArrowFunction(node); case SyntaxKind.DeleteExpression: - return emitDeleteExpression(node as DeleteExpression); + return emitDeleteExpression(node); case SyntaxKind.TypeOfExpression: - return emitTypeOfExpression(node as TypeOfExpression); + return emitTypeOfExpression(node); case SyntaxKind.VoidExpression: - return emitVoidExpression(node as VoidExpression); + return emitVoidExpression(node); case SyntaxKind.AwaitExpression: - return emitAwaitExpression(node as AwaitExpression); + return emitAwaitExpression(node); case SyntaxKind.PrefixUnaryExpression: - return emitPrefixUnaryExpression(node as PrefixUnaryExpression); + return emitPrefixUnaryExpression(node); case SyntaxKind.PostfixUnaryExpression: - return emitPostfixUnaryExpression(node as PostfixUnaryExpression); + return emitPostfixUnaryExpression(node); case SyntaxKind.BinaryExpression: - return emitBinaryExpression(node as BinaryExpression); + return emitBinaryExpression(node); case SyntaxKind.ConditionalExpression: - return emitConditionalExpression(node as ConditionalExpression); + return emitConditionalExpression(node); case SyntaxKind.TemplateExpression: - return emitTemplateExpression(node as TemplateExpression); + return emitTemplateExpression(node); case SyntaxKind.YieldExpression: - return emitYieldExpression(node as YieldExpression); + return emitYieldExpression(node); case SyntaxKind.SpreadElement: - return emitSpreadElement(node as SpreadElement); + return emitSpreadElement(node); case SyntaxKind.ClassExpression: - return emitClassExpression(node as ClassExpression); + return emitClassExpression(node); case SyntaxKind.OmittedExpression: return; case SyntaxKind.AsExpression: - return emitAsExpression(node as AsExpression); + return emitAsExpression(node); case SyntaxKind.NonNullExpression: - return emitNonNullExpression(node as NonNullExpression); + return emitNonNullExpression(node); case SyntaxKind.ExpressionWithTypeArguments: - return emitExpressionWithTypeArguments(node as ExpressionWithTypeArguments); + return emitExpressionWithTypeArguments(node); case SyntaxKind.SatisfiesExpression: - return emitSatisfiesExpression(node as SatisfiesExpression); + return emitSatisfiesExpression(node); case SyntaxKind.MetaProperty: - return emitMetaProperty(node as MetaProperty); + return emitMetaProperty(node); case SyntaxKind.SyntheticExpression: return Debug.fail("SyntheticExpression should never be printed."); case SyntaxKind.MissingDeclaration: @@ -2298,11 +2299,11 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri // JSX case SyntaxKind.JsxElement: - return emitJsxElement(node as JsxElement); + return emitJsxElement(node); case SyntaxKind.JsxSelfClosingElement: - return emitJsxSelfClosingElement(node as JsxSelfClosingElement); + return emitJsxSelfClosingElement(node); case SyntaxKind.JsxFragment: - return emitJsxFragment(node as JsxFragment); + return emitJsxFragment(node); // Synthesized list case SyntaxKind.SyntaxList: @@ -2312,9 +2313,9 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri case SyntaxKind.NotEmittedStatement: return; case SyntaxKind.PartiallyEmittedExpression: - return emitPartiallyEmittedExpression(node as PartiallyEmittedExpression); + return emitPartiallyEmittedExpression(node); case SyntaxKind.CommaListExpression: - return emitCommaList(node as CommaListExpression); + return emitCommaList(node); case SyntaxKind.SyntheticReferenceExpression: return Debug.fail("SyntheticReferenceExpression should not be printed"); } @@ -2363,7 +2364,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri function emitHelpers(node: Node) { let helpersEmitted = false; - const bundle = node.kind === SyntaxKind.Bundle ? node as Bundle : undefined; + const bundle = node.kind === SyntaxKind.Bundle ? node : undefined; if (bundle && moduleKind === ModuleKind.None) { return; } @@ -2428,13 +2429,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri emitLiteral(node, /*jsxAttributeEscape*/ false); } - // SyntaxKind.StringLiteral - // SyntaxKind.RegularExpressionLiteral - // SyntaxKind.NoSubstitutionTemplateLiteral - // SyntaxKind.TemplateHead - // SyntaxKind.TemplateMiddle - // SyntaxKind.TemplateTail - function emitLiteral(node: LiteralLikeNode, jsxAttributeEscape: boolean) { + function emitLiteral(node: PseudoLiteralToken | LiteralLikeNode, jsxAttributeEscape: boolean) { const text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape); if ( (printerOptions.sourceMap || printerOptions.inlineSourceMap) @@ -3063,7 +3058,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri expression = skipPartiallyEmittedExpressions(expression); if (isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot - const text = getLiteralTextOfNode(expression as LiteralExpression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false); + const text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false); // If the number will be printed verbatim and it doesn't already contain a dot or an exponent indicator, add one // if the expression doesn't have any comments that will be emitted. return !(expression.numericLiteralFlags & TokenFlags.WithSpecifier) @@ -3211,8 +3206,8 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri // The same is true of minus of course. const operand = node.operand; return operand.kind === SyntaxKind.PrefixUnaryExpression - && ((node.operator === SyntaxKind.PlusToken && ((operand as PrefixUnaryExpression).operator === SyntaxKind.PlusToken || (operand as PrefixUnaryExpression).operator === SyntaxKind.PlusPlusToken)) - || (node.operator === SyntaxKind.MinusToken && ((operand as PrefixUnaryExpression).operator === SyntaxKind.MinusToken || (operand as PrefixUnaryExpression).operator === SyntaxKind.MinusMinusToken))); + && ((node.operator === SyntaxKind.PlusToken && (operand.operator === SyntaxKind.PlusToken || operand.operator === SyntaxKind.PlusPlusToken)) + || (node.operator === SyntaxKind.MinusToken && (operand.operator === SyntaxKind.MinusToken || operand.operator === SyntaxKind.MinusMinusToken))); } function emitPostfixUnaryExpression(node: PostfixUnaryExpression) { @@ -5585,7 +5580,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri function skipSynthesizedParentheses(node: Node) { while (node.kind === SyntaxKind.ParenthesizedExpression && nodeIsSynthesized(node)) { - node = (node as ParenthesizedExpression).expression; + node = node.expression; } return node; @@ -5613,15 +5608,16 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri else { Debug.assertNode(node, isLiteralExpression); // not strictly necessary if (!canUseSourceFile) { + // @ts-expect-error -- ?! return node.text; } } return getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node: LiteralLikeNode, neverAsciiEscape: boolean | undefined, jsxAttributeEscape: boolean): string { - if (node.kind === SyntaxKind.StringLiteral && (node as StringLiteral).textSourceNode) { - const textSourceNode = (node as StringLiteral).textSourceNode!; + function getLiteralTextOfNode(node: PseudoLiteralToken | LiteralLikeNode, neverAsciiEscape: boolean | undefined, jsxAttributeEscape: boolean): string { + if (node.kind === SyntaxKind.StringLiteral && node.textSourceNode) { + const textSourceNode = node.textSourceNode; if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode) || isJsxNamespacedName(textSourceNode)) { const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode); return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : @@ -5703,17 +5699,17 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri if (!node) return; switch (node.kind) { case SyntaxKind.Block: - forEach((node as Block).statements, generateNames); + forEach(node.statements, generateNames); break; case SyntaxKind.LabeledStatement: case SyntaxKind.WithStatement: case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: - generateNames((node as LabeledStatement | WithStatement | DoStatement | WhileStatement).statement); + generateNames(node.statement); break; case SyntaxKind.IfStatement: - generateNames((node as IfStatement).thenStatement); - generateNames((node as IfStatement).elseStatement); + generateNames(node.thenStatement); + generateNames(node.elseStatement); break; case SyntaxKind.ForStatement: case SyntaxKind.ForOfStatement: @@ -5722,41 +5718,41 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri generateNames((node as ForStatement | ForInOrOfStatement).statement); break; case SyntaxKind.SwitchStatement: - generateNames((node as SwitchStatement).caseBlock); + generateNames(node.caseBlock); break; case SyntaxKind.CaseBlock: - forEach((node as CaseBlock).clauses, generateNames); + forEach(node.clauses, generateNames); break; case SyntaxKind.CaseClause: case SyntaxKind.DefaultClause: forEach((node as CaseOrDefaultClause).statements, generateNames); break; case SyntaxKind.TryStatement: - generateNames((node as TryStatement).tryBlock); - generateNames((node as TryStatement).catchClause); - generateNames((node as TryStatement).finallyBlock); + generateNames(node.tryBlock); + generateNames(node.catchClause); + generateNames(node.finallyBlock); break; case SyntaxKind.CatchClause: - generateNames((node as CatchClause).variableDeclaration); - generateNames((node as CatchClause).block); + generateNames(node.variableDeclaration); + generateNames(node.block); break; case SyntaxKind.VariableStatement: - generateNames((node as VariableStatement).declarationList); + generateNames(node.declarationList); break; case SyntaxKind.VariableDeclarationList: - forEach((node as VariableDeclarationList).declarations, generateNames); + forEach(node.declarations, generateNames); break; case SyntaxKind.VariableDeclaration: case SyntaxKind.Parameter: case SyntaxKind.BindingElement: case SyntaxKind.ClassDeclaration: - generateNameIfNeeded((node as NamedDeclaration).name); + generateNameIfNeeded((node as NamedDeclarationBase).name); break; case SyntaxKind.FunctionDeclaration: - generateNameIfNeeded((node as FunctionDeclaration).name); + generateNameIfNeeded(node.name); if (getEmitFlags(node) & EmitFlags.ReuseTempVariableScope) { - forEach((node as FunctionDeclaration).parameters, generateNames); - generateNames((node as FunctionDeclaration).body); + forEach(node.parameters, generateNames); + generateNames(node.body); } break; case SyntaxKind.ObjectBindingPattern: @@ -5764,23 +5760,23 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri forEach((node as BindingPattern).elements, generateNames); break; case SyntaxKind.ImportDeclaration: - generateNames((node as ImportDeclaration).importClause); + generateNames(node.importClause); break; case SyntaxKind.ImportClause: - generateNameIfNeeded((node as ImportClause).name); - generateNames((node as ImportClause).namedBindings); + generateNameIfNeeded(node.name); + generateNames(node.namedBindings); break; case SyntaxKind.NamespaceImport: - generateNameIfNeeded((node as NamespaceImport).name); + generateNameIfNeeded(node.name); break; case SyntaxKind.NamespaceExport: - generateNameIfNeeded((node as NamespaceExport).name); + generateNameIfNeeded(node.name); break; case SyntaxKind.NamedImports: - forEach((node as NamedImports).elements, generateNames); + forEach(node.elements, generateNames); break; case SyntaxKind.ImportSpecifier: - generateNameIfNeeded((node as ImportSpecifier).propertyName || (node as ImportSpecifier).name); + generateNameIfNeeded(node.propertyName || node.name); break; } } @@ -5794,7 +5790,7 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - generateNameIfNeeded((node as NamedDeclaration).name); + generateNameIfNeeded((node as NamedDeclarationBase).name); break; } } @@ -6068,15 +6064,15 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri case SyntaxKind.ModuleDeclaration: case SyntaxKind.EnumDeclaration: Debug.assert(!prefix && !suffix && !privateName); - return generateNameForModuleOrEnum(node as ModuleDeclaration | EnumDeclaration); + return generateNameForModuleOrEnum(node); case SyntaxKind.ImportDeclaration: case SyntaxKind.ExportDeclaration: Debug.assert(!prefix && !suffix && !privateName); - return generateNameForImportOrExportDeclaration(node as ImportDeclaration | ExportDeclaration); + return generateNameForImportOrExportDeclaration(node); case SyntaxKind.FunctionDeclaration: case SyntaxKind.ClassDeclaration: { Debug.assert(!prefix && !suffix && !privateName); - const name = (node as ClassDeclaration | FunctionDeclaration).name; + const name = node.name; if (name && !isGeneratedIdentifier(name)) { return generateNameForNode(name, /*privateName*/ false, flags, prefix, suffix); } diff --git a/src/compiler/factory/baseNodeFactory.ts b/src/compiler/factory/baseNodeFactory.ts index 9ea81cdf5632b..f9a7d93e3049e 100644 --- a/src/compiler/factory/baseNodeFactory.ts +++ b/src/compiler/factory/baseNodeFactory.ts @@ -2,6 +2,8 @@ import { Node, objectAllocator, SyntaxKind, + Token, + TokenSyntaxKind, } from "../_namespaces/ts"; /** @@ -14,7 +16,7 @@ export interface BaseNodeFactory { createBaseSourceFileNode(kind: SyntaxKind.SourceFile): Node; createBaseIdentifierNode(kind: SyntaxKind.Identifier): Node; createBasePrivateIdentifierNode(kind: SyntaxKind.PrivateIdentifier): Node; - createBaseTokenNode(kind: SyntaxKind): Node; + createBaseTokenNode(kind: TokenSyntaxKind): Node; createBaseNode(kind: SyntaxKind): Node; } @@ -25,7 +27,7 @@ export interface BaseNodeFactory { */ export function createBaseNodeFactory(): BaseNodeFactory { let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node; - let TokenConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node; + let TokenConstructor: new (kind: TKind, pos: number, end: number) => Token; let IdentifierConstructor: new (kind: SyntaxKind.Identifier, pos: number, end: number) => Node; let PrivateIdentifierConstructor: new (kind: SyntaxKind.PrivateIdentifier, pos: number, end: number) => Node; let SourceFileConstructor: new (kind: SyntaxKind.SourceFile, pos: number, end: number) => Node; @@ -50,7 +52,7 @@ export function createBaseNodeFactory(): BaseNodeFactory { return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = objectAllocator.getPrivateIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1); } - function createBaseTokenNode(kind: SyntaxKind): Node { + function createBaseTokenNode(kind: TokenSyntaxKind): Node { return new (TokenConstructor || (TokenConstructor = objectAllocator.getTokenConstructor()))(kind, /*pos*/ -1, /*end*/ -1); } diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts index 6964705e9432e..cbdaed09712ba 100644 --- a/src/compiler/factory/nodeFactory.ts +++ b/src/compiler/factory/nodeFactory.ts @@ -336,6 +336,7 @@ import { NewExpression, Node, NodeArray, + NodeBase, NodeFactory, NodeFlags, nodeIsSynthesized, @@ -405,7 +406,7 @@ import { setTextRange, setTextRangePosWidth, ShorthandPropertyAssignment, - SignatureDeclarationBase, + SignatureDeclaration, singleOrUndefined, skipOuterExpressions, skipParentheses, @@ -509,26 +510,120 @@ export function addNodeFactoryPatcher(fn: (factory: NodeFactory) => void) { * * @internal */ -export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNodeFactory): NodeFactory { - const update = flags & NodeFactoryFlags.NoOriginalNode ? updateWithoutOriginal : updateWithOriginal; +export function createNodeFactory( + flags: NodeFactoryFlags, + baseFactory: BaseNodeFactory, +): NodeFactory { + const update = flags & NodeFactoryFlags.NoOriginalNode + ? updateWithoutOriginal + : updateWithOriginal; // Lazily load the parenthesizer, node converters, and some factory methods until they are used. - const parenthesizerRules = memoize(() => flags & NodeFactoryFlags.NoParenthesizerRules ? nullParenthesizerRules : createParenthesizerRules(factory)); - const converters = memoize(() => flags & NodeFactoryFlags.NoNodeConverters ? nullNodeConverters : createNodeConverters(factory)); + const parenthesizerRules = memoize(() => + flags & NodeFactoryFlags.NoParenthesizerRules + ? nullParenthesizerRules + : createParenthesizerRules(factory) + ); + const converters = memoize(() => + flags & NodeFactoryFlags.NoNodeConverters + ? nullNodeConverters + : createNodeConverters(factory) + ); // lazy initializaton of common operator factories - const getBinaryCreateFunction = memoizeOne((operator: BinaryOperator) => (left: Expression, right: Expression) => createBinaryExpression(left, operator, right)); - const getPrefixUnaryCreateFunction = memoizeOne((operator: PrefixUnaryOperator) => (operand: Expression) => createPrefixUnaryExpression(operator, operand)); - const getPostfixUnaryCreateFunction = memoizeOne((operator: PostfixUnaryOperator) => (operand: Expression) => createPostfixUnaryExpression(operand, operator)); - const getJSDocPrimaryTypeCreateFunction = memoizeOne((kind: T["kind"]) => () => createJSDocPrimaryTypeWorker(kind)); - const getJSDocUnaryTypeCreateFunction = memoizeOne((kind: T["kind"]) => (type: T["type"]) => createJSDocUnaryTypeWorker(kind, type)); - const getJSDocUnaryTypeUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, type: T["type"]) => updateJSDocUnaryTypeWorker(kind, node, type)); - const getJSDocPrePostfixUnaryTypeCreateFunction = memoizeOne((kind: T["kind"]) => (type: T["type"], postfix?: boolean) => createJSDocPrePostfixUnaryTypeWorker(kind, type, postfix)); - const getJSDocPrePostfixUnaryTypeUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, type: T["type"]) => updateJSDocPrePostfixUnaryTypeWorker(kind, node, type)); - const getJSDocSimpleTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, comment?: NodeArray) => createJSDocSimpleTagWorker(kind, tagName, comment)); - const getJSDocSimpleTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, comment?: NodeArray) => updateJSDocSimpleTagWorker(kind, node, tagName, comment)); - const getJSDocTypeLikeTagCreateFunction = memoizeOne((kind: T["kind"]) => (tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment)); - const getJSDocTypeLikeTagUpdateFunction = memoizeOne((kind: T["kind"]) => (node: T, tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: NodeArray) => updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment)); + const getBinaryCreateFunction = memoizeOne( + (operator: BinaryOperator) => (left: Expression, right: Expression) => createBinaryExpression(left, operator, right), + ); + const getPrefixUnaryCreateFunction = memoizeOne( + (operator: PrefixUnaryOperator) => (operand: Expression) => createPrefixUnaryExpression(operator, operand), + ); + const getPostfixUnaryCreateFunction = memoizeOne( + (operator: PostfixUnaryOperator) => (operand: Expression) => createPostfixUnaryExpression(operand, operator), + ); + const getJSDocPrimaryTypeCreateFunction = memoizeOne( + (kind: T["kind"]) => () => createJSDocPrimaryTypeWorker(kind), + ); + const getJSDocUnaryTypeCreateFunction = memoizeOne( + ( + kind: T["kind"], + ) => + (type: T["type"]) => createJSDocUnaryTypeWorker(kind, type), + ); + const getJSDocUnaryTypeUpdateFunction = memoizeOne( + ( + kind: T["kind"], + ) => + (node: T, type: T["type"]) => updateJSDocUnaryTypeWorker(kind, node, type), + ); + const getJSDocPrePostfixUnaryTypeCreateFunction = memoizeOne( + < + T extends JSDocType & { + readonly type: TypeNode | undefined; + readonly postfix: boolean; + }, + >( + kind: T["kind"], + ) => + (type: T["type"], postfix?: boolean) => createJSDocPrePostfixUnaryTypeWorker(kind, type, postfix), + ); + const getJSDocPrePostfixUnaryTypeUpdateFunction = memoizeOne( + < + T extends JSDocType & { + readonly type: TypeNode | undefined; + readonly postfix: boolean; + }, + >( + kind: T["kind"], + ) => + (node: T, type: T["type"]) => updateJSDocPrePostfixUnaryTypeWorker(kind, node, type), + ); + const getJSDocSimpleTagCreateFunction = memoizeOne( + (kind: T["kind"]) => + ( + tagName: Identifier | undefined, + comment?: NodeArray, + ) => createJSDocSimpleTagWorker(kind, tagName, comment), + ); + const getJSDocSimpleTagUpdateFunction = memoizeOne( + (kind: T["kind"]) => + ( + node: T, + tagName: Identifier | undefined, + comment?: NodeArray, + ) => updateJSDocSimpleTagWorker(kind, node, tagName, comment), + ); + const getJSDocTypeLikeTagCreateFunction = memoizeOne( + ( + kind: T["kind"], + ) => + ( + tagName: Identifier | undefined, + typeExpression?: JSDocTypeExpression, + comment?: NodeArray, + ) => createJSDocTypeLikeTagWorker( + kind, + tagName, + typeExpression, + comment, + ), + ); + const getJSDocTypeLikeTagUpdateFunction = memoizeOne( + ( + kind: T["kind"], + ) => + ( + node: T, + tagName: Identifier | undefined, + typeExpression?: JSDocTypeExpression, + comment?: NodeArray, + ) => updateJSDocTypeLikeTagWorker( + kind, + node, + tagName, + typeExpression, + comment, + ), + ); const factory: NodeFactory = { get parenthesizer() { @@ -652,13 +747,25 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode updateArrayLiteralExpression, createObjectLiteralExpression, updateObjectLiteralExpression, - createPropertyAccessExpression: flags & NodeFactoryFlags.NoIndentationOnFreshPropertyAccess ? - (expression, name) => setEmitFlags(createPropertyAccessExpression(expression, name), EmitFlags.NoIndentation) : - createPropertyAccessExpression, + createPropertyAccessExpression: flags & NodeFactoryFlags.NoIndentationOnFreshPropertyAccess + ? (expression, name) => + setEmitFlags( + createPropertyAccessExpression(expression, name), + EmitFlags.NoIndentation, + ) + : createPropertyAccessExpression, updatePropertyAccessExpression, - createPropertyAccessChain: flags & NodeFactoryFlags.NoIndentationOnFreshPropertyAccess ? - (expression, questionDotToken, name: string) => setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), EmitFlags.NoIndentation) : - createPropertyAccessChain, + createPropertyAccessChain: flags & NodeFactoryFlags.NoIndentationOnFreshPropertyAccess + ? (expression, questionDotToken, name: string) => + setEmitFlags( + createPropertyAccessChain( + expression, + questionDotToken, + name, + ), + EmitFlags.NoIndentation, + ) + : createPropertyAccessChain, updatePropertyAccessChain, createElementAccessExpression, updateElementAccessExpression, @@ -820,40 +927,64 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode updateExternalModuleReference, // lazily load factory members for JSDoc types with similar structure get createJSDocAllType() { - return getJSDocPrimaryTypeCreateFunction(SyntaxKind.JSDocAllType); + return getJSDocPrimaryTypeCreateFunction( + SyntaxKind.JSDocAllType, + ); }, get createJSDocUnknownType() { - return getJSDocPrimaryTypeCreateFunction(SyntaxKind.JSDocUnknownType); + return getJSDocPrimaryTypeCreateFunction( + SyntaxKind.JSDocUnknownType, + ); }, get createJSDocNonNullableType() { - return getJSDocPrePostfixUnaryTypeCreateFunction(SyntaxKind.JSDocNonNullableType); + return getJSDocPrePostfixUnaryTypeCreateFunction( + SyntaxKind.JSDocNonNullableType, + ); }, get updateJSDocNonNullableType() { - return getJSDocPrePostfixUnaryTypeUpdateFunction(SyntaxKind.JSDocNonNullableType); + return getJSDocPrePostfixUnaryTypeUpdateFunction( + SyntaxKind.JSDocNonNullableType, + ); }, get createJSDocNullableType() { - return getJSDocPrePostfixUnaryTypeCreateFunction(SyntaxKind.JSDocNullableType); + return getJSDocPrePostfixUnaryTypeCreateFunction( + SyntaxKind.JSDocNullableType, + ); }, get updateJSDocNullableType() { - return getJSDocPrePostfixUnaryTypeUpdateFunction(SyntaxKind.JSDocNullableType); + return getJSDocPrePostfixUnaryTypeUpdateFunction( + SyntaxKind.JSDocNullableType, + ); }, get createJSDocOptionalType() { - return getJSDocUnaryTypeCreateFunction(SyntaxKind.JSDocOptionalType); + return getJSDocUnaryTypeCreateFunction( + SyntaxKind.JSDocOptionalType, + ); }, get updateJSDocOptionalType() { - return getJSDocUnaryTypeUpdateFunction(SyntaxKind.JSDocOptionalType); + return getJSDocUnaryTypeUpdateFunction( + SyntaxKind.JSDocOptionalType, + ); }, get createJSDocVariadicType() { - return getJSDocUnaryTypeCreateFunction(SyntaxKind.JSDocVariadicType); + return getJSDocUnaryTypeCreateFunction( + SyntaxKind.JSDocVariadicType, + ); }, get updateJSDocVariadicType() { - return getJSDocUnaryTypeUpdateFunction(SyntaxKind.JSDocVariadicType); + return getJSDocUnaryTypeUpdateFunction( + SyntaxKind.JSDocVariadicType, + ); }, get createJSDocNamepathType() { - return getJSDocUnaryTypeCreateFunction(SyntaxKind.JSDocNamepathType); + return getJSDocUnaryTypeCreateFunction( + SyntaxKind.JSDocNamepathType, + ); }, get updateJSDocNamepathType() { - return getJSDocUnaryTypeUpdateFunction(SyntaxKind.JSDocNamepathType); + return getJSDocUnaryTypeUpdateFunction( + SyntaxKind.JSDocNamepathType, + ); }, createJSDocFunctionType, updateJSDocFunctionType, @@ -893,82 +1024,134 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode updateJSDocLinkPlain, // lazily load factory members for JSDoc tags with similar structure get createJSDocTypeTag() { - return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocTypeTag); + return getJSDocTypeLikeTagCreateFunction( + SyntaxKind.JSDocTypeTag, + ); }, get updateJSDocTypeTag() { - return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocTypeTag); + return getJSDocTypeLikeTagUpdateFunction( + SyntaxKind.JSDocTypeTag, + ); }, get createJSDocReturnTag() { - return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocReturnTag); + return getJSDocTypeLikeTagCreateFunction( + SyntaxKind.JSDocReturnTag, + ); }, get updateJSDocReturnTag() { - return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocReturnTag); + return getJSDocTypeLikeTagUpdateFunction( + SyntaxKind.JSDocReturnTag, + ); }, get createJSDocThisTag() { - return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocThisTag); + return getJSDocTypeLikeTagCreateFunction( + SyntaxKind.JSDocThisTag, + ); }, get updateJSDocThisTag() { - return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocThisTag); + return getJSDocTypeLikeTagUpdateFunction( + SyntaxKind.JSDocThisTag, + ); }, get createJSDocAuthorTag() { - return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocAuthorTag); + return getJSDocSimpleTagCreateFunction( + SyntaxKind.JSDocAuthorTag, + ); }, get updateJSDocAuthorTag() { - return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocAuthorTag); + return getJSDocSimpleTagUpdateFunction( + SyntaxKind.JSDocAuthorTag, + ); }, get createJSDocClassTag() { - return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocClassTag); + return getJSDocSimpleTagCreateFunction( + SyntaxKind.JSDocClassTag, + ); }, get updateJSDocClassTag() { - return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocClassTag); + return getJSDocSimpleTagUpdateFunction( + SyntaxKind.JSDocClassTag, + ); }, get createJSDocPublicTag() { - return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocPublicTag); + return getJSDocSimpleTagCreateFunction( + SyntaxKind.JSDocPublicTag, + ); }, get updateJSDocPublicTag() { - return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocPublicTag); + return getJSDocSimpleTagUpdateFunction( + SyntaxKind.JSDocPublicTag, + ); }, get createJSDocPrivateTag() { - return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocPrivateTag); + return getJSDocSimpleTagCreateFunction( + SyntaxKind.JSDocPrivateTag, + ); }, get updateJSDocPrivateTag() { - return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocPrivateTag); + return getJSDocSimpleTagUpdateFunction( + SyntaxKind.JSDocPrivateTag, + ); }, get createJSDocProtectedTag() { - return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocProtectedTag); + return getJSDocSimpleTagCreateFunction( + SyntaxKind.JSDocProtectedTag, + ); }, get updateJSDocProtectedTag() { - return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocProtectedTag); + return getJSDocSimpleTagUpdateFunction( + SyntaxKind.JSDocProtectedTag, + ); }, get createJSDocReadonlyTag() { - return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocReadonlyTag); + return getJSDocSimpleTagCreateFunction( + SyntaxKind.JSDocReadonlyTag, + ); }, get updateJSDocReadonlyTag() { - return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocReadonlyTag); + return getJSDocSimpleTagUpdateFunction( + SyntaxKind.JSDocReadonlyTag, + ); }, get createJSDocOverrideTag() { - return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocOverrideTag); + return getJSDocSimpleTagCreateFunction( + SyntaxKind.JSDocOverrideTag, + ); }, get updateJSDocOverrideTag() { - return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocOverrideTag); + return getJSDocSimpleTagUpdateFunction( + SyntaxKind.JSDocOverrideTag, + ); }, get createJSDocDeprecatedTag() { - return getJSDocSimpleTagCreateFunction(SyntaxKind.JSDocDeprecatedTag); + return getJSDocSimpleTagCreateFunction( + SyntaxKind.JSDocDeprecatedTag, + ); }, get updateJSDocDeprecatedTag() { - return getJSDocSimpleTagUpdateFunction(SyntaxKind.JSDocDeprecatedTag); + return getJSDocSimpleTagUpdateFunction( + SyntaxKind.JSDocDeprecatedTag, + ); }, get createJSDocThrowsTag() { - return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocThrowsTag); + return getJSDocTypeLikeTagCreateFunction( + SyntaxKind.JSDocThrowsTag, + ); }, get updateJSDocThrowsTag() { - return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocThrowsTag); + return getJSDocTypeLikeTagUpdateFunction( + SyntaxKind.JSDocThrowsTag, + ); }, get createJSDocSatisfiesTag() { - return getJSDocTypeLikeTagCreateFunction(SyntaxKind.JSDocSatisfiesTag); + return getJSDocTypeLikeTagCreateFunction( + SyntaxKind.JSDocSatisfiesTag, + ); }, get updateJSDocSatisfiesTag() { - return getJSDocTypeLikeTagUpdateFunction(SyntaxKind.JSDocSatisfiesTag); + return getJSDocTypeLikeTagUpdateFunction( + SyntaxKind.JSDocSatisfiesTag, + ); }, createJSDocEnumTag, @@ -1046,7 +1229,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return getBinaryCreateFunction(SyntaxKind.CommaToken); }, get createAssignment() { - return getBinaryCreateFunction(SyntaxKind.EqualsToken) as NodeFactory["createAssignment"]; + return getBinaryCreateFunction( + SyntaxKind.EqualsToken, + ) as NodeFactory["createAssignment"]; }, get createLogicalOr() { return getBinaryCreateFunction(SyntaxKind.BarBarToken); @@ -1067,7 +1252,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return getBinaryCreateFunction(SyntaxKind.EqualsEqualsEqualsToken); }, get createStrictInequality() { - return getBinaryCreateFunction(SyntaxKind.ExclamationEqualsEqualsToken); + return getBinaryCreateFunction( + SyntaxKind.ExclamationEqualsEqualsToken, + ); }, get createEquality() { return getBinaryCreateFunction(SyntaxKind.EqualsEqualsToken); @@ -1091,10 +1278,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return getBinaryCreateFunction(SyntaxKind.LessThanLessThanToken); }, get createRightShift() { - return getBinaryCreateFunction(SyntaxKind.GreaterThanGreaterThanToken); + return getBinaryCreateFunction( + SyntaxKind.GreaterThanGreaterThanToken, + ); }, get createUnsignedRightShift() { - return getBinaryCreateFunction(SyntaxKind.GreaterThanGreaterThanGreaterThanToken); + return getBinaryCreateFunction( + SyntaxKind.GreaterThanGreaterThanGreaterThanToken, + ); }, get createAdd() { return getBinaryCreateFunction(SyntaxKind.PlusToken); @@ -1189,12 +1380,18 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return factory; // @api - function createNodeArray(elements?: readonly T[], hasTrailingComma?: boolean): NodeArray { + function createNodeArray( + elements?: readonly T[], + hasTrailingComma?: boolean, + ): NodeArray { if (elements === undefined || elements === emptyArray) { elements = []; } else if (isNodeArray(elements)) { - if (hasTrailingComma === undefined || elements.hasTrailingComma === hasTrailingComma) { + if ( + hasTrailingComma === undefined || + elements.hasTrailingComma === hasTrailingComma + ) { // Ensure the transform flags have been aggregated for this NodeArray if (elements.transformFlags === undefined) { aggregateChildrenFlags(elements as MutableNodeArray); @@ -1219,7 +1416,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation. const length = elements.length; - const array = (length >= 1 && length <= 4 ? elements.slice() : elements) as MutableNodeArray; + const array = ( + length >= 1 && length <= 4 ? elements.slice() : elements + ) as MutableNodeArray; array.pos = -1; array.end = -1; array.hasTrailingComma = !!hasTrailingComma; @@ -1229,7 +1428,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return array; } - function createBaseNode(kind: T["kind"]) { + function createBaseNode(kind: T["kind"]) { return baseFactory.createBaseNode(kind) as Mutable; } @@ -1240,7 +1439,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return node; } - function finishUpdateBaseSignatureDeclaration(updated: Mutable, original: T) { + function finishUpdateBaseSignatureDeclaration< + T extends SignatureDeclaration, + >(updated: Mutable, original: T) { if (updated !== original) { // copy children used for quick info updated.typeArguments = original.typeArguments; @@ -1253,10 +1454,18 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // // @api - function createNumericLiteral(value: string | number, numericLiteralFlags: TokenFlags = TokenFlags.None): NumericLiteral { + function createNumericLiteral( + value: string | number, + numericLiteralFlags: TokenFlags = TokenFlags.None, + ): NumericLiteral { const text = typeof value === "number" ? value + "" : value; - Debug.assert(text.charCodeAt(0) !== CharacterCodes.minus, "Negative numbers should be created in combination with createPrefixUnaryExpression"); - const node = createBaseDeclaration(SyntaxKind.NumericLiteral); + Debug.assert( + text.charCodeAt(0) !== CharacterCodes.minus, + "Negative numbers should be created in combination with createPrefixUnaryExpression", + ); + const node = createBaseDeclaration( + SyntaxKind.NumericLiteral, + ); node.text = text; node.numericLiteralFlags = numericLiteralFlags; if (numericLiteralFlags & TokenFlags.BinaryOrOctalSpecifier) node.transformFlags |= TransformFlags.ContainsES2015; @@ -1266,20 +1475,28 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createBigIntLiteral(value: string | PseudoBigInt): BigIntLiteral { const node = createBaseToken(SyntaxKind.BigIntLiteral); - node.text = typeof value === "string" ? value : pseudoBigIntToString(value) + "n"; + node.text = typeof value === "string" + ? value + : pseudoBigIntToString(value) + "n"; node.transformFlags |= TransformFlags.ContainsES2020; return node; } function createBaseStringLiteral(text: string, isSingleQuote?: boolean) { - const node = createBaseDeclaration(SyntaxKind.StringLiteral); + const node = createBaseDeclaration( + SyntaxKind.StringLiteral, + ); node.text = text; node.singleQuote = isSingleQuote; return node; } // @api - function createStringLiteral(text: string, isSingleQuote?: boolean, hasExtendedUnicodeEscape?: boolean): StringLiteral { + function createStringLiteral( + text: string, + isSingleQuote?: boolean, + hasExtendedUnicodeEscape?: boolean, + ): StringLiteral { const node = createBaseStringLiteral(text, isSingleQuote); node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; if (hasExtendedUnicodeEscape) node.transformFlags |= TransformFlags.ContainsES2015; @@ -1287,21 +1504,33 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createStringLiteralFromNode(sourceNode: PropertyNameLiteral | PrivateIdentifier): StringLiteral { - const node = createBaseStringLiteral(getTextOfIdentifierOrLiteral(sourceNode), /*isSingleQuote*/ undefined); + function createStringLiteralFromNode( + sourceNode: PropertyNameLiteral | PrivateIdentifier, + ): StringLiteral { + const node = createBaseStringLiteral( + getTextOfIdentifierOrLiteral(sourceNode), + /*isSingleQuote*/ undefined, + ); node.textSourceNode = sourceNode; return node; } // @api - function createRegularExpressionLiteral(text: string): RegularExpressionLiteral { - const node = createBaseToken(SyntaxKind.RegularExpressionLiteral); + function createRegularExpressionLiteral( + text: string, + ): RegularExpressionLiteral { + const node = createBaseToken( + SyntaxKind.RegularExpressionLiteral, + ); node.text = text; return node; } // @api - function createLiteralLikeNode(kind: LiteralToken["kind"] | SyntaxKind.JsxTextAllWhiteSpaces, text: string): LiteralToken { + function createLiteralLikeNode( + kind: LiteralToken["kind"] | SyntaxKind.JsxTextAllWhiteSpaces, + text: string, + ): LiteralToken { switch (kind) { case SyntaxKind.NumericLiteral: return createNumericLiteral(text, /*numericLiteralFlags*/ 0); @@ -1310,13 +1539,24 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode case SyntaxKind.StringLiteral: return createStringLiteral(text, /*isSingleQuote*/ undefined); case SyntaxKind.JsxText: - return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ false); + return createJsxText( + text, + /*containsOnlyTriviaWhiteSpaces*/ false, + ); case SyntaxKind.JsxTextAllWhiteSpaces: - return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ true); + return createJsxText( + text, + /*containsOnlyTriviaWhiteSpaces*/ true, + ); case SyntaxKind.RegularExpressionLiteral: return createRegularExpressionLiteral(text); case SyntaxKind.NoSubstitutionTemplateLiteral: - return createTemplateLiteralLikeNode(kind, text, /*rawText*/ undefined, /*templateFlags*/ 0) as NoSubstitutionTemplateLiteral; + return createTemplateLiteralLikeNode( + kind, + text, + /*rawText*/ undefined, + /*templateFlags*/ 0, + ) as NoSubstitutionTemplateLiteral; } } @@ -1325,7 +1565,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // function createBaseIdentifier(escapedText: __String) { - const node = baseFactory.createBaseIdentifierNode(SyntaxKind.Identifier) as Mutable; + const node = baseFactory.createBaseIdentifierNode( + SyntaxKind.Identifier, + ) as Mutable; node.escapedText = escapedText; node.jsDoc = undefined; // initialized by parser (JsDocContainer) node.flowNode = undefined; // initialized by binder (FlowContainer) @@ -1333,8 +1575,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return node; } - function createBaseGeneratedIdentifier(text: string, autoGenerateFlags: GeneratedIdentifierFlags, prefix: string | GeneratedNamePart | undefined, suffix: string | undefined) { - const node = createBaseIdentifier(escapeLeadingUnderscores(text)) as Mutable; + function createBaseGeneratedIdentifier( + text: string, + autoGenerateFlags: GeneratedIdentifierFlags, + prefix: string | GeneratedNamePart | undefined, + suffix: string | undefined, + ) { + const node = createBaseIdentifier( + escapeLeadingUnderscores(text), + ) as Mutable; setIdentifierAutoGenerate(node, { flags: autoGenerateFlags, id: nextAutoGenerateId, @@ -1346,7 +1595,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createIdentifier(text: string, originalKeywordKind?: SyntaxKind, hasExtendedUnicodeEscape?: boolean): Identifier { + function createIdentifier( + text: string, + originalKeywordKind?: SyntaxKind, + hasExtendedUnicodeEscape?: boolean, + ): Identifier { if (originalKeywordKind === undefined && text) { originalKeywordKind = stringToToken(text); } @@ -1369,7 +1622,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean, prefix?: string | GeneratedNamePart, suffix?: string): GeneratedIdentifier { + function createTempVariable( + recordTempVariable: ((node: Identifier) => void) | undefined, + reservedInNestedScopes?: boolean, + prefix?: string | GeneratedNamePart, + suffix?: string, + ): GeneratedIdentifier { let flags = GeneratedIdentifierFlags.Auto; if (reservedInNestedScopes) flags |= GeneratedIdentifierFlags.ReservedInNestedScopes; const name = createBaseGeneratedIdentifier("", flags, prefix, suffix); @@ -1384,32 +1642,79 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createLoopVariable(reservedInNestedScopes?: boolean): Identifier { let flags = GeneratedIdentifierFlags.Loop; if (reservedInNestedScopes) flags |= GeneratedIdentifierFlags.ReservedInNestedScopes; - return createBaseGeneratedIdentifier("", flags, /*prefix*/ undefined, /*suffix*/ undefined); + return createBaseGeneratedIdentifier( + "", + flags, + /*prefix*/ undefined, + /*suffix*/ undefined, + ); } /** Create a unique name based on the supplied text. */ // @api - function createUniqueName(text: string, flags: GeneratedIdentifierFlags = GeneratedIdentifierFlags.None, prefix?: string | GeneratedNamePart, suffix?: string): Identifier { - Debug.assert(!(flags & GeneratedIdentifierFlags.KindMask), "Argument out of range: flags"); - Debug.assert((flags & (GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel)) !== GeneratedIdentifierFlags.FileLevel, "GeneratedIdentifierFlags.FileLevel cannot be set without also setting GeneratedIdentifierFlags.Optimistic"); - return createBaseGeneratedIdentifier(text, GeneratedIdentifierFlags.Unique | flags, prefix, suffix); + function createUniqueName( + text: string, + flags: GeneratedIdentifierFlags = GeneratedIdentifierFlags.None, + prefix?: string | GeneratedNamePart, + suffix?: string, + ): Identifier { + Debug.assert( + !(flags & GeneratedIdentifierFlags.KindMask), + "Argument out of range: flags", + ); + Debug.assert( + (flags & + (GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel)) !== + GeneratedIdentifierFlags.FileLevel, + "GeneratedIdentifierFlags.FileLevel cannot be set without also setting GeneratedIdentifierFlags.Optimistic", + ); + return createBaseGeneratedIdentifier( + text, + GeneratedIdentifierFlags.Unique | flags, + prefix, + suffix, + ); } /** Create a unique name generated for a node. */ // @api - function getGeneratedNameForNode(node: Node | undefined, flags: GeneratedIdentifierFlags = 0, prefix?: string | GeneratedNamePart, suffix?: string): Identifier { - Debug.assert(!(flags & GeneratedIdentifierFlags.KindMask), "Argument out of range: flags"); - const text = !node ? "" : - isMemberName(node) ? formatGeneratedName(/*privateName*/ false, prefix, node, suffix, idText) : - `generated@${getNodeId(node)}`; + function getGeneratedNameForNode( + node: Node | undefined, + flags: GeneratedIdentifierFlags = 0, + prefix?: string | GeneratedNamePart, + suffix?: string, + ): Identifier { + Debug.assert( + !(flags & GeneratedIdentifierFlags.KindMask), + "Argument out of range: flags", + ); + const text = !node + ? "" + : isMemberName(node) + ? formatGeneratedName( + /*privateName*/ false, + prefix, + node, + suffix, + idText, + ) + : `generated@${getNodeId(node)}`; if (prefix || suffix) flags |= GeneratedIdentifierFlags.Optimistic; - const name = createBaseGeneratedIdentifier(text, GeneratedIdentifierFlags.Node | flags, prefix, suffix); + const name = createBaseGeneratedIdentifier( + text, + GeneratedIdentifierFlags.Node | flags, + prefix, + suffix, + ); name.original = node; return name; } function createBasePrivateIdentifier(escapedText: __String) { - const node = baseFactory.createBasePrivateIdentifierNode(SyntaxKind.PrivateIdentifier) as Mutable; + const node = baseFactory.createBasePrivateIdentifierNode( + SyntaxKind.PrivateIdentifier, + ) as Mutable; node.escapedText = escapedText; node.transformFlags |= TransformFlags.ContainsClassFields; return node; @@ -1417,12 +1722,23 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createPrivateIdentifier(text: string): PrivateIdentifier { - if (!startsWith(text, "#")) Debug.fail("First character of private identifier must be #: " + text); + if (!startsWith(text, "#")) { + Debug.fail( + "First character of private identifier must be #: " + text, + ); + } return createBasePrivateIdentifier(escapeLeadingUnderscores(text)); } - function createBaseGeneratedPrivateIdentifier(text: string, autoGenerateFlags: GeneratedIdentifierFlags, prefix: string | GeneratedNamePart | undefined, suffix: string | undefined) { - const node = createBasePrivateIdentifier(escapeLeadingUnderscores(text)); + function createBaseGeneratedPrivateIdentifier( + text: string, + autoGenerateFlags: GeneratedIdentifierFlags, + prefix: string | GeneratedNamePart | undefined, + suffix: string | undefined, + ) { + const node = createBasePrivateIdentifier( + escapeLeadingUnderscores(text), + ); setIdentifierAutoGenerate(node, { flags: autoGenerateFlags, id: nextAutoGenerateId, @@ -1435,19 +1751,52 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode /** Create a unique name based on the supplied text. */ // @api - function createUniquePrivateName(text?: string, prefix?: string | GeneratedNamePart, suffix?: string): PrivateIdentifier { - if (text && !startsWith(text, "#")) Debug.fail("First character of private identifier must be #: " + text); + function createUniquePrivateName( + text?: string, + prefix?: string | GeneratedNamePart, + suffix?: string, + ): PrivateIdentifier { + if (text && !startsWith(text, "#")) { + Debug.fail( + "First character of private identifier must be #: " + text, + ); + } const autoGenerateFlags = GeneratedIdentifierFlags.ReservedInNestedScopes | - (text ? GeneratedIdentifierFlags.Unique : GeneratedIdentifierFlags.Auto); - return createBaseGeneratedPrivateIdentifier(text ?? "", autoGenerateFlags, prefix, suffix); + (text + ? GeneratedIdentifierFlags.Unique + : GeneratedIdentifierFlags.Auto); + return createBaseGeneratedPrivateIdentifier( + text ?? "", + autoGenerateFlags, + prefix, + suffix, + ); } // @api - function getGeneratedPrivateNameForNode(node: Node, prefix?: string | GeneratedNamePart, suffix?: string): PrivateIdentifier { - const text = isMemberName(node) ? formatGeneratedName(/*privateName*/ true, prefix, node, suffix, idText) : - `#generated@${getNodeId(node)}`; - const flags = prefix || suffix ? GeneratedIdentifierFlags.Optimistic : GeneratedIdentifierFlags.None; - const name = createBaseGeneratedPrivateIdentifier(text, GeneratedIdentifierFlags.Node | flags, prefix, suffix); + function getGeneratedPrivateNameForNode( + node: Node, + prefix?: string | GeneratedNamePart, + suffix?: string, + ): PrivateIdentifier { + const text = isMemberName(node) + ? formatGeneratedName( + /*privateName*/ true, + prefix, + node, + suffix, + idText, + ) + : `#generated@${getNodeId(node)}`; + const flags = prefix || suffix + ? GeneratedIdentifierFlags.Optimistic + : GeneratedIdentifierFlags.None; + const name = createBaseGeneratedPrivateIdentifier( + text, + GeneratedIdentifierFlags.Node | flags, + prefix, + suffix, + ); name.original = node; return name; } @@ -1456,7 +1805,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // Punctuation // - function createBaseToken(kind: T["kind"]) { + function createBaseToken(kind: T["kind"]) { return baseFactory.createBaseTokenNode(kind) as Mutable; } @@ -1468,16 +1817,38 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createToken(token: SyntaxKind.FalseKeyword): FalseLiteral; function createToken(token: SyntaxKind.EndOfFileToken): EndOfFileToken; function createToken(token: SyntaxKind.Unknown): Token; - function createToken(token: TKind): PunctuationToken; - function createToken(token: TKind): KeywordTypeNode; - function createToken(token: TKind): ModifierToken; - function createToken(token: TKind): KeywordToken; + function createToken( + token: TKind, + ): PunctuationToken; + function createToken( + token: TKind, + ): KeywordTypeNode; + function createToken( + token: TKind, + ): ModifierToken; + function createToken( + token: TKind, + ): KeywordToken; function createToken(token: TKind): Token; function createToken(token: TKind) { - Debug.assert(token >= SyntaxKind.FirstToken && token <= SyntaxKind.LastToken, "Invalid token"); - Debug.assert(token <= SyntaxKind.FirstTemplateToken || token >= SyntaxKind.LastTemplateToken, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals."); - Debug.assert(token <= SyntaxKind.FirstLiteralToken || token >= SyntaxKind.LastLiteralToken, "Invalid token. Use 'createLiteralLikeNode' to create literals."); - Debug.assert(token !== SyntaxKind.Identifier, "Invalid token. Use 'createIdentifier' to create identifiers"); + Debug.assert( + token >= SyntaxKind.FirstToken && token <= SyntaxKind.LastToken, + "Invalid token", + ); + Debug.assert( + token <= SyntaxKind.FirstTemplateToken || + token >= SyntaxKind.LastTemplateToken, + "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals.", + ); + Debug.assert( + token <= SyntaxKind.FirstLiteralToken || + token >= SyntaxKind.LastLiteralToken, + "Invalid token. Use 'createLiteralLikeNode' to create literals.", + ); + Debug.assert( + token !== SyntaxKind.Identifier, + "Invalid token. Use 'createIdentifier' to create identifiers", + ); const node = createBaseToken>(token); let transformFlags = TransformFlags.None; switch (token) { @@ -1515,8 +1886,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode transformFlags = TransformFlags.ContainsTypeScript; break; case SyntaxKind.SuperKeyword: - transformFlags = TransformFlags.ContainsES2015 | TransformFlags.ContainsLexicalSuper; - (node as Mutable> as Mutable).flowNode = undefined; // initialized by binder (FlowContainer) + transformFlags = TransformFlags.ContainsES2015 | + TransformFlags.ContainsLexicalSuper; + ( + node as Mutable< + Token + > as Mutable + ).flowNode = undefined; // initialized by binder (FlowContainer) break; case SyntaxKind.StaticKeyword: transformFlags = TransformFlags.ContainsES2015; @@ -1527,7 +1903,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode case SyntaxKind.ThisKeyword: // 'this' indicates a lexical 'this' transformFlags = TransformFlags.ContainsLexicalThis; - (node as Mutable> as Mutable).flowNode = undefined; // initialized by binder (FlowContainer) + ( + node as Mutable< + Token + > as Mutable + ).flowNode = undefined; // initialized by binder (FlowContainer) break; } if (transformFlags) { @@ -1612,17 +1992,24 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier) { - return node.left !== left - || node.right !== right + function updateQualifiedName( + node: QualifiedName, + left: EntityName, + right: Identifier, + ) { + return node.left !== left || node.right !== right ? update(createQualifiedName(left, right), node) : node; } // @api function createComputedPropertyName(expression: Expression) { - const node = createBaseNode(SyntaxKind.ComputedPropertyName); - node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); + const node = createBaseNode( + SyntaxKind.ComputedPropertyName, + ); + node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName( + expression, + ); node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsES2015 | TransformFlags.ContainsComputedPropertyName; @@ -1630,7 +2017,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression) { + function updateComputedPropertyName( + node: ComputedPropertyName, + expression: Expression, + ) { return node.expression !== expression ? update(createComputedPropertyName(expression), node) : node; @@ -1641,8 +2031,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // // @api - function createTypeParameterDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration { - const node = createBaseDeclaration(SyntaxKind.TypeParameter); + function createTypeParameterDeclaration( + modifiers: readonly Modifier[] | undefined, + name: string | Identifier, + constraint?: TypeNode, + defaultType?: TypeNode, + ): TypeParameterDeclaration { + const node = createBaseDeclaration( + SyntaxKind.TypeParameter, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.constraint = constraint; @@ -1655,12 +2052,26 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration { - return node.modifiers !== modifiers - || node.name !== name - || node.constraint !== constraint - || node.default !== defaultType - ? update(createTypeParameterDeclaration(modifiers, name, constraint, defaultType), node) + function updateTypeParameterDeclaration( + node: TypeParameterDeclaration, + modifiers: readonly Modifier[] | undefined, + name: Identifier, + constraint: TypeNode | undefined, + defaultType: TypeNode | undefined, + ): TypeParameterDeclaration { + return node.modifiers !== modifiers || + node.name !== name || + node.constraint !== constraint || + node.default !== defaultType + ? update( + createTypeParameterDeclaration( + modifiers, + name, + constraint, + defaultType, + ), + node, + ) : node; } @@ -1673,7 +2084,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode type?: TypeNode, initializer?: Expression, ) { - const node = createBaseDeclaration(SyntaxKind.Parameter); + const node = createBaseDeclaration( + SyntaxKind.Parameter, + ); node.modifiers = asNodeArray(modifiers); node.dotDotDotToken = dotDotDotToken; node.name = asName(name); @@ -1690,9 +2103,16 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode propagateNameFlags(node.name) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.initializer) | - (node.questionToken ?? node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None) | - (node.dotDotDotToken ?? node.initializer ? TransformFlags.ContainsES2015 : TransformFlags.None) | - (modifiersToFlags(node.modifiers) & ModifierFlags.ParameterPropertyModifier ? TransformFlags.ContainsTypeScriptClassSyntax : TransformFlags.None); + (node.questionToken ?? node.type + ? TransformFlags.ContainsTypeScript + : TransformFlags.None) | + (node.dotDotDotToken ?? node.initializer + ? TransformFlags.ContainsES2015 + : TransformFlags.None) | + (modifiersToFlags(node.modifiers) & + ModifierFlags.ParameterPropertyModifier + ? TransformFlags.ContainsTypeScriptClassSyntax + : TransformFlags.None); } node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -1709,20 +2129,33 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode type: TypeNode | undefined, initializer: Expression | undefined, ) { - return node.modifiers !== modifiers - || node.dotDotDotToken !== dotDotDotToken - || node.name !== name - || node.questionToken !== questionToken - || node.type !== type - || node.initializer !== initializer - ? update(createParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, type, initializer), node) + return node.modifiers !== modifiers || + node.dotDotDotToken !== dotDotDotToken || + node.name !== name || + node.questionToken !== questionToken || + node.type !== type || + node.initializer !== initializer + ? update( + createParameterDeclaration( + modifiers, + dotDotDotToken, + name, + questionToken, + type, + initializer, + ), + node, + ) : node; } // @api function createDecorator(expression: Expression) { const node = createBaseNode(SyntaxKind.Decorator); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ false, + ); node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsTypeScript | TransformFlags.ContainsTypeScriptClassSyntax | @@ -1748,7 +2181,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode questionToken: QuestionToken | undefined, type: TypeNode | undefined, ): PropertySignature { - const node = createBaseDeclaration(SyntaxKind.PropertySignature); + const node = createBaseDeclaration( + SyntaxKind.PropertySignature, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.type = type; @@ -1768,15 +2203,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode questionToken: QuestionToken | undefined, type: TypeNode | undefined, ) { - return node.modifiers !== modifiers - || node.name !== name - || node.questionToken !== questionToken - || node.type !== type - ? finishUpdatePropertySignature(createPropertySignature(modifiers, name, questionToken, type), node) + return node.modifiers !== modifiers || + node.name !== name || + node.questionToken !== questionToken || + node.type !== type + ? finishUpdatePropertySignature( + createPropertySignature(modifiers, name, questionToken, type), + node, + ) : node; } - function finishUpdatePropertySignature(updated: Mutable, original: PropertySignature) { + function finishUpdatePropertySignature( + updated: Mutable, + original: PropertySignature, + ) { if (updated !== original) { // copy children used only for error reporting updated.initializer = original.initializer; @@ -1788,25 +2229,46 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createPropertyDeclaration( modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, - questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, + questionOrExclamationToken: + | QuestionToken + | ExclamationToken + | undefined, type: TypeNode | undefined, initializer: Expression | undefined, ) { - const node = createBaseDeclaration(SyntaxKind.PropertyDeclaration); + const node = createBaseDeclaration( + SyntaxKind.PropertyDeclaration, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); - node.questionToken = questionOrExclamationToken && isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; - node.exclamationToken = questionOrExclamationToken && isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined; + node.questionToken = questionOrExclamationToken && + isQuestionToken(questionOrExclamationToken) + ? questionOrExclamationToken + : undefined; + node.exclamationToken = questionOrExclamationToken && + isExclamationToken(questionOrExclamationToken) + ? questionOrExclamationToken + : undefined; node.type = type; node.initializer = asInitializer(initializer); - const isAmbient = node.flags & NodeFlags.Ambient || modifiersToFlags(node.modifiers) & ModifierFlags.Ambient; + const isAmbient = node.flags & NodeFlags.Ambient || + modifiersToFlags(node.modifiers) & ModifierFlags.Ambient; node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | - (isAmbient || node.questionToken || node.exclamationToken || node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None) | - (isComputedPropertyName(node.name) || modifiersToFlags(node.modifiers) & ModifierFlags.Static && node.initializer ? TransformFlags.ContainsTypeScriptClassSyntax : TransformFlags.None) | + (isAmbient || + node.questionToken || + node.exclamationToken || + node.type + ? TransformFlags.ContainsTypeScript + : TransformFlags.None) | + (isComputedPropertyName(node.name) || + (modifiersToFlags(node.modifiers) & ModifierFlags.Static && + node.initializer) + ? TransformFlags.ContainsTypeScriptClassSyntax + : TransformFlags.None) | TransformFlags.ContainsClassFields; node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -1818,17 +2280,37 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node: PropertyDeclaration, modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, - questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, + questionOrExclamationToken: + | QuestionToken + | ExclamationToken + | undefined, type: TypeNode | undefined, initializer: Expression | undefined, ) { - return node.modifiers !== modifiers - || node.name !== name - || node.questionToken !== (questionOrExclamationToken !== undefined && isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) - || node.exclamationToken !== (questionOrExclamationToken !== undefined && isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined) - || node.type !== type - || node.initializer !== initializer - ? update(createPropertyDeclaration(modifiers, name, questionOrExclamationToken, type, initializer), node) + return node.modifiers !== modifiers || + node.name !== name || + node.questionToken !== + (questionOrExclamationToken !== undefined && + isQuestionToken(questionOrExclamationToken) + ? questionOrExclamationToken + : undefined) || + node.exclamationToken !== + (questionOrExclamationToken !== undefined && + isExclamationToken(questionOrExclamationToken) + ? questionOrExclamationToken + : undefined) || + node.type !== type || + node.initializer !== initializer + ? update( + createPropertyDeclaration( + modifiers, + name, + questionOrExclamationToken, + type, + initializer, + ), + node, + ) : node; } @@ -1841,7 +2323,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, ) { - const node = createBaseDeclaration(SyntaxKind.MethodSignature); + const node = createBaseDeclaration( + SyntaxKind.MethodSignature, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.questionToken = questionToken; @@ -1867,13 +2351,23 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: NodeArray, type: TypeNode | undefined, ) { - return node.modifiers !== modifiers - || node.name !== name - || node.questionToken !== questionToken - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? finishUpdateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node) + return node.modifiers !== modifiers || + node.name !== name || + node.questionToken !== questionToken || + node.typeParameters !== typeParameters || + node.parameters !== parameters || + node.type !== type + ? finishUpdateBaseSignatureDeclaration( + createMethodSignature( + modifiers, + name, + questionToken, + typeParameters, + parameters, + type, + ), + node, + ) : node; } @@ -1888,7 +2382,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode type: TypeNode | undefined, body: Block | undefined, ) { - const node = createBaseDeclaration(SyntaxKind.MethodDeclaration); + const node = createBaseDeclaration( + SyntaxKind.MethodDeclaration, + ); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -1914,12 +2410,18 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | - (propagateChildFlags(node.body) & ~TransformFlags.ContainsPossibleTopLevelAwait) | - (isAsyncGenerator ? TransformFlags.ContainsES2018 : - isAsync ? TransformFlags.ContainsES2017 : - isGenerator ? TransformFlags.ContainsGenerator : - TransformFlags.None) | - (node.questionToken || node.typeParameters || node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None) | + (propagateChildFlags(node.body) & + ~TransformFlags.ContainsPossibleTopLevelAwait) | + (isAsyncGenerator + ? TransformFlags.ContainsES2018 + : isAsync + ? TransformFlags.ContainsES2017 + : isGenerator + ? TransformFlags.ContainsGenerator + : TransformFlags.None) | + (node.questionToken || node.typeParameters || node.type + ? TransformFlags.ContainsTypeScript + : TransformFlags.None) | TransformFlags.ContainsES2015; } @@ -1945,19 +2447,34 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode type: TypeNode | undefined, body: Block | undefined, ) { - return node.modifiers !== modifiers - || node.asteriskToken !== asteriskToken - || node.name !== name - || node.questionToken !== questionToken - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.body !== body - ? finishUpdateMethodDeclaration(createMethodDeclaration(modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node) - : node; - } - - function finishUpdateMethodDeclaration(updated: Mutable, original: MethodDeclaration) { + return node.modifiers !== modifiers || + node.asteriskToken !== asteriskToken || + node.name !== name || + node.questionToken !== questionToken || + node.typeParameters !== typeParameters || + node.parameters !== parameters || + node.type !== type || + node.body !== body + ? finishUpdateMethodDeclaration( + createMethodDeclaration( + modifiers, + asteriskToken, + name, + questionToken, + typeParameters, + parameters, + type, + body, + ), + node, + ) + : node; + } + + function finishUpdateMethodDeclaration( + updated: Mutable, + original: MethodDeclaration, + ) { if (updated !== original) { // copy children used only for error reporting updated.exclamationToken = original.exclamationToken; @@ -1969,7 +2486,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createClassStaticBlockDeclaration( body: Block, ): ClassStaticBlockDeclaration { - const node = createBaseDeclaration(SyntaxKind.ClassStaticBlockDeclaration); + const node = createBaseDeclaration( + SyntaxKind.ClassStaticBlockDeclaration, + ); node.body = body; node.transformFlags = propagateChildFlags(body) | TransformFlags.ContainsClassFields; @@ -1988,11 +2507,17 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode body: Block, ): ClassStaticBlockDeclaration { return node.body !== body - ? finishUpdateClassStaticBlockDeclaration(createClassStaticBlockDeclaration(body), node) + ? finishUpdateClassStaticBlockDeclaration( + createClassStaticBlockDeclaration(body), + node, + ) : node; } - function finishUpdateClassStaticBlockDeclaration(updated: Mutable, original: ClassStaticBlockDeclaration) { + function finishUpdateClassStaticBlockDeclaration( + updated: Mutable, + original: ClassStaticBlockDeclaration, + ) { if (updated !== original) { // copy children used only for error reporting updated.modifiers = original.modifiers; @@ -2006,14 +2531,17 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], body: Block | undefined, ) { - const node = createBaseDeclaration(SyntaxKind.Constructor); + const node = createBaseDeclaration( + SyntaxKind.Constructor, + ); node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); node.body = body; node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.parameters) | - (propagateChildFlags(node.body) & ~TransformFlags.ContainsPossibleTopLevelAwait) | + (propagateChildFlags(node.body) & + ~TransformFlags.ContainsPossibleTopLevelAwait) | TransformFlags.ContainsES2015; node.typeParameters = undefined; // initialized by parser for grammar errors @@ -2034,14 +2562,20 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], body: Block | undefined, ) { - return node.modifiers !== modifiers - || node.parameters !== parameters - || node.body !== body - ? finishUpdateConstructorDeclaration(createConstructorDeclaration(modifiers, parameters, body), node) + return node.modifiers !== modifiers || + node.parameters !== parameters || + node.body !== body + ? finishUpdateConstructorDeclaration( + createConstructorDeclaration(modifiers, parameters, body), + node, + ) : node; } - function finishUpdateConstructorDeclaration(updated: Mutable, original: ConstructorDeclaration) { + function finishUpdateConstructorDeclaration( + updated: Mutable, + original: ConstructorDeclaration, + ) { if (updated !== original) { updated.typeParameters = original.typeParameters; updated.type = original.type; @@ -2057,7 +2591,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode type: TypeNode | undefined, body: Block | undefined, ) { - const node = createBaseDeclaration(SyntaxKind.GetAccessor); + const node = createBaseDeclaration( + SyntaxKind.GetAccessor, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.parameters = createNodeArray(parameters); @@ -2072,8 +2608,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode propagateNameFlags(node.name) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | - (propagateChildFlags(node.body) & ~TransformFlags.ContainsPossibleTopLevelAwait) | - (node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None); + (propagateChildFlags(node.body) & + ~TransformFlags.ContainsPossibleTopLevelAwait) | + (node.type + ? TransformFlags.ContainsTypeScript + : TransformFlags.None); } node.typeArguments = undefined; // used in quick info @@ -2096,16 +2635,28 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode type: TypeNode | undefined, body: Block | undefined, ) { - return node.modifiers !== modifiers - || node.name !== name - || node.parameters !== parameters - || node.type !== type - || node.body !== body - ? finishUpdateGetAccessorDeclaration(createGetAccessorDeclaration(modifiers, name, parameters, type, body), node) - : node; - } - - function finishUpdateGetAccessorDeclaration(updated: Mutable, original: GetAccessorDeclaration) { + return node.modifiers !== modifiers || + node.name !== name || + node.parameters !== parameters || + node.type !== type || + node.body !== body + ? finishUpdateGetAccessorDeclaration( + createGetAccessorDeclaration( + modifiers, + name, + parameters, + type, + body, + ), + node, + ) + : node; + } + + function finishUpdateGetAccessorDeclaration( + updated: Mutable, + original: GetAccessorDeclaration, + ) { if (updated !== original) { // copy children used only for error reporting updated.typeParameters = original.typeParameters; @@ -2120,7 +2671,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], body: Block | undefined, ) { - const node = createBaseDeclaration(SyntaxKind.SetAccessor); + const node = createBaseDeclaration( + SyntaxKind.SetAccessor, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.parameters = createNodeArray(parameters); @@ -2133,8 +2686,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateNameFlags(node.name) | propagateChildrenFlags(node.parameters) | - (propagateChildFlags(node.body) & ~TransformFlags.ContainsPossibleTopLevelAwait) | - (node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None); + (propagateChildFlags(node.body) & + ~TransformFlags.ContainsPossibleTopLevelAwait) | + (node.type + ? TransformFlags.ContainsTypeScript + : TransformFlags.None); } node.typeArguments = undefined; // used in quick info @@ -2157,15 +2713,26 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], body: Block | undefined, ) { - return node.modifiers !== modifiers - || node.name !== name - || node.parameters !== parameters - || node.body !== body - ? finishUpdateSetAccessorDeclaration(createSetAccessorDeclaration(modifiers, name, parameters, body), node) - : node; - } - - function finishUpdateSetAccessorDeclaration(updated: Mutable, original: SetAccessorDeclaration) { + return node.modifiers !== modifiers || + node.name !== name || + node.parameters !== parameters || + node.body !== body + ? finishUpdateSetAccessorDeclaration( + createSetAccessorDeclaration( + modifiers, + name, + parameters, + body, + ), + node, + ) + : node; + } + + function finishUpdateSetAccessorDeclaration( + updated: Mutable, + original: SetAccessorDeclaration, + ) { if (updated !== original) { // copy children used only for error reporting updated.typeParameters = original.typeParameters; @@ -2180,7 +2747,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, ): CallSignatureDeclaration { - const node = createBaseDeclaration(SyntaxKind.CallSignature); + const node = createBaseDeclaration( + SyntaxKind.CallSignature, + ); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; @@ -2200,10 +2769,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: NodeArray, type: TypeNode | undefined, ) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? finishUpdateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node) + return node.typeParameters !== typeParameters || + node.parameters !== parameters || + node.type !== type + ? finishUpdateBaseSignatureDeclaration( + createCallSignature(typeParameters, parameters, type), + node, + ) : node; } @@ -2213,7 +2785,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, ): ConstructSignatureDeclaration { - const node = createBaseDeclaration(SyntaxKind.ConstructSignature); + const node = createBaseDeclaration( + SyntaxKind.ConstructSignature, + ); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; @@ -2233,10 +2807,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: NodeArray, type: TypeNode | undefined, ) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? finishUpdateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node) + return node.typeParameters !== typeParameters || + node.parameters !== parameters || + node.type !== type + ? finishUpdateBaseSignatureDeclaration( + createConstructSignature(typeParameters, parameters, type), + node, + ) : node; } @@ -2246,7 +2823,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, ): IndexSignatureDeclaration { - const node = createBaseDeclaration(SyntaxKind.IndexSignature); + const node = createBaseDeclaration( + SyntaxKind.IndexSignature, + ); node.modifiers = asNodeArray(modifiers); node.parameters = asNodeArray(parameters); node.type = type!; // TODO(rbuckton): We mark this as required in IndexSignatureDeclaration, but it looks like the parser allows it to be elided. @@ -2266,16 +2845,24 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], type: TypeNode, ) { - return node.parameters !== parameters - || node.type !== type - || node.modifiers !== modifiers - ? finishUpdateBaseSignatureDeclaration(createIndexSignature(modifiers, parameters, type), node) + return node.parameters !== parameters || + node.type !== type || + node.modifiers !== modifiers + ? finishUpdateBaseSignatureDeclaration( + createIndexSignature(modifiers, parameters, type), + node, + ) : node; } // @api - function createTemplateLiteralTypeSpan(type: TypeNode, literal: TemplateMiddle | TemplateTail) { - const node = createBaseNode(SyntaxKind.TemplateLiteralTypeSpan); + function createTemplateLiteralTypeSpan( + type: TypeNode, + literal: TemplateMiddle | TemplateTail, + ) { + const node = createBaseNode( + SyntaxKind.TemplateLiteralTypeSpan, + ); node.type = type; node.literal = literal; node.transformFlags = TransformFlags.ContainsTypeScript; @@ -2283,9 +2870,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateTemplateLiteralTypeSpan(node: TemplateLiteralTypeSpan, type: TypeNode, literal: TemplateMiddle | TemplateTail) { - return node.type !== type - || node.literal !== literal + function updateTemplateLiteralTypeSpan( + node: TemplateLiteralTypeSpan, + type: TypeNode, + literal: TemplateMiddle | TemplateTail, + ) { + return node.type !== type || node.literal !== literal ? update(createTemplateLiteralTypeSpan(type, literal), node) : node; } @@ -2295,13 +2885,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // // @api - function createKeywordTypeNode(kind: TKind) { + function createKeywordTypeNode( + kind: TKind, + ) { return createToken(kind); } // @api - function createTypePredicateNode(assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode | string, type: TypeNode | undefined) { - const node = createBaseNode(SyntaxKind.TypePredicate); + function createTypePredicateNode( + assertsModifier: AssertsKeyword | undefined, + parameterName: Identifier | ThisTypeNode | string, + type: TypeNode | undefined, + ) { + const node = createBaseNode( + SyntaxKind.TypePredicate, + ); node.assertsModifier = assertsModifier; node.parameterName = asName(parameterName); node.type = type; @@ -2310,27 +2908,47 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateTypePredicateNode(node: TypePredicateNode, assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode, type: TypeNode | undefined) { - return node.assertsModifier !== assertsModifier - || node.parameterName !== parameterName - || node.type !== type - ? update(createTypePredicateNode(assertsModifier, parameterName, type), node) + function updateTypePredicateNode( + node: TypePredicateNode, + assertsModifier: AssertsKeyword | undefined, + parameterName: Identifier | ThisTypeNode, + type: TypeNode | undefined, + ) { + return node.assertsModifier !== assertsModifier || + node.parameterName !== parameterName || + node.type !== type + ? update( + createTypePredicateNode(assertsModifier, parameterName, type), + node, + ) : node; } // @api - function createTypeReferenceNode(typeName: string | EntityName, typeArguments: readonly TypeNode[] | undefined) { - const node = createBaseNode(SyntaxKind.TypeReference); + function createTypeReferenceNode( + typeName: string | EntityName, + typeArguments: readonly TypeNode[] | undefined, + ) { + const node = createBaseNode( + SyntaxKind.TypeReference, + ); node.typeName = asName(typeName); - node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments)); + node.typeArguments = typeArguments && + parenthesizerRules().parenthesizeTypeArguments( + createNodeArray(typeArguments), + ); node.transformFlags = TransformFlags.ContainsTypeScript; return node; } // @api - function updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined) { - return node.typeName !== typeName - || node.typeArguments !== typeArguments + function updateTypeReferenceNode( + node: TypeReferenceNode, + typeName: EntityName, + typeArguments: NodeArray | undefined, + ) { + return node.typeName !== typeName || + node.typeArguments !== typeArguments ? update(createTypeReferenceNode(typeName, typeArguments), node) : node; } @@ -2341,7 +2959,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], type: TypeNode, ): FunctionTypeNode { - const node = createBaseDeclaration(SyntaxKind.FunctionType); + const node = createBaseDeclaration( + SyntaxKind.FunctionType, + ); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; @@ -2362,14 +2982,20 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: NodeArray, type: TypeNode, ) { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? finishUpdateFunctionTypeNode(createFunctionTypeNode(typeParameters, parameters, type), node) + return node.typeParameters !== typeParameters || + node.parameters !== parameters || + node.type !== type + ? finishUpdateFunctionTypeNode( + createFunctionTypeNode(typeParameters, parameters, type), + node, + ) : node; } - function finishUpdateFunctionTypeNode(updated: Mutable, original: FunctionTypeNode) { + function finishUpdateFunctionTypeNode( + updated: Mutable, + original: FunctionTypeNode, + ) { if (updated !== original) { // copy children used only for error reporting updated.modifiers = original.modifiers; @@ -2378,10 +3004,17 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createConstructorTypeNode(...args: Parameters) { - return args.length === 4 ? createConstructorTypeNode1(...args) : - args.length === 3 ? createConstructorTypeNode2(...args) : - Debug.fail("Incorrect number of arguments specified."); + function createConstructorTypeNode( + ...args: Parameters< + | typeof createConstructorTypeNode1 + | typeof createConstructorTypeNode2 + > + ) { + return args.length === 4 + ? createConstructorTypeNode1(...args) + : args.length === 3 + ? createConstructorTypeNode2(...args) + : Debug.fail("Incorrect number of arguments specified."); } function createConstructorTypeNode1( @@ -2390,7 +3023,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], type: TypeNode, ): ConstructorTypeNode { - const node = createBaseDeclaration(SyntaxKind.ConstructorType); + const node = createBaseDeclaration( + SyntaxKind.ConstructorType, + ); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); @@ -2410,14 +3045,26 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: readonly ParameterDeclaration[], type: TypeNode, ): ConstructorTypeNode { - return createConstructorTypeNode1(/*modifiers*/ undefined, typeParameters, parameters, type); + return createConstructorTypeNode1( + /*modifiers*/ undefined, + typeParameters, + parameters, + type, + ); } // @api - function updateConstructorTypeNode(...args: Parameters) { - return args.length === 5 ? updateConstructorTypeNode1(...args) : - args.length === 4 ? updateConstructorTypeNode2(...args) : - Debug.fail("Incorrect number of arguments specified."); + function updateConstructorTypeNode( + ...args: Parameters< + | typeof updateConstructorTypeNode1 + | typeof updateConstructorTypeNode2 + > + ) { + return args.length === 5 + ? updateConstructorTypeNode1(...args) + : args.length === 4 + ? updateConstructorTypeNode2(...args) + : Debug.fail("Incorrect number of arguments specified."); } function updateConstructorTypeNode1( @@ -2427,11 +3074,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: NodeArray, type: TypeNode, ) { - return node.modifiers !== modifiers - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? finishUpdateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node) + return node.modifiers !== modifiers || + node.typeParameters !== typeParameters || + node.parameters !== parameters || + node.type !== type + ? finishUpdateBaseSignatureDeclaration( + createConstructorTypeNode( + modifiers, + typeParameters, + parameters, + type, + ), + node, + ) : node; } @@ -2442,36 +3097,57 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode parameters: NodeArray, type: TypeNode, ) { - return updateConstructorTypeNode1(node, node.modifiers, typeParameters, parameters, type); + return updateConstructorTypeNode1( + node, + node.modifiers, + typeParameters, + parameters, + type, + ); } // @api - function createTypeQueryNode(exprName: EntityName, typeArguments?: readonly TypeNode[]) { + function createTypeQueryNode( + exprName: EntityName, + typeArguments?: readonly TypeNode[], + ) { const node = createBaseNode(SyntaxKind.TypeQuery); node.exprName = exprName; - node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); + node.typeArguments = typeArguments && + parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags = TransformFlags.ContainsTypeScript; return node; } // @api - function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName, typeArguments?: readonly TypeNode[]) { - return node.exprName !== exprName - || node.typeArguments !== typeArguments + function updateTypeQueryNode( + node: TypeQueryNode, + exprName: EntityName, + typeArguments?: readonly TypeNode[], + ) { + return node.exprName !== exprName || + node.typeArguments !== typeArguments ? update(createTypeQueryNode(exprName, typeArguments), node) : node; } // @api - function createTypeLiteralNode(members: readonly TypeElement[] | undefined) { - const node = createBaseDeclaration(SyntaxKind.TypeLiteral); + function createTypeLiteralNode( + members: readonly TypeElement[] | undefined, + ) { + const node = createBaseDeclaration( + SyntaxKind.TypeLiteral, + ); node.members = createNodeArray(members); node.transformFlags = TransformFlags.ContainsTypeScript; return node; } // @api - function updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray) { + function updateTypeLiteralNode( + node: TypeLiteralNode, + members: NodeArray, + ) { return node.members !== members ? update(createTypeLiteralNode(members), node) : node; @@ -2480,36 +3156,55 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createArrayTypeNode(elementType: TypeNode) { const node = createBaseNode(SyntaxKind.ArrayType); - node.elementType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(elementType); + node.elementType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType( + elementType, + ); node.transformFlags = TransformFlags.ContainsTypeScript; return node; } // @api - function updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode { + function updateArrayTypeNode( + node: ArrayTypeNode, + elementType: TypeNode, + ): ArrayTypeNode { return node.elementType !== elementType ? update(createArrayTypeNode(elementType), node) : node; } // @api - function createTupleTypeNode(elements: readonly (TypeNode | NamedTupleMember)[]) { + function createTupleTypeNode( + elements: readonly (TypeNode | NamedTupleMember)[], + ) { const node = createBaseNode(SyntaxKind.TupleType); - node.elements = createNodeArray(parenthesizerRules().parenthesizeElementTypesOfTupleType(elements)); + node.elements = createNodeArray( + parenthesizerRules().parenthesizeElementTypesOfTupleType(elements), + ); node.transformFlags = TransformFlags.ContainsTypeScript; return node; } // @api - function updateTupleTypeNode(node: TupleTypeNode, elements: readonly (TypeNode | NamedTupleMember)[]) { + function updateTupleTypeNode( + node: TupleTypeNode, + elements: readonly (TypeNode | NamedTupleMember)[], + ) { return node.elements !== elements ? update(createTupleTypeNode(elements), node) : node; } // @api - function createNamedTupleMember(dotDotDotToken: DotDotDotToken | undefined, name: Identifier, questionToken: QuestionToken | undefined, type: TypeNode) { - const node = createBaseDeclaration(SyntaxKind.NamedTupleMember); + function createNamedTupleMember( + dotDotDotToken: DotDotDotToken | undefined, + name: Identifier, + questionToken: QuestionToken | undefined, + type: TypeNode, + ) { + const node = createBaseDeclaration( + SyntaxKind.NamedTupleMember, + ); node.dotDotDotToken = dotDotDotToken; node.name = name; node.questionToken = questionToken; @@ -2521,12 +3216,26 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateNamedTupleMember(node: NamedTupleMember, dotDotDotToken: DotDotDotToken | undefined, name: Identifier, questionToken: QuestionToken | undefined, type: TypeNode) { - return node.dotDotDotToken !== dotDotDotToken - || node.name !== name - || node.questionToken !== questionToken - || node.type !== type - ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node) + function updateNamedTupleMember( + node: NamedTupleMember, + dotDotDotToken: DotDotDotToken | undefined, + name: Identifier, + questionToken: QuestionToken | undefined, + type: TypeNode, + ) { + return node.dotDotDotToken !== dotDotDotToken || + node.name !== name || + node.questionToken !== questionToken || + node.type !== type + ? update( + createNamedTupleMember( + dotDotDotToken, + name, + questionToken, + type, + ), + node, + ) : node; } @@ -2539,7 +3248,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateOptionalTypeNode(node: OptionalTypeNode, type: TypeNode): OptionalTypeNode { + function updateOptionalTypeNode( + node: OptionalTypeNode, + type: TypeNode, + ): OptionalTypeNode { return node.type !== type ? update(createOptionalTypeNode(type), node) : node; @@ -2554,50 +3266,105 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateRestTypeNode(node: RestTypeNode, type: TypeNode): RestTypeNode { + function updateRestTypeNode( + node: RestTypeNode, + type: TypeNode, + ): RestTypeNode { return node.type !== type ? update(createRestTypeNode(type), node) : node; } - function createUnionOrIntersectionTypeNode(kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, types: readonly TypeNode[], parenthesize: (nodes: readonly TypeNode[]) => readonly TypeNode[]) { + function createUnionOrIntersectionTypeNode( + kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType, + types: readonly TypeNode[], + parenthesize: (nodes: readonly TypeNode[]) => readonly TypeNode[], + ) { const node = createBaseNode(kind); node.types = factory.createNodeArray(parenthesize(types)); node.transformFlags = TransformFlags.ContainsTypeScript; return node; } - function updateUnionOrIntersectionTypeNode(node: T, types: NodeArray, parenthesize: (nodes: readonly TypeNode[]) => readonly TypeNode[]): T { + function updateUnionOrIntersectionTypeNode< + T extends UnionOrIntersectionTypeNode, + >( + node: T, + types: NodeArray, + parenthesize: (nodes: readonly TypeNode[]) => readonly TypeNode[], + ): T { return node.types !== types - ? update(createUnionOrIntersectionTypeNode(node.kind, types, parenthesize) as T, node) + ? update( + createUnionOrIntersectionTypeNode( + node.kind, + types, + parenthesize, + ) as T, + node, + ) : node; } // @api function createUnionTypeNode(types: readonly TypeNode[]): UnionTypeNode { - return createUnionOrIntersectionTypeNode(SyntaxKind.UnionType, types, parenthesizerRules().parenthesizeConstituentTypesOfUnionType) as UnionTypeNode; + return createUnionOrIntersectionTypeNode( + SyntaxKind.UnionType, + types, + parenthesizerRules().parenthesizeConstituentTypesOfUnionType, + ) as UnionTypeNode; } // @api - function updateUnionTypeNode(node: UnionTypeNode, types: NodeArray) { - return updateUnionOrIntersectionTypeNode(node, types, parenthesizerRules().parenthesizeConstituentTypesOfUnionType); + function updateUnionTypeNode( + node: UnionTypeNode, + types: NodeArray, + ) { + return updateUnionOrIntersectionTypeNode( + node, + types, + parenthesizerRules().parenthesizeConstituentTypesOfUnionType, + ); } // @api - function createIntersectionTypeNode(types: readonly TypeNode[]): IntersectionTypeNode { - return createUnionOrIntersectionTypeNode(SyntaxKind.IntersectionType, types, parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType) as IntersectionTypeNode; + function createIntersectionTypeNode( + types: readonly TypeNode[], + ): IntersectionTypeNode { + return createUnionOrIntersectionTypeNode( + SyntaxKind.IntersectionType, + types, + parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType, + ) as IntersectionTypeNode; } // @api - function updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray) { - return updateUnionOrIntersectionTypeNode(node, types, parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType); + function updateIntersectionTypeNode( + node: IntersectionTypeNode, + types: NodeArray, + ) { + return updateUnionOrIntersectionTypeNode( + node, + types, + parenthesizerRules().parenthesizeConstituentTypesOfIntersectionType, + ); } // @api - function createConditionalTypeNode(checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode) { - const node = createBaseNode(SyntaxKind.ConditionalType); - node.checkType = parenthesizerRules().parenthesizeCheckTypeOfConditionalType(checkType); - node.extendsType = parenthesizerRules().parenthesizeExtendsTypeOfConditionalType(extendsType); + function createConditionalTypeNode( + checkType: TypeNode, + extendsType: TypeNode, + trueType: TypeNode, + falseType: TypeNode, + ) { + const node = createBaseNode( + SyntaxKind.ConditionalType, + ); + node.checkType = parenthesizerRules().parenthesizeCheckTypeOfConditionalType( + checkType, + ); + node.extendsType = parenthesizerRules().parenthesizeExtendsTypeOfConditionalType( + extendsType, + ); node.trueType = trueType; node.falseType = falseType; node.transformFlags = TransformFlags.ContainsTypeScript; @@ -2608,12 +3375,26 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode) { - return node.checkType !== checkType - || node.extendsType !== extendsType - || node.trueType !== trueType - || node.falseType !== falseType - ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node) + function updateConditionalTypeNode( + node: ConditionalTypeNode, + checkType: TypeNode, + extendsType: TypeNode, + trueType: TypeNode, + falseType: TypeNode, + ) { + return node.checkType !== checkType || + node.extendsType !== extendsType || + node.trueType !== trueType || + node.falseType !== falseType + ? update( + createConditionalTypeNode( + checkType, + extendsType, + trueType, + falseType, + ), + node, + ) : node; } @@ -2626,15 +3407,23 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration) { + function updateInferTypeNode( + node: InferTypeNode, + typeParameter: TypeParameterDeclaration, + ) { return node.typeParameter !== typeParameter ? update(createInferTypeNode(typeParameter), node) : node; } // @api - function createTemplateLiteralType(head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]) { - const node = createBaseNode(SyntaxKind.TemplateLiteralType); + function createTemplateLiteralType( + head: TemplateHead, + templateSpans: readonly TemplateLiteralTypeSpan[], + ) { + const node = createBaseNode( + SyntaxKind.TemplateLiteralType, + ); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags = TransformFlags.ContainsTypeScript; @@ -2642,9 +3431,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateTemplateLiteralType(node: TemplateLiteralTypeNode, head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]) { - return node.head !== head - || node.templateSpans !== templateSpans + function updateTemplateLiteralType( + node: TemplateLiteralTypeNode, + head: TemplateHead, + templateSpans: readonly TemplateLiteralTypeSpan[], + ) { + return node.head !== head || node.templateSpans !== templateSpans ? update(createTemplateLiteralType(head, templateSpans), node) : node; } @@ -2660,11 +3452,18 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode const node = createBaseNode(SyntaxKind.ImportType); node.argument = argument; node.attributes = attributes; - if (node.assertions && node.assertions.assertClause && node.attributes) { - (node.assertions as Mutable).assertClause = node.attributes; + if ( + node.assertions && + node.assertions.assertClause && + node.attributes + ) { + ( + node.assertions as Mutable + ).assertClause = node.attributes; } node.qualifier = qualifier; - node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); + node.typeArguments = typeArguments && + parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.isTypeOf = isTypeOf; node.transformFlags = TransformFlags.ContainsTypeScript; return node; @@ -2679,25 +3478,39 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode typeArguments: readonly TypeNode[] | undefined, isTypeOf: boolean = node.isTypeOf, ): ImportTypeNode { - return node.argument !== argument - || node.attributes !== attributes - || node.qualifier !== qualifier - || node.typeArguments !== typeArguments - || node.isTypeOf !== isTypeOf - ? update(createImportTypeNode(argument, attributes, qualifier, typeArguments, isTypeOf), node) + return node.argument !== argument || + node.attributes !== attributes || + node.qualifier !== qualifier || + node.typeArguments !== typeArguments || + node.isTypeOf !== isTypeOf + ? update( + createImportTypeNode( + argument, + attributes, + qualifier, + typeArguments, + isTypeOf, + ), + node, + ) : node; } // @api function createParenthesizedType(type: TypeNode) { - const node = createBaseNode(SyntaxKind.ParenthesizedType); + const node = createBaseNode( + SyntaxKind.ParenthesizedType, + ); node.type = type; node.transformFlags = TransformFlags.ContainsTypeScript; return node; } // @api - function updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode) { + function updateParenthesizedType( + node: ParenthesizedTypeNode, + type: TypeNode, + ) { return node.type !== type ? update(createParenthesizedType(type), node) : node; @@ -2711,12 +3524,20 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword, type: TypeNode): TypeOperatorNode { + function createTypeOperatorNode( + operator: + | SyntaxKind.KeyOfKeyword + | SyntaxKind.UniqueKeyword + | SyntaxKind.ReadonlyKeyword, + type: TypeNode, + ): TypeOperatorNode { const node = createBaseNode(SyntaxKind.TypeOperator); node.operator = operator; - node.type = operator === SyntaxKind.ReadonlyKeyword ? - parenthesizerRules().parenthesizeOperandOfReadonlyTypeOperator(type) : - parenthesizerRules().parenthesizeOperandOfTypeOperator(type); + node.type = operator === SyntaxKind.ReadonlyKeyword + ? parenthesizerRules().parenthesizeOperandOfReadonlyTypeOperator( + type, + ) + : parenthesizerRules().parenthesizeOperandOfTypeOperator(type); node.transformFlags = TransformFlags.ContainsTypeScript; return node; } @@ -2729,25 +3550,44 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode) { - const node = createBaseNode(SyntaxKind.IndexedAccessType); - node.objectType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(objectType); + function createIndexedAccessTypeNode( + objectType: TypeNode, + indexType: TypeNode, + ) { + const node = createBaseNode( + SyntaxKind.IndexedAccessType, + ); + node.objectType = parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType( + objectType, + ); node.indexType = indexType; node.transformFlags = TransformFlags.ContainsTypeScript; return node; } // @api - function updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode) { - return node.objectType !== objectType - || node.indexType !== indexType + function updateIndexedAccessTypeNode( + node: IndexedAccessTypeNode, + objectType: TypeNode, + indexType: TypeNode, + ) { + return node.objectType !== objectType || node.indexType !== indexType ? update(createIndexedAccessTypeNode(objectType, indexType), node) : node; } // @api - function createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: readonly TypeElement[] | undefined): MappedTypeNode { - const node = createBaseDeclaration(SyntaxKind.MappedType); + function createMappedTypeNode( + readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, + typeParameter: TypeParameterDeclaration, + nameType: TypeNode | undefined, + questionToken: QuestionToken | PlusToken | MinusToken | undefined, + type: TypeNode | undefined, + members: readonly TypeElement[] | undefined, + ): MappedTypeNode { + const node = createBaseDeclaration( + SyntaxKind.MappedType, + ); node.readonlyToken = readonlyToken; node.typeParameter = typeParameter; node.nameType = nameType; @@ -2762,14 +3602,32 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: readonly TypeElement[] | undefined): MappedTypeNode { - return node.readonlyToken !== readonlyToken - || node.typeParameter !== typeParameter - || node.nameType !== nameType - || node.questionToken !== questionToken - || node.type !== type - || node.members !== members - ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node) + function updateMappedTypeNode( + node: MappedTypeNode, + readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, + typeParameter: TypeParameterDeclaration, + nameType: TypeNode | undefined, + questionToken: QuestionToken | PlusToken | MinusToken | undefined, + type: TypeNode | undefined, + members: readonly TypeElement[] | undefined, + ): MappedTypeNode { + return node.readonlyToken !== readonlyToken || + node.typeParameter !== typeParameter || + node.nameType !== nameType || + node.questionToken !== questionToken || + node.type !== type || + node.members !== members + ? update( + createMappedTypeNode( + readonlyToken, + typeParameter, + nameType, + questionToken, + type, + members, + ), + node, + ) : node; } @@ -2782,7 +3640,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]) { + function updateLiteralTypeNode( + node: LiteralTypeNode, + literal: LiteralTypeNode["literal"], + ) { return node.literal !== literal ? update(createLiteralTypeNode(literal), node) : node; @@ -2794,7 +3655,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createObjectBindingPattern(elements: readonly BindingElement[]) { - const node = createBaseNode(SyntaxKind.ObjectBindingPattern); + const node = createBaseNode( + SyntaxKind.ObjectBindingPattern, + ); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | TransformFlags.ContainsES2015 | @@ -2807,15 +3670,22 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateObjectBindingPattern(node: ObjectBindingPattern, elements: readonly BindingElement[]) { + function updateObjectBindingPattern( + node: ObjectBindingPattern, + elements: readonly BindingElement[], + ) { return node.elements !== elements ? update(createObjectBindingPattern(elements), node) : node; } // @api - function createArrayBindingPattern(elements: readonly ArrayBindingElement[]) { - const node = createBaseNode(SyntaxKind.ArrayBindingPattern); + function createArrayBindingPattern( + elements: readonly ArrayBindingElement[], + ) { + const node = createBaseNode( + SyntaxKind.ArrayBindingPattern, + ); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | TransformFlags.ContainsES2015 | @@ -2824,15 +3694,25 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateArrayBindingPattern(node: ArrayBindingPattern, elements: readonly ArrayBindingElement[]) { + function updateArrayBindingPattern( + node: ArrayBindingPattern, + elements: readonly ArrayBindingElement[], + ) { return node.elements !== elements ? update(createArrayBindingPattern(elements), node) : node; } // @api - function createBindingElement(dotDotDotToken: DotDotDotToken | undefined, propertyName: string | PropertyName | undefined, name: string | BindingName, initializer?: Expression) { - const node = createBaseDeclaration(SyntaxKind.BindingElement); + function createBindingElement( + dotDotDotToken: DotDotDotToken | undefined, + propertyName: string | PropertyName | undefined, + name: string | BindingName, + initializer?: Expression, + ) { + const node = createBaseDeclaration( + SyntaxKind.BindingElement, + ); node.dotDotDotToken = dotDotDotToken; node.propertyName = asName(propertyName); node.name = asName(name); @@ -2841,7 +3721,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode propagateNameFlags(node.propertyName) | propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | - (node.dotDotDotToken ? TransformFlags.ContainsRestOrSpread : TransformFlags.None) | + (node.dotDotDotToken + ? TransformFlags.ContainsRestOrSpread + : TransformFlags.None) | TransformFlags.ContainsES2015; node.flowNode = undefined; // initialized by binder (FlowContainer) @@ -2849,12 +3731,26 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken | undefined, propertyName: PropertyName | undefined, name: BindingName, initializer: Expression | undefined) { - return node.propertyName !== propertyName - || node.dotDotDotToken !== dotDotDotToken - || node.name !== name - || node.initializer !== initializer - ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node) + function updateBindingElement( + node: BindingElement, + dotDotDotToken: DotDotDotToken | undefined, + propertyName: PropertyName | undefined, + name: BindingName, + initializer: Expression | undefined, + ) { + return node.propertyName !== propertyName || + node.dotDotDotToken !== dotDotDotToken || + node.name !== name || + node.initializer !== initializer + ? update( + createBindingElement( + dotDotDotToken, + propertyName, + name, + initializer, + ), + node, + ) : node; } @@ -2863,29 +3759,50 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // // @api - function createArrayLiteralExpression(elements?: readonly Expression[], multiLine?: boolean) { - const node = createBaseNode(SyntaxKind.ArrayLiteralExpression); + function createArrayLiteralExpression( + elements?: readonly Expression[], + multiLine?: boolean, + ) { + const node = createBaseNode( + SyntaxKind.ArrayLiteralExpression, + ); // Ensure we add a trailing comma for something like `[NumericLiteral(1), NumericLiteral(2), OmittedExpresion]` so that // we end up with `[1, 2, ,]` instead of `[1, 2, ]` otherwise the `OmittedExpression` will just end up being treated like // a trailing comma. const lastElement = elements && lastOrUndefined(elements); - const elementsArray = createNodeArray(elements, lastElement && isOmittedExpression(lastElement) ? true : undefined); - node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(elementsArray); + const elementsArray = createNodeArray( + elements, + lastElement && isOmittedExpression(lastElement) ? true : undefined, + ); + node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList( + elementsArray, + ); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.elements); return node; } // @api - function updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]) { + function updateArrayLiteralExpression( + node: ArrayLiteralExpression, + elements: readonly Expression[], + ) { return node.elements !== elements - ? update(createArrayLiteralExpression(elements, node.multiLine), node) + ? update( + createArrayLiteralExpression(elements, node.multiLine), + node, + ) : node; } // @api - function createObjectLiteralExpression(properties?: readonly ObjectLiteralElementLike[], multiLine?: boolean) { - const node = createBaseDeclaration(SyntaxKind.ObjectLiteralExpression); + function createObjectLiteralExpression( + properties?: readonly ObjectLiteralElementLike[], + multiLine?: boolean, + ) { + const node = createBaseDeclaration( + SyntaxKind.ObjectLiteralExpression, + ); node.properties = createNodeArray(properties); node.multiLine = multiLine; node.transformFlags |= propagateChildrenFlags(node.properties); @@ -2895,22 +3812,35 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]) { + function updateObjectLiteralExpression( + node: ObjectLiteralExpression, + properties: readonly ObjectLiteralElementLike[], + ) { return node.properties !== properties - ? update(createObjectLiteralExpression(properties, node.multiLine), node) + ? update( + createObjectLiteralExpression(properties, node.multiLine), + node, + ) : node; } - function createBasePropertyAccessExpression(expression: LeftHandSideExpression, questionDotToken: QuestionDotToken | undefined, name: MemberName) { - const node = createBaseDeclaration(SyntaxKind.PropertyAccessExpression); + function createBasePropertyAccessExpression( + expression: LeftHandSideExpression, + questionDotToken: QuestionDotToken | undefined, + name: MemberName, + ) { + const node = createBaseDeclaration( + SyntaxKind.PropertyAccessExpression, + ); node.expression = expression; node.questionDotToken = questionDotToken; node.name = name; node.transformFlags = propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | - (isIdentifier(node.name) ? - propagateIdentifierNameFlags(node.name) : - propagateChildFlags(node.name) | TransformFlags.ContainsPrivateIdentifierInExpression); + (isIdentifier(node.name) + ? propagateIdentifierNameFlags(node.name) + : propagateChildFlags(node.name) | + TransformFlags.ContainsPrivateIdentifierInExpression); node.jsDoc = undefined; // initialized by parser (JsDocContainer) node.flowNode = undefined; // initialized by binder (FlowContainer) @@ -2918,36 +3848,56 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createPropertyAccessExpression(expression: Expression, name: string | Identifier | PrivateIdentifier) { + function createPropertyAccessExpression( + expression: Expression, + name: string | Identifier | PrivateIdentifier, + ) { const node = createBasePropertyAccessExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false), + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ false, + ), /*questionDotToken*/ undefined, asName(name), ); if (isSuperKeyword(expression)) { // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators - node.transformFlags |= TransformFlags.ContainsES2017 | - TransformFlags.ContainsES2018; + node.transformFlags |= TransformFlags.ContainsES2017 | TransformFlags.ContainsES2018; } return node; } // @api - function updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: Identifier | PrivateIdentifier) { + function updatePropertyAccessExpression( + node: PropertyAccessExpression, + expression: Expression, + name: Identifier | PrivateIdentifier, + ) { if (isPropertyAccessChain(node)) { - return updatePropertyAccessChain(node, expression, node.questionDotToken, cast(name, isIdentifier)); + return updatePropertyAccessChain( + node, + expression, + node.questionDotToken, + cast(name, isIdentifier), + ); } - return node.expression !== expression - || node.name !== name + return node.expression !== expression || node.name !== name ? update(createPropertyAccessExpression(expression, name), node) : node; } // @api - function createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | Identifier | PrivateIdentifier) { + function createPropertyAccessChain( + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + name: string | Identifier | PrivateIdentifier, + ) { const node = createBasePropertyAccessExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true), + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ true, + ), questionDotToken, asName(name), ) as Mutable; @@ -2957,19 +3907,36 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: Identifier | PrivateIdentifier) { - Debug.assert(!!(node.flags & NodeFlags.OptionalChain), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead."); + function updatePropertyAccessChain( + node: PropertyAccessChain, + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + name: Identifier | PrivateIdentifier, + ) { + Debug.assert( + !!(node.flags & NodeFlags.OptionalChain), + "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.", + ); // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags // instead of using the default from createPropertyAccess - return node.expression !== expression - || node.questionDotToken !== questionDotToken - || node.name !== name - ? update(createPropertyAccessChain(expression, questionDotToken, name), node) + return node.expression !== expression || + node.questionDotToken !== questionDotToken || + node.name !== name + ? update( + createPropertyAccessChain(expression, questionDotToken, name), + node, + ) : node; } - function createBaseElementAccessExpression(expression: LeftHandSideExpression, questionDotToken: QuestionDotToken | undefined, argumentExpression: Expression) { - const node = createBaseDeclaration(SyntaxKind.ElementAccessExpression); + function createBaseElementAccessExpression( + expression: LeftHandSideExpression, + questionDotToken: QuestionDotToken | undefined, + argumentExpression: Expression, + ) { + const node = createBaseDeclaration( + SyntaxKind.ElementAccessExpression, + ); node.expression = expression; node.questionDotToken = questionDotToken; node.argumentExpression = argumentExpression; @@ -2983,36 +3950,60 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createElementAccessExpression(expression: Expression, index: number | Expression) { + function createElementAccessExpression( + expression: Expression, + index: number | Expression, + ) { const node = createBaseElementAccessExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false), + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ false, + ), /*questionDotToken*/ undefined, asExpression(index), ); if (isSuperKeyword(expression)) { // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators - node.transformFlags |= TransformFlags.ContainsES2017 | - TransformFlags.ContainsES2018; + node.transformFlags |= TransformFlags.ContainsES2017 | TransformFlags.ContainsES2018; } return node; } // @api - function updateElementAccessExpression(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression) { + function updateElementAccessExpression( + node: ElementAccessExpression, + expression: Expression, + argumentExpression: Expression, + ) { if (isElementAccessChain(node)) { - return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + return updateElementAccessChain( + node, + expression, + node.questionDotToken, + argumentExpression, + ); } - return node.expression !== expression - || node.argumentExpression !== argumentExpression - ? update(createElementAccessExpression(expression, argumentExpression), node) + return node.expression !== expression || + node.argumentExpression !== argumentExpression + ? update( + createElementAccessExpression(expression, argumentExpression), + node, + ) : node; } // @api - function createElementAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, index: number | Expression) { + function createElementAccessChain( + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + index: number | Expression, + ) { const node = createBaseElementAccessExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true), + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ true, + ), questionDotToken, asExpression(index), ) as Mutable; @@ -3022,19 +4013,41 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateElementAccessChain(node: ElementAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, argumentExpression: Expression) { - Debug.assert(!!(node.flags & NodeFlags.OptionalChain), "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead."); + function updateElementAccessChain( + node: ElementAccessChain, + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + argumentExpression: Expression, + ) { + Debug.assert( + !!(node.flags & NodeFlags.OptionalChain), + "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.", + ); // Because we are updating an existing ElementAccessChain we want to inherit its emitFlags // instead of using the default from createElementAccess - return node.expression !== expression - || node.questionDotToken !== questionDotToken - || node.argumentExpression !== argumentExpression - ? update(createElementAccessChain(expression, questionDotToken, argumentExpression), node) - : node; - } - - function createBaseCallExpression(expression: LeftHandSideExpression, questionDotToken: QuestionDotToken | undefined, typeArguments: NodeArray | undefined, argumentsArray: NodeArray) { - const node = createBaseDeclaration(SyntaxKind.CallExpression); + return node.expression !== expression || + node.questionDotToken !== questionDotToken || + node.argumentExpression !== argumentExpression + ? update( + createElementAccessChain( + expression, + questionDotToken, + argumentExpression, + ), + node, + ) + : node; + } + + function createBaseCallExpression( + expression: LeftHandSideExpression, + questionDotToken: QuestionDotToken | undefined, + typeArguments: NodeArray | undefined, + argumentsArray: NodeArray, + ) { + const node = createBaseDeclaration( + SyntaxKind.CallExpression, + ); node.expression = expression; node.questionDotToken = questionDotToken; node.typeArguments = typeArguments; @@ -3053,12 +4066,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createCallExpression(expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined) { - const node = createBaseCallExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false), + function createCallExpression( + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[] | undefined, + ) { + const node = createBaseCallExpression( + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ false, + ), /*questionDotToken*/ undefined, asNodeArray(typeArguments), - parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)), + parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList( + createNodeArray(argumentsArray), + ), ); if (isImportKeyword(node.expression)) { node.transformFlags |= TransformFlags.ContainsDynamicImport; @@ -3067,24 +4089,52 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateCallExpression(node: CallExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]) { + function updateCallExpression( + node: CallExpression, + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[], + ) { if (isCallChain(node)) { - return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + return updateCallChain( + node, + expression, + node.questionDotToken, + typeArguments, + argumentsArray, + ); } - return node.expression !== expression - || node.typeArguments !== typeArguments - || node.arguments !== argumentsArray - ? update(createCallExpression(expression, typeArguments, argumentsArray), node) + return node.expression !== expression || + node.typeArguments !== typeArguments || + node.arguments !== argumentsArray + ? update( + createCallExpression( + expression, + typeArguments, + argumentsArray, + ), + node, + ) : node; } // @api - function createCallChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined) { + function createCallChain( + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[] | undefined, + ) { const node = createBaseCallExpression( - parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true), + parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ true, + ), questionDotToken, asNodeArray(typeArguments), - parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray)), + parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList( + createNodeArray(argumentsArray), + ), ) as Mutable; node.flags |= NodeFlags.OptionalChain; node.transformFlags |= TransformFlags.ContainsES2020; @@ -3092,22 +4142,49 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateCallChain(node: CallChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]) { - Debug.assert(!!(node.flags & NodeFlags.OptionalChain), "Cannot update a CallExpression using updateCallChain. Use updateCall instead."); - return node.expression !== expression - || node.questionDotToken !== questionDotToken - || node.typeArguments !== typeArguments - || node.arguments !== argumentsArray - ? update(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node) + function updateCallChain( + node: CallChain, + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[], + ) { + Debug.assert( + !!(node.flags & NodeFlags.OptionalChain), + "Cannot update a CallExpression using updateCallChain. Use updateCall instead.", + ); + return node.expression !== expression || + node.questionDotToken !== questionDotToken || + node.typeArguments !== typeArguments || + node.arguments !== argumentsArray + ? update( + createCallChain( + expression, + questionDotToken, + typeArguments, + argumentsArray, + ), + node, + ) : node; } // @api - function createNewExpression(expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined) { - const node = createBaseDeclaration(SyntaxKind.NewExpression); + function createNewExpression( + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[] | undefined, + ) { + const node = createBaseDeclaration( + SyntaxKind.NewExpression, + ); node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression); node.typeArguments = asNodeArray(typeArguments); - node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined; + node.arguments = argumentsArray + ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList( + argumentsArray, + ) + : undefined; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | @@ -3119,18 +4196,39 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateNewExpression(node: NewExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined) { - return node.expression !== expression - || node.typeArguments !== typeArguments - || node.arguments !== argumentsArray - ? update(createNewExpression(expression, typeArguments, argumentsArray), node) + function updateNewExpression( + node: NewExpression, + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[] | undefined, + ) { + return node.expression !== expression || + node.typeArguments !== typeArguments || + node.arguments !== argumentsArray + ? update( + createNewExpression( + expression, + typeArguments, + argumentsArray, + ), + node, + ) : node; } // @api - function createTaggedTemplateExpression(tag: Expression, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral) { - const node = createBaseNode(SyntaxKind.TaggedTemplateExpression); - node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag, /*optionalChain*/ false); + function createTaggedTemplateExpression( + tag: Expression, + typeArguments: readonly TypeNode[] | undefined, + template: TemplateLiteral, + ) { + const node = createBaseNode( + SyntaxKind.TaggedTemplateExpression, + ); + node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess( + tag, + /*optionalChain*/ false, + ); node.typeArguments = asNodeArray(typeArguments); node.template = template; node.transformFlags |= propagateChildFlags(node.tag) | @@ -3147,17 +4245,27 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateTaggedTemplateExpression(node: TaggedTemplateExpression, tag: Expression, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral) { - return node.tag !== tag - || node.typeArguments !== typeArguments - || node.template !== template - ? update(createTaggedTemplateExpression(tag, typeArguments, template), node) + function updateTaggedTemplateExpression( + node: TaggedTemplateExpression, + tag: Expression, + typeArguments: readonly TypeNode[] | undefined, + template: TemplateLiteral, + ) { + return node.tag !== tag || + node.typeArguments !== typeArguments || + node.template !== template + ? update( + createTaggedTemplateExpression(tag, typeArguments, template), + node, + ) : node; } // @api function createTypeAssertion(type: TypeNode, expression: Expression) { - const node = createBaseNode(SyntaxKind.TypeAssertionExpression); + const node = createBaseNode( + SyntaxKind.TypeAssertionExpression, + ); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.type = type; node.transformFlags |= propagateChildFlags(node.expression) | @@ -3167,16 +4275,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression) { - return node.type !== type - || node.expression !== expression + function updateTypeAssertion( + node: TypeAssertion, + type: TypeNode, + expression: Expression, + ) { + return node.type !== type || node.expression !== expression ? update(createTypeAssertion(type, expression), node) : node; } // @api function createParenthesizedExpression(expression: Expression) { - const node = createBaseNode(SyntaxKind.ParenthesizedExpression); + const node = createBaseNode( + SyntaxKind.ParenthesizedExpression, + ); node.expression = expression; node.transformFlags = propagateChildFlags(node.expression); @@ -3185,7 +4298,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateParenthesizedExpression(node: ParenthesizedExpression, expression: Expression) { + function updateParenthesizedExpression( + node: ParenthesizedExpression, + expression: Expression, + ) { return node.expression !== expression ? update(createParenthesizedExpression(expression), node) : node; @@ -3201,7 +4317,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode type: TypeNode | undefined, body: Block, ) { - const node = createBaseDeclaration(SyntaxKind.FunctionExpression); + const node = createBaseDeclaration( + SyntaxKind.FunctionExpression, + ); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -3220,12 +4338,18 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | - (propagateChildFlags(node.body) & ~TransformFlags.ContainsPossibleTopLevelAwait) | - (isAsyncGenerator ? TransformFlags.ContainsES2018 : - isAsync ? TransformFlags.ContainsES2017 : - isGenerator ? TransformFlags.ContainsGenerator : - TransformFlags.None) | - (node.typeParameters || node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None) | + (propagateChildFlags(node.body) & + ~TransformFlags.ContainsPossibleTopLevelAwait) | + (isAsyncGenerator + ? TransformFlags.ContainsES2018 + : isAsync + ? TransformFlags.ContainsES2017 + : isGenerator + ? TransformFlags.ContainsGenerator + : TransformFlags.None) | + (node.typeParameters || node.type + ? TransformFlags.ContainsTypeScript + : TransformFlags.None) | TransformFlags.ContainsHoistedDeclarationOrCompletion; node.typeArguments = undefined; // used in quick info @@ -3249,14 +4373,25 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode type: TypeNode | undefined, body: Block, ) { - return node.name !== name - || node.modifiers !== modifiers - || node.asteriskToken !== asteriskToken - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.body !== body - ? finishUpdateBaseSignatureDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) + return node.name !== name || + node.modifiers !== modifiers || + node.asteriskToken !== asteriskToken || + node.typeParameters !== typeParameters || + node.parameters !== parameters || + node.type !== type || + node.body !== body + ? finishUpdateBaseSignatureDeclaration( + createFunctionExpression( + modifiers, + asteriskToken, + name, + typeParameters, + parameters, + type, + body, + ), + node, + ) : node; } @@ -3269,12 +4404,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody, ) { - const node = createBaseDeclaration(SyntaxKind.ArrowFunction); + const node = createBaseDeclaration( + SyntaxKind.ArrowFunction, + ); node.modifiers = asNodeArray(modifiers); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken ?? createToken(SyntaxKind.EqualsGreaterThanToken); + node.equalsGreaterThanToken = equalsGreaterThanToken ?? + createToken(SyntaxKind.EqualsGreaterThanToken); node.body = parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body); const isAsync = modifiersToFlags(node.modifiers) & ModifierFlags.Async; @@ -3284,9 +4422,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | propagateChildFlags(node.equalsGreaterThanToken) | - (propagateChildFlags(node.body) & ~TransformFlags.ContainsPossibleTopLevelAwait) | - (node.typeParameters || node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None) | - (isAsync ? TransformFlags.ContainsES2017 | TransformFlags.ContainsLexicalThis : TransformFlags.None) | + (propagateChildFlags(node.body) & + ~TransformFlags.ContainsPossibleTopLevelAwait) | + (node.typeParameters || node.type + ? TransformFlags.ContainsTypeScript + : TransformFlags.None) | + (isAsync + ? TransformFlags.ContainsES2017 | + TransformFlags.ContainsLexicalThis + : TransformFlags.None) | TransformFlags.ContainsES2015; node.typeArguments = undefined; // used in quick info @@ -3309,26 +4453,41 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode equalsGreaterThanToken: EqualsGreaterThanToken, body: ConciseBody, ): ArrowFunction { - return node.modifiers !== modifiers - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.equalsGreaterThanToken !== equalsGreaterThanToken - || node.body !== body - ? finishUpdateBaseSignatureDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node) + return node.modifiers !== modifiers || + node.typeParameters !== typeParameters || + node.parameters !== parameters || + node.type !== type || + node.equalsGreaterThanToken !== equalsGreaterThanToken || + node.body !== body + ? finishUpdateBaseSignatureDeclaration( + createArrowFunction( + modifiers, + typeParameters, + parameters, + type, + equalsGreaterThanToken, + body, + ), + node, + ) : node; } // @api function createDeleteExpression(expression: Expression) { - const node = createBaseNode(SyntaxKind.DeleteExpression); + const node = createBaseNode( + SyntaxKind.DeleteExpression, + ); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; } // @api - function updateDeleteExpression(node: DeleteExpression, expression: Expression) { + function updateDeleteExpression( + node: DeleteExpression, + expression: Expression, + ) { return node.expression !== expression ? update(createDeleteExpression(expression), node) : node; @@ -3336,14 +4495,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createTypeOfExpression(expression: Expression) { - const node = createBaseNode(SyntaxKind.TypeOfExpression); + const node = createBaseNode( + SyntaxKind.TypeOfExpression, + ); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression); return node; } // @api - function updateTypeOfExpression(node: TypeOfExpression, expression: Expression) { + function updateTypeOfExpression( + node: TypeOfExpression, + expression: Expression, + ) { return node.expression !== expression ? update(createTypeOfExpression(expression), node) : node; @@ -3358,7 +4522,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateVoidExpression(node: VoidExpression, expression: Expression) { + function updateVoidExpression( + node: VoidExpression, + expression: Expression, + ) { return node.expression !== expression ? update(createVoidExpression(expression), node) : node; @@ -3366,7 +4533,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createAwaitExpression(expression: Expression) { - const node = createBaseNode(SyntaxKind.AwaitExpression); + const node = createBaseNode( + SyntaxKind.AwaitExpression, + ); node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsES2017 | @@ -3376,22 +4545,31 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateAwaitExpression(node: AwaitExpression, expression: Expression) { + function updateAwaitExpression( + node: AwaitExpression, + expression: Expression, + ) { return node.expression !== expression ? update(createAwaitExpression(expression), node) : node; } // @api - function createPrefixUnaryExpression(operator: PrefixUnaryOperator, operand: Expression) { - const node = createBaseNode(SyntaxKind.PrefixUnaryExpression); + function createPrefixUnaryExpression( + operator: PrefixUnaryOperator, + operand: Expression, + ) { + const node = createBaseNode( + SyntaxKind.PrefixUnaryExpression, + ); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); // Only set this flag for non-generated identifiers and non-"local" names. See the // comment in `visitPreOrPostfixUnaryExpression` in module.ts if ( - (operator === SyntaxKind.PlusPlusToken || operator === SyntaxKind.MinusMinusToken) && + (operator === SyntaxKind.PlusPlusToken || + operator === SyntaxKind.MinusMinusToken) && isIdentifier(node.operand) && !isGeneratedIdentifier(node.operand) && !isLocalName(node.operand) @@ -3402,15 +4580,23 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updatePrefixUnaryExpression(node: PrefixUnaryExpression, operand: Expression) { + function updatePrefixUnaryExpression( + node: PrefixUnaryExpression, + operand: Expression, + ) { return node.operand !== operand ? update(createPrefixUnaryExpression(node.operator, operand), node) : node; } // @api - function createPostfixUnaryExpression(operand: Expression, operator: PostfixUnaryOperator) { - const node = createBaseNode(SyntaxKind.PostfixUnaryExpression); + function createPostfixUnaryExpression( + operand: Expression, + operator: PostfixUnaryOperator, + ) { + const node = createBaseNode( + SyntaxKind.PostfixUnaryExpression, + ); node.operator = operator; node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand); node.transformFlags |= propagateChildFlags(node.operand); @@ -3427,20 +4613,36 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updatePostfixUnaryExpression(node: PostfixUnaryExpression, operand: Expression) { + function updatePostfixUnaryExpression( + node: PostfixUnaryExpression, + operand: Expression, + ) { return node.operand !== operand ? update(createPostfixUnaryExpression(operand, node.operator), node) : node; } // @api - function createBinaryExpression(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression) { - const node = createBaseDeclaration(SyntaxKind.BinaryExpression); + function createBinaryExpression( + left: Expression, + operator: BinaryOperator | BinaryOperatorToken, + right: Expression, + ) { + const node = createBaseDeclaration( + SyntaxKind.BinaryExpression, + ); const operatorToken = asToken(operator); const operatorKind = operatorToken.kind; - node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left); + node.left = parenthesizerRules().parenthesizeLeftSideOfBinary( + operatorKind, + left, + ); node.operatorToken = operatorToken; - node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right); + node.right = parenthesizerRules().parenthesizeRightSideOfBinary( + operatorKind, + node.left, + right, + ); node.transformFlags |= propagateChildFlags(node.left) | propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); @@ -3460,13 +4662,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode propagateAssignmentPatternFlags(node.left); } } - else if (operatorKind === SyntaxKind.AsteriskAsteriskToken || operatorKind === SyntaxKind.AsteriskAsteriskEqualsToken) { + else if ( + operatorKind === SyntaxKind.AsteriskAsteriskToken || + operatorKind === SyntaxKind.AsteriskAsteriskEqualsToken + ) { node.transformFlags |= TransformFlags.ContainsES2016; } else if (isLogicalOrCoalescingAssignmentOperator(operatorKind)) { node.transformFlags |= TransformFlags.ContainsES2021; } - if (operatorKind === SyntaxKind.InKeyword && isPrivateIdentifier(node.left)) { + if ( + operatorKind === SyntaxKind.InKeyword && + isPrivateIdentifier(node.left) + ) { node.transformFlags |= TransformFlags.ContainsPrivateIdentifierInExpression; } @@ -3474,27 +4682,50 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return node; } - function propagateAssignmentPatternFlags(node: AssignmentPattern): TransformFlags { - return containsObjectRestOrSpread(node) ? TransformFlags.ContainsObjectRestOrSpread : TransformFlags.None; + function propagateAssignmentPatternFlags( + node: AssignmentPattern, + ): TransformFlags { + return containsObjectRestOrSpread(node) + ? TransformFlags.ContainsObjectRestOrSpread + : TransformFlags.None; } // @api - function updateBinaryExpression(node: BinaryExpression, left: Expression, operator: BinaryOperatorToken, right: Expression) { - return node.left !== left - || node.operatorToken !== operator - || node.right !== right + function updateBinaryExpression( + node: BinaryExpression, + left: Expression, + operator: BinaryOperatorToken, + right: Expression, + ) { + return node.left !== left || + node.operatorToken !== operator || + node.right !== right ? update(createBinaryExpression(left, operator, right), node) : node; } // @api - function createConditionalExpression(condition: Expression, questionToken: QuestionToken | undefined, whenTrue: Expression, colonToken: ColonToken | undefined, whenFalse: Expression) { - const node = createBaseNode(SyntaxKind.ConditionalExpression); - node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition); + function createConditionalExpression( + condition: Expression, + questionToken: QuestionToken | undefined, + whenTrue: Expression, + colonToken: ColonToken | undefined, + whenFalse: Expression, + ) { + const node = createBaseNode( + SyntaxKind.ConditionalExpression, + ); + node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression( + condition, + ); node.questionToken = questionToken ?? createToken(SyntaxKind.QuestionToken); - node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue); + node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression( + whenTrue, + ); node.colonToken = colonToken ?? createToken(SyntaxKind.ColonToken); - node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse); + node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression( + whenFalse, + ); node.transformFlags |= propagateChildFlags(node.condition) | propagateChildFlags(node.questionToken) | propagateChildFlags(node.whenTrue) | @@ -3512,18 +4743,32 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode colonToken: Token, whenFalse: Expression, ): ConditionalExpression { - return node.condition !== condition - || node.questionToken !== questionToken - || node.whenTrue !== whenTrue - || node.colonToken !== colonToken - || node.whenFalse !== whenFalse - ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node) - : node; - } - - // @api - function createTemplateExpression(head: TemplateHead, templateSpans: readonly TemplateSpan[]) { - const node = createBaseNode(SyntaxKind.TemplateExpression); + return node.condition !== condition || + node.questionToken !== questionToken || + node.whenTrue !== whenTrue || + node.colonToken !== colonToken || + node.whenFalse !== whenFalse + ? update( + createConditionalExpression( + condition, + questionToken, + whenTrue, + colonToken, + whenFalse, + ), + node, + ) + : node; + } + + // @api + function createTemplateExpression( + head: TemplateHead, + templateSpans: readonly TemplateSpan[], + ) { + const node = createBaseNode( + SyntaxKind.TemplateExpression, + ); node.head = head; node.templateSpans = createNodeArray(templateSpans); node.transformFlags |= propagateChildFlags(node.head) | @@ -3533,15 +4778,26 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: readonly TemplateSpan[]) { - return node.head !== head - || node.templateSpans !== templateSpans + function updateTemplateExpression( + node: TemplateExpression, + head: TemplateHead, + templateSpans: readonly TemplateSpan[], + ) { + return node.head !== head || node.templateSpans !== templateSpans ? update(createTemplateExpression(head, templateSpans), node) : node; } - function checkTemplateLiteralLikeNode(kind: TemplateLiteralToken["kind"], text: string | undefined, rawText: string | undefined, templateFlags = TokenFlags.None) { - Debug.assert(!(templateFlags & ~TokenFlags.TemplateLiteralLikeFlags), "Unsupported template flags."); + function checkTemplateLiteralLikeNode( + kind: TemplateLiteralToken["kind"], + text: string | undefined, + rawText: string | undefined, + templateFlags = TokenFlags.None, + ) { + Debug.assert( + !(templateFlags & ~TokenFlags.TemplateLiteralLikeFlags), + "Unsupported template flags.", + ); // NOTE: without the assignment to `undefined`, we don't narrow the initial type of `cooked`. // eslint-disable-next-line no-undef-init let cooked: string | object | undefined = undefined; @@ -3553,12 +4809,17 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } if (text === undefined) { if (cooked === undefined) { - return Debug.fail("Arguments 'text' and 'rawText' may not both be undefined."); + return Debug.fail( + "Arguments 'text' and 'rawText' may not both be undefined.", + ); } text = cooked; } else if (cooked !== undefined) { - Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'."); + Debug.assert( + text === cooked, + "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.", + ); } return text; } @@ -3574,61 +4835,157 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // NOTE: `createTemplateLiteralLikeToken` and `createTemplateLiteralLikeDeclaration` are identical except for // the underlying nodes they create. To avoid polymorphism due to two different node shapes, these // functions are intentionally duplicated. - function createTemplateLiteralLikeToken(kind: TemplateLiteralToken["kind"], text: string, rawText: string | undefined, templateFlags: TokenFlags | undefined) { + function createTemplateLiteralLikeToken( + kind: TemplateLiteralToken["kind"], + text: string, + rawText: string | undefined, + templateFlags: TokenFlags | undefined, + ) { const node = createBaseToken(kind); node.text = text; node.rawText = rawText; node.templateFlags = templateFlags! & TokenFlags.TemplateLiteralLikeFlags; - node.transformFlags = getTransformFlagsOfTemplateLiteralLike(node.templateFlags); + node.transformFlags = getTransformFlagsOfTemplateLiteralLike( + node.templateFlags, + ); return node; } - function createTemplateLiteralLikeDeclaration(kind: SyntaxKind.NoSubstitutionTemplateLiteral, text: string, rawText: string | undefined, templateFlags: TokenFlags | undefined) { + function createTemplateLiteralLikeDeclaration( + kind: SyntaxKind.NoSubstitutionTemplateLiteral, + text: string, + rawText: string | undefined, + templateFlags: TokenFlags | undefined, + ) { const node = createBaseDeclaration(kind); node.text = text; node.rawText = rawText; node.templateFlags = templateFlags! & TokenFlags.TemplateLiteralLikeFlags; - node.transformFlags = getTransformFlagsOfTemplateLiteralLike(node.templateFlags); + node.transformFlags = getTransformFlagsOfTemplateLiteralLike( + node.templateFlags, + ); return node; } // @api - function createTemplateLiteralLikeNode(kind: TemplateLiteralToken["kind"], text: string, rawText: string | undefined, templateFlags: TokenFlags | undefined) { + function createTemplateLiteralLikeNode( + kind: TemplateLiteralToken["kind"], + text: string, + rawText: string | undefined, + templateFlags: TokenFlags | undefined, + ) { if (kind === SyntaxKind.NoSubstitutionTemplateLiteral) { - return createTemplateLiteralLikeDeclaration(kind, text, rawText, templateFlags); + return createTemplateLiteralLikeDeclaration( + kind, + text, + rawText, + templateFlags, + ); } - return createTemplateLiteralLikeToken(kind, text, rawText, templateFlags); + return createTemplateLiteralLikeToken( + kind, + text, + rawText, + templateFlags, + ); } // @api - function createTemplateHead(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) { - text = checkTemplateLiteralLikeNode(SyntaxKind.TemplateHead, text, rawText, templateFlags); - return createTemplateLiteralLikeNode(SyntaxKind.TemplateHead, text, rawText, templateFlags) as TemplateHead; + function createTemplateHead( + text: string | undefined, + rawText?: string, + templateFlags?: TokenFlags, + ) { + text = checkTemplateLiteralLikeNode( + SyntaxKind.TemplateHead, + text, + rawText, + templateFlags, + ); + return createTemplateLiteralLikeNode( + SyntaxKind.TemplateHead, + text, + rawText, + templateFlags, + ) as TemplateHead; } // @api - function createTemplateMiddle(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) { - text = checkTemplateLiteralLikeNode(SyntaxKind.TemplateHead, text, rawText, templateFlags); - return createTemplateLiteralLikeNode(SyntaxKind.TemplateMiddle, text, rawText, templateFlags) as TemplateMiddle; + function createTemplateMiddle( + text: string | undefined, + rawText?: string, + templateFlags?: TokenFlags, + ) { + text = checkTemplateLiteralLikeNode( + SyntaxKind.TemplateHead, + text, + rawText, + templateFlags, + ); + return createTemplateLiteralLikeNode( + SyntaxKind.TemplateMiddle, + text, + rawText, + templateFlags, + ) as TemplateMiddle; } // @api - function createTemplateTail(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) { - text = checkTemplateLiteralLikeNode(SyntaxKind.TemplateHead, text, rawText, templateFlags); - return createTemplateLiteralLikeNode(SyntaxKind.TemplateTail, text, rawText, templateFlags) as TemplateTail; + function createTemplateTail( + text: string | undefined, + rawText?: string, + templateFlags?: TokenFlags, + ) { + text = checkTemplateLiteralLikeNode( + SyntaxKind.TemplateHead, + text, + rawText, + templateFlags, + ); + return createTemplateLiteralLikeNode( + SyntaxKind.TemplateTail, + text, + rawText, + templateFlags, + ) as TemplateTail; } // @api - function createNoSubstitutionTemplateLiteral(text: string | undefined, rawText?: string, templateFlags?: TokenFlags) { - text = checkTemplateLiteralLikeNode(SyntaxKind.TemplateHead, text, rawText, templateFlags); - return createTemplateLiteralLikeDeclaration(SyntaxKind.NoSubstitutionTemplateLiteral, text, rawText, templateFlags) as NoSubstitutionTemplateLiteral; + function createNoSubstitutionTemplateLiteral( + text: string | undefined, + rawText?: string, + templateFlags?: TokenFlags, + ) { + text = checkTemplateLiteralLikeNode( + SyntaxKind.TemplateHead, + text, + rawText, + templateFlags, + ); + return createTemplateLiteralLikeDeclaration( + SyntaxKind.NoSubstitutionTemplateLiteral, + text, + rawText, + templateFlags, + ) as NoSubstitutionTemplateLiteral; } // @api - function createYieldExpression(asteriskToken: AsteriskToken | undefined, expression: Expression | undefined): YieldExpression { - Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression."); - const node = createBaseNode(SyntaxKind.YieldExpression); - node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + function createYieldExpression( + asteriskToken: AsteriskToken | undefined, + expression: Expression | undefined, + ): YieldExpression { + Debug.assert( + !asteriskToken || !!expression, + "A `YieldExpression` with an asteriskToken must have an expression.", + ); + const node = createBaseNode( + SyntaxKind.YieldExpression, + ); + node.expression = expression && + parenthesizerRules().parenthesizeExpressionForDisallowedComma( + expression, + ); node.asteriskToken = asteriskToken; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | @@ -3639,9 +4996,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateYieldExpression(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression) { - return node.expression !== expression - || node.asteriskToken !== asteriskToken + function updateYieldExpression( + node: YieldExpression, + asteriskToken: AsteriskToken | undefined, + expression: Expression, + ) { + return node.expression !== expression || + node.asteriskToken !== asteriskToken ? update(createYieldExpression(asteriskToken, expression), node) : node; } @@ -3649,7 +5010,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createSpreadElement(expression: Expression) { const node = createBaseNode(SyntaxKind.SpreadElement); - node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma( + expression, + ); node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsES2015 | TransformFlags.ContainsRestOrSpread; @@ -3671,7 +5034,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[], ) { - const node = createBaseDeclaration(SyntaxKind.ClassExpression); + const node = createBaseDeclaration( + SyntaxKind.ClassExpression, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.typeParameters = asNodeArray(typeParameters); @@ -3682,7 +5047,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.heritageClauses) | propagateChildrenFlags(node.members) | - (node.typeParameters ? TransformFlags.ContainsTypeScript : TransformFlags.None) | + (node.typeParameters + ? TransformFlags.ContainsTypeScript + : TransformFlags.None) | TransformFlags.ContainsES2015; node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -3698,12 +5065,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[], ) { - return node.modifiers !== modifiers - || node.name !== name - || node.typeParameters !== typeParameters - || node.heritageClauses !== heritageClauses - || node.members !== members - ? update(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node) + return node.modifiers !== modifiers || + node.name !== name || + node.typeParameters !== typeParameters || + node.heritageClauses !== heritageClauses || + node.members !== members + ? update( + createClassExpression( + modifiers, + name, + typeParameters, + heritageClauses, + members, + ), + node, + ) : node; } @@ -3713,10 +5089,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createExpressionWithTypeArguments(expression: Expression, typeArguments: readonly TypeNode[] | undefined) { - const node = createBaseNode(SyntaxKind.ExpressionWithTypeArguments); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); - node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments); + function createExpressionWithTypeArguments( + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + ) { + const node = createBaseNode( + SyntaxKind.ExpressionWithTypeArguments, + ); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ false, + ); + node.typeArguments = typeArguments && + parenthesizerRules().parenthesizeTypeArguments(typeArguments); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | TransformFlags.ContainsES2015; @@ -3724,10 +5109,17 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, expression: Expression, typeArguments: readonly TypeNode[] | undefined) { - return node.expression !== expression - || node.typeArguments !== typeArguments - ? update(createExpressionWithTypeArguments(expression, typeArguments), node) + function updateExpressionWithTypeArguments( + node: ExpressionWithTypeArguments, + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + ) { + return node.expression !== expression || + node.typeArguments !== typeArguments + ? update( + createExpressionWithTypeArguments(expression, typeArguments), + node, + ) : node; } @@ -3743,24 +5135,35 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode) { - return node.expression !== expression - || node.type !== type + function updateAsExpression( + node: AsExpression, + expression: Expression, + type: TypeNode, + ) { + return node.expression !== expression || node.type !== type ? update(createAsExpression(expression, type), node) : node; } // @api function createNonNullExpression(expression: Expression) { - const node = createBaseNode(SyntaxKind.NonNullExpression); - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); + const node = createBaseNode( + SyntaxKind.NonNullExpression, + ); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ false, + ); node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsTypeScript; return node; } // @api - function updateNonNullExpression(node: NonNullExpression, expression: Expression) { + function updateNonNullExpression( + node: NonNullExpression, + expression: Expression, + ) { if (isNonNullChain(node)) { return updateNonNullChain(node, expression); } @@ -3771,7 +5174,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createSatisfiesExpression(expression: Expression, type: TypeNode) { - const node = createBaseNode(SyntaxKind.SatisfiesExpression); + const node = createBaseNode( + SyntaxKind.SatisfiesExpression, + ); node.expression = expression; node.type = type; node.transformFlags |= propagateChildFlags(node.expression) | @@ -3781,9 +5186,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode) { - return node.expression !== expression - || node.type !== type + function updateSatisfiesExpression( + node: SatisfiesExpression, + expression: Expression, + type: TypeNode, + ) { + return node.expression !== expression || node.type !== type ? update(createSatisfiesExpression(expression, type), node) : node; } @@ -3792,7 +5200,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function createNonNullChain(expression: Expression) { const node = createBaseNode(SyntaxKind.NonNullExpression); node.flags |= NodeFlags.OptionalChain; - node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ true); + node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ true, + ); node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsTypeScript; return node; @@ -3800,14 +5211,20 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateNonNullChain(node: NonNullChain, expression: Expression) { - Debug.assert(!!(node.flags & NodeFlags.OptionalChain), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead."); + Debug.assert( + !!(node.flags & NodeFlags.OptionalChain), + "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.", + ); return node.expression !== expression ? update(createNonNullChain(expression), node) : node; } // @api - function createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier) { + function createMetaProperty( + keywordToken: MetaProperty["keywordToken"], + name: Identifier, + ) { const node = createBaseNode(SyntaxKind.MetaProperty); node.keywordToken = keywordToken; node.name = name; @@ -3839,7 +5256,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // // @api - function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail) { + function createTemplateSpan( + expression: Expression, + literal: TemplateMiddle | TemplateTail, + ) { const node = createBaseNode(SyntaxKind.TemplateSpan); node.expression = expression; node.literal = literal; @@ -3850,16 +5270,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail) { - return node.expression !== expression - || node.literal !== literal + function updateTemplateSpan( + node: TemplateSpan, + expression: Expression, + literal: TemplateMiddle | TemplateTail, + ) { + return node.expression !== expression || node.literal !== literal ? update(createTemplateSpan(expression, literal), node) : node; } // @api function createSemicolonClassElement() { - const node = createBaseNode(SyntaxKind.SemicolonClassElement); + const node = createBaseNode( + SyntaxKind.SemicolonClassElement, + ); node.transformFlags |= TransformFlags.ContainsES2015; return node; } @@ -3869,7 +5294,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // // @api - function createBlock(statements: readonly Statement[], multiLine?: boolean): Block { + function createBlock( + statements: readonly Statement[], + multiLine?: boolean, + ): Block { const node = createBaseNode(SyntaxKind.Block); node.statements = createNodeArray(statements); node.multiLine = multiLine; @@ -3889,10 +5317,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createVariableStatement(modifiers: readonly ModifierLike[] | undefined, declarationList: VariableDeclarationList | readonly VariableDeclaration[]) { - const node = createBaseNode(SyntaxKind.VariableStatement); + function createVariableStatement( + modifiers: readonly ModifierLike[] | undefined, + declarationList: + | VariableDeclarationList + | readonly VariableDeclaration[], + ) { + const node = createBaseNode( + SyntaxKind.VariableStatement, + ); node.modifiers = asNodeArray(modifiers); - node.declarationList = isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList; + node.declarationList = isArray(declarationList) + ? createVariableDeclarationList(declarationList) + : declarationList; node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.declarationList); if (modifiersToFlags(node.modifiers) & ModifierFlags.Ambient) { @@ -3905,9 +5342,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateVariableStatement(node: VariableStatement, modifiers: readonly ModifierLike[] | undefined, declarationList: VariableDeclarationList) { - return node.modifiers !== modifiers - || node.declarationList !== declarationList + function updateVariableStatement( + node: VariableStatement, + modifiers: readonly ModifierLike[] | undefined, + declarationList: VariableDeclarationList, + ) { + return node.modifiers !== modifiers || + node.declarationList !== declarationList ? update(createVariableStatement(modifiers, declarationList), node) : node; } @@ -3920,9 +5361,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createExpressionStatement(expression: Expression): ExpressionStatement { - const node = createBaseNode(SyntaxKind.ExpressionStatement); - node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression); + function createExpressionStatement( + expression: Expression, + ): ExpressionStatement { + const node = createBaseNode( + SyntaxKind.ExpressionStatement, + ); + node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement( + expression, + ); node.transformFlags |= propagateChildFlags(node.expression); node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -3931,14 +5378,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateExpressionStatement(node: ExpressionStatement, expression: Expression) { + function updateExpressionStatement( + node: ExpressionStatement, + expression: Expression, + ) { return node.expression !== expression ? update(createExpressionStatement(expression), node) : node; } // @api - function createIfStatement(expression: Expression, thenStatement: Statement, elseStatement?: Statement) { + function createIfStatement( + expression: Expression, + thenStatement: Statement, + elseStatement?: Statement, + ) { const node = createBaseNode(SyntaxKind.IfStatement); node.expression = expression; node.thenStatement = asEmbeddedStatement(thenStatement); @@ -3953,11 +5407,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateIfStatement(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement: Statement | undefined) { - return node.expression !== expression - || node.thenStatement !== thenStatement - || node.elseStatement !== elseStatement - ? update(createIfStatement(expression, thenStatement, elseStatement), node) + function updateIfStatement( + node: IfStatement, + expression: Expression, + thenStatement: Statement, + elseStatement: Statement | undefined, + ) { + return node.expression !== expression || + node.thenStatement !== thenStatement || + node.elseStatement !== elseStatement + ? update( + createIfStatement(expression, thenStatement, elseStatement), + node, + ) : node; } @@ -3975,15 +5437,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateDoStatement(node: DoStatement, statement: Statement, expression: Expression) { - return node.statement !== statement - || node.expression !== expression + function updateDoStatement( + node: DoStatement, + statement: Statement, + expression: Expression, + ) { + return node.statement !== statement || node.expression !== expression ? update(createDoStatement(statement, expression), node) : node; } // @api - function createWhileStatement(expression: Expression, statement: Statement) { + function createWhileStatement( + expression: Expression, + statement: Statement, + ) { const node = createBaseNode(SyntaxKind.WhileStatement); node.expression = expression; node.statement = asEmbeddedStatement(statement); @@ -3996,15 +5464,23 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateWhileStatement(node: WhileStatement, expression: Expression, statement: Statement) { - return node.expression !== expression - || node.statement !== statement + function updateWhileStatement( + node: WhileStatement, + expression: Expression, + statement: Statement, + ) { + return node.expression !== expression || node.statement !== statement ? update(createWhileStatement(expression, statement), node) : node; } // @api - function createForStatement(initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement) { + function createForStatement( + initializer: ForInitializer | undefined, + condition: Expression | undefined, + incrementor: Expression | undefined, + statement: Statement, + ) { const node = createBaseNode(SyntaxKind.ForStatement); node.initializer = initializer; node.condition = condition; @@ -4023,17 +5499,35 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateForStatement(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement) { - return node.initializer !== initializer - || node.condition !== condition - || node.incrementor !== incrementor - || node.statement !== statement - ? update(createForStatement(initializer, condition, incrementor, statement), node) + function updateForStatement( + node: ForStatement, + initializer: ForInitializer | undefined, + condition: Expression | undefined, + incrementor: Expression | undefined, + statement: Statement, + ) { + return node.initializer !== initializer || + node.condition !== condition || + node.incrementor !== incrementor || + node.statement !== statement + ? update( + createForStatement( + initializer, + condition, + incrementor, + statement, + ), + node, + ) : node; } // @api - function createForInStatement(initializer: ForInitializer, expression: Expression, statement: Statement) { + function createForInStatement( + initializer: ForInitializer, + expression: Expression, + statement: Statement, + ) { const node = createBaseNode(SyntaxKind.ForInStatement); node.initializer = initializer; node.expression = expression; @@ -4050,20 +5544,35 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateForInStatement(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement) { - return node.initializer !== initializer - || node.expression !== expression - || node.statement !== statement - ? update(createForInStatement(initializer, expression, statement), node) + function updateForInStatement( + node: ForInStatement, + initializer: ForInitializer, + expression: Expression, + statement: Statement, + ) { + return node.initializer !== initializer || + node.expression !== expression || + node.statement !== statement + ? update( + createForInStatement(initializer, expression, statement), + node, + ) : node; } // @api - function createForOfStatement(awaitModifier: AwaitKeyword | undefined, initializer: ForInitializer, expression: Expression, statement: Statement) { + function createForOfStatement( + awaitModifier: AwaitKeyword | undefined, + initializer: ForInitializer, + expression: Expression, + statement: Statement, + ) { const node = createBaseNode(SyntaxKind.ForOfStatement); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma( + expression, + ); node.statement = asEmbeddedStatement(statement); node.transformFlags |= propagateChildFlags(node.awaitModifier) | propagateChildFlags(node.initializer) | @@ -4080,18 +5589,36 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateForOfStatement(node: ForOfStatement, awaitModifier: AwaitKeyword | undefined, initializer: ForInitializer, expression: Expression, statement: Statement) { - return node.awaitModifier !== awaitModifier - || node.initializer !== initializer - || node.expression !== expression - || node.statement !== statement - ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node) - : node; - } - - // @api - function createContinueStatement(label?: string | Identifier): ContinueStatement { - const node = createBaseNode(SyntaxKind.ContinueStatement); + function updateForOfStatement( + node: ForOfStatement, + awaitModifier: AwaitKeyword | undefined, + initializer: ForInitializer, + expression: Expression, + statement: Statement, + ) { + return node.awaitModifier !== awaitModifier || + node.initializer !== initializer || + node.expression !== expression || + node.statement !== statement + ? update( + createForOfStatement( + awaitModifier, + initializer, + expression, + statement, + ), + node, + ) + : node; + } + + // @api + function createContinueStatement( + label?: string | Identifier, + ): ContinueStatement { + const node = createBaseNode( + SyntaxKind.ContinueStatement, + ); node.label = asName(label); node.transformFlags |= propagateChildFlags(node.label) | TransformFlags.ContainsHoistedDeclarationOrCompletion; @@ -4102,7 +5629,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateContinueStatement(node: ContinueStatement, label: Identifier | undefined) { + function updateContinueStatement( + node: ContinueStatement, + label: Identifier | undefined, + ) { return node.label !== label ? update(createContinueStatement(label), node) : node; @@ -4121,7 +5651,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateBreakStatement(node: BreakStatement, label: Identifier | undefined) { + function updateBreakStatement( + node: BreakStatement, + label: Identifier | undefined, + ) { return node.label !== label ? update(createBreakStatement(label), node) : node; @@ -4129,7 +5662,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createReturnStatement(expression?: Expression): ReturnStatement { - const node = createBaseNode(SyntaxKind.ReturnStatement); + const node = createBaseNode( + SyntaxKind.ReturnStatement, + ); node.expression = expression; // return in an ES2018 async generator must be awaited node.transformFlags |= propagateChildFlags(node.expression) | @@ -4142,7 +5677,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateReturnStatement(node: ReturnStatement, expression: Expression | undefined) { + function updateReturnStatement( + node: ReturnStatement, + expression: Expression | undefined, + ) { return node.expression !== expression ? update(createReturnStatement(expression), node) : node; @@ -4162,17 +5700,27 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateWithStatement(node: WithStatement, expression: Expression, statement: Statement) { - return node.expression !== expression - || node.statement !== statement + function updateWithStatement( + node: WithStatement, + expression: Expression, + statement: Statement, + ) { + return node.expression !== expression || node.statement !== statement ? update(createWithStatement(expression, statement), node) : node; } // @api - function createSwitchStatement(expression: Expression, caseBlock: CaseBlock): SwitchStatement { - const node = createBaseNode(SyntaxKind.SwitchStatement); - node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + function createSwitchStatement( + expression: Expression, + caseBlock: CaseBlock, + ): SwitchStatement { + const node = createBaseNode( + SyntaxKind.SwitchStatement, + ); + node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma( + expression, + ); node.caseBlock = caseBlock; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.caseBlock); @@ -4184,16 +5732,24 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateSwitchStatement(node: SwitchStatement, expression: Expression, caseBlock: CaseBlock) { - return node.expression !== expression - || node.caseBlock !== caseBlock + function updateSwitchStatement( + node: SwitchStatement, + expression: Expression, + caseBlock: CaseBlock, + ) { + return node.expression !== expression || node.caseBlock !== caseBlock ? update(createSwitchStatement(expression, caseBlock), node) : node; } // @api - function createLabeledStatement(label: string | Identifier, statement: Statement) { - const node = createBaseNode(SyntaxKind.LabeledStatement); + function createLabeledStatement( + label: string | Identifier, + statement: Statement, + ) { + const node = createBaseNode( + SyntaxKind.LabeledStatement, + ); node.label = asName(label); node.statement = asEmbeddedStatement(statement); node.transformFlags |= propagateChildFlags(node.label) | @@ -4205,9 +5761,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateLabeledStatement(node: LabeledStatement, label: Identifier, statement: Statement) { - return node.label !== label - || node.statement !== statement + function updateLabeledStatement( + node: LabeledStatement, + label: Identifier, + statement: Statement, + ) { + return node.label !== label || node.statement !== statement ? update(createLabeledStatement(label, statement), node) : node; } @@ -4224,14 +5783,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateThrowStatement(node: ThrowStatement, expression: Expression) { + function updateThrowStatement( + node: ThrowStatement, + expression: Expression, + ) { return node.expression !== expression ? update(createThrowStatement(expression), node) : node; } // @api - function createTryStatement(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined) { + function createTryStatement( + tryBlock: Block, + catchClause: CatchClause | undefined, + finallyBlock: Block | undefined, + ) { const node = createBaseNode(SyntaxKind.TryStatement); node.tryBlock = tryBlock; node.catchClause = catchClause; @@ -4246,17 +5812,27 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateTryStatement(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined) { - return node.tryBlock !== tryBlock - || node.catchClause !== catchClause - || node.finallyBlock !== finallyBlock - ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node) + function updateTryStatement( + node: TryStatement, + tryBlock: Block, + catchClause: CatchClause | undefined, + finallyBlock: Block | undefined, + ) { + return node.tryBlock !== tryBlock || + node.catchClause !== catchClause || + node.finallyBlock !== finallyBlock + ? update( + createTryStatement(tryBlock, catchClause, finallyBlock), + node, + ) : node; } // @api function createDebuggerStatement() { - const node = createBaseNode(SyntaxKind.DebuggerStatement); + const node = createBaseNode( + SyntaxKind.DebuggerStatement, + ); node.jsDoc = undefined; // initialized by parser (JsDocContainer) node.flowNode = undefined; // initialized by binder (FlowContainer) @@ -4264,33 +5840,61 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createVariableDeclaration(name: string | BindingName, exclamationToken: ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) { - const node = createBaseDeclaration(SyntaxKind.VariableDeclaration); + function createVariableDeclaration( + name: string | BindingName, + exclamationToken: ExclamationToken | undefined, + type: TypeNode | undefined, + initializer: Expression | undefined, + ) { + const node = createBaseDeclaration( + SyntaxKind.VariableDeclaration, + ); node.name = asName(name); node.exclamationToken = exclamationToken; node.type = type; node.initializer = asInitializer(initializer); node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer) | - (node.exclamationToken ?? node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None); + (node.exclamationToken ?? node.type + ? TransformFlags.ContainsTypeScript + : TransformFlags.None); node.jsDoc = undefined; // initialized by parser (JsDocContainer) return node; } // @api - function updateVariableDeclaration(node: VariableDeclaration, name: BindingName, exclamationToken: ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined) { - return node.name !== name - || node.type !== type - || node.exclamationToken !== exclamationToken - || node.initializer !== initializer - ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node) + function updateVariableDeclaration( + node: VariableDeclaration, + name: BindingName, + exclamationToken: ExclamationToken | undefined, + type: TypeNode | undefined, + initializer: Expression | undefined, + ) { + return node.name !== name || + node.type !== type || + node.exclamationToken !== exclamationToken || + node.initializer !== initializer + ? update( + createVariableDeclaration( + name, + exclamationToken, + type, + initializer, + ), + node, + ) : node; } // @api - function createVariableDeclarationList(declarations: readonly VariableDeclaration[], flags = NodeFlags.None) { - const node = createBaseNode(SyntaxKind.VariableDeclarationList); + function createVariableDeclarationList( + declarations: readonly VariableDeclaration[], + flags = NodeFlags.None, + ) { + const node = createBaseNode( + SyntaxKind.VariableDeclarationList, + ); node.flags |= flags & NodeFlags.BlockScoped; node.declarations = createNodeArray(declarations); node.transformFlags |= propagateChildrenFlags(node.declarations) | @@ -4306,9 +5910,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateVariableDeclarationList(node: VariableDeclarationList, declarations: readonly VariableDeclaration[]) { + function updateVariableDeclarationList( + node: VariableDeclarationList, + declarations: readonly VariableDeclaration[], + ) { return node.declarations !== declarations - ? update(createVariableDeclarationList(declarations, node.flags), node) + ? update( + createVariableDeclarationList(declarations, node.flags), + node, + ) : node; } @@ -4322,7 +5932,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode type: TypeNode | undefined, body: Block | undefined, ) { - const node = createBaseDeclaration(SyntaxKind.FunctionDeclaration); + const node = createBaseDeclaration( + SyntaxKind.FunctionDeclaration, + ); node.modifiers = asNodeArray(modifiers); node.asteriskToken = asteriskToken; node.name = asName(name); @@ -4331,7 +5943,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode node.type = type; node.body = body; - if (!node.body || modifiersToFlags(node.modifiers) & ModifierFlags.Ambient) { + if ( + !node.body || + modifiersToFlags(node.modifiers) & ModifierFlags.Ambient + ) { node.transformFlags = TransformFlags.ContainsTypeScript; } else { @@ -4345,12 +5960,18 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.type) | - (propagateChildFlags(node.body) & ~TransformFlags.ContainsPossibleTopLevelAwait) | - (isAsyncGenerator ? TransformFlags.ContainsES2018 : - isAsync ? TransformFlags.ContainsES2017 : - isGenerator ? TransformFlags.ContainsGenerator : - TransformFlags.None) | - (node.typeParameters || node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None) | + (propagateChildFlags(node.body) & + ~TransformFlags.ContainsPossibleTopLevelAwait) | + (isAsyncGenerator + ? TransformFlags.ContainsES2018 + : isAsync + ? TransformFlags.ContainsES2017 + : isGenerator + ? TransformFlags.ContainsGenerator + : TransformFlags.None) | + (node.typeParameters || node.type + ? TransformFlags.ContainsTypeScript + : TransformFlags.None) | TransformFlags.ContainsHoistedDeclarationOrCompletion; } @@ -4374,18 +5995,32 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode type: TypeNode | undefined, body: Block | undefined, ) { - return node.modifiers !== modifiers - || node.asteriskToken !== asteriskToken - || node.name !== name - || node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - || node.body !== body - ? finishUpdateFunctionDeclaration(createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node) - : node; - } - - function finishUpdateFunctionDeclaration(updated: Mutable, original: FunctionDeclaration) { + return node.modifiers !== modifiers || + node.asteriskToken !== asteriskToken || + node.name !== name || + node.typeParameters !== typeParameters || + node.parameters !== parameters || + node.type !== type || + node.body !== body + ? finishUpdateFunctionDeclaration( + createFunctionDeclaration( + modifiers, + asteriskToken, + name, + typeParameters, + parameters, + type, + body, + ), + node, + ) + : node; + } + + function finishUpdateFunctionDeclaration( + updated: Mutable, + original: FunctionDeclaration, + ) { if (updated !== original) { // copy children used only for error reporting if (updated.modifiers === original.modifiers) { @@ -4403,7 +6038,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[], ) { - const node = createBaseDeclaration(SyntaxKind.ClassDeclaration); + const node = createBaseDeclaration( + SyntaxKind.ClassDeclaration, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.typeParameters = asNodeArray(typeParameters); @@ -4419,9 +6056,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode propagateChildrenFlags(node.typeParameters) | propagateChildrenFlags(node.heritageClauses) | propagateChildrenFlags(node.members) | - (node.typeParameters ? TransformFlags.ContainsTypeScript : TransformFlags.None) | + (node.typeParameters + ? TransformFlags.ContainsTypeScript + : TransformFlags.None) | TransformFlags.ContainsES2015; - if (node.transformFlags & TransformFlags.ContainsTypeScriptClassSyntax) { + if ( + node.transformFlags & + TransformFlags.ContainsTypeScriptClassSyntax + ) { node.transformFlags |= TransformFlags.ContainsTypeScript; } } @@ -4439,12 +6081,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[], ) { - return node.modifiers !== modifiers - || node.name !== name - || node.typeParameters !== typeParameters - || node.heritageClauses !== heritageClauses - || node.members !== members - ? update(createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) + return node.modifiers !== modifiers || + node.name !== name || + node.typeParameters !== typeParameters || + node.heritageClauses !== heritageClauses || + node.members !== members + ? update( + createClassDeclaration( + modifiers, + name, + typeParameters, + heritageClauses, + members, + ), + node, + ) : node; } @@ -4456,7 +6107,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[], ) { - const node = createBaseDeclaration(SyntaxKind.InterfaceDeclaration); + const node = createBaseDeclaration( + SyntaxKind.InterfaceDeclaration, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.typeParameters = asNodeArray(typeParameters); @@ -4477,12 +6130,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[], ) { - return node.modifiers !== modifiers - || node.name !== name - || node.typeParameters !== typeParameters - || node.heritageClauses !== heritageClauses - || node.members !== members - ? update(createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members), node) + return node.modifiers !== modifiers || + node.name !== name || + node.typeParameters !== typeParameters || + node.heritageClauses !== heritageClauses || + node.members !== members + ? update( + createInterfaceDeclaration( + modifiers, + name, + typeParameters, + heritageClauses, + members, + ), + node, + ) : node; } @@ -4493,7 +6155,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode, ) { - const node = createBaseDeclaration(SyntaxKind.TypeAliasDeclaration); + const node = createBaseDeclaration( + SyntaxKind.TypeAliasDeclaration, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.typeParameters = asNodeArray(typeParameters); @@ -4514,11 +6178,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode, ) { - return node.modifiers !== modifiers - || node.name !== name - || node.typeParameters !== typeParameters - || node.type !== type - ? update(createTypeAliasDeclaration(modifiers, name, typeParameters, type), node) + return node.modifiers !== modifiers || + node.name !== name || + node.typeParameters !== typeParameters || + node.type !== type + ? update( + createTypeAliasDeclaration( + modifiers, + name, + typeParameters, + type, + ), + node, + ) : node; } @@ -4528,7 +6200,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: string | Identifier, members: readonly EnumMember[], ) { - const node = createBaseDeclaration(SyntaxKind.EnumDeclaration); + const node = createBaseDeclaration( + SyntaxKind.EnumDeclaration, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.members = createNodeArray(members); @@ -4549,9 +6223,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: Identifier, members: readonly EnumMember[], ) { - return node.modifiers !== modifiers - || node.name !== name - || node.members !== members + return node.modifiers !== modifiers || + node.name !== name || + node.members !== members ? update(createEnumDeclaration(modifiers, name, members), node) : node; } @@ -4563,9 +6237,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode body: ModuleBody | undefined, flags = NodeFlags.None, ) { - const node = createBaseDeclaration(SyntaxKind.ModuleDeclaration); + const node = createBaseDeclaration( + SyntaxKind.ModuleDeclaration, + ); node.modifiers = asNodeArray(modifiers); - node.flags |= flags & (NodeFlags.Namespace | NodeFlags.NestedNamespace | NodeFlags.GlobalAugmentation); + node.flags |= flags & + (NodeFlags.Namespace | + NodeFlags.NestedNamespace | + NodeFlags.GlobalAugmentation); node.name = name; node.body = body; if (modifiersToFlags(node.modifiers) & ModifierFlags.Ambient) { @@ -4592,10 +6271,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: ModuleName, body: ModuleBody | undefined, ) { - return node.modifiers !== modifiers - || node.name !== name - || node.body !== body - ? update(createModuleDeclaration(modifiers, name, body, node.flags), node) + return node.modifiers !== modifiers || + node.name !== name || + node.body !== body + ? update( + createModuleDeclaration(modifiers, name, body, node.flags), + node, + ) : node; } @@ -4610,14 +6292,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateModuleBlock(node: ModuleBlock, statements: readonly Statement[]) { + function updateModuleBlock( + node: ModuleBlock, + statements: readonly Statement[], + ) { return node.statements !== statements ? update(createModuleBlock(statements), node) : node; } // @api - function createCaseBlock(clauses: readonly CaseOrDefaultClause[]): CaseBlock { + function createCaseBlock( + clauses: readonly CaseOrDefaultClause[], + ): CaseBlock { const node = createBaseNode(SyntaxKind.CaseBlock); node.clauses = createNodeArray(clauses); node.transformFlags |= propagateChildrenFlags(node.clauses); @@ -4628,7 +6315,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateCaseBlock(node: CaseBlock, clauses: readonly CaseOrDefaultClause[]) { + function updateCaseBlock( + node: CaseBlock, + clauses: readonly CaseOrDefaultClause[], + ) { return node.clauses !== clauses ? update(createCaseBlock(clauses), node) : node; @@ -4636,7 +6326,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createNamespaceExportDeclaration(name: string | Identifier) { - const node = createBaseDeclaration(SyntaxKind.NamespaceExportDeclaration); + const node = createBaseDeclaration( + SyntaxKind.NamespaceExportDeclaration, + ); node.name = asName(name); node.transformFlags |= propagateIdentifierNameFlags(node.name) | TransformFlags.ContainsTypeScript; @@ -4647,13 +6339,22 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier) { + function updateNamespaceExportDeclaration( + node: NamespaceExportDeclaration, + name: Identifier, + ) { return node.name !== name - ? finishUpdateNamespaceExportDeclaration(createNamespaceExportDeclaration(name), node) + ? finishUpdateNamespaceExportDeclaration( + createNamespaceExportDeclaration(name), + node, + ) : node; } - function finishUpdateNamespaceExportDeclaration(updated: Mutable, original: NamespaceExportDeclaration) { + function finishUpdateNamespaceExportDeclaration( + updated: Mutable, + original: NamespaceExportDeclaration, + ) { if (updated !== original) { // copy children used only for error reporting updated.modifiers = original.modifiers; @@ -4668,7 +6369,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: string | Identifier, moduleReference: ModuleReference, ) { - const node = createBaseDeclaration(SyntaxKind.ImportEqualsDeclaration); + const node = createBaseDeclaration( + SyntaxKind.ImportEqualsDeclaration, + ); node.modifiers = asNodeArray(modifiers); node.name = asName(name); node.isTypeOnly = isTypeOnly; @@ -4695,11 +6398,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode name: Identifier, moduleReference: ModuleReference, ) { - return node.modifiers !== modifiers - || node.isTypeOnly !== isTypeOnly - || node.name !== name - || node.moduleReference !== moduleReference - ? update(createImportEqualsDeclaration(modifiers, isTypeOnly, name, moduleReference), node) + return node.modifiers !== modifiers || + node.isTypeOnly !== isTypeOnly || + node.name !== name || + node.moduleReference !== moduleReference + ? update( + createImportEqualsDeclaration( + modifiers, + isTypeOnly, + name, + moduleReference, + ), + node, + ) : node; } @@ -4710,7 +6421,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode moduleSpecifier: Expression, attributes: ImportAttributes | undefined, ): ImportDeclaration { - const node = createBaseNode(SyntaxKind.ImportDeclaration); + const node = createBaseNode( + SyntaxKind.ImportDeclaration, + ); node.modifiers = asNodeArray(modifiers); node.importClause = importClause; node.moduleSpecifier = moduleSpecifier; @@ -4731,17 +6444,31 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode moduleSpecifier: Expression, attributes: ImportAttributes | undefined, ) { - return node.modifiers !== modifiers - || node.importClause !== importClause - || node.moduleSpecifier !== moduleSpecifier - || node.attributes !== attributes - ? update(createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes), node) + return node.modifiers !== modifiers || + node.importClause !== importClause || + node.moduleSpecifier !== moduleSpecifier || + node.attributes !== attributes + ? update( + createImportDeclaration( + modifiers, + importClause, + moduleSpecifier, + attributes, + ), + node, + ) : node; } // @api - function createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause { - const node = createBaseDeclaration(SyntaxKind.ImportClause); + function createImportClause( + isTypeOnly: boolean, + name: Identifier | undefined, + namedBindings: NamedImportBindings | undefined, + ): ImportClause { + const node = createBaseDeclaration( + SyntaxKind.ImportClause, + ); node.isTypeOnly = isTypeOnly; node.name = name; node.namedBindings = namedBindings; @@ -4755,16 +6482,24 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined) { - return node.isTypeOnly !== isTypeOnly - || node.name !== name - || node.namedBindings !== namedBindings + function updateImportClause( + node: ImportClause, + isTypeOnly: boolean, + name: Identifier | undefined, + namedBindings: NamedImportBindings | undefined, + ) { + return node.isTypeOnly !== isTypeOnly || + node.name !== name || + node.namedBindings !== namedBindings ? update(createImportClause(isTypeOnly, name, namedBindings), node) : node; } // @api - function createAssertClause(elements: readonly AssertEntry[], multiLine?: boolean): AssertClause { + function createAssertClause( + elements: readonly AssertEntry[], + multiLine?: boolean, + ): AssertClause { const node = createBaseNode(SyntaxKind.AssertClause); node.elements = createNodeArray(elements); node.multiLine = multiLine; @@ -4774,15 +6509,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateAssertClause(node: AssertClause, elements: readonly AssertEntry[], multiLine?: boolean): AssertClause { - return node.elements !== elements - || node.multiLine !== multiLine + function updateAssertClause( + node: AssertClause, + elements: readonly AssertEntry[], + multiLine?: boolean, + ): AssertClause { + return node.elements !== elements || node.multiLine !== multiLine ? update(createAssertClause(elements, multiLine), node) : node; } // @api - function createAssertEntry(name: AssertionKey, value: Expression): AssertEntry { + function createAssertEntry( + name: AssertionKey, + value: Expression, + ): AssertEntry { const node = createBaseNode(SyntaxKind.AssertEntry); node.name = name; node.value = value; @@ -4791,34 +6532,61 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateAssertEntry(node: AssertEntry, name: AssertionKey, value: Expression): AssertEntry { - return node.name !== name - || node.value !== value + function updateAssertEntry( + node: AssertEntry, + name: AssertionKey, + value: Expression, + ): AssertEntry { + return node.name !== name || node.value !== value ? update(createAssertEntry(name, value), node) : node; } // @api - function createImportTypeAssertionContainer(clause: AssertClause, multiLine?: boolean): ImportTypeAssertionContainer { - const node = createBaseNode(SyntaxKind.ImportTypeAssertionContainer); + function createImportTypeAssertionContainer( + clause: AssertClause, + multiLine?: boolean, + ): ImportTypeAssertionContainer { + const node = createBaseNode( + SyntaxKind.ImportTypeAssertionContainer, + ); node.assertClause = clause; node.multiLine = multiLine; return node; } // @api - function updateImportTypeAssertionContainer(node: ImportTypeAssertionContainer, clause: AssertClause, multiLine?: boolean): ImportTypeAssertionContainer { - return node.assertClause !== clause - || node.multiLine !== multiLine - ? update(createImportTypeAssertionContainer(clause, multiLine), node) + function updateImportTypeAssertionContainer( + node: ImportTypeAssertionContainer, + clause: AssertClause, + multiLine?: boolean, + ): ImportTypeAssertionContainer { + return node.assertClause !== clause || node.multiLine !== multiLine + ? update( + createImportTypeAssertionContainer(clause, multiLine), + node, + ) : node; } // @api - function createImportAttributes(elements: readonly ImportAttribute[], multiLine?: boolean): ImportAttributes; - function createImportAttributes(elements: readonly ImportAttribute[], multiLine?: boolean, token?: ImportAttributes["token"]): ImportAttributes; - function createImportAttributes(elements: readonly ImportAttribute[], multiLine?: boolean, token?: ImportAttributes["token"]): ImportAttributes { - const node = createBaseNode(SyntaxKind.ImportAttributes); + function createImportAttributes( + elements: readonly ImportAttribute[], + multiLine?: boolean, + ): ImportAttributes; + function createImportAttributes( + elements: readonly ImportAttribute[], + multiLine?: boolean, + token?: ImportAttributes["token"], + ): ImportAttributes; + function createImportAttributes( + elements: readonly ImportAttribute[], + multiLine?: boolean, + token?: ImportAttributes["token"], + ): ImportAttributes { + const node = createBaseNode( + SyntaxKind.ImportAttributes, + ); node.token = token ?? SyntaxKind.WithKeyword; node.elements = createNodeArray(elements); node.multiLine = multiLine; @@ -4827,16 +6595,27 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateImportAttributes(node: ImportAttributes, elements: readonly ImportAttribute[], multiLine?: boolean): ImportAttributes { - return node.elements !== elements - || node.multiLine !== multiLine - ? update(createImportAttributes(elements, multiLine, node.token), node) + function updateImportAttributes( + node: ImportAttributes, + elements: readonly ImportAttribute[], + multiLine?: boolean, + ): ImportAttributes { + return node.elements !== elements || node.multiLine !== multiLine + ? update( + createImportAttributes(elements, multiLine, node.token), + node, + ) : node; } // @api - function createImportAttribute(name: ImportAttributeName, value: Expression): ImportAttribute { - const node = createBaseNode(SyntaxKind.ImportAttribute); + function createImportAttribute( + name: ImportAttributeName, + value: Expression, + ): ImportAttribute { + const node = createBaseNode( + SyntaxKind.ImportAttribute, + ); node.name = name; node.value = value; node.transformFlags |= TransformFlags.ContainsESNext; @@ -4844,16 +6623,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateImportAttribute(node: ImportAttribute, name: ImportAttributeName, value: Expression): ImportAttribute { - return node.name !== name - || node.value !== value + function updateImportAttribute( + node: ImportAttribute, + name: ImportAttributeName, + value: Expression, + ): ImportAttribute { + return node.name !== name || node.value !== value ? update(createImportAttribute(name, value), node) : node; } // @api function createNamespaceImport(name: Identifier): NamespaceImport { - const node = createBaseDeclaration(SyntaxKind.NamespaceImport); + const node = createBaseDeclaration( + SyntaxKind.NamespaceImport, + ); node.name = name; node.transformFlags |= propagateChildFlags(node.name); node.transformFlags &= ~TransformFlags.ContainsPossibleTopLevelAwait; // always parsed in an Await context @@ -4869,10 +6653,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createNamespaceExport(name: Identifier): NamespaceExport { - const node = createBaseDeclaration(SyntaxKind.NamespaceExport); + const node = createBaseDeclaration( + SyntaxKind.NamespaceExport, + ); node.name = name; - node.transformFlags |= propagateChildFlags(node.name) | - TransformFlags.ContainsES2020; + node.transformFlags |= propagateChildFlags(node.name) | TransformFlags.ContainsES2020; node.transformFlags &= ~TransformFlags.ContainsPossibleTopLevelAwait; // always parsed in an Await context return node; } @@ -4885,7 +6670,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createNamedImports(elements: readonly ImportSpecifier[]): NamedImports { + function createNamedImports( + elements: readonly ImportSpecifier[], + ): NamedImports { const node = createBaseNode(SyntaxKind.NamedImports); node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements); @@ -4894,15 +6681,24 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]) { + function updateNamedImports( + node: NamedImports, + elements: readonly ImportSpecifier[], + ) { return node.elements !== elements ? update(createNamedImports(elements), node) : node; } // @api - function createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) { - const node = createBaseDeclaration(SyntaxKind.ImportSpecifier); + function createImportSpecifier( + isTypeOnly: boolean, + propertyName: Identifier | undefined, + name: Identifier, + ) { + const node = createBaseDeclaration( + SyntaxKind.ImportSpecifier, + ); node.isTypeOnly = isTypeOnly; node.propertyName = propertyName; node.name = name; @@ -4913,11 +6709,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) { - return node.isTypeOnly !== isTypeOnly - || node.propertyName !== propertyName - || node.name !== name - ? update(createImportSpecifier(isTypeOnly, propertyName, name), node) + function updateImportSpecifier( + node: ImportSpecifier, + isTypeOnly: boolean, + propertyName: Identifier | undefined, + name: Identifier, + ) { + return node.isTypeOnly !== isTypeOnly || + node.propertyName !== propertyName || + node.name !== name + ? update( + createImportSpecifier(isTypeOnly, propertyName, name), + node, + ) : node; } @@ -4927,13 +6731,22 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode isExportEquals: boolean | undefined, expression: Expression, ) { - const node = createBaseDeclaration(SyntaxKind.ExportAssignment); + const node = createBaseDeclaration( + SyntaxKind.ExportAssignment, + ); node.modifiers = asNodeArray(modifiers); node.isExportEquals = isExportEquals; node.expression = isExportEquals - ? parenthesizerRules().parenthesizeRightSideOfBinary(SyntaxKind.EqualsToken, /*leftSide*/ undefined, expression) - : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression); - node.transformFlags |= propagateChildrenFlags(node.modifiers) | propagateChildFlags(node.expression); + ? parenthesizerRules().parenthesizeRightSideOfBinary( + SyntaxKind.EqualsToken, + /*leftSide*/ undefined, + expression, + ) + : parenthesizerRules().parenthesizeExpressionOfExportDefault( + expression, + ); + node.transformFlags |= propagateChildrenFlags(node.modifiers) | + propagateChildFlags(node.expression); node.transformFlags &= ~TransformFlags.ContainsPossibleTopLevelAwait; // always parsed in an Await context node.jsDoc = undefined; // initialized by parser (JsDocContainer) @@ -4946,9 +6759,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode modifiers: readonly ModifierLike[] | undefined, expression: Expression, ) { - return node.modifiers !== modifiers - || node.expression !== expression - ? update(createExportAssignment(modifiers, node.isExportEquals, expression), node) + return node.modifiers !== modifiers || node.expression !== expression + ? update( + createExportAssignment( + modifiers, + node.isExportEquals, + expression, + ), + node, + ) : node; } @@ -4960,7 +6779,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode moduleSpecifier?: Expression, attributes?: ImportAttributes, ) { - const node = createBaseDeclaration(SyntaxKind.ExportDeclaration); + const node = createBaseDeclaration( + SyntaxKind.ExportDeclaration, + ); node.modifiers = asNodeArray(modifiers); node.isTypeOnly = isTypeOnly; node.exportClause = exportClause; @@ -4984,16 +6805,28 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode moduleSpecifier: Expression | undefined, attributes: ImportAttributes | undefined, ) { - return node.modifiers !== modifiers - || node.isTypeOnly !== isTypeOnly - || node.exportClause !== exportClause - || node.moduleSpecifier !== moduleSpecifier - || node.attributes !== attributes - ? finishUpdateExportDeclaration(createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes), node) - : node; - } - - function finishUpdateExportDeclaration(updated: Mutable, original: ExportDeclaration) { + return node.modifiers !== modifiers || + node.isTypeOnly !== isTypeOnly || + node.exportClause !== exportClause || + node.moduleSpecifier !== moduleSpecifier || + node.attributes !== attributes + ? finishUpdateExportDeclaration( + createExportDeclaration( + modifiers, + isTypeOnly, + exportClause, + moduleSpecifier, + attributes, + ), + node, + ) + : node; + } + + function finishUpdateExportDeclaration( + updated: Mutable, + original: ExportDeclaration, + ) { if (updated !== original) { // copy children used only for error reporting if (updated.modifiers === original.modifiers) { @@ -5013,15 +6846,24 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]) { + function updateNamedExports( + node: NamedExports, + elements: readonly ExportSpecifier[], + ) { return node.elements !== elements ? update(createNamedExports(elements), node) : node; } // @api - function createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier) { - const node = createBaseNode(SyntaxKind.ExportSpecifier); + function createExportSpecifier( + isTypeOnly: boolean, + propertyName: string | Identifier | undefined, + name: string | Identifier, + ) { + const node = createBaseNode( + SyntaxKind.ExportSpecifier, + ); node.isTypeOnly = isTypeOnly; node.propertyName = asName(propertyName); node.name = asName(name); @@ -5034,17 +6876,27 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) { - return node.isTypeOnly !== isTypeOnly - || node.propertyName !== propertyName - || node.name !== name - ? update(createExportSpecifier(isTypeOnly, propertyName, name), node) + function updateExportSpecifier( + node: ExportSpecifier, + isTypeOnly: boolean, + propertyName: Identifier | undefined, + name: Identifier, + ) { + return node.isTypeOnly !== isTypeOnly || + node.propertyName !== propertyName || + node.name !== name + ? update( + createExportSpecifier(isTypeOnly, propertyName, name), + node, + ) : node; } // @api function createMissingDeclaration(): MissingDeclaration { - const node = createBaseDeclaration(SyntaxKind.MissingDeclaration); + const node = createBaseDeclaration( + SyntaxKind.MissingDeclaration, + ); node.jsDoc = undefined; // initialized by parser (JsDocContainer) return node; @@ -5056,7 +6908,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createExternalModuleReference(expression: Expression) { - const node = createBaseNode(SyntaxKind.ExternalModuleReference); + const node = createBaseNode( + SyntaxKind.ExternalModuleReference, + ); node.expression = expression; node.transformFlags |= propagateChildFlags(node.expression); node.transformFlags &= ~TransformFlags.ContainsPossibleTopLevelAwait; // always parsed in an Await context @@ -5064,7 +6918,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateExternalModuleReference(node: ExternalModuleReference, expression: Expression) { + function updateExternalModuleReference( + node: ExternalModuleReference, + expression: Expression, + ) { return node.expression !== expression ? update(createExternalModuleReference(expression), node) : node; @@ -5077,17 +6934,29 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api // createJSDocAllType // createJSDocUnknownType - function createJSDocPrimaryTypeWorker(kind: T["kind"]) { + function createJSDocPrimaryTypeWorker( + kind: T["kind"], + ) { return createBaseNode(kind); } // @api // createJSDocNullableType // createJSDocNonNullableType - function createJSDocPrePostfixUnaryTypeWorker(kind: T["kind"], type: T["type"], postfix = false): T { + function createJSDocPrePostfixUnaryTypeWorker< + T extends JSDocType & { + readonly type: TypeNode | undefined; + readonly postfix: boolean; + }, + >(kind: T["kind"], type: T["type"], postfix = false): T { const node = createJSDocUnaryTypeWorker( kind, - postfix ? type && parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType(type) : type, + postfix + ? type && + parenthesizerRules().parenthesizeNonArrayTypeOfPostfixType( + type, + ) + : type, ) as Mutable; node.postfix = postfix; return node; @@ -5097,7 +6966,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // createJSDocOptionalType // createJSDocVariadicType // createJSDocNamepathType - function createJSDocUnaryTypeWorker(kind: T["kind"], type: T["type"]): T { + function createJSDocUnaryTypeWorker< + T extends JSDocType & { readonly type: TypeNode | undefined; }, + >(kind: T["kind"], type: T["type"]): T { const node = createBaseNode(kind); node.type = type; return node; @@ -5106,9 +6977,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api // updateJSDocNonNullableType // updateJSDocNullableType - function updateJSDocPrePostfixUnaryTypeWorker(kind: T["kind"], node: T, type: T["type"]): T { + function updateJSDocPrePostfixUnaryTypeWorker< + T extends JSDocType & { + readonly type: TypeNode | undefined; + readonly postfix: boolean; + }, + >(kind: T["kind"], node: T, type: T["type"]): T { return node.type !== type - ? update(createJSDocPrePostfixUnaryTypeWorker(kind, type, node.postfix), node) + ? update( + createJSDocPrePostfixUnaryTypeWorker( + kind, + type, + node.postfix, + ), + node, + ) : node; } @@ -5116,19 +6999,28 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // updateJSDocOptionalType // updateJSDocVariadicType // updateJSDocNamepathType - function updateJSDocUnaryTypeWorker(kind: T["kind"], node: T, type: T["type"]): T { + function updateJSDocUnaryTypeWorker< + T extends JSDocType & { readonly type: TypeNode | undefined; }, + >(kind: T["kind"], node: T, type: T["type"]): T { return node.type !== type ? update(createJSDocUnaryTypeWorker(kind, type), node) : node; } // @api - function createJSDocFunctionType(parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): JSDocFunctionType { - const node = createBaseDeclaration(SyntaxKind.JSDocFunctionType); + function createJSDocFunctionType( + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + ): JSDocFunctionType { + const node = createBaseDeclaration( + SyntaxKind.JSDocFunctionType, + ); node.parameters = asNodeArray(parameters); node.type = type; node.transformFlags = propagateChildrenFlags(node.parameters) | - (node.type ? TransformFlags.ContainsTypeScript : TransformFlags.None); + (node.type + ? TransformFlags.ContainsTypeScript + : TransformFlags.None); node.jsDoc = undefined; // initialized by parser (JsDocContainer) node.locals = undefined; // initialized by binder (LocalsContainer) @@ -5138,46 +7030,69 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJSDocFunctionType(node: JSDocFunctionType, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): JSDocFunctionType { - return node.parameters !== parameters - || node.type !== type + function updateJSDocFunctionType( + node: JSDocFunctionType, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + ): JSDocFunctionType { + return node.parameters !== parameters || node.type !== type ? update(createJSDocFunctionType(parameters, type), node) : node; } // @api - function createJSDocTypeLiteral(propertyTags?: readonly JSDocPropertyLikeTag[], isArrayType = false): JSDocTypeLiteral { - const node = createBaseDeclaration(SyntaxKind.JSDocTypeLiteral); + function createJSDocTypeLiteral( + propertyTags?: readonly JSDocPropertyLikeTag[], + isArrayType = false, + ): JSDocTypeLiteral { + const node = createBaseDeclaration( + SyntaxKind.JSDocTypeLiteral, + ); node.jsDocPropertyTags = asNodeArray(propertyTags); node.isArrayType = isArrayType; return node; } // @api - function updateJSDocTypeLiteral(node: JSDocTypeLiteral, propertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean): JSDocTypeLiteral { - return node.jsDocPropertyTags !== propertyTags - || node.isArrayType !== isArrayType + function updateJSDocTypeLiteral( + node: JSDocTypeLiteral, + propertyTags: readonly JSDocPropertyLikeTag[] | undefined, + isArrayType: boolean, + ): JSDocTypeLiteral { + return node.jsDocPropertyTags !== propertyTags || + node.isArrayType !== isArrayType ? update(createJSDocTypeLiteral(propertyTags, isArrayType), node) : node; } // @api function createJSDocTypeExpression(type: TypeNode): JSDocTypeExpression { - const node = createBaseNode(SyntaxKind.JSDocTypeExpression); + const node = createBaseNode( + SyntaxKind.JSDocTypeExpression, + ); node.type = type; return node; } // @api - function updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression { + function updateJSDocTypeExpression( + node: JSDocTypeExpression, + type: TypeNode, + ): JSDocTypeExpression { return node.type !== type ? update(createJSDocTypeExpression(type), node) : node; } // @api - function createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature { - const node = createBaseDeclaration(SyntaxKind.JSDocSignature); + function createJSDocSignature( + typeParameters: readonly JSDocTemplateTag[] | undefined, + parameters: readonly JSDocParameterTag[], + type?: JSDocReturnTag, + ): JSDocSignature { + const node = createBaseDeclaration( + SyntaxKind.JSDocSignature, + ); node.typeParameters = asNodeArray(typeParameters); node.parameters = createNodeArray(parameters); node.type = type; @@ -5189,30 +7104,47 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature { - return node.typeParameters !== typeParameters - || node.parameters !== parameters - || node.type !== type - ? update(createJSDocSignature(typeParameters, parameters, type), node) + function updateJSDocSignature( + node: JSDocSignature, + typeParameters: readonly JSDocTemplateTag[] | undefined, + parameters: readonly JSDocParameterTag[], + type: JSDocReturnTag | undefined, + ): JSDocSignature { + return node.typeParameters !== typeParameters || + node.parameters !== parameters || + node.type !== type + ? update( + createJSDocSignature(typeParameters, parameters, type), + node, + ) : node; } function getDefaultTagName(node: JSDocTag) { const defaultTagName = getDefaultTagNameForKind(node.kind); - return node.tagName.escapedText === escapeLeadingUnderscores(defaultTagName) + return node.tagName.escapedText === + escapeLeadingUnderscores(defaultTagName) ? node.tagName : createIdentifier(defaultTagName); } // @api - function createBaseJSDocTag(kind: T["kind"], tagName: Identifier, comment: string | NodeArray | undefined) { + function createBaseJSDocTag( + kind: T["kind"], + tagName: Identifier, + comment: string | NodeArray | undefined, + ) { const node = createBaseNode(kind); node.tagName = tagName; node.comment = comment; return node; } - function createBaseJSDocTagDeclaration(kind: T["kind"], tagName: Identifier, comment: string | NodeArray | undefined) { + function createBaseJSDocTagDeclaration( + kind: T["kind"], + tagName: Identifier, + comment: string | NodeArray | undefined, + ) { const node = createBaseDeclaration(kind); node.tagName = tagName; node.comment = comment; @@ -5220,26 +7152,58 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag { - const node = createBaseJSDocTag(SyntaxKind.JSDocTemplateTag, tagName ?? createIdentifier("template"), comment); + function createJSDocTemplateTag( + tagName: Identifier | undefined, + constraint: JSDocTypeExpression | undefined, + typeParameters: readonly TypeParameterDeclaration[], + comment?: string | NodeArray, + ): JSDocTemplateTag { + const node = createBaseJSDocTag( + SyntaxKind.JSDocTemplateTag, + tagName ?? createIdentifier("template"), + comment, + ); node.constraint = constraint; node.typeParameters = createNodeArray(typeParameters); return node; } // @api - function updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier = getDefaultTagName(node), constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag { - return node.tagName !== tagName - || node.constraint !== constraint - || node.typeParameters !== typeParameters - || node.comment !== comment - ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node) - : node; - } - - // @api - function createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag { - const node = createBaseJSDocTagDeclaration(SyntaxKind.JSDocTypedefTag, tagName ?? createIdentifier("typedef"), comment); + function updateJSDocTemplateTag( + node: JSDocTemplateTag, + tagName: Identifier = getDefaultTagName(node), + constraint: JSDocTypeExpression | undefined, + typeParameters: readonly TypeParameterDeclaration[], + comment: string | NodeArray | undefined, + ): JSDocTemplateTag { + return node.tagName !== tagName || + node.constraint !== constraint || + node.typeParameters !== typeParameters || + node.comment !== comment + ? update( + createJSDocTemplateTag( + tagName, + constraint, + typeParameters, + comment, + ), + node, + ) + : node; + } + + // @api + function createJSDocTypedefTag( + tagName: Identifier | undefined, + typeExpression?: JSDocTypeExpression, + fullName?: Identifier | JSDocNamespaceDeclaration, + comment?: string | NodeArray, + ): JSDocTypedefTag { + const node = createBaseJSDocTagDeclaration( + SyntaxKind.JSDocTypedefTag, + tagName ?? createIdentifier("typedef"), + comment, + ); node.typeExpression = typeExpression; node.fullName = fullName; node.name = getJSDocTypeAliasName(fullName); @@ -5250,18 +7214,43 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag { - return node.tagName !== tagName - || node.typeExpression !== typeExpression - || node.fullName !== fullName - || node.comment !== comment - ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node) - : node; - } - - // @api - function createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag { - const node = createBaseJSDocTagDeclaration(SyntaxKind.JSDocParameterTag, tagName ?? createIdentifier("param"), comment); + function updateJSDocTypedefTag( + node: JSDocTypedefTag, + tagName: Identifier = getDefaultTagName(node), + typeExpression: JSDocTypeExpression | undefined, + fullName: Identifier | JSDocNamespaceDeclaration | undefined, + comment: string | NodeArray | undefined, + ): JSDocTypedefTag { + return node.tagName !== tagName || + node.typeExpression !== typeExpression || + node.fullName !== fullName || + node.comment !== comment + ? update( + createJSDocTypedefTag( + tagName, + typeExpression, + fullName, + comment, + ), + node, + ) + : node; + } + + // @api + function createJSDocParameterTag( + tagName: Identifier | undefined, + name: EntityName, + isBracketed: boolean, + typeExpression?: JSDocTypeExpression, + isNameFirst?: boolean, + comment?: string | NodeArray, + ): JSDocParameterTag { + const node = createBaseJSDocTagDeclaration( + SyntaxKind.JSDocParameterTag, + tagName ?? createIdentifier("param"), + comment, + ); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -5270,20 +7259,49 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag { - return node.tagName !== tagName - || node.name !== name - || node.isBracketed !== isBracketed - || node.typeExpression !== typeExpression - || node.isNameFirst !== isNameFirst - || node.comment !== comment - ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) - : node; - } - - // @api - function createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag { - const node = createBaseJSDocTagDeclaration(SyntaxKind.JSDocPropertyTag, tagName ?? createIdentifier("prop"), comment); + function updateJSDocParameterTag( + node: JSDocParameterTag, + tagName: Identifier = getDefaultTagName(node), + name: EntityName, + isBracketed: boolean, + typeExpression: JSDocTypeExpression | undefined, + isNameFirst: boolean, + comment: string | NodeArray | undefined, + ): JSDocParameterTag { + return node.tagName !== tagName || + node.name !== name || + node.isBracketed !== isBracketed || + node.typeExpression !== typeExpression || + node.isNameFirst !== isNameFirst || + node.comment !== comment + ? update( + createJSDocParameterTag( + tagName, + name, + isBracketed, + typeExpression, + isNameFirst, + comment, + ), + node, + ) + : node; + } + + // @api + function createJSDocPropertyTag( + tagName: Identifier | undefined, + name: EntityName, + isBracketed: boolean, + typeExpression?: JSDocTypeExpression, + isNameFirst?: boolean, + comment?: string | NodeArray, + ): JSDocPropertyTag { + const node = createBaseJSDocTagDeclaration( + SyntaxKind.JSDocPropertyTag, + tagName ?? createIdentifier("prop"), + comment, + ); node.typeExpression = typeExpression; node.name = name; node.isNameFirst = !!isNameFirst; @@ -5292,20 +7310,47 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier = getDefaultTagName(node), name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag { - return node.tagName !== tagName - || node.name !== name - || node.isBracketed !== isBracketed - || node.typeExpression !== typeExpression - || node.isNameFirst !== isNameFirst - || node.comment !== comment - ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node) - : node; - } - - // @api - function createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag { - const node = createBaseJSDocTagDeclaration(SyntaxKind.JSDocCallbackTag, tagName ?? createIdentifier("callback"), comment); + function updateJSDocPropertyTag( + node: JSDocPropertyTag, + tagName: Identifier = getDefaultTagName(node), + name: EntityName, + isBracketed: boolean, + typeExpression: JSDocTypeExpression | undefined, + isNameFirst: boolean, + comment: string | NodeArray | undefined, + ): JSDocPropertyTag { + return node.tagName !== tagName || + node.name !== name || + node.isBracketed !== isBracketed || + node.typeExpression !== typeExpression || + node.isNameFirst !== isNameFirst || + node.comment !== comment + ? update( + createJSDocPropertyTag( + tagName, + name, + isBracketed, + typeExpression, + isNameFirst, + comment, + ), + node, + ) + : node; + } + + // @api + function createJSDocCallbackTag( + tagName: Identifier | undefined, + typeExpression: JSDocSignature, + fullName?: Identifier | JSDocNamespaceDeclaration, + comment?: string | NodeArray, + ): JSDocCallbackTag { + const node = createBaseJSDocTagDeclaration( + SyntaxKind.JSDocCallbackTag, + tagName ?? createIdentifier("callback"), + comment, + ); node.typeExpression = typeExpression; node.fullName = fullName; node.name = getJSDocTypeAliasName(fullName); @@ -5316,104 +7361,185 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag { - return node.tagName !== tagName - || node.typeExpression !== typeExpression - || node.fullName !== fullName - || node.comment !== comment - ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node) - : node; - } - - // @api - function createJSDocOverloadTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, comment?: string | NodeArray): JSDocOverloadTag { - const node = createBaseJSDocTag(SyntaxKind.JSDocOverloadTag, tagName ?? createIdentifier("overload"), comment); + function updateJSDocCallbackTag( + node: JSDocCallbackTag, + tagName: Identifier = getDefaultTagName(node), + typeExpression: JSDocSignature, + fullName: Identifier | JSDocNamespaceDeclaration | undefined, + comment: string | NodeArray | undefined, + ): JSDocCallbackTag { + return node.tagName !== tagName || + node.typeExpression !== typeExpression || + node.fullName !== fullName || + node.comment !== comment + ? update( + createJSDocCallbackTag( + tagName, + typeExpression, + fullName, + comment, + ), + node, + ) + : node; + } + + // @api + function createJSDocOverloadTag( + tagName: Identifier | undefined, + typeExpression: JSDocSignature, + comment?: string | NodeArray, + ): JSDocOverloadTag { + const node = createBaseJSDocTag( + SyntaxKind.JSDocOverloadTag, + tagName ?? createIdentifier("overload"), + comment, + ); node.typeExpression = typeExpression; return node; } // @api - function updateJSDocOverloadTag(node: JSDocOverloadTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocSignature, comment: string | NodeArray | undefined): JSDocOverloadTag { - return node.tagName !== tagName - || node.typeExpression !== typeExpression - || node.comment !== comment - ? update(createJSDocOverloadTag(tagName, typeExpression, comment), node) + function updateJSDocOverloadTag( + node: JSDocOverloadTag, + tagName: Identifier = getDefaultTagName(node), + typeExpression: JSDocSignature, + comment: string | NodeArray | undefined, + ): JSDocOverloadTag { + return node.tagName !== tagName || + node.typeExpression !== typeExpression || + node.comment !== comment + ? update( + createJSDocOverloadTag(tagName, typeExpression, comment), + node, + ) : node; } // @api - function createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag { - const node = createBaseJSDocTag(SyntaxKind.JSDocAugmentsTag, tagName ?? createIdentifier("augments"), comment); + function createJSDocAugmentsTag( + tagName: Identifier | undefined, + className: JSDocAugmentsTag["class"], + comment?: string | NodeArray, + ): JSDocAugmentsTag { + const node = createBaseJSDocTag( + SyntaxKind.JSDocAugmentsTag, + tagName ?? createIdentifier("augments"), + comment, + ); node.class = className; return node; } // @api - function updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag { - return node.tagName !== tagName - || node.class !== className - || node.comment !== comment + function updateJSDocAugmentsTag( + node: JSDocAugmentsTag, + tagName: Identifier = getDefaultTagName(node), + className: JSDocAugmentsTag["class"], + comment: string | NodeArray | undefined, + ): JSDocAugmentsTag { + return node.tagName !== tagName || + node.class !== className || + node.comment !== comment ? update(createJSDocAugmentsTag(tagName, className, comment), node) : node; } // @api - function createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag { - const node = createBaseJSDocTag(SyntaxKind.JSDocImplementsTag, tagName ?? createIdentifier("implements"), comment); + function createJSDocImplementsTag( + tagName: Identifier | undefined, + className: JSDocImplementsTag["class"], + comment?: string | NodeArray, + ): JSDocImplementsTag { + const node = createBaseJSDocTag( + SyntaxKind.JSDocImplementsTag, + tagName ?? createIdentifier("implements"), + comment, + ); node.class = className; return node; } // @api - function createJSDocSeeTag(tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag { - const node = createBaseJSDocTag(SyntaxKind.JSDocSeeTag, tagName ?? createIdentifier("see"), comment); + function createJSDocSeeTag( + tagName: Identifier | undefined, + name: JSDocNameReference | undefined, + comment?: string | NodeArray, + ): JSDocSeeTag { + const node = createBaseJSDocTag( + SyntaxKind.JSDocSeeTag, + tagName ?? createIdentifier("see"), + comment, + ); node.name = name; return node; } // @api - function updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, name: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag { - return node.tagName !== tagName - || node.name !== name - || node.comment !== comment + function updateJSDocSeeTag( + node: JSDocSeeTag, + tagName: Identifier | undefined, + name: JSDocNameReference | undefined, + comment?: string | NodeArray, + ): JSDocSeeTag { + return node.tagName !== tagName || + node.name !== name || + node.comment !== comment ? update(createJSDocSeeTag(tagName, name, comment), node) : node; } // @api - function createJSDocNameReference(name: EntityName | JSDocMemberName): JSDocNameReference { - const node = createBaseNode(SyntaxKind.JSDocNameReference); + function createJSDocNameReference( + name: EntityName | JSDocMemberName, + ): JSDocNameReference { + const node = createBaseNode( + SyntaxKind.JSDocNameReference, + ); node.name = name; return node; } // @api - function updateJSDocNameReference(node: JSDocNameReference, name: EntityName | JSDocMemberName): JSDocNameReference { + function updateJSDocNameReference( + node: JSDocNameReference, + name: EntityName | JSDocMemberName, + ): JSDocNameReference { return node.name !== name ? update(createJSDocNameReference(name), node) : node; } // @api - function createJSDocMemberName(left: EntityName | JSDocMemberName, right: Identifier) { - const node = createBaseNode(SyntaxKind.JSDocMemberName); + function createJSDocMemberName( + left: EntityName | JSDocMemberName, + right: Identifier, + ) { + const node = createBaseNode( + SyntaxKind.JSDocMemberName, + ); node.left = left; node.right = right; - node.transformFlags |= propagateChildFlags(node.left) | - propagateChildFlags(node.right); + node.transformFlags |= propagateChildFlags(node.left) | propagateChildFlags(node.right); return node; } // @api - function updateJSDocMemberName(node: JSDocMemberName, left: EntityName | JSDocMemberName, right: Identifier) { - return node.left !== left - || node.right !== right + function updateJSDocMemberName( + node: JSDocMemberName, + left: EntityName | JSDocMemberName, + right: Identifier, + ) { + return node.left !== left || node.right !== right ? update(createJSDocMemberName(left, right), node) : node; } // @api - function createJSDocLink(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink { + function createJSDocLink( + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLink { const node = createBaseNode(SyntaxKind.JSDocLink); node.name = name; node.text = text; @@ -5421,14 +7547,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJSDocLink(node: JSDocLink, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink { + function updateJSDocLink( + node: JSDocLink, + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLink { return node.name !== name ? update(createJSDocLink(name, text), node) : node; } // @api - function createJSDocLinkCode(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode { + function createJSDocLinkCode( + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLinkCode { const node = createBaseNode(SyntaxKind.JSDocLinkCode); node.name = name; node.text = text; @@ -5436,14 +7569,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJSDocLinkCode(node: JSDocLinkCode, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode { + function updateJSDocLinkCode( + node: JSDocLinkCode, + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLinkCode { return node.name !== name ? update(createJSDocLinkCode(name, text), node) : node; } // @api - function createJSDocLinkPlain(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain { + function createJSDocLinkPlain( + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLinkPlain { const node = createBaseNode(SyntaxKind.JSDocLinkPlain); node.name = name; node.text = text; @@ -5451,18 +7591,30 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJSDocLinkPlain(node: JSDocLinkPlain, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain { + function updateJSDocLinkPlain( + node: JSDocLinkPlain, + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLinkPlain { return node.name !== name ? update(createJSDocLinkPlain(name, text), node) : node; } // @api - function updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier = getDefaultTagName(node), className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag { - return node.tagName !== tagName - || node.class !== className - || node.comment !== comment - ? update(createJSDocImplementsTag(tagName, className, comment), node) + function updateJSDocImplementsTag( + node: JSDocImplementsTag, + tagName: Identifier = getDefaultTagName(node), + className: JSDocImplementsTag["class"], + comment: string | NodeArray | undefined, + ): JSDocImplementsTag { + return node.tagName !== tagName || + node.class !== className || + node.comment !== comment + ? update( + createJSDocImplementsTag(tagName, className, comment), + node, + ) : node; } @@ -5474,8 +7626,16 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // createJSDocProtectedTag // createJSDocReadonlyTag // createJSDocDeprecatedTag - function createJSDocSimpleTagWorker(kind: T["kind"], tagName: Identifier | undefined, comment?: string | NodeArray) { - const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); + function createJSDocSimpleTagWorker( + kind: T["kind"], + tagName: Identifier | undefined, + comment?: string | NodeArray, + ) { + const node = createBaseJSDocTag( + kind, + tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), + comment, + ); return node; } @@ -5487,11 +7647,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // updateJSDocProtectedTag // updateJSDocReadonlyTag // updateJSDocDeprecatedTag - function updateJSDocSimpleTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), comment: string | NodeArray | undefined) { - return node.tagName !== tagName - || node.comment !== comment - ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) : - node; + function updateJSDocSimpleTagWorker( + kind: T["kind"], + node: T, + tagName: Identifier = getDefaultTagName(node), + comment: string | NodeArray | undefined, + ) { + return node.tagName !== tagName || node.comment !== comment + ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) + : node; } // @api @@ -5500,8 +7664,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // createJSDocThisTag // createJSDocEnumTag // createJSDocSatisfiesTag - function createJSDocTypeLikeTagWorker(kind: T["kind"], tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray) { - const node = createBaseJSDocTag(kind, tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), comment); + function createJSDocTypeLikeTagWorker< + T extends JSDocTag & { typeExpression?: JSDocTypeExpression; }, + >( + kind: T["kind"], + tagName: Identifier | undefined, + typeExpression?: JSDocTypeExpression, + comment?: string | NodeArray, + ) { + const node = createBaseJSDocTag( + kind, + tagName ?? createIdentifier(getDefaultTagNameForKind(kind)), + comment, + ); node.typeExpression = typeExpression; return node; } @@ -5512,31 +7687,68 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // updateJSDocThisTag // updateJSDocEnumTag // updateJSDocSatisfiesTag - function updateJSDocTypeLikeTagWorker(kind: T["kind"], node: T, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined) { - return node.tagName !== tagName - || node.typeExpression !== typeExpression - || node.comment !== comment - ? update(createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment), node) - : node; - } - - // @api - function createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag { - const node = createBaseJSDocTag(SyntaxKind.JSDocTag, tagName, comment); + function updateJSDocTypeLikeTagWorker< + T extends JSDocTag & { typeExpression?: JSDocTypeExpression; }, + >( + kind: T["kind"], + node: T, + tagName: Identifier = getDefaultTagName(node), + typeExpression: JSDocTypeExpression | undefined, + comment: string | NodeArray | undefined, + ) { + return node.tagName !== tagName || + node.typeExpression !== typeExpression || + node.comment !== comment + ? update( + createJSDocTypeLikeTagWorker( + kind, + tagName, + typeExpression, + comment, + ), + node, + ) + : node; + } + + // @api + function createJSDocUnknownTag( + tagName: Identifier, + comment?: string | NodeArray, + ): JSDocUnknownTag { + const node = createBaseJSDocTag( + SyntaxKind.JSDocTag, + tagName, + comment, + ); return node; } // @api - function updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag { - return node.tagName !== tagName - || node.comment !== comment + function updateJSDocUnknownTag( + node: JSDocUnknownTag, + tagName: Identifier, + comment: string | NodeArray | undefined, + ): JSDocUnknownTag { + return node.tagName !== tagName || node.comment !== comment ? update(createJSDocUnknownTag(tagName, comment), node) : node; } // @api - function createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray) { - const node = createBaseJSDocTagDeclaration(SyntaxKind.JSDocEnumTag, tagName ?? createIdentifier(getDefaultTagNameForKind(SyntaxKind.JSDocEnumTag)), comment); + function createJSDocEnumTag( + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression, + comment?: string | NodeArray, + ) { + const node = createBaseJSDocTagDeclaration( + SyntaxKind.JSDocEnumTag, + tagName ?? + createIdentifier( + getDefaultTagNameForKind(SyntaxKind.JSDocEnumTag), + ), + comment, + ); node.typeExpression = typeExpression; node.locals = undefined; // initialized by binder (LocalsContainer) @@ -5545,10 +7757,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier = getDefaultTagName(node), typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined) { - return node.tagName !== tagName - || node.typeExpression !== typeExpression - || node.comment !== comment + function updateJSDocEnumTag( + node: JSDocEnumTag, + tagName: Identifier = getDefaultTagName(node), + typeExpression: JSDocTypeExpression, + comment: string | NodeArray | undefined, + ) { + return node.tagName !== tagName || + node.typeExpression !== typeExpression || + node.comment !== comment ? update(createJSDocEnumTag(tagName, typeExpression, comment), node) : node; } @@ -5562,13 +7779,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function updateJSDocText(node: JSDocText, text: string): JSDocText { - return node.text !== text - ? update(createJSDocText(text), node) - : node; + return node.text !== text ? update(createJSDocText(text), node) : node; } // @api - function createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined) { + function createJSDocComment( + comment?: string | NodeArray | undefined, + tags?: readonly JSDocTag[] | undefined, + ) { const node = createBaseNode(SyntaxKind.JSDoc); node.comment = comment; node.tags = asNodeArray(tags); @@ -5576,9 +7794,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined) { - return node.comment !== comment - || node.tags !== tags + function updateJSDocComment( + node: JSDoc, + comment: string | NodeArray | undefined, + tags: readonly JSDocTag[] | undefined, + ) { + return node.comment !== comment || node.tags !== tags ? update(createJSDocComment(comment, tags), node) : node; } @@ -5588,7 +7809,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // // @api - function createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement) { + function createJsxElement( + openingElement: JsxOpeningElement, + children: readonly JsxChild[], + closingElement: JsxClosingElement, + ) { const node = createBaseNode(SyntaxKind.JsxElement); node.openingElement = openingElement; node.children = createNodeArray(children); @@ -5601,17 +7826,31 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement) { - return node.openingElement !== openingElement - || node.children !== children - || node.closingElement !== closingElement - ? update(createJsxElement(openingElement, children, closingElement), node) + function updateJsxElement( + node: JsxElement, + openingElement: JsxOpeningElement, + children: readonly JsxChild[], + closingElement: JsxClosingElement, + ) { + return node.openingElement !== openingElement || + node.children !== children || + node.closingElement !== closingElement + ? update( + createJsxElement(openingElement, children, closingElement), + node, + ) : node; } // @api - function createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes) { - const node = createBaseNode(SyntaxKind.JsxSelfClosingElement); + function createJsxSelfClosingElement( + tagName: JsxTagNameExpression, + typeArguments: readonly TypeNode[] | undefined, + attributes: JsxAttributes, + ) { + const node = createBaseNode( + SyntaxKind.JsxSelfClosingElement, + ); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -5626,17 +7865,35 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes) { - return node.tagName !== tagName - || node.typeArguments !== typeArguments - || node.attributes !== attributes - ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node) + function updateJsxSelfClosingElement( + node: JsxSelfClosingElement, + tagName: JsxTagNameExpression, + typeArguments: readonly TypeNode[] | undefined, + attributes: JsxAttributes, + ) { + return node.tagName !== tagName || + node.typeArguments !== typeArguments || + node.attributes !== attributes + ? update( + createJsxSelfClosingElement( + tagName, + typeArguments, + attributes, + ), + node, + ) : node; } // @api - function createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes) { - const node = createBaseNode(SyntaxKind.JsxOpeningElement); + function createJsxOpeningElement( + tagName: JsxTagNameExpression, + typeArguments: readonly TypeNode[] | undefined, + attributes: JsxAttributes, + ) { + const node = createBaseNode( + SyntaxKind.JsxOpeningElement, + ); node.tagName = tagName; node.typeArguments = asNodeArray(typeArguments); node.attributes = attributes; @@ -5651,32 +7908,48 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes) { - return node.tagName !== tagName - || node.typeArguments !== typeArguments - || node.attributes !== attributes - ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node) + function updateJsxOpeningElement( + node: JsxOpeningElement, + tagName: JsxTagNameExpression, + typeArguments: readonly TypeNode[] | undefined, + attributes: JsxAttributes, + ) { + return node.tagName !== tagName || + node.typeArguments !== typeArguments || + node.attributes !== attributes + ? update( + createJsxOpeningElement(tagName, typeArguments, attributes), + node, + ) : node; } // @api function createJsxClosingElement(tagName: JsxTagNameExpression) { - const node = createBaseNode(SyntaxKind.JsxClosingElement); + const node = createBaseNode( + SyntaxKind.JsxClosingElement, + ); node.tagName = tagName; - node.transformFlags |= propagateChildFlags(node.tagName) | - TransformFlags.ContainsJsx; + node.transformFlags |= propagateChildFlags(node.tagName) | TransformFlags.ContainsJsx; return node; } // @api - function updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression) { + function updateJsxClosingElement( + node: JsxClosingElement, + tagName: JsxTagNameExpression, + ) { return node.tagName !== tagName ? update(createJsxClosingElement(tagName), node) : node; } // @api - function createJsxFragment(openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment) { + function createJsxFragment( + openingFragment: JsxOpeningFragment, + children: readonly JsxChild[], + closingFragment: JsxClosingFragment, + ) { const node = createBaseNode(SyntaxKind.JsxFragment); node.openingFragment = openingFragment; node.children = createNodeArray(children); @@ -5689,16 +7962,27 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment) { - return node.openingFragment !== openingFragment - || node.children !== children - || node.closingFragment !== closingFragment - ? update(createJsxFragment(openingFragment, children, closingFragment), node) + function updateJsxFragment( + node: JsxFragment, + openingFragment: JsxOpeningFragment, + children: readonly JsxChild[], + closingFragment: JsxClosingFragment, + ) { + return node.openingFragment !== openingFragment || + node.children !== children || + node.closingFragment !== closingFragment + ? update( + createJsxFragment(openingFragment, children, closingFragment), + node, + ) : node; } // @api - function createJsxText(text: string, containsOnlyTriviaWhiteSpaces?: boolean) { + function createJsxText( + text: string, + containsOnlyTriviaWhiteSpaces?: boolean, + ) { const node = createBaseNode(SyntaxKind.JsxText); node.text = text; node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces; @@ -5707,30 +7991,43 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJsxText(node: JsxText, text: string, containsOnlyTriviaWhiteSpaces?: boolean) { - return node.text !== text - || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces + function updateJsxText( + node: JsxText, + text: string, + containsOnlyTriviaWhiteSpaces?: boolean, + ) { + return node.text !== text || + node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces ? update(createJsxText(text, containsOnlyTriviaWhiteSpaces), node) : node; } // @api function createJsxOpeningFragment() { - const node = createBaseNode(SyntaxKind.JsxOpeningFragment); + const node = createBaseNode( + SyntaxKind.JsxOpeningFragment, + ); node.transformFlags |= TransformFlags.ContainsJsx; return node; } // @api function createJsxJsxClosingFragment() { - const node = createBaseNode(SyntaxKind.JsxClosingFragment); + const node = createBaseNode( + SyntaxKind.JsxClosingFragment, + ); node.transformFlags |= TransformFlags.ContainsJsx; return node; } // @api - function createJsxAttribute(name: JsxAttributeName, initializer: JsxAttributeValue | undefined) { - const node = createBaseDeclaration(SyntaxKind.JsxAttribute); + function createJsxAttribute( + name: JsxAttributeName, + initializer: JsxAttributeValue | undefined, + ) { + const node = createBaseDeclaration( + SyntaxKind.JsxAttribute, + ); node.name = name; node.initializer = initializer; node.transformFlags |= propagateChildFlags(node.name) | @@ -5740,16 +8037,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJsxAttribute(node: JsxAttribute, name: JsxAttributeName, initializer: JsxAttributeValue | undefined) { - return node.name !== name - || node.initializer !== initializer + function updateJsxAttribute( + node: JsxAttribute, + name: JsxAttributeName, + initializer: JsxAttributeValue | undefined, + ) { + return node.name !== name || node.initializer !== initializer ? update(createJsxAttribute(name, initializer), node) : node; } // @api function createJsxAttributes(properties: readonly JsxAttributeLike[]) { - const node = createBaseDeclaration(SyntaxKind.JsxAttributes); + const node = createBaseDeclaration( + SyntaxKind.JsxAttributes, + ); node.properties = createNodeArray(properties); node.transformFlags |= propagateChildrenFlags(node.properties) | TransformFlags.ContainsJsx; @@ -5757,7 +8059,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJsxAttributes(node: JsxAttributes, properties: readonly JsxAttributeLike[]) { + function updateJsxAttributes( + node: JsxAttributes, + properties: readonly JsxAttributeLike[], + ) { return node.properties !== properties ? update(createJsxAttributes(properties), node) : node; @@ -5765,22 +8070,29 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createJsxSpreadAttribute(expression: Expression) { - const node = createBaseNode(SyntaxKind.JsxSpreadAttribute); + const node = createBaseNode( + SyntaxKind.JsxSpreadAttribute, + ); node.expression = expression; - node.transformFlags |= propagateChildFlags(node.expression) | - TransformFlags.ContainsJsx; + node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsJsx; return node; } // @api - function updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression) { + function updateJsxSpreadAttribute( + node: JsxSpreadAttribute, + expression: Expression, + ) { return node.expression !== expression ? update(createJsxSpreadAttribute(expression), node) : node; } // @api - function createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined) { + function createJsxExpression( + dotDotDotToken: DotDotDotToken | undefined, + expression: Expression | undefined, + ) { const node = createBaseNode(SyntaxKind.JsxExpression); node.dotDotDotToken = dotDotDotToken; node.expression = expression; @@ -5791,7 +8103,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJsxExpression(node: JsxExpression, expression: Expression | undefined) { + function updateJsxExpression( + node: JsxExpression, + expression: Expression | undefined, + ) { return node.expression !== expression ? update(createJsxExpression(node.dotDotDotToken, expression), node) : node; @@ -5799,7 +8114,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createJsxNamespacedName(namespace: Identifier, name: Identifier) { - const node = createBaseNode(SyntaxKind.JsxNamespacedName); + const node = createBaseNode( + SyntaxKind.JsxNamespacedName, + ); node.namespace = namespace; node.name = name; node.transformFlags |= propagateChildFlags(node.namespace) | @@ -5809,9 +8126,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateJsxNamespacedName(node: JsxNamespacedName, namespace: Identifier, name: Identifier) { - return node.namespace !== namespace - || node.name !== name + function updateJsxNamespacedName( + node: JsxNamespacedName, + namespace: Identifier, + name: Identifier, + ) { + return node.namespace !== namespace || node.name !== name ? update(createJsxNamespacedName(namespace, name), node) : node; } @@ -5821,9 +8141,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // // @api - function createCaseClause(expression: Expression, statements: readonly Statement[]) { + function createCaseClause( + expression: Expression, + statements: readonly Statement[], + ) { const node = createBaseNode(SyntaxKind.CaseClause); - node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma( + expression, + ); node.statements = createNodeArray(statements); node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.statements); @@ -5833,9 +8158,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateCaseClause(node: CaseClause, expression: Expression, statements: readonly Statement[]) { - return node.expression !== expression - || node.statements !== statements + function updateCaseClause( + node: CaseClause, + expression: Expression, + statements: readonly Statement[], + ) { + return node.expression !== expression || node.statements !== statements ? update(createCaseClause(expression, statements), node) : node; } @@ -5849,14 +8177,20 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateDefaultClause(node: DefaultClause, statements: readonly Statement[]) { + function updateDefaultClause( + node: DefaultClause, + statements: readonly Statement[], + ) { return node.statements !== statements ? update(createDefaultClause(statements), node) : node; } // @api - function createHeritageClause(token: HeritageClause["token"], types: readonly ExpressionWithTypeArguments[]) { + function createHeritageClause( + token: HeritageClause["token"], + types: readonly ExpressionWithTypeArguments[], + ) { const node = createBaseNode(SyntaxKind.HeritageClause); node.token = token; node.types = createNodeArray(types); @@ -5875,21 +8209,33 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateHeritageClause(node: HeritageClause, types: readonly ExpressionWithTypeArguments[]) { + function updateHeritageClause( + node: HeritageClause, + types: readonly ExpressionWithTypeArguments[], + ) { return node.types !== types ? update(createHeritageClause(node.token, types), node) : node; } // @api - function createCatchClause(variableDeclaration: string | BindingName | VariableDeclaration | undefined, block: Block) { + function createCatchClause( + variableDeclaration: + | string + | BindingName + | VariableDeclaration + | undefined, + block: Block, + ) { const node = createBaseNode(SyntaxKind.CatchClause); node.variableDeclaration = asVariableDeclaration(variableDeclaration); node.block = block; node.transformFlags |= propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block) | - (!variableDeclaration ? TransformFlags.ContainsES2019 : TransformFlags.None); + (!variableDeclaration + ? TransformFlags.ContainsES2019 + : TransformFlags.None); node.locals = undefined; // initialized by binder (LocalsContainer) node.nextContainer = undefined; // initialized by binder (LocalsContainer) @@ -5897,9 +8243,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block) { - return node.variableDeclaration !== variableDeclaration - || node.block !== block + function updateCatchClause( + node: CatchClause, + variableDeclaration: VariableDeclaration | undefined, + block: Block, + ) { + return node.variableDeclaration !== variableDeclaration || + node.block !== block ? update(createCatchClause(variableDeclaration, block), node) : node; } @@ -5909,10 +8259,17 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // // @api - function createPropertyAssignment(name: string | PropertyName, initializer: Expression) { - const node = createBaseDeclaration(SyntaxKind.PropertyAssignment); + function createPropertyAssignment( + name: string | PropertyName, + initializer: Expression, + ) { + const node = createBaseDeclaration( + SyntaxKind.PropertyAssignment, + ); node.name = asName(name); - node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); + node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma( + initializer, + ); node.transformFlags |= propagateNameFlags(node.name) | propagateChildFlags(node.initializer); @@ -5924,14 +8281,23 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression) { - return node.name !== name - || node.initializer !== initializer - ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node) + function updatePropertyAssignment( + node: PropertyAssignment, + name: PropertyName, + initializer: Expression, + ) { + return node.name !== name || node.initializer !== initializer + ? finishUpdatePropertyAssignment( + createPropertyAssignment(name, initializer), + node, + ) : node; } - function finishUpdatePropertyAssignment(updated: Mutable, original: PropertyAssignment) { + function finishUpdatePropertyAssignment( + updated: Mutable, + original: PropertyAssignment, + ) { // copy children used only for error reporting if (updated !== original) { // copy children used only for error reporting @@ -5943,10 +8309,18 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression) { - const node = createBaseDeclaration(SyntaxKind.ShorthandPropertyAssignment); + function createShorthandPropertyAssignment( + name: string | Identifier, + objectAssignmentInitializer?: Expression, + ) { + const node = createBaseDeclaration( + SyntaxKind.ShorthandPropertyAssignment, + ); node.name = asName(name); - node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); + node.objectAssignmentInitializer = objectAssignmentInitializer && + parenthesizerRules().parenthesizeExpressionForDisallowedComma( + objectAssignmentInitializer, + ); node.transformFlags |= propagateIdentifierNameFlags(node.name) | propagateChildFlags(node.objectAssignmentInitializer) | TransformFlags.ContainsES2015; @@ -5960,14 +8334,27 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression | undefined) { - return node.name !== name - || node.objectAssignmentInitializer !== objectAssignmentInitializer - ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node) + function updateShorthandPropertyAssignment( + node: ShorthandPropertyAssignment, + name: Identifier, + objectAssignmentInitializer: Expression | undefined, + ) { + return node.name !== name || + node.objectAssignmentInitializer !== objectAssignmentInitializer + ? finishUpdateShorthandPropertyAssignment( + createShorthandPropertyAssignment( + name, + objectAssignmentInitializer, + ), + node, + ) : node; } - function finishUpdateShorthandPropertyAssignment(updated: Mutable, original: ShorthandPropertyAssignment) { + function finishUpdateShorthandPropertyAssignment( + updated: Mutable, + original: ShorthandPropertyAssignment, + ) { if (updated !== original) { // copy children used only for error reporting updated.modifiers = original.modifiers; @@ -5980,8 +8367,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createSpreadAssignment(expression: Expression) { - const node = createBaseDeclaration(SyntaxKind.SpreadAssignment); - node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); + const node = createBaseDeclaration( + SyntaxKind.SpreadAssignment, + ); + node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma( + expression, + ); node.transformFlags |= propagateChildFlags(node.expression) | TransformFlags.ContainsES2018 | TransformFlags.ContainsObjectRestOrSpread; @@ -5991,7 +8382,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateSpreadAssignment(node: SpreadAssignment, expression: Expression) { + function updateSpreadAssignment( + node: SpreadAssignment, + expression: Expression, + ) { return node.expression !== expression ? update(createSpreadAssignment(expression), node) : node; @@ -6002,10 +8396,16 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // // @api - function createEnumMember(name: string | PropertyName, initializer?: Expression) { + function createEnumMember( + name: string | PropertyName, + initializer?: Expression, + ) { const node = createBaseDeclaration(SyntaxKind.EnumMember); node.name = asName(name); - node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer); + node.initializer = initializer && + parenthesizerRules().parenthesizeExpressionForDisallowedComma( + initializer, + ); node.transformFlags |= propagateChildFlags(node.name) | propagateChildFlags(node.initializer) | TransformFlags.ContainsTypeScript; @@ -6015,9 +8415,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined) { - return node.name !== name - || node.initializer !== initializer + function updateEnumMember( + node: EnumMember, + name: PropertyName, + initializer: Expression | undefined, + ) { + return node.name !== name || node.initializer !== initializer ? update(createEnumMember(name, initializer), node) : node; } @@ -6032,7 +8435,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode endOfFileToken: EndOfFileToken, flags: NodeFlags, ) { - const node = baseFactory.createBaseSourceFileNode(SyntaxKind.SourceFile) as Mutable; + const node = baseFactory.createBaseSourceFileNode( + SyntaxKind.SourceFile, + ) as Mutable; node.statements = createNodeArray(statements); node.endOfFileToken = endOfFileToken; node.flags |= flags; @@ -6106,7 +8511,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } function cloneRedirectedSourceFile(source: SourceFile) { - const node = createRedirectedSourceFile(source.redirectInfo!) as Mutable; + const node = createRedirectedSourceFile( + source.redirectInfo!, + ) as Mutable; node.flags |= source.flags & ~NodeFlags.Synthesized; node.fileName = source.fileName; node.path = source.path; @@ -6121,7 +8528,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode function cloneSourceFileWorker(source: SourceFile) { // TODO: This mechanism for cloning results in megamorphic property reads and writes. In future perf-related // work, we should consider switching explicit property assignments instead of using `for..in`. - const node = baseFactory.createBaseSourceFileNode(SyntaxKind.SourceFile) as Mutable; + const node = baseFactory.createBaseSourceFileNode( + SyntaxKind.SourceFile, + ) as Mutable; node.flags |= source.flags & ~NodeFlags.Synthesized; for (const p in source) { if (hasProperty(node, p) || !hasProperty(source, p)) { @@ -6137,7 +8546,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } function cloneSourceFile(source: SourceFile) { - const node = source.redirectInfo ? cloneRedirectedSourceFile(source) : cloneSourceFileWorker(source); + const node = source.redirectInfo + ? cloneRedirectedSourceFile(source) + : cloneSourceFileWorker(source); setOriginalNode(node, source); return node; } @@ -6173,18 +8584,32 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode hasNoDefaultLib = node.hasNoDefaultLib, libReferenceDirectives = node.libReferenceDirectives, ) { - return node.statements !== statements - || node.isDeclarationFile !== isDeclarationFile - || node.referencedFiles !== referencedFiles - || node.typeReferenceDirectives !== typeReferenceDirectives - || node.hasNoDefaultLib !== hasNoDefaultLib - || node.libReferenceDirectives !== libReferenceDirectives - ? update(cloneSourceFileWithChanges(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives), node) - : node; - } - - // @api - function createBundle(sourceFiles: readonly SourceFile[], prepends: readonly (UnparsedSource | InputFiles)[] = emptyArray) { + return node.statements !== statements || + node.isDeclarationFile !== isDeclarationFile || + node.referencedFiles !== referencedFiles || + node.typeReferenceDirectives !== typeReferenceDirectives || + node.hasNoDefaultLib !== hasNoDefaultLib || + node.libReferenceDirectives !== libReferenceDirectives + ? update( + cloneSourceFileWithChanges( + node, + statements, + isDeclarationFile, + referencedFiles, + typeReferenceDirectives, + hasNoDefaultLib, + libReferenceDirectives, + ), + node, + ) + : node; + } + + // @api + function createBundle( + sourceFiles: readonly SourceFile[], + prepends: readonly (UnparsedSource | InputFiles)[] = emptyArray, + ) { const node = createBaseNode(SyntaxKind.Bundle); node.prepends = prepends; node.sourceFiles = sourceFiles; @@ -6196,15 +8621,22 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateBundle(node: Bundle, sourceFiles: readonly SourceFile[], prepends: readonly (UnparsedSource | InputFiles)[] = emptyArray) { - return node.sourceFiles !== sourceFiles - || node.prepends !== prepends + function updateBundle( + node: Bundle, + sourceFiles: readonly SourceFile[], + prepends: readonly (UnparsedSource | InputFiles)[] = emptyArray, + ) { + return node.sourceFiles !== sourceFiles || node.prepends !== prepends ? update(createBundle(sourceFiles, prepends), node) : node; } // @api - function createUnparsedSource(prologues: readonly UnparsedPrologue[], syntheticReferences: readonly UnparsedSyntheticReference[] | undefined, texts: readonly UnparsedSourceText[]) { + function createUnparsedSource( + prologues: readonly UnparsedPrologue[], + syntheticReferences: readonly UnparsedSyntheticReference[] | undefined, + texts: readonly UnparsedSourceText[], + ) { const node = createBaseNode(SyntaxKind.UnparsedSource); node.prologues = prologues; node.syntheticReferences = syntheticReferences; @@ -6217,7 +8649,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return node; } - function createBaseUnparsedNode(kind: T["kind"], data?: string) { + function createBaseUnparsedNode( + kind: T["kind"], + data?: string, + ) { const node = createBaseNode(kind); node.data = data; return node; @@ -6229,20 +8664,38 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function createUnparsedPrepend(data: string | undefined, texts: readonly UnparsedTextLike[]): UnparsedPrepend { - const node = createBaseUnparsedNode(SyntaxKind.UnparsedPrepend, data); + function createUnparsedPrepend( + data: string | undefined, + texts: readonly UnparsedTextLike[], + ): UnparsedPrepend { + const node = createBaseUnparsedNode( + SyntaxKind.UnparsedPrepend, + data, + ); node.texts = texts; return node; } // @api - function createUnparsedTextLike(data: string | undefined, internal: boolean): UnparsedTextLike { - return createBaseUnparsedNode(internal ? SyntaxKind.UnparsedInternalText : SyntaxKind.UnparsedText, data); + function createUnparsedTextLike( + data: string | undefined, + internal: boolean, + ): UnparsedTextLike { + return createBaseUnparsedNode( + internal + ? SyntaxKind.UnparsedInternalText + : SyntaxKind.UnparsedText, + data, + ); } // @api - function createUnparsedSyntheticReference(section: BundleFileHasNoDefaultLib | BundleFileReference): UnparsedSyntheticReference { - const node = createBaseNode(SyntaxKind.UnparsedSyntheticReference); + function createUnparsedSyntheticReference( + section: BundleFileHasNoDefaultLib | BundleFileReference, + ): UnparsedSyntheticReference { + const node = createBaseNode( + SyntaxKind.UnparsedSyntheticReference, + ); node.data = section.data; node.section = section; return node; @@ -6261,8 +8714,14 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // // @api - function createSyntheticExpression(type: Type, isSpread = false, tupleNameSource?: ParameterDeclaration | NamedTupleMember) { - const node = createBaseNode(SyntaxKind.SyntheticExpression); + function createSyntheticExpression( + type: Type, + isSpread = false, + tupleNameSource?: ParameterDeclaration | NamedTupleMember, + ) { + const node = createBaseNode( + SyntaxKind.SyntheticExpression, + ); node.type = type; node.isSpread = isSpread; node.tupleNameSource = tupleNameSource; @@ -6288,7 +8747,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode */ // @api function createNotEmittedStatement(original: Node) { - const node = createBaseNode(SyntaxKind.NotEmittedStatement); + const node = createBaseNode( + SyntaxKind.NotEmittedStatement, + ); node.original = original; setTextRange(node, original); return node; @@ -6302,8 +8763,13 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * @param original The original outer expression. */ // @api - function createPartiallyEmittedExpression(expression: Expression, original?: Node) { - const node = createBaseNode(SyntaxKind.PartiallyEmittedExpression); + function createPartiallyEmittedExpression( + expression: Expression, + original?: Node, + ) { + const node = createBaseNode( + SyntaxKind.PartiallyEmittedExpression, + ); node.expression = expression; node.original = original; node.transformFlags |= propagateChildFlags(node.expression) | @@ -6313,14 +8779,28 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression) { + function updatePartiallyEmittedExpression( + node: PartiallyEmittedExpression, + expression: Expression, + ) { return node.expression !== expression - ? update(createPartiallyEmittedExpression(expression, node.original), node) + ? update( + createPartiallyEmittedExpression(expression, node.original), + node, + ) : node; } - function flattenCommaElements(node: Expression): Expression | readonly Expression[] { - if (nodeIsSynthesized(node) && !isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { + function flattenCommaElements( + node: Expression, + ): Expression | readonly Expression[] { + if ( + nodeIsSynthesized(node) && + !isParseTreeNode(node) && + !node.original && + !node.emitNode && + !node.id + ) { if (isCommaListExpression(node)) { return node.elements; } @@ -6333,22 +8813,34 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // @api function createCommaListExpression(elements: readonly Expression[]) { - const node = createBaseNode(SyntaxKind.CommaListExpression); - node.elements = createNodeArray(sameFlatMap(elements, flattenCommaElements)); + const node = createBaseNode( + SyntaxKind.CommaListExpression, + ); + node.elements = createNodeArray( + sameFlatMap(elements, flattenCommaElements), + ); node.transformFlags |= propagateChildrenFlags(node.elements); return node; } // @api - function updateCommaListExpression(node: CommaListExpression, elements: readonly Expression[]) { + function updateCommaListExpression( + node: CommaListExpression, + elements: readonly Expression[], + ) { return node.elements !== elements ? update(createCommaListExpression(elements), node) : node; } // @api - function createSyntheticReferenceExpression(expression: Expression, thisArg: Expression) { - const node = createBaseNode(SyntaxKind.SyntheticReferenceExpression); + function createSyntheticReferenceExpression( + expression: Expression, + thisArg: Expression, + ) { + const node = createBaseNode( + SyntaxKind.SyntheticReferenceExpression, + ); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= propagateChildFlags(node.expression) | @@ -6357,15 +8849,25 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function updateSyntheticReferenceExpression(node: SyntheticReferenceExpression, expression: Expression, thisArg: Expression) { - return node.expression !== expression - || node.thisArg !== thisArg - ? update(createSyntheticReferenceExpression(expression, thisArg), node) + function updateSyntheticReferenceExpression( + node: SyntheticReferenceExpression, + expression: Expression, + thisArg: Expression, + ) { + return node.expression !== expression || node.thisArg !== thisArg + ? update( + createSyntheticReferenceExpression(expression, thisArg), + node, + ) : node; } - function cloneGeneratedIdentifier(node: GeneratedIdentifier): GeneratedIdentifier { - const clone = createBaseIdentifier(node.escapedText) as Mutable; + function cloneGeneratedIdentifier( + node: GeneratedIdentifier, + ): GeneratedIdentifier { + const clone = createBaseIdentifier( + node.escapedText, + ) as Mutable; clone.flags |= node.flags & ~NodeFlags.Synthesized; clone.transformFlags = node.transformFlags; setOriginalNode(clone, node); @@ -6388,8 +8890,12 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return clone; } - function cloneGeneratedPrivateIdentifier(node: GeneratedPrivateIdentifier): GeneratedPrivateIdentifier { - const clone = createBasePrivateIdentifier(node.escapedText) as Mutable; + function cloneGeneratedPrivateIdentifier( + node: GeneratedPrivateIdentifier, + ): GeneratedPrivateIdentifier { + const clone = createBasePrivateIdentifier( + node.escapedText, + ) as Mutable; clone.flags |= node.flags & ~NodeFlags.Synthesized; clone.transformFlags = node.transformFlags; setOriginalNode(clone, node); @@ -6397,7 +8903,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return clone; } - function clonePrivateIdentifier(node: PrivateIdentifier): PrivateIdentifier { + function clonePrivateIdentifier( + node: PrivateIdentifier, + ): PrivateIdentifier { const clone = createBasePrivateIdentifier(node.escapedText); clone.flags |= node.flags & ~NodeFlags.Synthesized; clone.transformFlags = node.transformFlags; @@ -6406,8 +8914,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // @api - function cloneNode(node: T): T; - function cloneNode(node: T) { + function cloneNode(node: T): T; + function cloneNode(node: T) { // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). @@ -6424,18 +8932,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return cloneIdentifier(node) as T & Identifier; } if (isGeneratedPrivateIdentifier(node)) { - return cloneGeneratedPrivateIdentifier(node) as T & GeneratedPrivateIdentifier; + return cloneGeneratedPrivateIdentifier(node) as + & T + & GeneratedPrivateIdentifier; } if (isPrivateIdentifier(node)) { return clonePrivateIdentifier(node) as T & PrivateIdentifier; } - const clone = !isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) as T : - baseFactory.createBaseNode(node.kind) as T; + const clone = !isNodeKind(node.kind) + ? (baseFactory.createBaseTokenNode(node.kind) as T) + : (baseFactory.createBaseNode(node.kind) as T); (clone as Mutable).flags |= node.flags & ~NodeFlags.Synthesized; (clone as Mutable).transformFlags = node.transformFlags; - setOriginalNode(clone, node); + setOriginalNode(clone as Node, node as Node); for (const key in node) { if (hasProperty(clone, key) || !hasProperty(node, key)) { @@ -6449,9 +8960,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } // compound nodes - function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): ImmediatelyInvokedFunctionExpression; - function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedFunctionExpression; - function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param?: ParameterDeclaration, paramValue?: Expression) { + function createImmediatelyInvokedFunctionExpression( + statements: readonly Statement[], + ): ImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedFunctionExpression( + statements: readonly Statement[], + param: ParameterDeclaration, + paramValue: Expression, + ): ImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedFunctionExpression( + statements: readonly Statement[], + param?: ParameterDeclaration, + paramValue?: Expression, + ) { return createCallExpression( createFunctionExpression( /*modifiers*/ undefined, @@ -6467,9 +8988,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode ); } - function createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): ImmediatelyInvokedArrowFunction; - function createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedArrowFunction; - function createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param?: ParameterDeclaration, paramValue?: Expression) { + function createImmediatelyInvokedArrowFunction( + statements: readonly Statement[], + ): ImmediatelyInvokedArrowFunction; + function createImmediatelyInvokedArrowFunction( + statements: readonly Statement[], + param: ParameterDeclaration, + paramValue: Expression, + ): ImmediatelyInvokedArrowFunction; + function createImmediatelyInvokedArrowFunction( + statements: readonly Statement[], + param?: ParameterDeclaration, + paramValue?: Expression, + ) { return createCallExpression( createArrowFunction( /*modifiers*/ undefined, @@ -6501,7 +9032,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode /*modifiers*/ undefined, /*isTypeOnly*/ false, createNamedExports([ - createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName), + createExportSpecifier( + /*isTypeOnly*/ false, + /*propertyName*/ undefined, + exportName, + ), ]), ); } @@ -6511,22 +9046,40 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // function createTypeCheck(value: Expression, tag: TypeOfTag) { - return tag === "null" ? factory.createStrictEquality(value, createNull()) : - tag === "undefined" ? factory.createStrictEquality(value, createVoidZero()) : - factory.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag)); + return tag === "null" + ? factory.createStrictEquality(value, createNull()) + : tag === "undefined" + ? factory.createStrictEquality(value, createVoidZero()) + : factory.createStrictEquality( + createTypeOfExpression(value), + createStringLiteral(tag), + ); } function createIsNotTypeCheck(value: Expression, tag: TypeOfTag) { - return tag === "null" ? factory.createStrictInequality(value, createNull()) : - tag === "undefined" ? factory.createStrictInequality(value, createVoidZero()) : - factory.createStrictInequality(createTypeOfExpression(value), createStringLiteral(tag)); + return tag === "null" + ? factory.createStrictInequality(value, createNull()) + : tag === "undefined" + ? factory.createStrictInequality(value, createVoidZero()) + : factory.createStrictInequality( + createTypeOfExpression(value), + createStringLiteral(tag), + ); } - function createMethodCall(object: Expression, methodName: string | Identifier, argumentsList: readonly Expression[]) { + function createMethodCall( + object: Expression, + methodName: string | Identifier, + argumentsList: readonly Expression[], + ) { // Preserve the optionality of `object`. if (isCallChain(object)) { return createCallChain( - createPropertyAccessChain(object, /*questionDotToken*/ undefined, methodName), + createPropertyAccessChain( + object, + /*questionDotToken*/ undefined, + methodName, + ), /*questionDotToken*/ undefined, /*typeArguments*/ undefined, argumentsList, @@ -6539,47 +9092,117 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode ); } - function createFunctionBindCall(target: Expression, thisArg: Expression, argumentsList: readonly Expression[]) { + function createFunctionBindCall( + target: Expression, + thisArg: Expression, + argumentsList: readonly Expression[], + ) { return createMethodCall(target, "bind", [thisArg, ...argumentsList]); } - function createFunctionCallCall(target: Expression, thisArg: Expression, argumentsList: readonly Expression[]) { + function createFunctionCallCall( + target: Expression, + thisArg: Expression, + argumentsList: readonly Expression[], + ) { return createMethodCall(target, "call", [thisArg, ...argumentsList]); } - function createFunctionApplyCall(target: Expression, thisArg: Expression, argumentsExpression: Expression) { - return createMethodCall(target, "apply", [thisArg, argumentsExpression]); + function createFunctionApplyCall( + target: Expression, + thisArg: Expression, + argumentsExpression: Expression, + ) { + return createMethodCall(target, "apply", [ + thisArg, + argumentsExpression, + ]); } - function createGlobalMethodCall(globalObjectName: string, methodName: string, argumentsList: readonly Expression[]) { - return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList); + function createGlobalMethodCall( + globalObjectName: string, + methodName: string, + argumentsList: readonly Expression[], + ) { + return createMethodCall( + createIdentifier(globalObjectName), + methodName, + argumentsList, + ); } - function createArraySliceCall(array: Expression, start?: number | Expression) { - return createMethodCall(array, "slice", start === undefined ? [] : [asExpression(start)]); + function createArraySliceCall( + array: Expression, + start?: number | Expression, + ) { + return createMethodCall( + array, + "slice", + start === undefined ? [] : [asExpression(start)], + ); } - function createArrayConcatCall(array: Expression, argumentsList: readonly Expression[]) { + function createArrayConcatCall( + array: Expression, + argumentsList: readonly Expression[], + ) { return createMethodCall(array, "concat", argumentsList); } - function createObjectDefinePropertyCall(target: Expression, propertyName: string | Expression, attributes: Expression) { - return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]); - } - - function createObjectGetOwnPropertyDescriptorCall(target: Expression, propertyName: string | Expression) { - return createGlobalMethodCall("Object", "getOwnPropertyDescriptor", [target, asExpression(propertyName)]); + function createObjectDefinePropertyCall( + target: Expression, + propertyName: string | Expression, + attributes: Expression, + ) { + return createGlobalMethodCall("Object", "defineProperty", [ + target, + asExpression(propertyName), + attributes, + ]); } - function createReflectGetCall(target: Expression, propertyKey: Expression, receiver?: Expression): CallExpression { - return createGlobalMethodCall("Reflect", "get", receiver ? [target, propertyKey, receiver] : [target, propertyKey]); + function createObjectGetOwnPropertyDescriptorCall( + target: Expression, + propertyName: string | Expression, + ) { + return createGlobalMethodCall("Object", "getOwnPropertyDescriptor", [ + target, + asExpression(propertyName), + ]); + } + + function createReflectGetCall( + target: Expression, + propertyKey: Expression, + receiver?: Expression, + ): CallExpression { + return createGlobalMethodCall( + "Reflect", + "get", + receiver ? [target, propertyKey, receiver] : [target, propertyKey], + ); } - function createReflectSetCall(target: Expression, propertyKey: Expression, value: Expression, receiver?: Expression): CallExpression { - return createGlobalMethodCall("Reflect", "set", receiver ? [target, propertyKey, value, receiver] : [target, propertyKey, value]); + function createReflectSetCall( + target: Expression, + propertyKey: Expression, + value: Expression, + receiver?: Expression, + ): CallExpression { + return createGlobalMethodCall( + "Reflect", + "set", + receiver + ? [target, propertyKey, value, receiver] + : [target, propertyKey, value], + ); } - function tryAddPropertyAssignment(properties: PropertyAssignment[], propertyName: string, expression: Expression | undefined) { + function tryAddPropertyAssignment( + properties: PropertyAssignment[], + propertyName: string, + expression: Expression | undefined, + ) { if (expression) { properties.push(createPropertyAssignment(propertyName, expression)); return true; @@ -6587,35 +9210,80 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return false; } - function createPropertyDescriptor(attributes: PropertyDescriptorAttributes, singleLine?: boolean) { + function createPropertyDescriptor( + attributes: PropertyDescriptorAttributes, + singleLine?: boolean, + ) { const properties: PropertyAssignment[] = []; - tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable)); - tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable)); + tryAddPropertyAssignment( + properties, + "enumerable", + asExpression(attributes.enumerable), + ); + tryAddPropertyAssignment( + properties, + "configurable", + asExpression(attributes.configurable), + ); - let isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable)); - isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData; + let isData = tryAddPropertyAssignment( + properties, + "writable", + asExpression(attributes.writable), + ); + isData = tryAddPropertyAssignment(properties, "value", attributes.value) || + isData; - let isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get); - isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor; + let isAccessor = tryAddPropertyAssignment( + properties, + "get", + attributes.get, + ); + isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || + isAccessor; - Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor."); + Debug.assert( + !(isData && isAccessor), + "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.", + ); return createObjectLiteralExpression(properties, !singleLine); } - function updateOuterExpression(outerExpression: OuterExpression, expression: Expression) { + function updateOuterExpression( + outerExpression: OuterExpression, + expression: Expression, + ) { switch (outerExpression.kind) { case SyntaxKind.ParenthesizedExpression: - return updateParenthesizedExpression(outerExpression, expression); + return updateParenthesizedExpression( + outerExpression, + expression, + ); case SyntaxKind.TypeAssertionExpression: - return updateTypeAssertion(outerExpression, outerExpression.type, expression); + return updateTypeAssertion( + outerExpression, + outerExpression.type, + expression, + ); case SyntaxKind.AsExpression: - return updateAsExpression(outerExpression, expression, outerExpression.type); + return updateAsExpression( + outerExpression, + expression, + outerExpression.type, + ); case SyntaxKind.SatisfiesExpression: - return updateSatisfiesExpression(outerExpression, expression, outerExpression.type); + return updateSatisfiesExpression( + outerExpression, + expression, + outerExpression.type, + ); case SyntaxKind.NonNullExpression: return updateNonNullExpression(outerExpression, expression); case SyntaxKind.PartiallyEmittedExpression: - return updatePartiallyEmittedExpression(outerExpression, expression); + return updatePartiallyEmittedExpression( + outerExpression, + expression, + ); } } @@ -6634,25 +9302,42 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * the containing expression is created/updated. */ function isIgnorableParen(node: Expression) { - return isParenthesizedExpression(node) - && nodeIsSynthesized(node) - && nodeIsSynthesized(getSourceMapRange(node)) - && nodeIsSynthesized(getCommentRange(node)) - && !some(getSyntheticLeadingComments(node)) - && !some(getSyntheticTrailingComments(node)); + return ( + isParenthesizedExpression(node) && + nodeIsSynthesized(node) && + nodeIsSynthesized(getSourceMapRange(node)) && + nodeIsSynthesized(getCommentRange(node)) && + !some(getSyntheticLeadingComments(node)) && + !some(getSyntheticTrailingComments(node)) + ); } - function restoreOuterExpressions(outerExpression: Expression | undefined, innerExpression: Expression, kinds = OuterExpressionKinds.All): Expression { - if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { + function restoreOuterExpressions( + outerExpression: Expression | undefined, + innerExpression: Expression, + kinds = OuterExpressionKinds.All, + ): Expression { + if ( + outerExpression && + isOuterExpression(outerExpression, kinds) && + !isIgnorableParen(outerExpression) + ) { return updateOuterExpression( outerExpression, - restoreOuterExpressions(outerExpression.expression, innerExpression), + restoreOuterExpressions( + outerExpression.expression, + innerExpression, + ), ); } return innerExpression; } - function restoreEnclosingLabel(node: Statement, outermostLabeledStatement: LabeledStatement | undefined, afterRestoreLabelCallback?: (node: LabeledStatement) => void): Statement { + function restoreEnclosingLabel( + node: Statement, + outermostLabeledStatement: LabeledStatement | undefined, + afterRestoreLabelCallback?: (node: LabeledStatement) => void, + ): Statement { if (!outermostLabeledStatement) { return node; } @@ -6660,7 +9345,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode outermostLabeledStatement, outermostLabeledStatement.label, isLabeledStatement(outermostLabeledStatement.statement) - ? restoreEnclosingLabel(node, outermostLabeledStatement.statement) + ? restoreEnclosingLabel( + node, + outermostLabeledStatement.statement, + ) : node, ); if (afterRestoreLabelCallback) { @@ -6669,7 +9357,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return updated; } - function shouldBeCapturedInTempVariable(node: Expression, cacheIdentifiers: boolean): boolean { + function shouldBeCapturedInTempVariable( + node: Expression, + cacheIdentifiers: boolean, + ): boolean { const target = skipParentheses(node); switch (target.kind) { case SyntaxKind.Identifier: @@ -6680,20 +9371,30 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode case SyntaxKind.StringLiteral: return false; case SyntaxKind.ArrayLiteralExpression: - const elements = (target as ArrayLiteralExpression).elements; + const elements = target.elements; if (elements.length === 0) { return false; } return true; case SyntaxKind.ObjectLiteralExpression: - return (target as ObjectLiteralExpression).properties.length > 0; + return ( + target.properties.length > 0 + ); default: return true; } } - function createCallBinding(expression: Expression, recordTempVariable: (temp: Identifier) => void, languageVersion?: ScriptTarget, cacheIdentifiers = false): CallBinding { - const callee = skipOuterExpressions(expression, OuterExpressionKinds.All); + function createCallBinding( + expression: Expression, + recordTempVariable: (temp: Identifier) => void, + languageVersion?: ScriptTarget, + cacheIdentifiers = false, + ): CallBinding { + const callee = skipOuterExpressions( + expression, + OuterExpressionKinds.All, + ); let thisArg: Expression; let target: LeftHandSideExpression; if (isSuperProperty(callee)) { @@ -6702,24 +9403,30 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } else if (isSuperKeyword(callee)) { thisArg = createThis(); - target = languageVersion !== undefined && languageVersion < ScriptTarget.ES2015 + target = languageVersion !== undefined && + languageVersion < ScriptTarget.ES2015 ? setTextRange(createIdentifier("_super"), callee) - : callee as PrimaryExpression; + : callee; } else if (getEmitFlags(callee) & EmitFlags.HelperName) { thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee, /*optionalChain*/ false); + target = parenthesizerRules().parenthesizeLeftSideOfAccess( + callee, + /*optionalChain*/ false, + ); } else if (isPropertyAccessExpression(callee)) { - if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + if ( + shouldBeCapturedInTempVariable( + callee.expression, + cacheIdentifiers, + ) + ) { // for `a.b()` target is `(_a = a).b` and thisArg is `_a` thisArg = createTempVariable(recordTempVariable); target = createPropertyAccessExpression( setTextRange( - factory.createAssignment( - thisArg, - callee.expression, - ), + factory.createAssignment(thisArg, callee.expression), callee.expression, ), callee.name, @@ -6732,15 +9439,17 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } } else if (isElementAccessExpression(callee)) { - if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) { + if ( + shouldBeCapturedInTempVariable( + callee.expression, + cacheIdentifiers, + ) + ) { // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a` thisArg = createTempVariable(recordTempVariable); target = createElementAccessExpression( setTextRange( - factory.createAssignment( - thisArg, - callee.expression, - ), + factory.createAssignment(thisArg, callee.expression), callee.expression, ), callee.argumentExpression, @@ -6755,13 +9464,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode else { // for `a()` target is `a` and thisArg is `void 0` thisArg = createVoidZero(); - target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression, /*optionalChain*/ false); + target = parenthesizerRules().parenthesizeLeftSideOfAccess( + expression, + /*optionalChain*/ false, + ); } return { target, thisArg }; } - function createAssignmentTargetWrapper(paramName: Identifier, expression: Expression): PropertyAccessExpression { + function createAssignmentTargetWrapper( + paramName: Identifier, + expression: Expression, + ): PropertyAccessExpression { return createPropertyAccessExpression( // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560) createParenthesizedExpression( @@ -6769,17 +9484,17 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode createSetAccessorDeclaration( /*modifiers*/ undefined, "value", - [createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - paramName, - /*questionToken*/ undefined, - /*type*/ undefined, - /*initializer*/ undefined, - )], - createBlock([ - createExpressionStatement(expression), - ]), + [ + createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + paramName, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined, + ), + ], + createBlock([createExpressionStatement(expression)]), ), ]), ), @@ -6795,11 +9510,26 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode : reduceLeft(expressions, factory.createComma)!; } - function getName(node: Declaration | undefined, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags: EmitFlags = 0, ignoreAssignedName?: boolean) { - const nodeName = ignoreAssignedName ? node && getNonAssignedNameOfDeclaration(node) : getNameOfDeclaration(node); - if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { + function getName( + node: Declaration | undefined, + allowComments?: boolean, + allowSourceMaps?: boolean, + emitFlags: EmitFlags = 0, + ignoreAssignedName?: boolean, + ) { + const nodeName = ignoreAssignedName + ? node && getNonAssignedNameOfDeclaration(node) + : getNameOfDeclaration(node); + if ( + nodeName && + isIdentifier(nodeName) && + !isGeneratedIdentifier(nodeName) + ) { // TODO(rbuckton): Does this need to be parented? - const name = setParent(setTextRange(cloneNode(nodeName), nodeName), nodeName.parent); + const name = setParent( + setTextRange(cloneNode(nodeName), nodeName), + nodeName.parent, + ); emitFlags |= getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= EmitFlags.NoSourceMap; if (!allowComments) emitFlags |= EmitFlags.NoComments; @@ -6820,8 +9550,17 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * @param allowComments A value indicating whether comments may be emitted for the name. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. */ - function getInternalName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean) { - return getName(node, allowComments, allowSourceMaps, EmitFlags.LocalName | EmitFlags.InternalName); + function getInternalName( + node: Declaration, + allowComments?: boolean, + allowSourceMaps?: boolean, + ) { + return getName( + node, + allowComments, + allowSourceMaps, + EmitFlags.LocalName | EmitFlags.InternalName, + ); } /** @@ -6835,8 +9574,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. * @param ignoreAssignedName Indicates that the assigned name of a declaration shouldn't be considered. */ - function getLocalName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean, ignoreAssignedName?: boolean) { - return getName(node, allowComments, allowSourceMaps, EmitFlags.LocalName, ignoreAssignedName); + function getLocalName( + node: Declaration, + allowComments?: boolean, + allowSourceMaps?: boolean, + ignoreAssignedName?: boolean, + ) { + return getName( + node, + allowComments, + allowSourceMaps, + EmitFlags.LocalName, + ignoreAssignedName, + ); } /** @@ -6849,8 +9599,17 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * @param allowComments A value indicating whether comments may be emitted for the name. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. */ - function getExportName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier { - return getName(node, allowComments, allowSourceMaps, EmitFlags.ExportName); + function getExportName( + node: Declaration, + allowComments?: boolean, + allowSourceMaps?: boolean, + ): Identifier { + return getName( + node, + allowComments, + allowSourceMaps, + EmitFlags.ExportName, + ); } /** @@ -6860,7 +9619,11 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * @param allowComments A value indicating whether comments may be emitted for the name. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. */ - function getDeclarationName(node: Declaration | undefined, allowComments?: boolean, allowSourceMaps?: boolean) { + function getDeclarationName( + node: Declaration | undefined, + allowComments?: boolean, + allowSourceMaps?: boolean, + ) { return getName(node, allowComments, allowSourceMaps); } @@ -6872,8 +9635,16 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * @param allowComments A value indicating whether comments may be emitted for the name. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. */ - function getNamespaceMemberName(ns: Identifier, name: Identifier, allowComments?: boolean, allowSourceMaps?: boolean): PropertyAccessExpression { - const qualifiedName = createPropertyAccessExpression(ns, nodeIsSynthesized(name) ? name : cloneNode(name)); + function getNamespaceMemberName( + ns: Identifier, + name: Identifier, + allowComments?: boolean, + allowSourceMaps?: boolean, + ): PropertyAccessExpression { + const qualifiedName = createPropertyAccessExpression( + ns, + nodeIsSynthesized(name) ? name : cloneNode(name), + ); setTextRange(qualifiedName, name); let emitFlags: EmitFlags = 0; if (!allowSourceMaps) emitFlags |= EmitFlags.NoSourceMap; @@ -6893,9 +9664,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * @param allowComments A value indicating whether comments may be emitted for the name. * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. */ - function getExternalModuleOrNamespaceExportName(ns: Identifier | undefined, node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier | PropertyAccessExpression { + function getExternalModuleOrNamespaceExportName( + ns: Identifier | undefined, + node: Declaration, + allowComments?: boolean, + allowSourceMaps?: boolean, + ): Identifier | PropertyAccessExpression { if (ns && hasSyntacticModifier(node, ModifierFlags.Export)) { - return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps); + return getNamespaceMemberName( + ns, + getName(node), + allowComments, + allowSourceMaps, + ); } return getExportName(node, allowComments, allowSourceMaps); } @@ -6907,17 +9688,27 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * @param ensureUseStrict boolean determining whether the function need to add prologue-directives * @param visitor Optional callback used to visit any custom prologue directives. */ - function copyPrologue(source: readonly Statement[], target: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult): number { + function copyPrologue( + source: readonly Statement[], + target: Statement[], + ensureUseStrict?: boolean, + visitor?: (node: Node) => VisitResult, + ): number { const offset = copyStandardPrologue(source, target, 0, ensureUseStrict); return copyCustomPrologue(source, target, offset, visitor); } function isUseStrictPrologue(node: ExpressionStatement): boolean { - return isStringLiteral(node.expression) && node.expression.text === "use strict"; + return ( + isStringLiteral(node.expression) && + node.expression.text === "use strict" + ); } function createUseStrictPrologue() { - return startOnNewLine(createExpressionStatement(createStringLiteral("use strict"))) as PrologueDirective; + return startOnNewLine( + createExpressionStatement(createStringLiteral("use strict")), + ) as PrologueDirective; } /** @@ -6928,8 +9719,16 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * @param ensureUseStrict boolean determining whether the function need to add prologue-directives * @returns Count of how many directive statements were copied. */ - function copyStandardPrologue(source: readonly Statement[], target: Statement[], statementOffset = 0, ensureUseStrict?: boolean): number { - Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); + function copyStandardPrologue( + source: readonly Statement[], + target: Statement[], + statementOffset = 0, + ensureUseStrict?: boolean, + ): number { + Debug.assert( + target.length === 0, + "Prologue directives should be at the first statement in the target statements array", + ); let foundUseStrict = false; const numStatements = source.length; while (statementOffset < numStatements) { @@ -6958,14 +9757,43 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * @param statementOffset The offset at which to begin the copy. * @param visitor Optional callback used to visit any custom prologue directives. */ - function copyCustomPrologue(source: readonly Statement[], target: Statement[], statementOffset: number, visitor?: (node: Node) => VisitResult, filter?: (node: Statement) => boolean): number; - function copyCustomPrologue(source: readonly Statement[], target: Statement[], statementOffset: number | undefined, visitor?: (node: Node) => VisitResult, filter?: (node: Statement) => boolean): number | undefined; - function copyCustomPrologue(source: readonly Statement[], target: Statement[], statementOffset: number | undefined, visitor?: (node: Node) => VisitResult, filter: (node: Statement) => boolean = returnTrue): number | undefined { + function copyCustomPrologue( + source: readonly Statement[], + target: Statement[], + statementOffset: number, + visitor?: (node: Node) => VisitResult, + filter?: (node: Statement) => boolean, + ): number; + function copyCustomPrologue( + source: readonly Statement[], + target: Statement[], + statementOffset: number | undefined, + visitor?: (node: Node) => VisitResult, + filter?: (node: Statement) => boolean, + ): number | undefined; + function copyCustomPrologue( + source: readonly Statement[], + target: Statement[], + statementOffset: number | undefined, + visitor?: (node: Node) => VisitResult, + filter: (node: Statement) => boolean = returnTrue, + ): number | undefined { const numStatements = source.length; - while (statementOffset !== undefined && statementOffset < numStatements) { + while ( + statementOffset !== undefined && + statementOffset < numStatements + ) { const statement = source[statementOffset]; - if (getEmitFlags(statement) & EmitFlags.CustomPrologue && filter(statement)) { - append(target, visitor ? visitNode(statement, visitor, isStatement) : statement); + if ( + getEmitFlags(statement) & EmitFlags.CustomPrologue && + filter(statement) + ) { + append( + target, + visitor + ? visitNode(statement, visitor, isStatement) + : statement, + ); } else { break; @@ -6980,11 +9808,19 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * * @param statements An array of statements */ - function ensureUseStrict(statements: NodeArray): NodeArray { + function ensureUseStrict( + statements: NodeArray, + ): NodeArray { const foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { - return setTextRange(createNodeArray([createUseStrictPrologue(), ...statements]), statements); + return setTextRange( + createNodeArray([ + createUseStrictPrologue(), + ...statements, + ]), + statements, + ); } return statements; @@ -6996,11 +9832,21 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode * @param nodes The NodeArray. */ function liftToBlock(nodes: readonly Node[]): Statement { - Debug.assert(every(nodes, isStatementOrBlock), "Cannot lift nodes to a Block."); - return singleOrUndefined(nodes) as Statement || createBlock(nodes as readonly Statement[]); + Debug.assert( + every(nodes, isStatementOrBlock), + "Cannot lift nodes to a Block.", + ); + return ( + (singleOrUndefined(nodes) as Statement) || + createBlock(nodes) + ); } - function findSpanEnd(array: readonly T[], test: (value: T) => boolean, start: number) { + function findSpanEnd( + array: readonly T[], + test: (value: T) => boolean, + start: number, + ) { let i = start; while (i < array.length && test(array[i])) { i++; @@ -7008,9 +9854,18 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode return i; } - function mergeLexicalEnvironment(statements: NodeArray, declarations: readonly Statement[] | undefined): NodeArray; - function mergeLexicalEnvironment(statements: Statement[], declarations: readonly Statement[] | undefined): Statement[]; - function mergeLexicalEnvironment(statements: Statement[] | NodeArray, declarations: readonly Statement[] | undefined) { + function mergeLexicalEnvironment( + statements: NodeArray, + declarations: readonly Statement[] | undefined, + ): NodeArray; + function mergeLexicalEnvironment( + statements: Statement[], + declarations: readonly Statement[] | undefined, + ): Statement[]; + function mergeLexicalEnvironment( + statements: Statement[] | NodeArray, + declarations: readonly Statement[] | undefined, + ) { if (!some(declarations)) { return statements; } @@ -7045,16 +9900,47 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state. // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom - const leftStandardPrologueEnd = findSpanEnd(statements, isPrologueDirective, 0); - const leftHoistedFunctionsEnd = findSpanEnd(statements, isHoistedFunction, leftStandardPrologueEnd); - const leftHoistedVariablesEnd = findSpanEnd(statements, isHoistedVariableStatement, leftHoistedFunctionsEnd); + const leftStandardPrologueEnd = findSpanEnd( + statements, + isPrologueDirective, + 0, + ); + const leftHoistedFunctionsEnd = findSpanEnd( + statements, + isHoistedFunction, + leftStandardPrologueEnd, + ); + const leftHoistedVariablesEnd = findSpanEnd( + statements, + isHoistedVariableStatement, + leftHoistedFunctionsEnd, + ); // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom - const rightStandardPrologueEnd = findSpanEnd(declarations, isPrologueDirective, 0); - const rightHoistedFunctionsEnd = findSpanEnd(declarations, isHoistedFunction, rightStandardPrologueEnd); - const rightHoistedVariablesEnd = findSpanEnd(declarations, isHoistedVariableStatement, rightHoistedFunctionsEnd); - const rightCustomPrologueEnd = findSpanEnd(declarations, isCustomPrologue, rightHoistedVariablesEnd); - Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues"); + const rightStandardPrologueEnd = findSpanEnd( + declarations, + isPrologueDirective, + 0, + ); + const rightHoistedFunctionsEnd = findSpanEnd( + declarations, + isHoistedFunction, + rightStandardPrologueEnd, + ); + const rightHoistedVariablesEnd = findSpanEnd( + declarations, + isHoistedVariableStatement, + rightHoistedFunctionsEnd, + ); + const rightCustomPrologueEnd = findSpanEnd( + declarations, + isCustomPrologue, + rightHoistedVariablesEnd, + ); + Debug.assert( + rightCustomPrologueEnd === declarations.length, + "Expected declarations to be valid standard or custom prologues", + ); // splice prologues from the right into the left. We do this in reverse order // so that we don't need to recompute the index on the left when we insert items. @@ -7062,23 +9948,48 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode // splice other custom prologues from right into left if (rightCustomPrologueEnd > rightHoistedVariablesEnd) { - left.splice(leftHoistedVariablesEnd, 0, ...declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)); + left.splice( + leftHoistedVariablesEnd, + 0, + ...declarations.slice( + rightHoistedVariablesEnd, + rightCustomPrologueEnd, + ), + ); } // splice hoisted variables from right into left if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) { - left.splice(leftHoistedFunctionsEnd, 0, ...declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)); + left.splice( + leftHoistedFunctionsEnd, + 0, + ...declarations.slice( + rightHoistedFunctionsEnd, + rightHoistedVariablesEnd, + ), + ); } // splice hoisted functions from right into left if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) { - left.splice(leftStandardPrologueEnd, 0, ...declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)); + left.splice( + leftStandardPrologueEnd, + 0, + ...declarations.slice( + rightStandardPrologueEnd, + rightHoistedFunctionsEnd, + ), + ); } // splice standard prologues from right into left (that are not already in left) if (rightStandardPrologueEnd > 0) { if (leftStandardPrologueEnd === 0) { - left.splice(0, 0, ...declarations.slice(0, rightStandardPrologueEnd)); + left.splice( + 0, + 0, + ...declarations.slice(0, rightStandardPrologueEnd), + ); } else { const leftPrologues = new Map(); @@ -7096,14 +10007,23 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } if (isNodeArray(statements)) { - return setTextRange(createNodeArray(left, statements.hasTrailingComma), statements); + return setTextRange( + createNodeArray(left, statements.hasTrailingComma), + statements, + ); } return statements; } - function replaceModifiers(node: T, modifiers: readonly Modifier[] | ModifierFlags): T; - function replaceModifiers(node: HasModifiers, modifiers: readonly Modifier[] | ModifierFlags) { + function replaceModifiers( + node: T, + modifiers: readonly Modifier[] | ModifierFlags, + ): T; + function replaceModifiers( + node: HasModifiers, + modifiers: readonly Modifier[] | ModifierFlags, + ) { let modifierArray; if (typeof modifiers === "number") { modifierArray = createModifiersFromModifierFlags(modifiers); @@ -7111,100 +10031,446 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode else { modifierArray = modifiers; } - return isTypeParameterDeclaration(node) ? updateTypeParameterDeclaration(node, modifierArray, node.name, node.constraint, node.default) : - isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : - isConstructorTypeNode(node) ? updateConstructorTypeNode1(node, modifierArray, node.typeParameters, node.parameters, node.type) : - isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : - isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : - isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : - isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : - isConstructorDeclaration(node) ? updateConstructorDeclaration(node, modifierArray, node.parameters, node.body) : - isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : - isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : - isIndexSignatureDeclaration(node) ? updateIndexSignature(node, modifierArray, node.parameters, node.type) : - isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : - isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : - isFunctionDeclaration(node) ? updateFunctionDeclaration(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, modifierArray, node.name, node.typeParameters, node.type) : - isEnumDeclaration(node) ? updateEnumDeclaration(node, modifierArray, node.name, node.members) : - isModuleDeclaration(node) ? updateModuleDeclaration(node, modifierArray, node.name, node.body) : - isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : - isImportDeclaration(node) ? updateImportDeclaration(node, modifierArray, node.importClause, node.moduleSpecifier, node.attributes) : - isExportAssignment(node) ? updateExportAssignment(node, modifierArray, node.expression) : - isExportDeclaration(node) ? updateExportDeclaration(node, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.attributes) : - Debug.assertNever(node); - } - - function replaceDecoratorsAndModifiers(node: T, modifiers: readonly ModifierLike[]): T; - function replaceDecoratorsAndModifiers(node: HasModifiers & HasDecorators, modifierArray: readonly ModifierLike[]) { - return isParameter(node) ? updateParameterDeclaration(node, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : - isPropertyDeclaration(node) ? updatePropertyDeclaration(node, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) : - isMethodDeclaration(node) ? updateMethodDeclaration(node, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : - isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.type, node.body) : - isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, modifierArray, node.name, node.parameters, node.body) : - isClassExpression(node) ? updateClassExpression(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - isClassDeclaration(node) ? updateClassDeclaration(node, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : - Debug.assertNever(node); - } - - function replacePropertyName(node: T, name: T["name"]): T; - function replacePropertyName(node: AccessorDeclaration | MethodDeclaration | MethodSignature | PropertyDeclaration | PropertySignature | PropertyAssignment, name: PropertyName) { + return isTypeParameterDeclaration(node) + ? updateTypeParameterDeclaration( + node, + modifierArray, + node.name, + node.constraint, + node.default, + ) + : isParameter(node) + ? updateParameterDeclaration( + node, + modifierArray, + node.dotDotDotToken, + node.name, + node.questionToken, + node.type, + node.initializer, + ) + : isConstructorTypeNode(node) + ? updateConstructorTypeNode1( + node, + modifierArray, + node.typeParameters, + node.parameters, + node.type, + ) + : isPropertySignature(node) + ? updatePropertySignature( + node, + modifierArray, + node.name, + node.questionToken, + node.type, + ) + : isPropertyDeclaration(node) + ? updatePropertyDeclaration( + node, + modifierArray, + node.name, + node.questionToken ?? node.exclamationToken, + node.type, + node.initializer, + ) + : isMethodSignature(node) + ? updateMethodSignature( + node, + modifierArray, + node.name, + node.questionToken, + node.typeParameters, + node.parameters, + node.type, + ) + : isMethodDeclaration(node) + ? updateMethodDeclaration( + node, + modifierArray, + node.asteriskToken, + node.name, + node.questionToken, + node.typeParameters, + node.parameters, + node.type, + node.body, + ) + : isConstructorDeclaration(node) + ? updateConstructorDeclaration( + node, + modifierArray, + node.parameters, + node.body, + ) + : isGetAccessorDeclaration(node) + ? updateGetAccessorDeclaration( + node, + modifierArray, + node.name, + node.parameters, + node.type, + node.body, + ) + : isSetAccessorDeclaration(node) + ? updateSetAccessorDeclaration( + node, + modifierArray, + node.name, + node.parameters, + node.body, + ) + : isIndexSignatureDeclaration(node) + ? updateIndexSignature( + node, + modifierArray, + node.parameters, + node.type, + ) + : isFunctionExpression(node) + ? updateFunctionExpression( + node, + modifierArray, + node.asteriskToken, + node.name, + node.typeParameters, + node.parameters, + node.type, + node.body, + ) + : isArrowFunction(node) + ? updateArrowFunction( + node, + modifierArray, + node.typeParameters, + node.parameters, + node.type, + node.equalsGreaterThanToken, + node.body, + ) + : isClassExpression(node) + ? updateClassExpression( + node, + modifierArray, + node.name, + node.typeParameters, + node.heritageClauses, + node.members, + ) + : isVariableStatement(node) + ? updateVariableStatement(node, modifierArray, node.declarationList) + : isFunctionDeclaration(node) + ? updateFunctionDeclaration( + node, + modifierArray, + node.asteriskToken, + node.name, + node.typeParameters, + node.parameters, + node.type, + node.body, + ) + : isClassDeclaration(node) + ? updateClassDeclaration( + node, + modifierArray, + node.name, + node.typeParameters, + node.heritageClauses, + node.members, + ) + : isInterfaceDeclaration(node) + ? updateInterfaceDeclaration( + node, + modifierArray, + node.name, + node.typeParameters, + node.heritageClauses, + node.members, + ) + : isTypeAliasDeclaration(node) + ? updateTypeAliasDeclaration( + node, + modifierArray, + node.name, + node.typeParameters, + node.type, + ) + : isEnumDeclaration(node) + ? updateEnumDeclaration( + node, + modifierArray, + node.name, + node.members, + ) + : isModuleDeclaration(node) + ? updateModuleDeclaration(node, modifierArray, node.name, node.body) + : isImportEqualsDeclaration(node) + ? updateImportEqualsDeclaration( + node, + modifierArray, + node.isTypeOnly, + node.name, + node.moduleReference, + ) + : isImportDeclaration(node) + ? updateImportDeclaration( + node, + modifierArray, + node.importClause, + node.moduleSpecifier, + node.attributes, + ) + : isExportAssignment(node) + ? updateExportAssignment(node, modifierArray, node.expression) + : isExportDeclaration(node) + ? updateExportDeclaration( + node, + modifierArray, + node.isTypeOnly, + node.exportClause, + node.moduleSpecifier, + node.attributes, + ) + : Debug.assertNever(node); + } + + function replaceDecoratorsAndModifiers< + T extends HasModifiers & HasDecorators, + >(node: T, modifiers: readonly ModifierLike[]): T; + function replaceDecoratorsAndModifiers( + node: HasModifiers & HasDecorators, + modifierArray: readonly ModifierLike[], + ) { + return isParameter(node) + ? updateParameterDeclaration( + node, + modifierArray, + node.dotDotDotToken, + node.name, + node.questionToken, + node.type, + node.initializer, + ) + : isPropertyDeclaration(node) + ? updatePropertyDeclaration( + node, + modifierArray, + node.name, + node.questionToken ?? node.exclamationToken, + node.type, + node.initializer, + ) + : isMethodDeclaration(node) + ? updateMethodDeclaration( + node, + modifierArray, + node.asteriskToken, + node.name, + node.questionToken, + node.typeParameters, + node.parameters, + node.type, + node.body, + ) + : isGetAccessorDeclaration(node) + ? updateGetAccessorDeclaration( + node, + modifierArray, + node.name, + node.parameters, + node.type, + node.body, + ) + : isSetAccessorDeclaration(node) + ? updateSetAccessorDeclaration( + node, + modifierArray, + node.name, + node.parameters, + node.body, + ) + : isClassExpression(node) + ? updateClassExpression( + node, + modifierArray, + node.name, + node.typeParameters, + node.heritageClauses, + node.members, + ) + : isClassDeclaration(node) + ? updateClassDeclaration( + node, + modifierArray, + node.name, + node.typeParameters, + node.heritageClauses, + node.members, + ) + : Debug.assertNever(node); + } + + function replacePropertyName< + T extends + | AccessorDeclaration + | MethodDeclaration + | MethodSignature + | PropertyDeclaration + | PropertySignature + | PropertyAssignment, + >(node: T, name: T["name"]): T; + function replacePropertyName( + node: + | AccessorDeclaration + | MethodDeclaration + | MethodSignature + | PropertyDeclaration + | PropertySignature + | PropertyAssignment, + name: PropertyName, + ) { switch (node.kind) { case SyntaxKind.GetAccessor: - return updateGetAccessorDeclaration(node, node.modifiers, name, node.parameters, node.type, node.body); + return updateGetAccessorDeclaration( + node, + node.modifiers, + name, + node.parameters, + node.type, + node.body, + ); case SyntaxKind.SetAccessor: - return updateSetAccessorDeclaration(node, node.modifiers, name, node.parameters, node.body); + return updateSetAccessorDeclaration( + node, + node.modifiers, + name, + node.parameters, + node.body, + ); case SyntaxKind.MethodDeclaration: - return updateMethodDeclaration(node, node.modifiers, node.asteriskToken, name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body); + return updateMethodDeclaration( + node, + node.modifiers, + node.asteriskToken, + name, + node.questionToken, + node.typeParameters, + node.parameters, + node.type, + node.body, + ); case SyntaxKind.MethodSignature: - return updateMethodSignature(node, node.modifiers, name, node.questionToken, node.typeParameters, node.parameters, node.type); + return updateMethodSignature( + node, + node.modifiers, + name, + node.questionToken, + node.typeParameters, + node.parameters, + node.type, + ); case SyntaxKind.PropertyDeclaration: - return updatePropertyDeclaration(node, node.modifiers, name, node.questionToken ?? node.exclamationToken, node.type, node.initializer); + return updatePropertyDeclaration( + node, + node.modifiers, + name, + node.questionToken ?? node.exclamationToken, + node.type, + node.initializer, + ); case SyntaxKind.PropertySignature: - return updatePropertySignature(node, node.modifiers, name, node.questionToken, node.type); + return updatePropertySignature( + node, + node.modifiers, + name, + node.questionToken, + node.type, + ); case SyntaxKind.PropertyAssignment: return updatePropertyAssignment(node, name, node.initializer); } } function asNodeArray(array: readonly T[]): NodeArray; - function asNodeArray(array: readonly T[] | undefined): NodeArray | undefined; - function asNodeArray(array: readonly T[] | undefined): NodeArray | undefined { + function asNodeArray( + array: readonly T[] | undefined, + ): NodeArray | undefined; + function asNodeArray( + array: readonly T[] | undefined, + ): NodeArray | undefined { return array ? createNodeArray(array) : undefined; } - function asName(name: string | T): T | Identifier { - return typeof name === "string" ? createIdentifier(name) : - name; - } - - function asExpression(value: string | number | boolean | T): T | StringLiteral | NumericLiteral | BooleanLiteral { - return typeof value === "string" ? createStringLiteral(value) : - typeof value === "number" ? createNumericLiteral(value) : - typeof value === "boolean" ? value ? createTrue() : createFalse() : - value; + function asName< + T extends + | DeclarationName + | Identifier + | BindingName + | PropertyName + | NoSubstitutionTemplateLiteral + | EntityName + | ThisTypeNode + | undefined, + >(name: string | T): T | Identifier { + return typeof name === "string" ? createIdentifier(name) : name; + } + + function asExpression( + value: string | number | boolean | T, + ): T | StringLiteral | NumericLiteral | BooleanLiteral { + return typeof value === "string" + ? createStringLiteral(value) + : typeof value === "number" + ? createNumericLiteral(value) + : typeof value === "boolean" + ? value + ? createTrue() + : createFalse() + : value; } function asInitializer(node: Expression | undefined) { - return node && parenthesizerRules().parenthesizeExpressionForDisallowedComma(node); + return ( + node && + parenthesizerRules().parenthesizeExpressionForDisallowedComma(node) + ); } - function asToken(value: TKind | Token): Token { + function asToken( + value: TKind | Token, + ): Token { return typeof value === "number" ? createToken(value) : value; } - function asEmbeddedStatement(statement: T): T | EmptyStatement; - function asEmbeddedStatement(statement: T | undefined): T | EmptyStatement | undefined; - function asEmbeddedStatement(statement: T | undefined): T | EmptyStatement | undefined { - return statement && isNotEmittedStatement(statement) ? setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement; - } - - function asVariableDeclaration(variableDeclaration: string | BindingName | VariableDeclaration | undefined) { - if (typeof variableDeclaration === "string" || variableDeclaration && !isVariableDeclaration(variableDeclaration)) { + function asEmbeddedStatement( + statement: T, + ): T | EmptyStatement; + function asEmbeddedStatement( + statement: T | undefined, + ): T | EmptyStatement | undefined; + function asEmbeddedStatement( + statement: T | undefined, + ): T | EmptyStatement | undefined { + return statement && isNotEmittedStatement(statement) + ? setTextRange( + setOriginalNode(createEmptyStatement(), statement), + statement, + ) + : statement; + } + + function asVariableDeclaration( + variableDeclaration: + | string + | BindingName + | VariableDeclaration + | undefined, + ) { + if ( + typeof variableDeclaration === "string" || + (variableDeclaration && !isVariableDeclaration(variableDeclaration)) + ) { return createVariableDeclaration( variableDeclaration, /*exclamationToken*/ undefined, @@ -7216,14 +10482,20 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode } } -function updateWithoutOriginal(updated: Mutable, original: T): T { +function updateWithoutOriginal( + updated: Mutable, + original: T, +): T { if (updated !== original) { setTextRange(updated, original); } return updated; } -function updateWithOriginal(updated: Mutable, original: T): T { +function updateWithOriginal( + updated: Mutable, + original: T, +): T { if (updated !== original) { setOriginalNode(updated, original); setTextRange(updated, original); @@ -7272,7 +10544,9 @@ function getDefaultTagNameForKind(kind: JSDocTag["kind"]): string { case SyntaxKind.JSDocImplementsTag: return "implements"; default: - return Debug.fail(`Unsupported kind: ${Debug.formatSyntaxKind(kind)}`); + return Debug.fail( + `Unsupported kind: ${Debug.formatSyntaxKind(kind)}`, + ); } } @@ -7281,7 +10555,11 @@ const invalidValueSentinel: object = {}; function getCookedText(kind: TemplateLiteralToken["kind"], rawText: string) { if (!rawTextScanner) { - rawTextScanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ false, LanguageVariant.Standard); + rawTextScanner = createScanner( + ScriptTarget.Latest, + /*skipTrivia*/ false, + LanguageVariant.Standard, + ); } switch (kind) { case SyntaxKind.NoSubstitutionTemplateLiteral: @@ -7318,7 +10596,10 @@ function getCookedText(kind: TemplateLiteralToken["kind"], rawText: string) { break; } - if (tokenValue === undefined || rawTextScanner.scan() !== SyntaxKind.EndOfFileToken) { + if ( + tokenValue === undefined || + rawTextScanner.scan() !== SyntaxKind.EndOfFileToken + ) { rawTextScanner.setText(undefined); return invalidValueSentinel; } @@ -7327,26 +10608,47 @@ function getCookedText(kind: TemplateLiteralToken["kind"], rawText: string) { return tokenValue; } -function propagateNameFlags(node: PropertyName | BindingPattern | NoSubstitutionTemplateLiteral | undefined) { - return node && isIdentifier(node) ? propagateIdentifierNameFlags(node) : propagateChildFlags(node); +function propagateNameFlags( + node: + | PropertyName + | BindingPattern + | NoSubstitutionTemplateLiteral + | undefined, +) { + return node && isIdentifier(node) + ? propagateIdentifierNameFlags(node) + : propagateChildFlags(node); } function propagateIdentifierNameFlags(node: Identifier) { // An IdentifierName is allowed to be `await` - return propagateChildFlags(node) & ~TransformFlags.ContainsPossibleTopLevelAwait; + return ( + propagateChildFlags(node) & + ~TransformFlags.ContainsPossibleTopLevelAwait + ); } -function propagatePropertyNameFlagsOfChild(node: PropertyName, transformFlags: TransformFlags) { - return transformFlags | (node.transformFlags & TransformFlags.PropertyNamePropagatingFlags); +function propagatePropertyNameFlagsOfChild( + node: PropertyName, + transformFlags: TransformFlags, +) { + return ( + transformFlags | + (node.transformFlags & TransformFlags.PropertyNamePropagatingFlags) + ); } function propagateChildFlags(child: Node | undefined): TransformFlags { if (!child) return TransformFlags.None; const childFlags = child.transformFlags & ~getTransformFlagsSubtreeExclusions(child.kind); - return isNamedDeclaration(child) && isPropertyName(child.name) ? propagatePropertyNameFlagsOfChild(child.name, childFlags) : childFlags; + return isNamedDeclaration(child) && isPropertyName(child.name) + ? propagatePropertyNameFlagsOfChild(child.name, childFlags) + : childFlags; } -function propagateChildrenFlags(children: NodeArray | undefined): TransformFlags { +function propagateChildrenFlags( + children: NodeArray | undefined, +): TransformFlags { return children ? children.transformFlags : TransformFlags.None; } @@ -7450,15 +10752,30 @@ const syntheticFactory: BaseNodeFactory = { createBaseNode: kind => makeSynthetic(baseFactory.createBaseNode(kind)), }; -export const factory = createNodeFactory(NodeFactoryFlags.NoIndentationOnFreshPropertyAccess, syntheticFactory); +export const factory = createNodeFactory( + NodeFactoryFlags.NoIndentationOnFreshPropertyAccess, + syntheticFactory, +); /** @deprecated */ export function createUnparsedSourceFile(text: string): UnparsedSource; /** @deprecated */ -export function createUnparsedSourceFile(inputFile: InputFiles, type: "js" | "dts", stripInternal?: boolean): UnparsedSource; +export function createUnparsedSourceFile( + inputFile: InputFiles, + type: "js" | "dts", + stripInternal?: boolean, +): UnparsedSource; /** @deprecated */ -export function createUnparsedSourceFile(text: string, mapPath: string | undefined, map: string | undefined): UnparsedSource; -export function createUnparsedSourceFile(textOrInputFiles: string | InputFiles, mapPathOrType?: string, mapTextOrStripInternal?: string | boolean): UnparsedSource { +export function createUnparsedSourceFile( + text: string, + mapPath: string | undefined, + map: string | undefined, +): UnparsedSource; +export function createUnparsedSourceFile( + textOrInputFiles: string | InputFiles, + mapPathOrType?: string, + mapTextOrStripInternal?: string | boolean, +): UnparsedSource { let stripInternal: boolean | undefined; let bundleFileInfo: BundleFileInfo | undefined; let fileName: string; @@ -7472,15 +10789,30 @@ export function createUnparsedSourceFile(textOrInputFiles: string | InputFiles, if (!isString(textOrInputFiles)) { Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts"); - fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || ""; - sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath; - getText = () => mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; - getSourceMapText = () => mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; + fileName = (mapPathOrType === "js" + ? textOrInputFiles.javascriptPath + : textOrInputFiles.declarationPath) || ""; + sourceMapPath = mapPathOrType === "js" + ? textOrInputFiles.javascriptMapPath + : textOrInputFiles.declarationMapPath; + getText = () => + mapPathOrType === "js" + ? textOrInputFiles.javascriptText + : textOrInputFiles.declarationText; + getSourceMapText = () => + mapPathOrType === "js" + ? textOrInputFiles.javascriptMapText + : textOrInputFiles.declarationMapText; length = () => getText!().length; if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) { - Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean"); + Debug.assert( + mapTextOrStripInternal === undefined || + typeof mapTextOrStripInternal === "boolean", + ); stripInternal = mapTextOrStripInternal; - bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts; + bundleFileInfo = mapPathOrType === "js" + ? textOrInputFiles.buildInfo.bundle.js + : textOrInputFiles.buildInfo.bundle.dts; oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit; } } @@ -7491,9 +10823,9 @@ export function createUnparsedSourceFile(textOrInputFiles: string | InputFiles, sourceMapPath = mapPathOrType; sourceMapText = mapTextOrStripInternal as string; } - const node = oldFileOfCurrentEmit ? - parseOldFileOfCurrentEmit(Debug.checkDefined(bundleFileInfo)) : - parseUnparsedSourceFile(bundleFileInfo, stripInternal, length); + const node = oldFileOfCurrentEmit + ? parseOldFileOfCurrentEmit(Debug.checkDefined(bundleFileInfo)) + : parseUnparsedSourceFile(bundleFileInfo, stripInternal, length); node.fileName = fileName; node.sourceMapPath = sourceMapPath; node.oldFileOfCurrentEmit = oldFileOfCurrentEmit; @@ -7510,7 +10842,11 @@ export function createUnparsedSourceFile(textOrInputFiles: string | InputFiles, return node; } -function parseUnparsedSourceFile(bundleFileInfo: BundleFileInfo | undefined, stripInternal: boolean | undefined, length: number | (() => number)) { +function parseUnparsedSourceFile( + bundleFileInfo: BundleFileInfo | undefined, + stripInternal: boolean | undefined, + length: number | (() => number), +) { let prologues: UnparsedPrologue[] | undefined; let helpers: UnscopedEmitHelper[] | undefined; let referencedFiles: FileReference[] | undefined; @@ -7520,51 +10856,113 @@ function parseUnparsedSourceFile(bundleFileInfo: BundleFileInfo | undefined, str let texts: UnparsedSourceText[] | undefined; let hasNoDefaultLib: boolean | undefined; - for (const section of bundleFileInfo ? bundleFileInfo.sections : emptyArray) { + for ( + const section of bundleFileInfo + ? bundleFileInfo.sections + : emptyArray + ) { switch (section.kind) { case BundleFileSectionKind.Prologue: - prologues = append(prologues, setTextRange(factory.createUnparsedPrologue(section.data), section)); + prologues = append( + prologues, + setTextRange( + factory.createUnparsedPrologue(section.data), + section, + ), + ); break; case BundleFileSectionKind.EmitHelpers: - helpers = append(helpers, getAllUnscopedEmitHelpers().get(section.data)!); + helpers = append( + helpers, + getAllUnscopedEmitHelpers().get(section.data)!, + ); break; case BundleFileSectionKind.NoDefaultLib: hasNoDefaultLib = true; break; case BundleFileSectionKind.Reference: - referencedFiles = append(referencedFiles, { pos: -1, end: -1, fileName: section.data }); + referencedFiles = append(referencedFiles, { + pos: -1, + end: -1, + fileName: section.data, + }); break; case BundleFileSectionKind.Type: - typeReferenceDirectives = append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data }); + typeReferenceDirectives = append(typeReferenceDirectives, { + pos: -1, + end: -1, + fileName: section.data, + }); break; case BundleFileSectionKind.TypeResolutionModeImport: - typeReferenceDirectives = append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data, resolutionMode: ModuleKind.ESNext }); + typeReferenceDirectives = append(typeReferenceDirectives, { + pos: -1, + end: -1, + fileName: section.data, + resolutionMode: ModuleKind.ESNext, + }); break; case BundleFileSectionKind.TypeResolutionModeRequire: - typeReferenceDirectives = append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data, resolutionMode: ModuleKind.CommonJS }); + typeReferenceDirectives = append(typeReferenceDirectives, { + pos: -1, + end: -1, + fileName: section.data, + resolutionMode: ModuleKind.CommonJS, + }); break; case BundleFileSectionKind.Lib: - libReferenceDirectives = append(libReferenceDirectives, { pos: -1, end: -1, fileName: section.data }); + libReferenceDirectives = append(libReferenceDirectives, { + pos: -1, + end: -1, + fileName: section.data, + }); break; case BundleFileSectionKind.Prepend: let prependTexts: UnparsedTextLike[] | undefined; for (const text of section.texts) { - if (!stripInternal || text.kind !== BundleFileSectionKind.Internal) { - prependTexts = append(prependTexts, setTextRange(factory.createUnparsedTextLike(text.data, text.kind === BundleFileSectionKind.Internal), text)); + if ( + !stripInternal || + text.kind !== BundleFileSectionKind.Internal + ) { + prependTexts = append( + prependTexts, + setTextRange( + factory.createUnparsedTextLike( + text.data, + text.kind === BundleFileSectionKind.Internal, + ), + text, + ), + ); } } prependChildren = addRange(prependChildren, prependTexts); - texts = append(texts, factory.createUnparsedPrepend(section.data, prependTexts ?? emptyArray)); + texts = append( + texts, + factory.createUnparsedPrepend( + section.data, + prependTexts ?? emptyArray, + ), + ); break; case BundleFileSectionKind.Internal: if (stripInternal) { if (!texts) texts = []; break; } - // falls through + // falls through case BundleFileSectionKind.Text: - texts = append(texts, setTextRange(factory.createUnparsedTextLike(section.data, section.kind === BundleFileSectionKind.Internal), section)); + texts = append( + texts, + setTextRange( + factory.createUnparsedTextLike( + section.data, + section.kind === BundleFileSectionKind.Internal, + ), + section, + ), + ); break; default: Debug.assertNever(section); @@ -7572,12 +10970,23 @@ function parseUnparsedSourceFile(bundleFileInfo: BundleFileInfo | undefined, str } if (!texts) { - const textNode = factory.createUnparsedTextLike(/*data*/ undefined, /*internal*/ false); - setTextRangePosWidth(textNode, 0, typeof length === "function" ? length() : length); + const textNode = factory.createUnparsedTextLike( + /*data*/ undefined, + /*internal*/ false, + ); + setTextRangePosWidth( + textNode, + 0, + typeof length === "function" ? length() : length, + ); texts = [textNode]; } - const node = parseNodeFactory.createUnparsedSource(prologues ?? emptyArray, /*syntheticReferences*/ undefined, texts); + const node = parseNodeFactory.createUnparsedSource( + prologues ?? emptyArray, + /*syntheticReferences*/ undefined, + texts, + ); setEachParent(prologues, node); setEachParent(texts, node); setEachParent(prependChildren, node); @@ -7596,7 +11005,16 @@ function parseOldFileOfCurrentEmit(bundleFileInfo: BundleFileInfo) { switch (section.kind) { case BundleFileSectionKind.Internal: case BundleFileSectionKind.Text: - texts = append(texts, setTextRange(factory.createUnparsedTextLike(section.data, section.kind === BundleFileSectionKind.Internal), section)); + texts = append( + texts, + setTextRange( + factory.createUnparsedTextLike( + section.data, + section.kind === BundleFileSectionKind.Internal, + ), + section, + ), + ); break; case BundleFileSectionKind.NoDefaultLib: @@ -7605,7 +11023,13 @@ function parseOldFileOfCurrentEmit(bundleFileInfo: BundleFileInfo) { case BundleFileSectionKind.TypeResolutionModeImport: case BundleFileSectionKind.TypeResolutionModeRequire: case BundleFileSectionKind.Lib: - syntheticReferences = append(syntheticReferences, setTextRange(factory.createUnparsedSyntheticReference(section), section)); + syntheticReferences = append( + syntheticReferences, + setTextRange( + factory.createUnparsedSyntheticReference(section), + section, + ), + ); break; // Ignore @@ -7619,10 +11043,17 @@ function parseOldFileOfCurrentEmit(bundleFileInfo: BundleFileInfo) { } } - const node = factory.createUnparsedSource(emptyArray, syntheticReferences, texts ?? emptyArray); + const node = factory.createUnparsedSource( + emptyArray, + syntheticReferences, + texts ?? emptyArray, + ); setEachParent(syntheticReferences, node); setEachParent(texts, node); - node.helpers = map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, name => getAllUnscopedEmitHelpers().get(name)!); + node.helpers = map( + bundleFileInfo.sources && bundleFileInfo.sources.helpers, + name => getAllUnscopedEmitHelpers().get(name)!, + ); return node; } @@ -7651,23 +11082,25 @@ export function createInputFiles( buildInfoPath: string | undefined, ): InputFiles; export function createInputFiles( - javascriptTextOrReadFileText: string | ((path: string) => string | undefined), + javascriptTextOrReadFileText: + | string + | ((path: string) => string | undefined), declarationTextOrJavascriptPath: string, javascriptMapPath?: string, javascriptMapTextOrDeclarationPath?: string, declarationMapPath?: string, declarationMapTextOrBuildInfoPath?: string, ): InputFiles { - return !isString(javascriptTextOrReadFileText) ? - createInputFilesWithFilePaths( + return !isString(javascriptTextOrReadFileText) + ? createInputFilesWithFilePaths( javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath!, declarationMapPath, declarationMapTextOrBuildInfoPath, - ) : - createInputFilesWithFileTexts( + ) + : createInputFilesWithFileTexts( /*javascriptPath*/ undefined, javascriptTextOrReadFileText, javascriptMapPath, @@ -7703,21 +11136,26 @@ export function createInputFilesWithFilePaths( value = readFileText(path); cache.set(path, value !== undefined ? value : false); } - return value !== false ? value as string : undefined; + return value !== false ? (value as string) : undefined; }; const definedTextGetter = (path: string) => { const result = textGetter(path); - return result !== undefined ? result : `/* Input file ${path} was missing */\r\n`; + return result !== undefined + ? result + : `/* Input file ${path} was missing */\r\n`; }; let buildInfo: BuildInfo | false; const getAndCacheBuildInfo = () => { if (buildInfo === undefined && buildInfoPath) { if (host?.getBuildInfo) { - buildInfo = host.getBuildInfo(buildInfoPath, options!.configFilePath) ?? false; + buildInfo = host.getBuildInfo(buildInfoPath, options!.configFilePath) ?? + false; } else { const result = textGetter(buildInfoPath); - buildInfo = result !== undefined ? getBuildInfo(buildInfoPath, result) ?? false : false; + buildInfo = result !== undefined + ? getBuildInfo(buildInfoPath, result) ?? false + : false; } } return buildInfo || undefined; @@ -7725,7 +11163,9 @@ export function createInputFilesWithFilePaths( Object.defineProperties(node, { javascriptText: { get: () => definedTextGetter(javascriptPath) }, javascriptMapText: { get: () => textGetter(javascriptMapPath) }, // TODO:: if there is inline sourceMap in jsFile, use that - declarationText: { get: () => definedTextGetter(Debug.checkDefined(declarationPath)) }, + declarationText: { + get: () => definedTextGetter(Debug.checkDefined(declarationPath)), + }, declarationMapText: { get: () => textGetter(declarationMapPath) }, // TODO:: if there is inline sourceMap in dtsFile, use that buildInfo: { get: getAndCacheBuildInfo }, }); @@ -7760,18 +11200,34 @@ export function createInputFilesWithFileTexts( return node; } -let SourceMapSource: new (fileName: string, text: string, skipTrivia?: (pos: number) => number) => SourceMapSource; +let SourceMapSource: new ( + fileName: string, + text: string, + skipTrivia?: (pos: number) => number, +) => SourceMapSource; /** * Create an external source map source file reference */ -export function createSourceMapSource(fileName: string, text: string, skipTrivia?: (pos: number) => number): SourceMapSource { - return new (SourceMapSource || (SourceMapSource = objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia); +export function createSourceMapSource( + fileName: string, + text: string, + skipTrivia?: (pos: number) => number, +): SourceMapSource { + return new (SourceMapSource || + (SourceMapSource = objectAllocator.getSourceMapSourceConstructor()))( + fileName, + text, + skipTrivia, + ); } // Utilities -export function setOriginalNode(node: T, original: Node | undefined): T { +export function setOriginalNode( + node: T, + original: Node | undefined, +): T { if (node.original !== original) { node.original = original; if (original) { @@ -7782,7 +11238,10 @@ export function setOriginalNode(node: T, original: Node | undefi return node; } -function mergeEmitNode(sourceEmitNode: EmitNode, destEmitNode: EmitNode | undefined) { +function mergeEmitNode( + sourceEmitNode: EmitNode, + destEmitNode: EmitNode | undefined, +) { const { flags, internalFlags, @@ -7818,13 +11277,19 @@ function mergeEmitNode(sourceEmitNode: EmitNode, destEmitNode: EmitNode | undefi // `leadingComments` are concatenated with any existing leading comments on the destination if (leadingComments) { // We use `.slice()` in case `destEmitNode.leadingComments` is pushed to later - destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments); + destEmitNode.leadingComments = addRange( + leadingComments.slice(), + destEmitNode.leadingComments, + ); } // `trailingComments` are concatenated with any existing trailing comments on the destination if (trailingComments) { // We use `.slice()` in case `destEmitNode.trailingComments` is pushed to later - destEmitNode.trailingComments = addRange(trailingComments.slice(), destEmitNode.trailingComments); + destEmitNode.trailingComments = addRange( + trailingComments.slice(), + destEmitNode.trailingComments, + ); } // `commentRange` overwrites the destination @@ -7839,7 +11304,10 @@ function mergeEmitNode(sourceEmitNode: EmitNode, destEmitNode: EmitNode | undefi // `tokenSourceMapRanges` are merged with the destination if (tokenSourceMapRanges) { - destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges!); + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges( + tokenSourceMapRanges, + destEmitNode.tokenSourceMapRanges!, + ); } // `constantValue` overwrites the destination @@ -7887,7 +11355,10 @@ function mergeEmitNode(sourceEmitNode: EmitNode, destEmitNode: EmitNode | undefi return destEmitNode; } -function mergeTokenSourceMapRanges(sourceRanges: (TextRange | undefined)[], destRanges: (TextRange | undefined)[]) { +function mergeTokenSourceMapRanges( + sourceRanges: (TextRange | undefined)[], + destRanges: (TextRange | undefined)[], +) { if (!destRanges) destRanges = []; for (const key in sourceRanges) { destRanges[key] = sourceRanges[key]; diff --git a/src/compiler/factory/nodeTests.ts b/src/compiler/factory/nodeTests.ts index eca54d346d882..0f7da9f498bd0 100644 --- a/src/compiler/factory/nodeTests.ts +++ b/src/compiler/factory/nodeTests.ts @@ -152,7 +152,7 @@ import { NamespaceExportDeclaration, NamespaceImport, NewExpression, - Node, + NodeBase, NonNullExpression, NoSubstitutionTemplateLiteral, NotEmittedStatement, @@ -232,777 +232,777 @@ import { // Literals -export function isNumericLiteral(node: Node): node is NumericLiteral { +export function isNumericLiteral(node: NodeBase): node is NumericLiteral { return node.kind === SyntaxKind.NumericLiteral; } -export function isBigIntLiteral(node: Node): node is BigIntLiteral { +export function isBigIntLiteral(node: NodeBase): node is BigIntLiteral { return node.kind === SyntaxKind.BigIntLiteral; } -export function isStringLiteral(node: Node): node is StringLiteral { +export function isStringLiteral(node: NodeBase): node is StringLiteral { return node.kind === SyntaxKind.StringLiteral; } -export function isJsxText(node: Node): node is JsxText { +export function isJsxText(node: NodeBase): node is JsxText { return node.kind === SyntaxKind.JsxText; } -export function isRegularExpressionLiteral(node: Node): node is RegularExpressionLiteral { +export function isRegularExpressionLiteral(node: NodeBase): node is RegularExpressionLiteral { return node.kind === SyntaxKind.RegularExpressionLiteral; } -export function isNoSubstitutionTemplateLiteral(node: Node): node is NoSubstitutionTemplateLiteral { +export function isNoSubstitutionTemplateLiteral(node: NodeBase): node is NoSubstitutionTemplateLiteral { return node.kind === SyntaxKind.NoSubstitutionTemplateLiteral; } // Pseudo-literals -export function isTemplateHead(node: Node): node is TemplateHead { +export function isTemplateHead(node: NodeBase): node is TemplateHead { return node.kind === SyntaxKind.TemplateHead; } -export function isTemplateMiddle(node: Node): node is TemplateMiddle { +export function isTemplateMiddle(node: NodeBase): node is TemplateMiddle { return node.kind === SyntaxKind.TemplateMiddle; } -export function isTemplateTail(node: Node): node is TemplateTail { +export function isTemplateTail(node: NodeBase): node is TemplateTail { return node.kind === SyntaxKind.TemplateTail; } // Punctuation -export function isDotDotDotToken(node: Node): node is DotDotDotToken { +export function isDotDotDotToken(node: NodeBase): node is DotDotDotToken { return node.kind === SyntaxKind.DotDotDotToken; } /** @internal */ -export function isCommaToken(node: Node): node is Token { +export function isCommaToken(node: NodeBase): node is Token { return node.kind === SyntaxKind.CommaToken; } -export function isPlusToken(node: Node): node is PlusToken { +export function isPlusToken(node: NodeBase): node is PlusToken { return node.kind === SyntaxKind.PlusToken; } -export function isMinusToken(node: Node): node is MinusToken { +export function isMinusToken(node: NodeBase): node is MinusToken { return node.kind === SyntaxKind.MinusToken; } -export function isAsteriskToken(node: Node): node is AsteriskToken { +export function isAsteriskToken(node: NodeBase): node is AsteriskToken { return node.kind === SyntaxKind.AsteriskToken; } -export function isExclamationToken(node: Node): node is ExclamationToken { +export function isExclamationToken(node: NodeBase): node is ExclamationToken { return node.kind === SyntaxKind.ExclamationToken; } -export function isQuestionToken(node: Node): node is QuestionToken { +export function isQuestionToken(node: NodeBase): node is QuestionToken { return node.kind === SyntaxKind.QuestionToken; } -export function isColonToken(node: Node): node is ColonToken { +export function isColonToken(node: NodeBase): node is ColonToken { return node.kind === SyntaxKind.ColonToken; } -export function isQuestionDotToken(node: Node): node is QuestionDotToken { +export function isQuestionDotToken(node: NodeBase): node is QuestionDotToken { return node.kind === SyntaxKind.QuestionDotToken; } -export function isEqualsGreaterThanToken(node: Node): node is EqualsGreaterThanToken { +export function isEqualsGreaterThanToken(node: NodeBase): node is EqualsGreaterThanToken { return node.kind === SyntaxKind.EqualsGreaterThanToken; } // Identifiers -export function isIdentifier(node: Node): node is Identifier { +export function isIdentifier(node: NodeBase): node is Identifier { return node.kind === SyntaxKind.Identifier; } -export function isPrivateIdentifier(node: Node): node is PrivateIdentifier { +export function isPrivateIdentifier(node: NodeBase): node is PrivateIdentifier { return node.kind === SyntaxKind.PrivateIdentifier; } // Reserved Words /** @internal */ -export function isExportModifier(node: Node): node is ExportKeyword { +export function isExportModifier(node: NodeBase): node is ExportKeyword { return node.kind === SyntaxKind.ExportKeyword; } /** @internal */ -export function isDefaultModifier(node: Node): node is DefaultKeyword { +export function isDefaultModifier(node: NodeBase): node is DefaultKeyword { return node.kind === SyntaxKind.DefaultKeyword; } /** @internal */ -export function isAsyncModifier(node: Node): node is AsyncKeyword { +export function isAsyncModifier(node: NodeBase): node is AsyncKeyword { return node.kind === SyntaxKind.AsyncKeyword; } -export function isAssertsKeyword(node: Node): node is AssertsKeyword { +export function isAssertsKeyword(node: NodeBase): node is AssertsKeyword { return node.kind === SyntaxKind.AssertsKeyword; } -export function isAwaitKeyword(node: Node): node is AwaitKeyword { +export function isAwaitKeyword(node: NodeBase): node is AwaitKeyword { return node.kind === SyntaxKind.AwaitKeyword; } /** @internal */ -export function isReadonlyKeyword(node: Node): node is ReadonlyKeyword { +export function isReadonlyKeyword(node: NodeBase): node is ReadonlyKeyword { return node.kind === SyntaxKind.ReadonlyKeyword; } /** @internal */ -export function isStaticModifier(node: Node): node is StaticKeyword { +export function isStaticModifier(node: NodeBase): node is StaticKeyword { return node.kind === SyntaxKind.StaticKeyword; } /** @internal */ -export function isAbstractModifier(node: Node): node is AbstractKeyword { +export function isAbstractModifier(node: NodeBase): node is AbstractKeyword { return node.kind === SyntaxKind.AbstractKeyword; } /** @internal */ -export function isOverrideModifier(node: Node): node is OverrideKeyword { +export function isOverrideModifier(node: NodeBase): node is OverrideKeyword { return node.kind === SyntaxKind.OverrideKeyword; } /** @internal */ -export function isAccessorModifier(node: Node): node is AccessorKeyword { +export function isAccessorModifier(node: NodeBase): node is AccessorKeyword { return node.kind === SyntaxKind.AccessorKeyword; } /** @internal */ -export function isSuperKeyword(node: Node): node is SuperExpression { +export function isSuperKeyword(node: NodeBase): node is SuperExpression { return node.kind === SyntaxKind.SuperKeyword; } /** @internal */ -export function isImportKeyword(node: Node): node is ImportExpression { +export function isImportKeyword(node: NodeBase): node is ImportExpression { return node.kind === SyntaxKind.ImportKeyword; } /** @internal */ -export function isCaseKeyword(node: Node): node is CaseKeyword { +export function isCaseKeyword(node: NodeBase): node is CaseKeyword { return node.kind === SyntaxKind.CaseKeyword; } // Names -export function isQualifiedName(node: Node): node is QualifiedName { +export function isQualifiedName(node: NodeBase): node is QualifiedName { return node.kind === SyntaxKind.QualifiedName; } -export function isComputedPropertyName(node: Node): node is ComputedPropertyName { +export function isComputedPropertyName(node: NodeBase): node is ComputedPropertyName { return node.kind === SyntaxKind.ComputedPropertyName; } // Signature elements -export function isTypeParameterDeclaration(node: Node): node is TypeParameterDeclaration { +export function isTypeParameterDeclaration(node: NodeBase): node is TypeParameterDeclaration { return node.kind === SyntaxKind.TypeParameter; } // TODO(rbuckton): Rename to 'isParameterDeclaration' -export function isParameter(node: Node): node is ParameterDeclaration { +export function isParameter(node: NodeBase): node is ParameterDeclaration { return node.kind === SyntaxKind.Parameter; } -export function isDecorator(node: Node): node is Decorator { +export function isDecorator(node: NodeBase): node is Decorator { return node.kind === SyntaxKind.Decorator; } // TypeMember -export function isPropertySignature(node: Node): node is PropertySignature { +export function isPropertySignature(node: NodeBase): node is PropertySignature { return node.kind === SyntaxKind.PropertySignature; } -export function isPropertyDeclaration(node: Node): node is PropertyDeclaration { +export function isPropertyDeclaration(node: NodeBase): node is PropertyDeclaration { return node.kind === SyntaxKind.PropertyDeclaration; } -export function isMethodSignature(node: Node): node is MethodSignature { +export function isMethodSignature(node: NodeBase): node is MethodSignature { return node.kind === SyntaxKind.MethodSignature; } -export function isMethodDeclaration(node: Node): node is MethodDeclaration { +export function isMethodDeclaration(node: NodeBase): node is MethodDeclaration { return node.kind === SyntaxKind.MethodDeclaration; } -export function isClassStaticBlockDeclaration(node: Node): node is ClassStaticBlockDeclaration { +export function isClassStaticBlockDeclaration(node: NodeBase): node is ClassStaticBlockDeclaration { return node.kind === SyntaxKind.ClassStaticBlockDeclaration; } -export function isConstructorDeclaration(node: Node): node is ConstructorDeclaration { +export function isConstructorDeclaration(node: NodeBase): node is ConstructorDeclaration { return node.kind === SyntaxKind.Constructor; } -export function isGetAccessorDeclaration(node: Node): node is GetAccessorDeclaration { +export function isGetAccessorDeclaration(node: NodeBase): node is GetAccessorDeclaration { return node.kind === SyntaxKind.GetAccessor; } -export function isSetAccessorDeclaration(node: Node): node is SetAccessorDeclaration { +export function isSetAccessorDeclaration(node: NodeBase): node is SetAccessorDeclaration { return node.kind === SyntaxKind.SetAccessor; } -export function isCallSignatureDeclaration(node: Node): node is CallSignatureDeclaration { +export function isCallSignatureDeclaration(node: NodeBase): node is CallSignatureDeclaration { return node.kind === SyntaxKind.CallSignature; } -export function isConstructSignatureDeclaration(node: Node): node is ConstructSignatureDeclaration { +export function isConstructSignatureDeclaration(node: NodeBase): node is ConstructSignatureDeclaration { return node.kind === SyntaxKind.ConstructSignature; } -export function isIndexSignatureDeclaration(node: Node): node is IndexSignatureDeclaration { +export function isIndexSignatureDeclaration(node: NodeBase): node is IndexSignatureDeclaration { return node.kind === SyntaxKind.IndexSignature; } // Type -export function isTypePredicateNode(node: Node): node is TypePredicateNode { +export function isTypePredicateNode(node: NodeBase): node is TypePredicateNode { return node.kind === SyntaxKind.TypePredicate; } -export function isTypeReferenceNode(node: Node): node is TypeReferenceNode { +export function isTypeReferenceNode(node: NodeBase): node is TypeReferenceNode { return node.kind === SyntaxKind.TypeReference; } -export function isFunctionTypeNode(node: Node): node is FunctionTypeNode { +export function isFunctionTypeNode(node: NodeBase): node is FunctionTypeNode { return node.kind === SyntaxKind.FunctionType; } -export function isConstructorTypeNode(node: Node): node is ConstructorTypeNode { +export function isConstructorTypeNode(node: NodeBase): node is ConstructorTypeNode { return node.kind === SyntaxKind.ConstructorType; } -export function isTypeQueryNode(node: Node): node is TypeQueryNode { +export function isTypeQueryNode(node: NodeBase): node is TypeQueryNode { return node.kind === SyntaxKind.TypeQuery; } -export function isTypeLiteralNode(node: Node): node is TypeLiteralNode { +export function isTypeLiteralNode(node: NodeBase): node is TypeLiteralNode { return node.kind === SyntaxKind.TypeLiteral; } -export function isArrayTypeNode(node: Node): node is ArrayTypeNode { +export function isArrayTypeNode(node: NodeBase): node is ArrayTypeNode { return node.kind === SyntaxKind.ArrayType; } -export function isTupleTypeNode(node: Node): node is TupleTypeNode { +export function isTupleTypeNode(node: NodeBase): node is TupleTypeNode { return node.kind === SyntaxKind.TupleType; } -export function isNamedTupleMember(node: Node): node is NamedTupleMember { +export function isNamedTupleMember(node: NodeBase): node is NamedTupleMember { return node.kind === SyntaxKind.NamedTupleMember; } -export function isOptionalTypeNode(node: Node): node is OptionalTypeNode { +export function isOptionalTypeNode(node: NodeBase): node is OptionalTypeNode { return node.kind === SyntaxKind.OptionalType; } -export function isRestTypeNode(node: Node): node is RestTypeNode { +export function isRestTypeNode(node: NodeBase): node is RestTypeNode { return node.kind === SyntaxKind.RestType; } -export function isUnionTypeNode(node: Node): node is UnionTypeNode { +export function isUnionTypeNode(node: NodeBase): node is UnionTypeNode { return node.kind === SyntaxKind.UnionType; } -export function isIntersectionTypeNode(node: Node): node is IntersectionTypeNode { +export function isIntersectionTypeNode(node: NodeBase): node is IntersectionTypeNode { return node.kind === SyntaxKind.IntersectionType; } -export function isConditionalTypeNode(node: Node): node is ConditionalTypeNode { +export function isConditionalTypeNode(node: NodeBase): node is ConditionalTypeNode { return node.kind === SyntaxKind.ConditionalType; } -export function isInferTypeNode(node: Node): node is InferTypeNode { +export function isInferTypeNode(node: NodeBase): node is InferTypeNode { return node.kind === SyntaxKind.InferType; } -export function isParenthesizedTypeNode(node: Node): node is ParenthesizedTypeNode { +export function isParenthesizedTypeNode(node: NodeBase): node is ParenthesizedTypeNode { return node.kind === SyntaxKind.ParenthesizedType; } -export function isThisTypeNode(node: Node): node is ThisTypeNode { +export function isThisTypeNode(node: NodeBase): node is ThisTypeNode { return node.kind === SyntaxKind.ThisType; } -export function isTypeOperatorNode(node: Node): node is TypeOperatorNode { +export function isTypeOperatorNode(node: NodeBase): node is TypeOperatorNode { return node.kind === SyntaxKind.TypeOperator; } -export function isIndexedAccessTypeNode(node: Node): node is IndexedAccessTypeNode { +export function isIndexedAccessTypeNode(node: NodeBase): node is IndexedAccessTypeNode { return node.kind === SyntaxKind.IndexedAccessType; } -export function isMappedTypeNode(node: Node): node is MappedTypeNode { +export function isMappedTypeNode(node: NodeBase): node is MappedTypeNode { return node.kind === SyntaxKind.MappedType; } -export function isLiteralTypeNode(node: Node): node is LiteralTypeNode { +export function isLiteralTypeNode(node: NodeBase): node is LiteralTypeNode { return node.kind === SyntaxKind.LiteralType; } -export function isImportTypeNode(node: Node): node is ImportTypeNode { +export function isImportTypeNode(node: NodeBase): node is ImportTypeNode { return node.kind === SyntaxKind.ImportType; } -export function isTemplateLiteralTypeSpan(node: Node): node is TemplateLiteralTypeSpan { +export function isTemplateLiteralTypeSpan(node: NodeBase): node is TemplateLiteralTypeSpan { return node.kind === SyntaxKind.TemplateLiteralTypeSpan; } -export function isTemplateLiteralTypeNode(node: Node): node is TemplateLiteralTypeNode { +export function isTemplateLiteralTypeNode(node: NodeBase): node is TemplateLiteralTypeNode { return node.kind === SyntaxKind.TemplateLiteralType; } // Binding patterns -export function isObjectBindingPattern(node: Node): node is ObjectBindingPattern { +export function isObjectBindingPattern(node: NodeBase): node is ObjectBindingPattern { return node.kind === SyntaxKind.ObjectBindingPattern; } -export function isArrayBindingPattern(node: Node): node is ArrayBindingPattern { +export function isArrayBindingPattern(node: NodeBase): node is ArrayBindingPattern { return node.kind === SyntaxKind.ArrayBindingPattern; } -export function isBindingElement(node: Node): node is BindingElement { +export function isBindingElement(node: NodeBase): node is BindingElement { return node.kind === SyntaxKind.BindingElement; } // Expression -export function isArrayLiteralExpression(node: Node): node is ArrayLiteralExpression { +export function isArrayLiteralExpression(node: NodeBase): node is ArrayLiteralExpression { return node.kind === SyntaxKind.ArrayLiteralExpression; } -export function isObjectLiteralExpression(node: Node): node is ObjectLiteralExpression { +export function isObjectLiteralExpression(node: NodeBase): node is ObjectLiteralExpression { return node.kind === SyntaxKind.ObjectLiteralExpression; } -export function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression { +export function isPropertyAccessExpression(node: NodeBase): node is PropertyAccessExpression { return node.kind === SyntaxKind.PropertyAccessExpression; } -export function isElementAccessExpression(node: Node): node is ElementAccessExpression { +export function isElementAccessExpression(node: NodeBase): node is ElementAccessExpression { return node.kind === SyntaxKind.ElementAccessExpression; } -export function isCallExpression(node: Node): node is CallExpression { +export function isCallExpression(node: NodeBase): node is CallExpression { return node.kind === SyntaxKind.CallExpression; } -export function isNewExpression(node: Node): node is NewExpression { +export function isNewExpression(node: NodeBase): node is NewExpression { return node.kind === SyntaxKind.NewExpression; } -export function isTaggedTemplateExpression(node: Node): node is TaggedTemplateExpression { +export function isTaggedTemplateExpression(node: NodeBase): node is TaggedTemplateExpression { return node.kind === SyntaxKind.TaggedTemplateExpression; } -export function isTypeAssertionExpression(node: Node): node is TypeAssertion { +export function isTypeAssertionExpression(node: NodeBase): node is TypeAssertion { return node.kind === SyntaxKind.TypeAssertionExpression; } -export function isParenthesizedExpression(node: Node): node is ParenthesizedExpression { +export function isParenthesizedExpression(node: NodeBase): node is ParenthesizedExpression { return node.kind === SyntaxKind.ParenthesizedExpression; } -export function isFunctionExpression(node: Node): node is FunctionExpression { +export function isFunctionExpression(node: NodeBase): node is FunctionExpression { return node.kind === SyntaxKind.FunctionExpression; } -export function isArrowFunction(node: Node): node is ArrowFunction { +export function isArrowFunction(node: NodeBase): node is ArrowFunction { return node.kind === SyntaxKind.ArrowFunction; } -export function isDeleteExpression(node: Node): node is DeleteExpression { +export function isDeleteExpression(node: NodeBase): node is DeleteExpression { return node.kind === SyntaxKind.DeleteExpression; } -export function isTypeOfExpression(node: Node): node is TypeOfExpression { +export function isTypeOfExpression(node: NodeBase): node is TypeOfExpression { return node.kind === SyntaxKind.TypeOfExpression; } -export function isVoidExpression(node: Node): node is VoidExpression { +export function isVoidExpression(node: NodeBase): node is VoidExpression { return node.kind === SyntaxKind.VoidExpression; } -export function isAwaitExpression(node: Node): node is AwaitExpression { +export function isAwaitExpression(node: NodeBase): node is AwaitExpression { return node.kind === SyntaxKind.AwaitExpression; } -export function isPrefixUnaryExpression(node: Node): node is PrefixUnaryExpression { +export function isPrefixUnaryExpression(node: NodeBase): node is PrefixUnaryExpression { return node.kind === SyntaxKind.PrefixUnaryExpression; } -export function isPostfixUnaryExpression(node: Node): node is PostfixUnaryExpression { +export function isPostfixUnaryExpression(node: NodeBase): node is PostfixUnaryExpression { return node.kind === SyntaxKind.PostfixUnaryExpression; } -export function isBinaryExpression(node: Node): node is BinaryExpression { +export function isBinaryExpression(node: NodeBase): node is BinaryExpression { return node.kind === SyntaxKind.BinaryExpression; } -export function isConditionalExpression(node: Node): node is ConditionalExpression { +export function isConditionalExpression(node: NodeBase): node is ConditionalExpression { return node.kind === SyntaxKind.ConditionalExpression; } -export function isTemplateExpression(node: Node): node is TemplateExpression { +export function isTemplateExpression(node: NodeBase): node is TemplateExpression { return node.kind === SyntaxKind.TemplateExpression; } -export function isYieldExpression(node: Node): node is YieldExpression { +export function isYieldExpression(node: NodeBase): node is YieldExpression { return node.kind === SyntaxKind.YieldExpression; } -export function isSpreadElement(node: Node): node is SpreadElement { +export function isSpreadElement(node: NodeBase): node is SpreadElement { return node.kind === SyntaxKind.SpreadElement; } -export function isClassExpression(node: Node): node is ClassExpression { +export function isClassExpression(node: NodeBase): node is ClassExpression { return node.kind === SyntaxKind.ClassExpression; } -export function isOmittedExpression(node: Node): node is OmittedExpression { +export function isOmittedExpression(node: NodeBase): node is OmittedExpression { return node.kind === SyntaxKind.OmittedExpression; } -export function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments { +export function isExpressionWithTypeArguments(node: NodeBase): node is ExpressionWithTypeArguments { return node.kind === SyntaxKind.ExpressionWithTypeArguments; } -export function isAsExpression(node: Node): node is AsExpression { +export function isAsExpression(node: NodeBase): node is AsExpression { return node.kind === SyntaxKind.AsExpression; } -export function isSatisfiesExpression(node: Node): node is SatisfiesExpression { +export function isSatisfiesExpression(node: NodeBase): node is SatisfiesExpression { return node.kind === SyntaxKind.SatisfiesExpression; } -export function isNonNullExpression(node: Node): node is NonNullExpression { +export function isNonNullExpression(node: NodeBase): node is NonNullExpression { return node.kind === SyntaxKind.NonNullExpression; } -export function isMetaProperty(node: Node): node is MetaProperty { +export function isMetaProperty(node: NodeBase): node is MetaProperty { return node.kind === SyntaxKind.MetaProperty; } -export function isSyntheticExpression(node: Node): node is SyntheticExpression { +export function isSyntheticExpression(node: NodeBase): node is SyntheticExpression { return node.kind === SyntaxKind.SyntheticExpression; } -export function isPartiallyEmittedExpression(node: Node): node is PartiallyEmittedExpression { +export function isPartiallyEmittedExpression(node: NodeBase): node is PartiallyEmittedExpression { return node.kind === SyntaxKind.PartiallyEmittedExpression; } -export function isCommaListExpression(node: Node): node is CommaListExpression { +export function isCommaListExpression(node: NodeBase): node is CommaListExpression { return node.kind === SyntaxKind.CommaListExpression; } // Misc -export function isTemplateSpan(node: Node): node is TemplateSpan { +export function isTemplateSpan(node: NodeBase): node is TemplateSpan { return node.kind === SyntaxKind.TemplateSpan; } -export function isSemicolonClassElement(node: Node): node is SemicolonClassElement { +export function isSemicolonClassElement(node: NodeBase): node is SemicolonClassElement { return node.kind === SyntaxKind.SemicolonClassElement; } // Elements -export function isBlock(node: Node): node is Block { +export function isBlock(node: NodeBase): node is Block { return node.kind === SyntaxKind.Block; } -export function isVariableStatement(node: Node): node is VariableStatement { +export function isVariableStatement(node: NodeBase): node is VariableStatement { return node.kind === SyntaxKind.VariableStatement; } -export function isEmptyStatement(node: Node): node is EmptyStatement { +export function isEmptyStatement(node: NodeBase): node is EmptyStatement { return node.kind === SyntaxKind.EmptyStatement; } -export function isExpressionStatement(node: Node): node is ExpressionStatement { +export function isExpressionStatement(node: NodeBase): node is ExpressionStatement { return node.kind === SyntaxKind.ExpressionStatement; } -export function isIfStatement(node: Node): node is IfStatement { +export function isIfStatement(node: NodeBase): node is IfStatement { return node.kind === SyntaxKind.IfStatement; } -export function isDoStatement(node: Node): node is DoStatement { +export function isDoStatement(node: NodeBase): node is DoStatement { return node.kind === SyntaxKind.DoStatement; } -export function isWhileStatement(node: Node): node is WhileStatement { +export function isWhileStatement(node: NodeBase): node is WhileStatement { return node.kind === SyntaxKind.WhileStatement; } -export function isForStatement(node: Node): node is ForStatement { +export function isForStatement(node: NodeBase): node is ForStatement { return node.kind === SyntaxKind.ForStatement; } -export function isForInStatement(node: Node): node is ForInStatement { +export function isForInStatement(node: NodeBase): node is ForInStatement { return node.kind === SyntaxKind.ForInStatement; } -export function isForOfStatement(node: Node): node is ForOfStatement { +export function isForOfStatement(node: NodeBase): node is ForOfStatement { return node.kind === SyntaxKind.ForOfStatement; } -export function isContinueStatement(node: Node): node is ContinueStatement { +export function isContinueStatement(node: NodeBase): node is ContinueStatement { return node.kind === SyntaxKind.ContinueStatement; } -export function isBreakStatement(node: Node): node is BreakStatement { +export function isBreakStatement(node: NodeBase): node is BreakStatement { return node.kind === SyntaxKind.BreakStatement; } -export function isReturnStatement(node: Node): node is ReturnStatement { +export function isReturnStatement(node: NodeBase): node is ReturnStatement { return node.kind === SyntaxKind.ReturnStatement; } -export function isWithStatement(node: Node): node is WithStatement { +export function isWithStatement(node: NodeBase): node is WithStatement { return node.kind === SyntaxKind.WithStatement; } -export function isSwitchStatement(node: Node): node is SwitchStatement { +export function isSwitchStatement(node: NodeBase): node is SwitchStatement { return node.kind === SyntaxKind.SwitchStatement; } -export function isLabeledStatement(node: Node): node is LabeledStatement { +export function isLabeledStatement(node: NodeBase): node is LabeledStatement { return node.kind === SyntaxKind.LabeledStatement; } -export function isThrowStatement(node: Node): node is ThrowStatement { +export function isThrowStatement(node: NodeBase): node is ThrowStatement { return node.kind === SyntaxKind.ThrowStatement; } -export function isTryStatement(node: Node): node is TryStatement { +export function isTryStatement(node: NodeBase): node is TryStatement { return node.kind === SyntaxKind.TryStatement; } -export function isDebuggerStatement(node: Node): node is DebuggerStatement { +export function isDebuggerStatement(node: NodeBase): node is DebuggerStatement { return node.kind === SyntaxKind.DebuggerStatement; } -export function isVariableDeclaration(node: Node): node is VariableDeclaration { +export function isVariableDeclaration(node: NodeBase): node is VariableDeclaration { return node.kind === SyntaxKind.VariableDeclaration; } -export function isVariableDeclarationList(node: Node): node is VariableDeclarationList { +export function isVariableDeclarationList(node: NodeBase): node is VariableDeclarationList { return node.kind === SyntaxKind.VariableDeclarationList; } -export function isFunctionDeclaration(node: Node): node is FunctionDeclaration { +export function isFunctionDeclaration(node: NodeBase): node is FunctionDeclaration { return node.kind === SyntaxKind.FunctionDeclaration; } -export function isClassDeclaration(node: Node): node is ClassDeclaration { +export function isClassDeclaration(node: NodeBase): node is ClassDeclaration { return node.kind === SyntaxKind.ClassDeclaration; } -export function isInterfaceDeclaration(node: Node): node is InterfaceDeclaration { +export function isInterfaceDeclaration(node: NodeBase): node is InterfaceDeclaration { return node.kind === SyntaxKind.InterfaceDeclaration; } -export function isTypeAliasDeclaration(node: Node): node is TypeAliasDeclaration { +export function isTypeAliasDeclaration(node: NodeBase): node is TypeAliasDeclaration { return node.kind === SyntaxKind.TypeAliasDeclaration; } -export function isEnumDeclaration(node: Node): node is EnumDeclaration { +export function isEnumDeclaration(node: NodeBase): node is EnumDeclaration { return node.kind === SyntaxKind.EnumDeclaration; } -export function isModuleDeclaration(node: Node): node is ModuleDeclaration { +export function isModuleDeclaration(node: NodeBase): node is ModuleDeclaration { return node.kind === SyntaxKind.ModuleDeclaration; } -export function isModuleBlock(node: Node): node is ModuleBlock { +export function isModuleBlock(node: NodeBase): node is ModuleBlock { return node.kind === SyntaxKind.ModuleBlock; } -export function isCaseBlock(node: Node): node is CaseBlock { +export function isCaseBlock(node: NodeBase): node is CaseBlock { return node.kind === SyntaxKind.CaseBlock; } -export function isNamespaceExportDeclaration(node: Node): node is NamespaceExportDeclaration { +export function isNamespaceExportDeclaration(node: NodeBase): node is NamespaceExportDeclaration { return node.kind === SyntaxKind.NamespaceExportDeclaration; } -export function isImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration { +export function isImportEqualsDeclaration(node: NodeBase): node is ImportEqualsDeclaration { return node.kind === SyntaxKind.ImportEqualsDeclaration; } -export function isImportDeclaration(node: Node): node is ImportDeclaration { +export function isImportDeclaration(node: NodeBase): node is ImportDeclaration { return node.kind === SyntaxKind.ImportDeclaration; } -export function isImportClause(node: Node): node is ImportClause { +export function isImportClause(node: NodeBase): node is ImportClause { return node.kind === SyntaxKind.ImportClause; } -export function isImportTypeAssertionContainer(node: Node): node is ImportTypeAssertionContainer { +export function isImportTypeAssertionContainer(node: NodeBase): node is ImportTypeAssertionContainer { return node.kind === SyntaxKind.ImportTypeAssertionContainer; } /** @deprecated */ -export function isAssertClause(node: Node): node is AssertClause { +export function isAssertClause(node: NodeBase): node is AssertClause { return node.kind === SyntaxKind.AssertClause; } /** @deprecated */ -export function isAssertEntry(node: Node): node is AssertEntry { +export function isAssertEntry(node: NodeBase): node is AssertEntry { return node.kind === SyntaxKind.AssertEntry; } -export function isImportAttributes(node: Node): node is ImportAttributes { +export function isImportAttributes(node: NodeBase): node is ImportAttributes { return node.kind === SyntaxKind.ImportAttributes; } -export function isImportAttribute(node: Node): node is ImportAttribute { +export function isImportAttribute(node: NodeBase): node is ImportAttribute { return node.kind === SyntaxKind.ImportAttribute; } -export function isNamespaceImport(node: Node): node is NamespaceImport { +export function isNamespaceImport(node: NodeBase): node is NamespaceImport { return node.kind === SyntaxKind.NamespaceImport; } -export function isNamespaceExport(node: Node): node is NamespaceExport { +export function isNamespaceExport(node: NodeBase): node is NamespaceExport { return node.kind === SyntaxKind.NamespaceExport; } -export function isNamedImports(node: Node): node is NamedImports { +export function isNamedImports(node: NodeBase): node is NamedImports { return node.kind === SyntaxKind.NamedImports; } -export function isImportSpecifier(node: Node): node is ImportSpecifier { +export function isImportSpecifier(node: NodeBase): node is ImportSpecifier { return node.kind === SyntaxKind.ImportSpecifier; } -export function isExportAssignment(node: Node): node is ExportAssignment { +export function isExportAssignment(node: NodeBase): node is ExportAssignment { return node.kind === SyntaxKind.ExportAssignment; } -export function isExportDeclaration(node: Node): node is ExportDeclaration { +export function isExportDeclaration(node: NodeBase): node is ExportDeclaration { return node.kind === SyntaxKind.ExportDeclaration; } -export function isNamedExports(node: Node): node is NamedExports { +export function isNamedExports(node: NodeBase): node is NamedExports { return node.kind === SyntaxKind.NamedExports; } -export function isExportSpecifier(node: Node): node is ExportSpecifier { +export function isExportSpecifier(node: NodeBase): node is ExportSpecifier { return node.kind === SyntaxKind.ExportSpecifier; } -export function isMissingDeclaration(node: Node): node is MissingDeclaration { +export function isMissingDeclaration(node: NodeBase): node is MissingDeclaration { return node.kind === SyntaxKind.MissingDeclaration; } -export function isNotEmittedStatement(node: Node): node is NotEmittedStatement { +export function isNotEmittedStatement(node: NodeBase): node is NotEmittedStatement { return node.kind === SyntaxKind.NotEmittedStatement; } /** @internal */ -export function isSyntheticReference(node: Node): node is SyntheticReferenceExpression { +export function isSyntheticReference(node: NodeBase): node is SyntheticReferenceExpression { return node.kind === SyntaxKind.SyntheticReferenceExpression; } // Module References -export function isExternalModuleReference(node: Node): node is ExternalModuleReference { +export function isExternalModuleReference(node: NodeBase): node is ExternalModuleReference { return node.kind === SyntaxKind.ExternalModuleReference; } // JSX -export function isJsxElement(node: Node): node is JsxElement { +export function isJsxElement(node: NodeBase): node is JsxElement { return node.kind === SyntaxKind.JsxElement; } -export function isJsxSelfClosingElement(node: Node): node is JsxSelfClosingElement { +export function isJsxSelfClosingElement(node: NodeBase): node is JsxSelfClosingElement { return node.kind === SyntaxKind.JsxSelfClosingElement; } -export function isJsxOpeningElement(node: Node): node is JsxOpeningElement { +export function isJsxOpeningElement(node: NodeBase): node is JsxOpeningElement { return node.kind === SyntaxKind.JsxOpeningElement; } -export function isJsxClosingElement(node: Node): node is JsxClosingElement { +export function isJsxClosingElement(node: NodeBase): node is JsxClosingElement { return node.kind === SyntaxKind.JsxClosingElement; } -export function isJsxFragment(node: Node): node is JsxFragment { +export function isJsxFragment(node: NodeBase): node is JsxFragment { return node.kind === SyntaxKind.JsxFragment; } -export function isJsxOpeningFragment(node: Node): node is JsxOpeningFragment { +export function isJsxOpeningFragment(node: NodeBase): node is JsxOpeningFragment { return node.kind === SyntaxKind.JsxOpeningFragment; } -export function isJsxClosingFragment(node: Node): node is JsxClosingFragment { +export function isJsxClosingFragment(node: NodeBase): node is JsxClosingFragment { return node.kind === SyntaxKind.JsxClosingFragment; } -export function isJsxAttribute(node: Node): node is JsxAttribute { +export function isJsxAttribute(node: NodeBase): node is JsxAttribute { return node.kind === SyntaxKind.JsxAttribute; } -export function isJsxAttributes(node: Node): node is JsxAttributes { +export function isJsxAttributes(node: NodeBase): node is JsxAttributes { return node.kind === SyntaxKind.JsxAttributes; } -export function isJsxSpreadAttribute(node: Node): node is JsxSpreadAttribute { +export function isJsxSpreadAttribute(node: NodeBase): node is JsxSpreadAttribute { return node.kind === SyntaxKind.JsxSpreadAttribute; } -export function isJsxExpression(node: Node): node is JsxExpression { +export function isJsxExpression(node: NodeBase): node is JsxExpression { return node.kind === SyntaxKind.JsxExpression; } -export function isJsxNamespacedName(node: Node): node is JsxNamespacedName { +export function isJsxNamespacedName(node: NodeBase): node is JsxNamespacedName { return node.kind === SyntaxKind.JsxNamespacedName; } // Clauses -export function isCaseClause(node: Node): node is CaseClause { +export function isCaseClause(node: NodeBase): node is CaseClause { return node.kind === SyntaxKind.CaseClause; } -export function isDefaultClause(node: Node): node is DefaultClause { +export function isDefaultClause(node: NodeBase): node is DefaultClause { return node.kind === SyntaxKind.DefaultClause; } -export function isHeritageClause(node: Node): node is HeritageClause { +export function isHeritageClause(node: NodeBase): node is HeritageClause { return node.kind === SyntaxKind.HeritageClause; } -export function isCatchClause(node: Node): node is CatchClause { +export function isCatchClause(node: NodeBase): node is CatchClause { return node.kind === SyntaxKind.CatchClause; } // Property assignments -export function isPropertyAssignment(node: Node): node is PropertyAssignment { +export function isPropertyAssignment(node: NodeBase): node is PropertyAssignment { return node.kind === SyntaxKind.PropertyAssignment; } -export function isShorthandPropertyAssignment(node: Node): node is ShorthandPropertyAssignment { +export function isShorthandPropertyAssignment(node: NodeBase): node is ShorthandPropertyAssignment { return node.kind === SyntaxKind.ShorthandPropertyAssignment; } -export function isSpreadAssignment(node: Node): node is SpreadAssignment { +export function isSpreadAssignment(node: NodeBase): node is SpreadAssignment { return node.kind === SyntaxKind.SpreadAssignment; } // Enum -export function isEnumMember(node: Node): node is EnumMember { +export function isEnumMember(node: NodeBase): node is EnumMember { return node.kind === SyntaxKind.EnumMember; } @@ -1010,7 +1010,7 @@ export function isEnumMember(node: Node): node is EnumMember { // TODO(rbuckton): isUnparsedPrologue /** @deprecated */ -export function isUnparsedPrepend(node: Node): node is UnparsedPrepend { +export function isUnparsedPrepend(node: NodeBase): node is UnparsedPrepend { return node.kind === SyntaxKind.UnparsedPrepend; } @@ -1019,16 +1019,16 @@ export function isUnparsedPrepend(node: Node): node is UnparsedPrepend { // TODO(rbuckton): isUnparsedSyntheticReference // Top-level nodes -export function isSourceFile(node: Node): node is SourceFile { +export function isSourceFile(node: NodeBase): node is SourceFile { return node.kind === SyntaxKind.SourceFile; } -export function isBundle(node: Node): node is Bundle { +export function isBundle(node: NodeBase): node is Bundle { return node.kind === SyntaxKind.Bundle; } /** @deprecated */ -export function isUnparsedSource(node: Node): node is UnparsedSource { +export function isUnparsedSource(node: NodeBase): node is UnparsedSource { return node.kind === SyntaxKind.UnparsedSource; } @@ -1036,175 +1036,175 @@ export function isUnparsedSource(node: Node): node is UnparsedSource { // JSDoc Elements -export function isJSDocTypeExpression(node: Node): node is JSDocTypeExpression { +export function isJSDocTypeExpression(node: NodeBase): node is JSDocTypeExpression { return node.kind === SyntaxKind.JSDocTypeExpression; } -export function isJSDocNameReference(node: Node): node is JSDocNameReference { +export function isJSDocNameReference(node: NodeBase): node is JSDocNameReference { return node.kind === SyntaxKind.JSDocNameReference; } -export function isJSDocMemberName(node: Node): node is JSDocMemberName { +export function isJSDocMemberName(node: NodeBase): node is JSDocMemberName { return node.kind === SyntaxKind.JSDocMemberName; } -export function isJSDocLink(node: Node): node is JSDocLink { +export function isJSDocLink(node: NodeBase): node is JSDocLink { return node.kind === SyntaxKind.JSDocLink; } -export function isJSDocLinkCode(node: Node): node is JSDocLinkCode { +export function isJSDocLinkCode(node: NodeBase): node is JSDocLinkCode { return node.kind === SyntaxKind.JSDocLinkCode; } -export function isJSDocLinkPlain(node: Node): node is JSDocLinkPlain { +export function isJSDocLinkPlain(node: NodeBase): node is JSDocLinkPlain { return node.kind === SyntaxKind.JSDocLinkPlain; } -export function isJSDocAllType(node: Node): node is JSDocAllType { +export function isJSDocAllType(node: NodeBase): node is JSDocAllType { return node.kind === SyntaxKind.JSDocAllType; } -export function isJSDocUnknownType(node: Node): node is JSDocUnknownType { +export function isJSDocUnknownType(node: NodeBase): node is JSDocUnknownType { return node.kind === SyntaxKind.JSDocUnknownType; } -export function isJSDocNullableType(node: Node): node is JSDocNullableType { +export function isJSDocNullableType(node: NodeBase): node is JSDocNullableType { return node.kind === SyntaxKind.JSDocNullableType; } -export function isJSDocNonNullableType(node: Node): node is JSDocNonNullableType { +export function isJSDocNonNullableType(node: NodeBase): node is JSDocNonNullableType { return node.kind === SyntaxKind.JSDocNonNullableType; } -export function isJSDocOptionalType(node: Node): node is JSDocOptionalType { +export function isJSDocOptionalType(node: NodeBase): node is JSDocOptionalType { return node.kind === SyntaxKind.JSDocOptionalType; } -export function isJSDocFunctionType(node: Node): node is JSDocFunctionType { +export function isJSDocFunctionType(node: NodeBase): node is JSDocFunctionType { return node.kind === SyntaxKind.JSDocFunctionType; } -export function isJSDocVariadicType(node: Node): node is JSDocVariadicType { +export function isJSDocVariadicType(node: NodeBase): node is JSDocVariadicType { return node.kind === SyntaxKind.JSDocVariadicType; } -export function isJSDocNamepathType(node: Node): node is JSDocNamepathType { +export function isJSDocNamepathType(node: NodeBase): node is JSDocNamepathType { return node.kind === SyntaxKind.JSDocNamepathType; } -export function isJSDoc(node: Node): node is JSDoc { +export function isJSDoc(node: NodeBase): node is JSDoc { return node.kind === SyntaxKind.JSDoc; } -export function isJSDocTypeLiteral(node: Node): node is JSDocTypeLiteral { +export function isJSDocTypeLiteral(node: NodeBase): node is JSDocTypeLiteral { return node.kind === SyntaxKind.JSDocTypeLiteral; } -export function isJSDocSignature(node: Node): node is JSDocSignature { +export function isJSDocSignature(node: NodeBase): node is JSDocSignature { return node.kind === SyntaxKind.JSDocSignature; } // JSDoc Tags -export function isJSDocAugmentsTag(node: Node): node is JSDocAugmentsTag { +export function isJSDocAugmentsTag(node: NodeBase): node is JSDocAugmentsTag { return node.kind === SyntaxKind.JSDocAugmentsTag; } -export function isJSDocAuthorTag(node: Node): node is JSDocAuthorTag { +export function isJSDocAuthorTag(node: NodeBase): node is JSDocAuthorTag { return node.kind === SyntaxKind.JSDocAuthorTag; } -export function isJSDocClassTag(node: Node): node is JSDocClassTag { +export function isJSDocClassTag(node: NodeBase): node is JSDocClassTag { return node.kind === SyntaxKind.JSDocClassTag; } -export function isJSDocCallbackTag(node: Node): node is JSDocCallbackTag { +export function isJSDocCallbackTag(node: NodeBase): node is JSDocCallbackTag { return node.kind === SyntaxKind.JSDocCallbackTag; } -export function isJSDocPublicTag(node: Node): node is JSDocPublicTag { +export function isJSDocPublicTag(node: NodeBase): node is JSDocPublicTag { return node.kind === SyntaxKind.JSDocPublicTag; } -export function isJSDocPrivateTag(node: Node): node is JSDocPrivateTag { +export function isJSDocPrivateTag(node: NodeBase): node is JSDocPrivateTag { return node.kind === SyntaxKind.JSDocPrivateTag; } -export function isJSDocProtectedTag(node: Node): node is JSDocProtectedTag { +export function isJSDocProtectedTag(node: NodeBase): node is JSDocProtectedTag { return node.kind === SyntaxKind.JSDocProtectedTag; } -export function isJSDocReadonlyTag(node: Node): node is JSDocReadonlyTag { +export function isJSDocReadonlyTag(node: NodeBase): node is JSDocReadonlyTag { return node.kind === SyntaxKind.JSDocReadonlyTag; } -export function isJSDocOverrideTag(node: Node): node is JSDocOverrideTag { +export function isJSDocOverrideTag(node: NodeBase): node is JSDocOverrideTag { return node.kind === SyntaxKind.JSDocOverrideTag; } -export function isJSDocOverloadTag(node: Node): node is JSDocOverloadTag { +export function isJSDocOverloadTag(node: NodeBase): node is JSDocOverloadTag { return node.kind === SyntaxKind.JSDocOverloadTag; } -export function isJSDocDeprecatedTag(node: Node): node is JSDocDeprecatedTag { +export function isJSDocDeprecatedTag(node: NodeBase): node is JSDocDeprecatedTag { return node.kind === SyntaxKind.JSDocDeprecatedTag; } -export function isJSDocSeeTag(node: Node): node is JSDocSeeTag { +export function isJSDocSeeTag(node: NodeBase): node is JSDocSeeTag { return node.kind === SyntaxKind.JSDocSeeTag; } -export function isJSDocEnumTag(node: Node): node is JSDocEnumTag { +export function isJSDocEnumTag(node: NodeBase): node is JSDocEnumTag { return node.kind === SyntaxKind.JSDocEnumTag; } -export function isJSDocParameterTag(node: Node): node is JSDocParameterTag { +export function isJSDocParameterTag(node: NodeBase): node is JSDocParameterTag { return node.kind === SyntaxKind.JSDocParameterTag; } -export function isJSDocReturnTag(node: Node): node is JSDocReturnTag { +export function isJSDocReturnTag(node: NodeBase): node is JSDocReturnTag { return node.kind === SyntaxKind.JSDocReturnTag; } -export function isJSDocThisTag(node: Node): node is JSDocThisTag { +export function isJSDocThisTag(node: NodeBase): node is JSDocThisTag { return node.kind === SyntaxKind.JSDocThisTag; } -export function isJSDocTypeTag(node: Node): node is JSDocTypeTag { +export function isJSDocTypeTag(node: NodeBase): node is JSDocTypeTag { return node.kind === SyntaxKind.JSDocTypeTag; } -export function isJSDocTemplateTag(node: Node): node is JSDocTemplateTag { +export function isJSDocTemplateTag(node: NodeBase): node is JSDocTemplateTag { return node.kind === SyntaxKind.JSDocTemplateTag; } -export function isJSDocTypedefTag(node: Node): node is JSDocTypedefTag { +export function isJSDocTypedefTag(node: NodeBase): node is JSDocTypedefTag { return node.kind === SyntaxKind.JSDocTypedefTag; } -export function isJSDocUnknownTag(node: Node): node is JSDocUnknownTag { +export function isJSDocUnknownTag(node: NodeBase): node is JSDocUnknownTag { return node.kind === SyntaxKind.JSDocTag; } -export function isJSDocPropertyTag(node: Node): node is JSDocPropertyTag { +export function isJSDocPropertyTag(node: NodeBase): node is JSDocPropertyTag { return node.kind === SyntaxKind.JSDocPropertyTag; } -export function isJSDocImplementsTag(node: Node): node is JSDocImplementsTag { +export function isJSDocImplementsTag(node: NodeBase): node is JSDocImplementsTag { return node.kind === SyntaxKind.JSDocImplementsTag; } -export function isJSDocSatisfiesTag(node: Node): node is JSDocSatisfiesTag { +export function isJSDocSatisfiesTag(node: NodeBase): node is JSDocSatisfiesTag { return node.kind === SyntaxKind.JSDocSatisfiesTag; } -export function isJSDocThrowsTag(node: Node): node is JSDocThrowsTag { +export function isJSDocThrowsTag(node: NodeBase): node is JSDocThrowsTag { return node.kind === SyntaxKind.JSDocThrowsTag; } // Synthesized list /** @internal */ -export function isSyntaxList(n: Node): n is SyntaxList { - return n.kind === SyntaxKind.SyntaxList; +export function isSyntaxList(node: NodeBase): node is SyntaxList { + return node.kind === SyntaxKind.SyntaxList; } diff --git a/src/compiler/factory/parenthesizerRules.ts b/src/compiler/factory/parenthesizerRules.ts index b90cc220fb616..d69d8a2765b84 100644 --- a/src/compiler/factory/parenthesizerRules.ts +++ b/src/compiler/factory/parenthesizerRules.ts @@ -51,13 +51,19 @@ import { } from "../_namespaces/ts"; /** @internal */ -export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRules { +export function createParenthesizerRules( + factory: NodeFactory, +): ParenthesizerRules { interface BinaryPlusExpression extends BinaryExpression { cachedLiteralKind: SyntaxKind; } - let binaryLeftOperandParenthesizerCache: Map Expression> | undefined; - let binaryRightOperandParenthesizerCache: Map Expression> | undefined; + let binaryLeftOperandParenthesizerCache: + | Map Expression> + | undefined; + let binaryRightOperandParenthesizerCache: + | Map Expression> + | undefined; return { getParenthesizeLeftSideOfBinaryForOperator, @@ -92,22 +98,37 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul parenthesizeLeadingTypeArgument, }; - function getParenthesizeLeftSideOfBinaryForOperator(operatorKind: BinaryOperator) { + function getParenthesizeLeftSideOfBinaryForOperator( + operatorKind: BinaryOperator, + ) { binaryLeftOperandParenthesizerCache ||= new Map(); let parenthesizerRule = binaryLeftOperandParenthesizerCache.get(operatorKind); if (!parenthesizerRule) { parenthesizerRule = node => parenthesizeLeftSideOfBinary(operatorKind, node); - binaryLeftOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + binaryLeftOperandParenthesizerCache.set( + operatorKind, + parenthesizerRule, + ); } return parenthesizerRule; } - function getParenthesizeRightSideOfBinaryForOperator(operatorKind: BinaryOperator) { + function getParenthesizeRightSideOfBinaryForOperator( + operatorKind: BinaryOperator, + ) { binaryRightOperandParenthesizerCache ||= new Map(); let parenthesizerRule = binaryRightOperandParenthesizerCache.get(operatorKind); if (!parenthesizerRule) { - parenthesizerRule = node => parenthesizeRightSideOfBinary(operatorKind, /*leftSide*/ undefined, node); - binaryRightOperandParenthesizerCache.set(operatorKind, parenthesizerRule); + parenthesizerRule = node => + parenthesizeRightSideOfBinary( + operatorKind, + /*leftSide*/ undefined, + node, + ); + binaryRightOperandParenthesizerCache.set( + operatorKind, + parenthesizerRule, + ); } return parenthesizerRule; } @@ -120,7 +141,12 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the * BinaryExpression. */ - function binaryOperandNeedsParentheses(binaryOperator: SyntaxKind, operand: Expression, isLeftSideOfBinary: boolean, leftOperand: Expression | undefined) { + function binaryOperandNeedsParentheses( + binaryOperator: SyntaxKind, + operand: Expression, + isLeftSideOfBinary: boolean, + leftOperand: Expression | undefined, + ) { // If the operand has lower precedence, then it needs to be parenthesized to preserve the // intent of the expression. For example, if the operand is `a + b` and the operator is // `*`, then we need to parenthesize the operand to preserve the intended order of @@ -138,10 +164,20 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul // // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve // the intended order of operations: `(a ** b) ** c` - const binaryOperatorPrecedence = getOperatorPrecedence(SyntaxKind.BinaryExpression, binaryOperator); - const binaryOperatorAssociativity = getOperatorAssociativity(SyntaxKind.BinaryExpression, binaryOperator); + const binaryOperatorPrecedence = getOperatorPrecedence( + SyntaxKind.BinaryExpression, + binaryOperator, + ); + const binaryOperatorAssociativity = getOperatorAssociativity( + SyntaxKind.BinaryExpression, + binaryOperator, + ); const emittedOperand = skipPartiallyEmittedExpressions(operand); - if (!isLeftSideOfBinary && operand.kind === SyntaxKind.ArrowFunction && binaryOperatorPrecedence > OperatorPrecedence.Assignment) { + if ( + !isLeftSideOfBinary && + operand.kind === SyntaxKind.ArrowFunction && + binaryOperatorPrecedence > OperatorPrecedence.Assignment + ) { // We need to parenthesize arrow functions on the right side to avoid it being // parsed as parenthesized expression: `a && (() => {})` return true; @@ -152,9 +188,9 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul // If the operand is the right side of a right-associative binary operation // and is a yield expression, then we do not need parentheses. if ( - !isLeftSideOfBinary - && binaryOperatorAssociativity === Associativity.Right - && operand.kind === SyntaxKind.YieldExpression + !isLeftSideOfBinary && + binaryOperatorAssociativity === Associativity.Right && + operand.kind === SyntaxKind.YieldExpression ) { return false; } @@ -179,8 +215,8 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul } else { if ( - isBinaryExpression(emittedOperand) - && emittedOperand.operatorToken.kind === binaryOperator + isBinaryExpression(emittedOperand) && + emittedOperand.operatorToken.kind === binaryOperator ) { // No need to parenthesize the right operand when the binary operator and // operand are the same and one of the following: @@ -199,8 +235,16 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul // "a"+(1+2) => "a"+(1+2) // "a"+("b"+"c") => "a"+"b"+"c" if (binaryOperator === SyntaxKind.PlusToken) { - const leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : SyntaxKind.Unknown; - if (isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) { + const leftKind = leftOperand + ? getLiteralKindOfBinaryPlusOperand(leftOperand) + : SyntaxKind.Unknown; + if ( + isLiteralKind(leftKind) && + leftKind === + getLiteralKindOfBinaryPlusOperand( + emittedOperand, + ) + ) { return false; } } @@ -236,11 +280,13 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul // // While addition is associative in mathematics, JavaScript's `+` is not // guaranteed to be associative as it is overloaded with string concatenation. - return binaryOperator === SyntaxKind.AsteriskToken - || binaryOperator === SyntaxKind.BarToken - || binaryOperator === SyntaxKind.AmpersandToken - || binaryOperator === SyntaxKind.CaretToken - || binaryOperator === SyntaxKind.CommaToken; + return ( + binaryOperator === SyntaxKind.AsteriskToken || + binaryOperator === SyntaxKind.BarToken || + binaryOperator === SyntaxKind.AmpersandToken || + binaryOperator === SyntaxKind.CaretToken || + binaryOperator === SyntaxKind.CommaToken + ); } /** @@ -256,14 +302,25 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul return node.kind; } - if (node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.PlusToken) { - if ((node as BinaryPlusExpression).cachedLiteralKind !== undefined) { + if ( + node.kind === SyntaxKind.BinaryExpression && + node.operatorToken.kind === + SyntaxKind.PlusToken + ) { + if ( + (node as BinaryPlusExpression).cachedLiteralKind !== undefined + ) { return (node as BinaryPlusExpression).cachedLiteralKind; } - const leftKind = getLiteralKindOfBinaryPlusOperand((node as BinaryExpression).left); - const literalKind = isLiteralKind(leftKind) - && leftKind === getLiteralKindOfBinaryPlusOperand((node as BinaryExpression).right) + const leftKind = getLiteralKindOfBinaryPlusOperand( + node.left, + ); + const literalKind = isLiteralKind(leftKind) && + leftKind === + getLiteralKindOfBinaryPlusOperand( + node.right, + ) ? leftKind : SyntaxKind.Unknown; @@ -283,7 +340,12 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the * BinaryExpression. */ - function parenthesizeBinaryOperand(binaryOperator: SyntaxKind, operand: Expression, isLeftSideOfBinary: boolean, leftOperand?: Expression) { + function parenthesizeBinaryOperand( + binaryOperator: SyntaxKind, + operand: Expression, + isLeftSideOfBinary: boolean, + leftOperand?: Expression, + ) { const skipped = skipPartiallyEmittedExpressions(operand); // If the resulting expression is already parenthesized, we do not need to do any further processing. @@ -291,34 +353,69 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul return operand; } - return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) + return binaryOperandNeedsParentheses( + binaryOperator, + operand, + isLeftSideOfBinary, + leftOperand, + ) ? factory.createParenthesizedExpression(operand) : operand; } - function parenthesizeLeftSideOfBinary(binaryOperator: SyntaxKind, leftSide: Expression): Expression { - return parenthesizeBinaryOperand(binaryOperator, leftSide, /*isLeftSideOfBinary*/ true); - } - - function parenthesizeRightSideOfBinary(binaryOperator: SyntaxKind, leftSide: Expression | undefined, rightSide: Expression): Expression { - return parenthesizeBinaryOperand(binaryOperator, rightSide, /*isLeftSideOfBinary*/ false, leftSide); - } - - function parenthesizeExpressionOfComputedPropertyName(expression: Expression): Expression { - return isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression; - } - - function parenthesizeConditionOfConditionalExpression(condition: Expression): Expression { - const conditionalPrecedence = getOperatorPrecedence(SyntaxKind.ConditionalExpression, SyntaxKind.QuestionToken); + function parenthesizeLeftSideOfBinary( + binaryOperator: SyntaxKind, + leftSide: Expression, + ): Expression { + return parenthesizeBinaryOperand( + binaryOperator, + leftSide, + /*isLeftSideOfBinary*/ true, + ); + } + + function parenthesizeRightSideOfBinary( + binaryOperator: SyntaxKind, + leftSide: Expression | undefined, + rightSide: Expression, + ): Expression { + return parenthesizeBinaryOperand( + binaryOperator, + rightSide, + /*isLeftSideOfBinary*/ false, + leftSide, + ); + } + + function parenthesizeExpressionOfComputedPropertyName( + expression: Expression, + ): Expression { + return isCommaSequence(expression) + ? factory.createParenthesizedExpression(expression) + : expression; + } + + function parenthesizeConditionOfConditionalExpression( + condition: Expression, + ): Expression { + const conditionalPrecedence = getOperatorPrecedence( + SyntaxKind.ConditionalExpression, + SyntaxKind.QuestionToken, + ); const emittedCondition = skipPartiallyEmittedExpressions(condition); const conditionPrecedence = getExpressionPrecedence(emittedCondition); - if (compareValues(conditionPrecedence, conditionalPrecedence) !== Comparison.GreaterThan) { + if ( + compareValues(conditionPrecedence, conditionalPrecedence) !== + Comparison.GreaterThan + ) { return factory.createParenthesizedExpression(condition); } return condition; } - function parenthesizeBranchOfConditionalExpression(branch: Expression): Expression { + function parenthesizeBranchOfConditionalExpression( + branch: Expression, + ): Expression { // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence @@ -339,33 +436,45 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul * - FunctionExpression * - ClassExpression */ - function parenthesizeExpressionOfExportDefault(expression: Expression): Expression { + function parenthesizeExpressionOfExportDefault( + expression: Expression, + ): Expression { const check = skipPartiallyEmittedExpressions(expression); let needsParens = isCommaSequence(check); if (!needsParens) { - switch (getLeftmostExpression(check, /*stopAtCallExpressions*/ false).kind) { + switch ( + getLeftmostExpression(check, /*stopAtCallExpressions*/ false) + .kind + ) { case SyntaxKind.ClassExpression: case SyntaxKind.FunctionExpression: needsParens = true; } } - return needsParens ? factory.createParenthesizedExpression(expression) : expression; + return needsParens + ? factory.createParenthesizedExpression(expression) + : expression; } /** * Wraps an expression in parentheses if it is needed in order to use the expression * as the expression of a `NewExpression` node. */ - function parenthesizeExpressionOfNew(expression: Expression): LeftHandSideExpression { - const leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true); + function parenthesizeExpressionOfNew( + expression: Expression, + ): LeftHandSideExpression { + const leftmostExpr = getLeftmostExpression( + expression, + /*stopAtCallExpressions*/ true, + ); switch (leftmostExpr.kind) { case SyntaxKind.CallExpression: return factory.createParenthesizedExpression(expression); case SyntaxKind.NewExpression: - return !(leftmostExpr as NewExpression).arguments + return !leftmostExpr.arguments ? factory.createParenthesizedExpression(expression) - : expression as LeftHandSideExpression; // TODO(rbuckton): Verify this assertion holds + : (expression as LeftHandSideExpression); // TODO(rbuckton): Verify this assertion holds } return parenthesizeLeftSideOfAccess(expression); @@ -375,7 +484,10 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul * Wraps an expression in parentheses if it is needed in order to use the expression for * property or element access. */ - function parenthesizeLeftSideOfAccess(expression: Expression, optionalChain?: boolean): LeftHandSideExpression { + function parenthesizeLeftSideOfAccess( + expression: Expression, + optionalChain?: boolean, + ): LeftHandSideExpression { // isLeftHandSideExpression is almost the correct criterion for when it is not necessary // to parenthesize the expression before a dot. The known exception is: // @@ -384,73 +496,144 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul // const emittedExpression = skipPartiallyEmittedExpressions(expression); if ( - isLeftHandSideExpression(emittedExpression) - && (emittedExpression.kind !== SyntaxKind.NewExpression || (emittedExpression as NewExpression).arguments) - && (optionalChain || !isOptionalChain(emittedExpression)) + isLeftHandSideExpression(emittedExpression) && + (emittedExpression.kind !== SyntaxKind.NewExpression || + emittedExpression.arguments) && + (optionalChain || !isOptionalChain(emittedExpression)) ) { // TODO(rbuckton): Verify whether this assertion holds. return expression as LeftHandSideExpression; } // TODO(rbuckton): Verifiy whether `setTextRange` is needed. - return setTextRange(factory.createParenthesizedExpression(expression), expression); + return setTextRange( + factory.createParenthesizedExpression(expression), + expression, + ); } - function parenthesizeOperandOfPostfixUnary(operand: Expression): LeftHandSideExpression { + function parenthesizeOperandOfPostfixUnary( + operand: Expression, + ): LeftHandSideExpression { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. - return isLeftHandSideExpression(operand) ? operand : setTextRange(factory.createParenthesizedExpression(operand), operand); + return isLeftHandSideExpression(operand) + ? operand + : setTextRange( + factory.createParenthesizedExpression(operand), + operand, + ); } - function parenthesizeOperandOfPrefixUnary(operand: Expression): UnaryExpression { + function parenthesizeOperandOfPrefixUnary( + operand: Expression, + ): UnaryExpression { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. - return isUnaryExpression(operand) ? operand : setTextRange(factory.createParenthesizedExpression(operand), operand); - } - - function parenthesizeExpressionsOfCommaDelimitedList(elements: NodeArray): NodeArray { - const result = sameMap(elements, parenthesizeExpressionForDisallowedComma); - return setTextRange(factory.createNodeArray(result, elements.hasTrailingComma), elements); - } - - function parenthesizeExpressionForDisallowedComma(expression: Expression): Expression { + return isUnaryExpression(operand) + ? operand + : setTextRange( + factory.createParenthesizedExpression(operand), + operand, + ); + } + + function parenthesizeExpressionsOfCommaDelimitedList( + elements: NodeArray, + ): NodeArray { + const result = sameMap( + elements, + parenthesizeExpressionForDisallowedComma, + ); + return setTextRange( + factory.createNodeArray(result, elements.hasTrailingComma), + elements, + ); + } + + function parenthesizeExpressionForDisallowedComma( + expression: Expression, + ): Expression { const emittedExpression = skipPartiallyEmittedExpressions(expression); const expressionPrecedence = getExpressionPrecedence(emittedExpression); - const commaPrecedence = getOperatorPrecedence(SyntaxKind.BinaryExpression, SyntaxKind.CommaToken); + const commaPrecedence = getOperatorPrecedence( + SyntaxKind.BinaryExpression, + SyntaxKind.CommaToken, + ); // TODO(rbuckton): Verifiy whether `setTextRange` is needed. - return expressionPrecedence > commaPrecedence ? expression : setTextRange(factory.createParenthesizedExpression(expression), expression); + return expressionPrecedence > commaPrecedence + ? expression + : setTextRange( + factory.createParenthesizedExpression(expression), + expression, + ); } - function parenthesizeExpressionOfExpressionStatement(expression: Expression): Expression { + function parenthesizeExpressionOfExpressionStatement( + expression: Expression, + ): Expression { const emittedExpression = skipPartiallyEmittedExpressions(expression); if (isCallExpression(emittedExpression)) { const callee = emittedExpression.expression; const kind = skipPartiallyEmittedExpressions(callee).kind; - if (kind === SyntaxKind.FunctionExpression || kind === SyntaxKind.ArrowFunction) { + if ( + kind === SyntaxKind.FunctionExpression || + kind === SyntaxKind.ArrowFunction + ) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. const updated = factory.updateCallExpression( emittedExpression, - setTextRange(factory.createParenthesizedExpression(callee), callee), + setTextRange( + factory.createParenthesizedExpression(callee), + callee, + ), emittedExpression.typeArguments, emittedExpression.arguments, ); - return factory.restoreOuterExpressions(expression, updated, OuterExpressionKinds.PartiallyEmittedExpressions); + return factory.restoreOuterExpressions( + expression, + updated, + OuterExpressionKinds.PartiallyEmittedExpressions, + ); } } - const leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind; - if (leftmostExpressionKind === SyntaxKind.ObjectLiteralExpression || leftmostExpressionKind === SyntaxKind.FunctionExpression) { + const leftmostExpressionKind = getLeftmostExpression( + emittedExpression, + /*stopAtCallExpressions*/ false, + ).kind; + if ( + leftmostExpressionKind === SyntaxKind.ObjectLiteralExpression || + leftmostExpressionKind === SyntaxKind.FunctionExpression + ) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. - return setTextRange(factory.createParenthesizedExpression(expression), expression); + return setTextRange( + factory.createParenthesizedExpression(expression), + expression, + ); } return expression; } - function parenthesizeConciseBodyOfArrowFunction(body: Expression): Expression; - function parenthesizeConciseBodyOfArrowFunction(body: ConciseBody): ConciseBody; - function parenthesizeConciseBodyOfArrowFunction(body: ConciseBody): ConciseBody { - if (!isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === SyntaxKind.ObjectLiteralExpression)) { + function parenthesizeConciseBodyOfArrowFunction( + body: Expression, + ): Expression; + function parenthesizeConciseBodyOfArrowFunction( + body: ConciseBody, + ): ConciseBody; + function parenthesizeConciseBodyOfArrowFunction( + body: ConciseBody, + ): ConciseBody { + if ( + !isBlock(body) && + (isCommaSequence(body) || + getLeftmostExpression(body, /*stopAtCallExpressions*/ false) + .kind === SyntaxKind.ObjectLiteralExpression) + ) { // TODO(rbuckton): Verifiy whether `setTextRange` is needed. - return setTextRange(factory.createParenthesizedExpression(body), body); + return setTextRange( + factory.createParenthesizedExpression(body), + body, + ); } return body; @@ -467,7 +650,9 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul // - The check type (the `UnionType`, above) does not allow function, constructor, or conditional types (they must be parenthesized) // - The extends type (the first `Type`, above) does not allow conditional types (they must be parenthesized). Function and constructor types are fine. // - The true and false branch types (the second and third `Type` non-terminals, above) allow any type - function parenthesizeCheckTypeOfConditionalType(checkType: TypeNode): TypeNode { + function parenthesizeCheckTypeOfConditionalType( + checkType: TypeNode, + ): TypeNode { switch (checkType.kind) { case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: @@ -477,7 +662,9 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul return checkType; } - function parenthesizeExtendsTypeOfConditionalType(extendsType: TypeNode): TypeNode { + function parenthesizeExtendsTypeOfConditionalType( + extendsType: TypeNode, + ): TypeNode { switch (extendsType.kind) { case SyntaxKind.ConditionalType: return factory.createParenthesizedType(extendsType); @@ -499,8 +686,12 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul return parenthesizeCheckTypeOfConditionalType(type); } - function parenthesizeConstituentTypesOfUnionType(members: readonly TypeNode[]): NodeArray { - return factory.createNodeArray(sameMap(members, parenthesizeConstituentTypeOfUnionType)); + function parenthesizeConstituentTypesOfUnionType( + members: readonly TypeNode[], + ): NodeArray { + return factory.createNodeArray( + sameMap(members, parenthesizeConstituentTypeOfUnionType), + ); } // IntersectionType[Extends] : @@ -517,8 +708,12 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul return parenthesizeConstituentTypeOfUnionType(type); } - function parenthesizeConstituentTypesOfIntersectionType(members: readonly TypeNode[]): NodeArray { - return factory.createNodeArray(sameMap(members, parenthesizeConstituentTypeOfIntersectionType)); + function parenthesizeConstituentTypesOfIntersectionType( + members: readonly TypeNode[], + ): NodeArray { + return factory.createNodeArray( + sameMap(members, parenthesizeConstituentTypeOfIntersectionType), + ); } // TypeOperator[Extends] : @@ -597,23 +792,40 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul // RestType : // `...` Type[~Extends] // - function parenthesizeElementTypesOfTupleType(types: readonly (TypeNode | NamedTupleMember)[]): NodeArray { - return factory.createNodeArray(sameMap(types, parenthesizeElementTypeOfTupleType)); + function parenthesizeElementTypesOfTupleType( + types: readonly (TypeNode | NamedTupleMember)[], + ): NodeArray { + return factory.createNodeArray( + sameMap(types, parenthesizeElementTypeOfTupleType), + ); } - function parenthesizeElementTypeOfTupleType(type: TypeNode | NamedTupleMember): TypeNode { + function parenthesizeElementTypeOfTupleType( + type: TypeNode | NamedTupleMember, + ): TypeNode { if (hasJSDocPostfixQuestion(type)) return factory.createParenthesizedType(type); return type; } - function hasJSDocPostfixQuestion(type: TypeNode | NamedTupleMember): boolean { + function hasJSDocPostfixQuestion( + type: TypeNode | NamedTupleMember, + ): boolean { if (isJSDocNullableType(type)) return type.postfix; if (isNamedTupleMember(type)) return hasJSDocPostfixQuestion(type.type); - if (isFunctionTypeNode(type) || isConstructorTypeNode(type) || isTypeOperatorNode(type)) return hasJSDocPostfixQuestion(type.type); + if ( + isFunctionTypeNode(type) || + isConstructorTypeNode(type) || + isTypeOperatorNode(type) + ) return hasJSDocPostfixQuestion(type.type); if (isConditionalTypeNode(type)) return hasJSDocPostfixQuestion(type.falseType); if (isUnionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.types)); if (isIntersectionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.types)); - if (isInferTypeNode(type)) return !!type.typeParameter.constraint && hasJSDocPostfixQuestion(type.typeParameter.constraint); + if (isInferTypeNode(type)) { + return ( + !!type.typeParameter.constraint && + hasJSDocPostfixQuestion(type.typeParameter.constraint) + ); + } return false; } @@ -644,16 +856,22 @@ export function createParenthesizerRules(factory: NodeFactory): ParenthesizerRul // } function parenthesizeLeadingTypeArgument(node: TypeNode) { - return isFunctionOrConstructorTypeNode(node) && node.typeParameters ? factory.createParenthesizedType(node) : node; + return isFunctionOrConstructorTypeNode(node) && node.typeParameters + ? factory.createParenthesizedType(node) + : node; } function parenthesizeOrdinalTypeArgument(node: TypeNode, i: number) { return i === 0 ? parenthesizeLeadingTypeArgument(node) : node; } - function parenthesizeTypeArguments(typeArguments: NodeArray | undefined): NodeArray | undefined { + function parenthesizeTypeArguments( + typeArguments: NodeArray | undefined, + ): NodeArray | undefined { if (some(typeArguments)) { - return factory.createNodeArray(sameMap(typeArguments, parenthesizeOrdinalTypeArgument)); + return factory.createNodeArray( + sameMap(typeArguments, parenthesizeOrdinalTypeArgument), + ); } } } diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts index e952b614251c7..a8436e82f4c29 100644 --- a/src/compiler/factory/utilities.ts +++ b/src/compiler/factory/utilities.ts @@ -185,13 +185,29 @@ import { /** @internal */ export function createEmptyExports(factory: NodeFactory) { - return factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); + return factory.createExportDeclaration( + /*modifiers*/ undefined, + /*isTypeOnly*/ false, + factory.createNamedExports([]), + /*moduleSpecifier*/ undefined, + ); } /** @internal */ -export function createMemberAccessForPropertyName(factory: NodeFactory, target: Expression, memberName: PropertyName, location?: TextRange): MemberExpression { +export function createMemberAccessForPropertyName( + factory: NodeFactory, + target: Expression, + memberName: PropertyName, + location?: TextRange, +): MemberExpression { if (isComputedPropertyName(memberName)) { - return setTextRange(factory.createElementAccessExpression(target, memberName.expression), location); + return setTextRange( + factory.createElementAccessExpression( + target, + memberName.expression, + ), + location, + ); } else { const expression = setTextRange( @@ -205,7 +221,10 @@ export function createMemberAccessForPropertyName(factory: NodeFactory, target: } } -function createReactNamespace(reactNamespace: string, parent: JsxOpeningLikeElement | JsxOpeningFragment) { +function createReactNamespace( + reactNamespace: string, + parent: JsxOpeningLikeElement | JsxOpeningFragment, +) { // To ensure the emit resolver can properly resolve the namespace, we need to // treat this identifier as if it were a source tree node by clearing the `Synthesized` // flag and setting a parent node. @@ -216,10 +235,20 @@ function createReactNamespace(reactNamespace: string, parent: JsxOpeningLikeElem return react; } -function createJsxFactoryExpressionFromEntityName(factory: NodeFactory, jsxFactory: EntityName, parent: JsxOpeningLikeElement | JsxOpeningFragment): Expression { +function createJsxFactoryExpressionFromEntityName( + factory: NodeFactory, + jsxFactory: EntityName, + parent: JsxOpeningLikeElement | JsxOpeningFragment, +): Expression { if (isQualifiedName(jsxFactory)) { - const left = createJsxFactoryExpressionFromEntityName(factory, jsxFactory.left, parent); - const right = factory.createIdentifier(idText(jsxFactory.right)) as Mutable; + const left = createJsxFactoryExpressionFromEntityName( + factory, + jsxFactory.left, + parent, + ); + const right = factory.createIdentifier( + idText(jsxFactory.right), + ) as Mutable; right.escapedText = jsxFactory.right.escapedText; return factory.createPropertyAccessExpression(left, right); } @@ -229,26 +258,51 @@ function createJsxFactoryExpressionFromEntityName(factory: NodeFactory, jsxFacto } /** @internal */ -export function createJsxFactoryExpression(factory: NodeFactory, jsxFactoryEntity: EntityName | undefined, reactNamespace: string, parent: JsxOpeningLikeElement | JsxOpeningFragment): Expression { - return jsxFactoryEntity ? - createJsxFactoryExpressionFromEntityName(factory, jsxFactoryEntity, parent) : - factory.createPropertyAccessExpression( +export function createJsxFactoryExpression( + factory: NodeFactory, + jsxFactoryEntity: EntityName | undefined, + reactNamespace: string, + parent: JsxOpeningLikeElement | JsxOpeningFragment, +): Expression { + return jsxFactoryEntity + ? createJsxFactoryExpressionFromEntityName( + factory, + jsxFactoryEntity, + parent, + ) + : factory.createPropertyAccessExpression( createReactNamespace(reactNamespace, parent), "createElement", ); } -function createJsxFragmentFactoryExpression(factory: NodeFactory, jsxFragmentFactoryEntity: EntityName | undefined, reactNamespace: string, parent: JsxOpeningLikeElement | JsxOpeningFragment): Expression { - return jsxFragmentFactoryEntity ? - createJsxFactoryExpressionFromEntityName(factory, jsxFragmentFactoryEntity, parent) : - factory.createPropertyAccessExpression( +function createJsxFragmentFactoryExpression( + factory: NodeFactory, + jsxFragmentFactoryEntity: EntityName | undefined, + reactNamespace: string, + parent: JsxOpeningLikeElement | JsxOpeningFragment, +): Expression { + return jsxFragmentFactoryEntity + ? createJsxFactoryExpressionFromEntityName( + factory, + jsxFragmentFactoryEntity, + parent, + ) + : factory.createPropertyAccessExpression( createReactNamespace(reactNamespace, parent), "Fragment", ); } /** @internal */ -export function createExpressionForJsxElement(factory: NodeFactory, callee: Expression, tagName: Expression, props: Expression | undefined, children: readonly Expression[] | undefined, location: TextRange): LeftHandSideExpression { +export function createExpressionForJsxElement( + factory: NodeFactory, + callee: Expression, + tagName: Expression, + props: Expression | undefined, + children: readonly Expression[] | undefined, + location: TextRange, +): LeftHandSideExpression { const argumentsList = [tagName]; if (props) { argumentsList.push(props); @@ -281,8 +335,21 @@ export function createExpressionForJsxElement(factory: NodeFactory, callee: Expr } /** @internal */ -export function createExpressionForJsxFragment(factory: NodeFactory, jsxFactoryEntity: EntityName | undefined, jsxFragmentFactoryEntity: EntityName | undefined, reactNamespace: string, children: readonly Expression[], parentElement: JsxOpeningFragment, location: TextRange): LeftHandSideExpression { - const tagName = createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parentElement); +export function createExpressionForJsxFragment( + factory: NodeFactory, + jsxFactoryEntity: EntityName | undefined, + jsxFragmentFactoryEntity: EntityName | undefined, + reactNamespace: string, + children: readonly Expression[], + parentElement: JsxOpeningFragment, + location: TextRange, +): LeftHandSideExpression { + const tagName = createJsxFragmentFactoryExpression( + factory, + jsxFragmentFactoryEntity, + reactNamespace, + parentElement, + ); const argumentsList = [tagName, factory.createNull()]; if (children && children.length > 0) { @@ -299,7 +366,12 @@ export function createExpressionForJsxFragment(factory: NodeFactory, jsxFactoryE return setTextRange( factory.createCallExpression( - createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parentElement), + createJsxFactoryExpression( + factory, + jsxFactoryEntity, + reactNamespace, + parentElement, + ), /*typeArguments*/ undefined, argumentsList, ), @@ -310,7 +382,11 @@ export function createExpressionForJsxFragment(factory: NodeFactory, jsxFactoryE // Utilities /** @internal */ -export function createForOfBindingStatement(factory: NodeFactory, node: ForInitializer, boundValue: Expression): Statement { +export function createForOfBindingStatement( + factory: NodeFactory, + node: ForInitializer, + boundValue: Expression, +): Statement { if (isVariableDeclarationList(node)) { const firstDeclaration = first(node.declarations); const updatedDeclaration = factory.updateVariableDeclaration( @@ -323,97 +399,155 @@ export function createForOfBindingStatement(factory: NodeFactory, node: ForIniti return setTextRange( factory.createVariableStatement( /*modifiers*/ undefined, - factory.updateVariableDeclarationList(node, [updatedDeclaration]), + factory.updateVariableDeclarationList(node, [ + updatedDeclaration, + ]), ), /*location*/ node, ); } else { - const updatedExpression = setTextRange(factory.createAssignment(node, boundValue), /*location*/ node); - return setTextRange(factory.createExpressionStatement(updatedExpression), /*location*/ node); + const updatedExpression = setTextRange( + factory.createAssignment(node, boundValue), + /*location*/ node, + ); + return setTextRange( + factory.createExpressionStatement(updatedExpression), + /*location*/ node, + ); } } /** @internal */ -export function insertLeadingStatement(factory: NodeFactory, dest: Statement, source: Statement): Block { +export function insertLeadingStatement( + factory: NodeFactory, + dest: Statement, + source: Statement, +): Block { if (isBlock(dest)) { - return factory.updateBlock(dest, setTextRange(factory.createNodeArray([source, ...dest.statements]), dest.statements)); + return factory.updateBlock( + dest, + setTextRange( + factory.createNodeArray([source, ...dest.statements]), + dest.statements, + ), + ); } else { - return factory.createBlock(factory.createNodeArray([dest, source]), /*multiLine*/ true); + return factory.createBlock( + factory.createNodeArray([dest, source]), + /*multiLine*/ true, + ); } } /** @internal */ -export function createExpressionFromEntityName(factory: NodeFactory, node: EntityName | Expression): Expression { +export function createExpressionFromEntityName( + factory: NodeFactory, + node: EntityName | Expression, +): Expression { if (isQualifiedName(node)) { const left = createExpressionFromEntityName(factory, node.left); // TODO(rbuckton): Does this need to be parented? - const right = setParent(setTextRange(factory.cloneNode(node.right), node.right), node.right.parent); - return setTextRange(factory.createPropertyAccessExpression(left, right), node); + const right = setParent( + setTextRange(factory.cloneNode(node.right), node.right), + node.right.parent, + ); + return setTextRange( + factory.createPropertyAccessExpression(left, right), + node, + ); } else { // TODO(rbuckton): Does this need to be parented? - return setParent(setTextRange(factory.cloneNode(node), node), node.parent); + return setParent( + setTextRange(factory.cloneNode(node), node), + node.parent, + ); } } /** @internal */ -export function createExpressionForPropertyName(factory: NodeFactory, memberName: Exclude): Expression { +export function createExpressionForPropertyName( + factory: NodeFactory, + memberName: Exclude, +): Expression { if (isIdentifier(memberName)) { return factory.createStringLiteralFromNode(memberName); } else if (isComputedPropertyName(memberName)) { // TODO(rbuckton): Does this need to be parented? - return setParent(setTextRange(factory.cloneNode(memberName.expression), memberName.expression), memberName.expression.parent); + return setParent( + setTextRange( + factory.cloneNode(memberName.expression), + memberName.expression, + ), + memberName.expression.parent, + ); } else { // TODO(rbuckton): Does this need to be parented? - return setParent(setTextRange(factory.cloneNode(memberName), memberName), memberName.parent); + return setParent( + setTextRange(factory.cloneNode(memberName), memberName), + memberName.parent, + ); } } -function createExpressionForAccessorDeclaration(factory: NodeFactory, properties: NodeArray, property: AccessorDeclaration & { readonly name: Exclude; }, receiver: Expression, multiLine: boolean) { +function createExpressionForAccessorDeclaration( + factory: NodeFactory, + properties: NodeArray, + property: AccessorDeclaration & { + readonly name: Exclude; + }, + receiver: Expression, + multiLine: boolean, +) { const { firstAccessor, getAccessor, setAccessor } = getAllAccessorDeclarations(properties, property); if (property === firstAccessor) { return setTextRange( factory.createObjectDefinePropertyCall( receiver, createExpressionForPropertyName(factory, property.name), - factory.createPropertyDescriptor({ - enumerable: factory.createFalse(), - configurable: true, - get: getAccessor && setTextRange( - setOriginalNode( - factory.createFunctionExpression( - getModifiers(getAccessor), - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, - getAccessor.parameters, - /*type*/ undefined, - getAccessor.body!, // TODO: GH#18217 + factory.createPropertyDescriptor( + { + enumerable: factory.createFalse(), + configurable: true, + get: getAccessor && + setTextRange( + setOriginalNode( + factory.createFunctionExpression( + getModifiers(getAccessor), + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + getAccessor.parameters, + /*type*/ undefined, + getAccessor.body!, // TODO: GH#18217 + ), + getAccessor, + ), + getAccessor, ), - getAccessor, - ), - getAccessor, - ), - set: setAccessor && setTextRange( - setOriginalNode( - factory.createFunctionExpression( - getModifiers(setAccessor), - /*asteriskToken*/ undefined, - /*name*/ undefined, - /*typeParameters*/ undefined, - setAccessor.parameters, - /*type*/ undefined, - setAccessor.body!, // TODO: GH#18217 + set: setAccessor && + setTextRange( + setOriginalNode( + factory.createFunctionExpression( + getModifiers(setAccessor), + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + setAccessor.parameters, + /*type*/ undefined, + setAccessor.body!, // TODO: GH#18217 + ), + setAccessor, + ), + setAccessor, ), - setAccessor, - ), - setAccessor, - ), - }, !multiLine), + }, + !multiLine, + ), ), firstAccessor, ); @@ -422,11 +556,20 @@ function createExpressionForAccessorDeclaration(factory: NodeFactory, properties return undefined; } -function createExpressionForPropertyAssignment(factory: NodeFactory, property: PropertyAssignment, receiver: Expression) { +function createExpressionForPropertyAssignment( + factory: NodeFactory, + property: PropertyAssignment, + receiver: Expression, +) { return setOriginalNode( setTextRange( factory.createAssignment( - createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), + createMemberAccessForPropertyName( + factory, + receiver, + property.name, + /*location*/ property.name, + ), property.initializer, ), property, @@ -435,11 +578,20 @@ function createExpressionForPropertyAssignment(factory: NodeFactory, property: P ); } -function createExpressionForShorthandPropertyAssignment(factory: NodeFactory, property: ShorthandPropertyAssignment, receiver: Expression) { +function createExpressionForShorthandPropertyAssignment( + factory: NodeFactory, + property: ShorthandPropertyAssignment, + receiver: Expression, +) { return setOriginalNode( setTextRange( factory.createAssignment( - createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), + createMemberAccessForPropertyName( + factory, + receiver, + property.name, + /*location*/ property.name, + ), factory.cloneNode(property.name), ), /*location*/ property, @@ -448,11 +600,20 @@ function createExpressionForShorthandPropertyAssignment(factory: NodeFactory, pr ); } -function createExpressionForMethodDeclaration(factory: NodeFactory, method: MethodDeclaration, receiver: Expression) { +function createExpressionForMethodDeclaration( + factory: NodeFactory, + method: MethodDeclaration, + receiver: Expression, +) { return setOriginalNode( setTextRange( factory.createAssignment( - createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), + createMemberAccessForPropertyName( + factory, + receiver, + method.name, + /*location*/ method.name, + ), setOriginalNode( setTextRange( factory.createFunctionExpression( @@ -476,20 +637,48 @@ function createExpressionForMethodDeclaration(factory: NodeFactory, method: Meth } /** @internal */ -export function createExpressionForObjectLiteralElementLike(factory: NodeFactory, node: ObjectLiteralExpression, property: ObjectLiteralElementLike, receiver: Expression): Expression | undefined { +export function createExpressionForObjectLiteralElementLike( + factory: NodeFactory, + node: ObjectLiteralExpression, + property: ObjectLiteralElementLike, + receiver: Expression, +): Expression | undefined { if (property.name && isPrivateIdentifier(property.name)) { - Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals."); + Debug.failBadSyntaxKind( + property.name, + "Private identifiers are not allowed in object literals.", + ); } switch (property.kind) { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return createExpressionForAccessorDeclaration(factory, node.properties, property as typeof property & { readonly name: Exclude; }, receiver, !!node.multiLine); + return createExpressionForAccessorDeclaration( + factory, + node.properties, + property as typeof property & { + readonly name: Exclude; + }, + receiver, + !!node.multiLine, + ); case SyntaxKind.PropertyAssignment: - return createExpressionForPropertyAssignment(factory, property, receiver); + return createExpressionForPropertyAssignment( + factory, + property, + receiver, + ); case SyntaxKind.ShorthandPropertyAssignment: - return createExpressionForShorthandPropertyAssignment(factory, property, receiver); + return createExpressionForShorthandPropertyAssignment( + factory, + property, + receiver, + ); case SyntaxKind.MethodDeclaration: - return createExpressionForMethodDeclaration(factory, property, receiver); + return createExpressionForMethodDeclaration( + factory, + property, + receiver, + ); } } @@ -527,17 +716,27 @@ export function createExpressionForObjectLiteralElementLike(factory: NodeFactory * * @internal */ -export function expandPreOrPostfixIncrementOrDecrementExpression(factory: NodeFactory, node: PrefixUnaryExpression | PostfixUnaryExpression, expression: Expression, recordTempVariable: (node: Identifier) => void, resultVariable: Identifier | undefined) { +export function expandPreOrPostfixIncrementOrDecrementExpression( + factory: NodeFactory, + node: PrefixUnaryExpression | PostfixUnaryExpression, + expression: Expression, + recordTempVariable: (node: Identifier) => void, + resultVariable: Identifier | undefined, +) { const operator = node.operator; - Debug.assert(operator === SyntaxKind.PlusPlusToken || operator === SyntaxKind.MinusMinusToken, "Expected 'node' to be a pre- or post-increment or pre- or post-decrement expression"); + Debug.assert( + operator === SyntaxKind.PlusPlusToken || + operator === SyntaxKind.MinusMinusToken, + "Expected 'node' to be a pre- or post-increment or pre- or post-decrement expression", + ); const temp = factory.createTempVariable(recordTempVariable); expression = factory.createAssignment(temp, expression); setTextRange(expression, node.operand); - let operation: Expression = isPrefixUnaryExpression(node) ? - factory.createPrefixUnaryExpression(operator, temp) : - factory.createPostfixUnaryExpression(temp, operator); + let operation: Expression = isPrefixUnaryExpression(node) + ? factory.createPrefixUnaryExpression(operator, temp) + : factory.createPostfixUnaryExpression(temp, operator); setTextRange(operation, node); if (resultVariable) { @@ -585,11 +784,16 @@ export function isExportName(node: Identifier) { } function isUseStrictPrologue(node: ExpressionStatement): boolean { - return isStringLiteral(node.expression) && node.expression.text === "use strict"; + return ( + isStringLiteral(node.expression) && + node.expression.text === "use strict" + ); } /** @internal */ -export function findUseStrictPrologue(statements: readonly Statement[]): Statement | undefined { +export function findUseStrictPrologue( + statements: readonly Statement[], +): Statement | undefined { for (const statement of statements) { if (isPrologueDirective(statement)) { if (isUseStrictPrologue(statement)) { @@ -606,26 +810,40 @@ export function findUseStrictPrologue(statements: readonly Statement[]): Stateme /** @internal */ export function startsWithUseStrict(statements: readonly Statement[]) { const firstStatement = firstOrUndefined(statements); - return firstStatement !== undefined - && isPrologueDirective(firstStatement) - && isUseStrictPrologue(firstStatement); + return ( + firstStatement !== undefined && + isPrologueDirective(firstStatement) && + isUseStrictPrologue(firstStatement) + ); } /** @internal */ -export function isCommaExpression(node: Expression): node is BinaryExpression & { operatorToken: Token; } { - return node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.CommaToken; +export function isCommaExpression( + node: Expression, +): node is BinaryExpression & { operatorToken: Token; } { + return ( + node.kind === SyntaxKind.BinaryExpression && + (node as BinaryExpression).operatorToken.kind === SyntaxKind.CommaToken + ); } /** @internal */ -export function isCommaSequence(node: Expression): node is BinaryExpression & { operatorToken: Token; } | CommaListExpression { +export function isCommaSequence( + node: Expression, +): node is + | (BinaryExpression & { operatorToken: Token; }) + | CommaListExpression +{ return isCommaExpression(node) || isCommaListExpression(node); } /** @internal */ export function isJSDocTypeAssertion(node: Node): node is JSDocTypeAssertion { - return isParenthesizedExpression(node) - && isInJSFile(node) - && !!getJSDocTypeTag(node); + return ( + isParenthesizedExpression(node) && + isInJSFile(node) && + !!getJSDocTypeTag(node) + ); } /** @internal */ @@ -636,10 +854,16 @@ export function getJSDocTypeAssertionType(node: JSDocTypeAssertion): TypeNode { } /** @internal */ -export function isOuterExpression(node: Node, kinds = OuterExpressionKinds.All): node is OuterExpression { +export function isOuterExpression( + node: Node, + kinds = OuterExpressionKinds.All, +): node is OuterExpression { switch (node.kind) { case SyntaxKind.ParenthesizedExpression: - if (kinds & OuterExpressionKinds.ExcludeJSDocTypeAssertion && isJSDocTypeAssertion(node)) { + if ( + kinds & OuterExpressionKinds.ExcludeJSDocTypeAssertion && + isJSDocTypeAssertion(node) + ) { return false; } return (kinds & OuterExpressionKinds.Parentheses) !== 0; @@ -651,19 +875,32 @@ export function isOuterExpression(node: Node, kinds = OuterExpressionKinds.All): case SyntaxKind.NonNullExpression: return (kinds & OuterExpressionKinds.NonNullAssertions) !== 0; case SyntaxKind.PartiallyEmittedExpression: - return (kinds & OuterExpressionKinds.PartiallyEmittedExpressions) !== 0; + return ( + (kinds & OuterExpressionKinds.PartiallyEmittedExpressions) !== 0 + ); } return false; } /** @internal */ -export function skipOuterExpressions(node: WrappedExpression): T; +export function skipOuterExpressions( + node: WrappedExpression, +): T; /** @internal */ -export function skipOuterExpressions(node: Expression, kinds?: OuterExpressionKinds): Expression; +export function skipOuterExpressions( + node: Expression, + kinds?: OuterExpressionKinds, +): Expression; /** @internal */ -export function skipOuterExpressions(node: Node, kinds?: OuterExpressionKinds): Node; +export function skipOuterExpressions( + node: Node, + kinds?: OuterExpressionKinds, +): Node; /** @internal */ -export function skipOuterExpressions(node: Node, kinds = OuterExpressionKinds.All) { +export function skipOuterExpressions( + node: Node, + kinds = OuterExpressionKinds.All, +) { while (isOuterExpression(node, kinds)) { node = node.expression; } @@ -671,7 +908,10 @@ export function skipOuterExpressions(node: Node, kinds = OuterExpressionKinds.Al } /** @internal */ -export function walkUpOuterExpressions(node: Expression, kinds = OuterExpressionKinds.All): Node { +export function walkUpOuterExpressions( + node: Expression, + kinds = OuterExpressionKinds.All, +): Node { let parent = node.parent; while (isOuterExpression(parent, kinds)) { parent = parent.parent; @@ -705,15 +945,33 @@ export function getExternalHelpersModuleName(node: SourceFile) { export function hasRecordedExternalHelpers(sourceFile: SourceFile) { const parseNode = getOriginalNode(sourceFile, isSourceFile); const emitNode = parseNode && parseNode.emitNode; - return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers); + return ( + !!emitNode && + (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers) + ); } /** @internal */ -export function createExternalHelpersImportDeclarationIfNeeded(nodeFactory: NodeFactory, helperFactory: EmitHelperFactory, sourceFile: SourceFile, compilerOptions: CompilerOptions, hasExportStarsToExportValues?: boolean, hasImportStar?: boolean, hasImportDefault?: boolean) { - if (compilerOptions.importHelpers && isEffectiveExternalModule(sourceFile, compilerOptions)) { +export function createExternalHelpersImportDeclarationIfNeeded( + nodeFactory: NodeFactory, + helperFactory: EmitHelperFactory, + sourceFile: SourceFile, + compilerOptions: CompilerOptions, + hasExportStarsToExportValues?: boolean, + hasImportStar?: boolean, + hasImportDefault?: boolean, +) { + if ( + compilerOptions.importHelpers && + isEffectiveExternalModule(sourceFile, compilerOptions) + ) { let namedBindings: NamedImportBindings | undefined; const moduleKind = getEmitModuleKind(compilerOptions); - if ((moduleKind >= ModuleKind.ES2015 && moduleKind <= ModuleKind.ESNext) || sourceFile.impliedNodeFormat === ModuleKind.ESNext) { + if ( + (moduleKind >= ModuleKind.ES2015 && + moduleKind <= ModuleKind.ESNext) || + sourceFile.impliedNodeFormat === ModuleKind.ESNext + ) { // use named imports const helpers = getEmitHelpers(sourceFile); if (helpers) { @@ -733,8 +991,16 @@ export function createExternalHelpersImportDeclarationIfNeeded(nodeFactory: Node namedBindings = nodeFactory.createNamedImports( map(helperNames, name => isFileLevelUniqueName(sourceFile, name) - ? nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, nodeFactory.createIdentifier(name)) - : nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name))), + ? nodeFactory.createImportSpecifier( + /*isTypeOnly*/ false, + /*propertyName*/ undefined, + nodeFactory.createIdentifier(name), + ) + : nodeFactory.createImportSpecifier( + /*isTypeOnly*/ false, + nodeFactory.createIdentifier(name), + helperFactory.getUnscopedHelperName(name), + )), ); const parseNode = getOriginalNode(sourceFile, isSourceFile); const emitNode = getOrCreateEmitNode(parseNode); @@ -744,36 +1010,65 @@ export function createExternalHelpersImportDeclarationIfNeeded(nodeFactory: Node } else { // use a namespace import - const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault); + const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded( + nodeFactory, + sourceFile, + compilerOptions, + hasExportStarsToExportValues, + hasImportStar || hasImportDefault, + ); if (externalHelpersModuleName) { - namedBindings = nodeFactory.createNamespaceImport(externalHelpersModuleName); + namedBindings = nodeFactory.createNamespaceImport( + externalHelpersModuleName, + ); } } if (namedBindings) { const externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( /*modifiers*/ undefined, - nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), - nodeFactory.createStringLiteral(externalHelpersModuleNameText), + nodeFactory.createImportClause( + /*isTypeOnly*/ false, + /*name*/ undefined, + namedBindings, + ), + nodeFactory.createStringLiteral( + externalHelpersModuleNameText, + ), /*attributes*/ undefined, ); - addInternalEmitFlags(externalHelpersImportDeclaration, InternalEmitFlags.NeverApplyImportHelper); + addInternalEmitFlags( + externalHelpersImportDeclaration, + InternalEmitFlags.NeverApplyImportHelper, + ); return externalHelpersImportDeclaration; } } } /** @internal */ -export function getOrCreateExternalHelpersModuleNameIfNeeded(factory: NodeFactory, node: SourceFile, compilerOptions: CompilerOptions, hasExportStarsToExportValues?: boolean, hasImportStarOrImportDefault?: boolean) { - if (compilerOptions.importHelpers && isEffectiveExternalModule(node, compilerOptions)) { +export function getOrCreateExternalHelpersModuleNameIfNeeded( + factory: NodeFactory, + node: SourceFile, + compilerOptions: CompilerOptions, + hasExportStarsToExportValues?: boolean, + hasImportStarOrImportDefault?: boolean, +) { + if ( + compilerOptions.importHelpers && + isEffectiveExternalModule(node, compilerOptions) + ) { const externalHelpersModuleName = getExternalHelpersModuleName(node); if (externalHelpersModuleName) { return externalHelpersModuleName; } const moduleKind = getEmitModuleKind(compilerOptions); - let create = (hasExportStarsToExportValues || (getESModuleInterop(compilerOptions) && hasImportStarOrImportDefault)) - && moduleKind !== ModuleKind.System - && (moduleKind < ModuleKind.ES2015 || node.impliedNodeFormat === ModuleKind.CommonJS); + let create = (hasExportStarsToExportValues || + (getESModuleInterop(compilerOptions) && + hasImportStarOrImportDefault)) && + moduleKind !== ModuleKind.System && + (moduleKind < ModuleKind.ES2015 || + node.impliedNodeFormat === ModuleKind.CommonJS); if (!create) { const helpers = getEmitHelpers(node); if (helpers) { @@ -789,7 +1084,12 @@ export function getOrCreateExternalHelpersModuleNameIfNeeded(factory: NodeFactor if (create) { const parseNode = getOriginalNode(node, isSourceFile); const emitNode = getOrCreateEmitNode(parseNode); - return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory.createUniqueName(externalHelpersModuleNameText)); + return ( + emitNode.externalHelpersModuleName || + (emitNode.externalHelpersModuleName = factory.createUniqueName( + externalHelpersModuleNameText, + )) + ); } } } @@ -799,11 +1099,24 @@ export function getOrCreateExternalHelpersModuleNameIfNeeded(factory: NodeFactor * * @internal */ -export function getLocalNameForExternalImport(factory: NodeFactory, node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, sourceFile: SourceFile): Identifier | undefined { +export function getLocalNameForExternalImport( + factory: NodeFactory, + node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration, + sourceFile: SourceFile, +): Identifier | undefined { const namespaceDeclaration = getNamespaceDeclarationNode(node); - if (namespaceDeclaration && !isDefaultImport(node) && !isExportNamespaceAsDefaultDeclaration(node)) { + if ( + namespaceDeclaration && + !isDefaultImport(node) && + !isExportNamespaceAsDefaultDeclaration(node) + ) { const name = namespaceDeclaration.name; - return isGeneratedIdentifier(name) ? name : factory.createIdentifier(getSourceTextOfNodeFromSourceFile(sourceFile, name) || idText(name)); + return isGeneratedIdentifier(name) + ? name + : factory.createIdentifier( + getSourceTextOfNodeFromSourceFile(sourceFile, name) || + idText(name), + ); } if (node.kind === SyntaxKind.ImportDeclaration && node.importClause) { return factory.getGeneratedNameForNode(node); @@ -824,12 +1137,31 @@ export function getLocalNameForExternalImport(factory: NodeFactory, node: Import * * @internal */ -export function getExternalModuleNameLiteral(factory: NodeFactory, importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration | ImportCall, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions) { +export function getExternalModuleNameLiteral( + factory: NodeFactory, + importNode: + | ImportDeclaration + | ExportDeclaration + | ImportEqualsDeclaration + | ImportCall, + sourceFile: SourceFile, + host: EmitHost, + resolver: EmitResolver, + compilerOptions: CompilerOptions, +) { const moduleName = getExternalModuleName(importNode); if (moduleName && isStringLiteral(moduleName)) { - return tryGetModuleNameFromDeclaration(importNode, host, factory, resolver, compilerOptions) - || tryRenameExternalModule(factory, moduleName, sourceFile) - || factory.cloneNode(moduleName); + return ( + tryGetModuleNameFromDeclaration( + importNode, + host, + factory, + resolver, + compilerOptions, + ) || + tryRenameExternalModule(factory, moduleName, sourceFile) || + factory.cloneNode(moduleName) + ); } return undefined; @@ -839,8 +1171,13 @@ export function getExternalModuleNameLiteral(factory: NodeFactory, importNode: I * Some bundlers (SystemJS builder) sometimes want to rename dependencies. * Here we check if alternative name was provided for a given moduleName and return it if possible. */ -function tryRenameExternalModule(factory: NodeFactory, moduleName: LiteralExpression, sourceFile: SourceFile) { - const rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text); +function tryRenameExternalModule( + factory: NodeFactory, + moduleName: LiteralExpression, + sourceFile: SourceFile, +) { + const rename = sourceFile.renamedDependencies && + sourceFile.renamedDependencies.get((moduleName as Identifier).text); return rename ? factory.createStringLiteral(rename) : undefined; } @@ -853,7 +1190,12 @@ function tryRenameExternalModule(factory: NodeFactory, moduleName: LiteralExpres * * @internal */ -export function tryGetModuleNameFromFile(factory: NodeFactory, file: SourceFile | undefined, host: EmitHost, options: CompilerOptions): StringLiteral | undefined { +export function tryGetModuleNameFromFile( + factory: NodeFactory, + file: SourceFile | undefined, + host: EmitHost, + options: CompilerOptions, +): StringLiteral | undefined { if (!file) { return undefined; } @@ -861,13 +1203,30 @@ export function tryGetModuleNameFromFile(factory: NodeFactory, file: SourceFile return factory.createStringLiteral(file.moduleName); } if (!file.isDeclarationFile && outFile(options)) { - return factory.createStringLiteral(getExternalModuleNameFromPath(host, file.fileName)); + return factory.createStringLiteral( + getExternalModuleNameFromPath(host, file.fileName), + ); } return undefined; } -function tryGetModuleNameFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ImportCall, host: EmitHost, factory: NodeFactory, resolver: EmitResolver, compilerOptions: CompilerOptions) { - return tryGetModuleNameFromFile(factory, resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); +function tryGetModuleNameFromDeclaration( + declaration: + | ImportEqualsDeclaration + | ImportDeclaration + | ExportDeclaration + | ImportCall, + host: EmitHost, + factory: NodeFactory, + resolver: EmitResolver, + compilerOptions: CompilerOptions, +) { + return tryGetModuleNameFromFile( + factory, + resolver.getExternalModuleFileFromDeclaration(declaration), + host, + compilerOptions, + ); } /** @@ -875,7 +1234,9 @@ function tryGetModuleNameFromDeclaration(declaration: ImportEqualsDeclaration | * * @internal */ -export function getInitializerOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): Expression | undefined { +export function getInitializerOfBindingOrAssignmentElement( + bindingElement: BindingOrAssignmentElement, +): Expression | undefined { if (isDeclarationBindingElement(bindingElement)) { // `1` in `let { a = 1 } = ...` // `1` in `let { a: b = 1 } = ...` @@ -892,7 +1253,10 @@ export function getInitializerOfBindingOrAssignmentElement(bindingElement: Bindi // `1` in `({ a: {b} = 1 } = ...)` // `1` in `({ a: [b] = 1 } = ...)` const initializer = bindingElement.initializer; - return isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true) + return isAssignmentExpression( + initializer, + /*excludeCompoundAssignment*/ true, + ) ? initializer.right : undefined; } @@ -902,7 +1266,12 @@ export function getInitializerOfBindingOrAssignmentElement(bindingElement: Bindi return bindingElement.objectAssignmentInitializer; } - if (isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + if ( + isAssignmentExpression( + bindingElement, + /*excludeCompoundAssignment*/ true, + ) + ) { // `1` in `[a = 1] = ...` // `1` in `[{a} = 1] = ...` // `1` in `[[a] = 1] = ...` @@ -911,7 +1280,9 @@ export function getInitializerOfBindingOrAssignmentElement(bindingElement: Bindi if (isSpreadElement(bindingElement)) { // Recovery consistent with existing emit. - return getInitializerOfBindingOrAssignmentElement(bindingElement.expression as BindingOrAssignmentElement); + return getInitializerOfBindingOrAssignmentElement( + bindingElement.expression as BindingOrAssignmentElement, + ); } } @@ -920,7 +1291,9 @@ export function getInitializerOfBindingOrAssignmentElement(bindingElement: Bindi * * @internal */ -export function getTargetOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementTarget | undefined { +export function getTargetOfBindingOrAssignmentElement( + bindingElement: BindingOrAssignmentElement, +): BindingOrAssignmentElementTarget | undefined { if (isDeclarationBindingElement(bindingElement)) { // `a` in `let { a } = ...` // `a` in `let { a = 1 } = ...` @@ -954,7 +1327,9 @@ export function getTargetOfBindingOrAssignmentElement(bindingElement: BindingOrA // `b.c` in `({ a: b.c = 1 } = ...)` // `b[0]` in `({ a: b[0] } = ...)` // `b[0]` in `({ a: b[0] = 1 } = ...)` - return getTargetOfBindingOrAssignmentElement(bindingElement.initializer as BindingOrAssignmentElement); + return getTargetOfBindingOrAssignmentElement( + bindingElement.initializer as BindingOrAssignmentElement, + ); case SyntaxKind.ShorthandPropertyAssignment: // `a` in `({ a } = ...)` @@ -963,25 +1338,36 @@ export function getTargetOfBindingOrAssignmentElement(bindingElement: BindingOrA case SyntaxKind.SpreadAssignment: // `a` in `({ ...a } = ...)` - return getTargetOfBindingOrAssignmentElement(bindingElement.expression as BindingOrAssignmentElement); + return getTargetOfBindingOrAssignmentElement( + bindingElement.expression as BindingOrAssignmentElement, + ); } // no target return undefined; } - if (isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) { + if ( + isAssignmentExpression( + bindingElement, + /*excludeCompoundAssignment*/ true, + ) + ) { // `a` in `[a = 1] = ...` // `{a}` in `[{a} = 1] = ...` // `[a]` in `[[a] = 1] = ...` // `a.b` in `[a.b = 1] = ...` // `a[0]` in `[a[0] = 1] = ...` - return getTargetOfBindingOrAssignmentElement(bindingElement.left as BindingOrAssignmentElement); + return getTargetOfBindingOrAssignmentElement( + bindingElement.left as BindingOrAssignmentElement, + ); } if (isSpreadElement(bindingElement)) { // `a` in `[...a] = ...` - return getTargetOfBindingOrAssignmentElement(bindingElement.expression as BindingOrAssignmentElement); + return getTargetOfBindingOrAssignmentElement( + bindingElement.expression as BindingOrAssignmentElement, + ); } // `a` in `[a] = ...` @@ -997,7 +1383,9 @@ export function getTargetOfBindingOrAssignmentElement(bindingElement: BindingOrA * * @internal */ -export function getRestIndicatorOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementRestIndicator | undefined { +export function getRestIndicatorOfBindingOrAssignmentElement( + bindingElement: BindingOrAssignmentElement, +): BindingOrAssignmentElementRestIndicator | undefined { switch (bindingElement.kind) { case SyntaxKind.Parameter: case SyntaxKind.BindingElement: @@ -1018,14 +1406,21 @@ export function getRestIndicatorOfBindingOrAssignmentElement(bindingElement: Bin * * @internal */ -export function getPropertyNameOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): Exclude | undefined { +export function getPropertyNameOfBindingOrAssignmentElement( + bindingElement: BindingOrAssignmentElement, +): Exclude | undefined { const propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement); - Debug.assert(!!propertyName || isSpreadAssignment(bindingElement), "Invalid property name for binding element."); + Debug.assert( + !!propertyName || isSpreadAssignment(bindingElement), + "Invalid property name for binding element.", + ); return propertyName; } /** @internal */ -export function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): Exclude | undefined { +export function tryGetPropertyNameOfBindingOrAssignmentElement( + bindingElement: BindingOrAssignmentElement, +): Exclude | undefined { switch (bindingElement.kind) { case SyntaxKind.BindingElement: // `a` in `let { a: b } = ...` @@ -1037,7 +1432,8 @@ export function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement: B if (isPrivateIdentifier(propertyName)) { return Debug.failBadSyntaxKind(propertyName); } - return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + return isComputedPropertyName(propertyName) && + isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -1054,7 +1450,8 @@ export function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement: B if (isPrivateIdentifier(propertyName)) { return Debug.failBadSyntaxKind(propertyName); } - return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression) + return isComputedPropertyName(propertyName) && + isStringOrNumericLiteral(propertyName.expression) ? propertyName.expression : propertyName; } @@ -1063,7 +1460,10 @@ export function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement: B case SyntaxKind.SpreadAssignment: // `a` in `({ ...a } = ...)` - if (bindingElement.name && isPrivateIdentifier(bindingElement.name)) { + if ( + bindingElement.name && + isPrivateIdentifier(bindingElement.name) + ) { return Debug.failBadSyntaxKind(bindingElement.name); } return bindingElement.name; @@ -1075,10 +1475,13 @@ export function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement: B } } -function isStringOrNumericLiteral(node: Node): node is StringLiteral | NumericLiteral { +function isStringOrNumericLiteral( + node: Node, +): node is StringLiteral | NumericLiteral { const kind = node.kind; - return kind === SyntaxKind.StringLiteral - || kind === SyntaxKind.NumericLiteral; + return ( + kind === SyntaxKind.StringLiteral || kind === SyntaxKind.NumericLiteral + ); } /** @@ -1086,7 +1489,9 @@ function isStringOrNumericLiteral(node: Node): node is StringLiteral | NumericLi * * @internal */ -export function getElementsOfBindingOrAssignmentPattern(name: BindingOrAssignmentPattern): readonly BindingOrAssignmentElement[] { +export function getElementsOfBindingOrAssignmentPattern( + name: BindingOrAssignmentPattern, +): readonly BindingOrAssignmentElement[] { switch (name.kind) { case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: @@ -1102,7 +1507,9 @@ export function getElementsOfBindingOrAssignmentPattern(name: BindingOrAssignmen } /** @internal */ -export function getJSDocTypeAliasName(fullName: JSDocNamespaceBody | undefined) { +export function getJSDocTypeAliasName( + fullName: JSDocNamespaceBody | undefined, +) { if (fullName) { let rightNode = fullName; while (true) { @@ -1117,63 +1524,82 @@ export function getJSDocTypeAliasName(fullName: JSDocNamespaceBody | undefined) /** @internal */ export function canHaveIllegalType(node: Node): node is HasIllegalType { const kind = node.kind; - return kind === SyntaxKind.Constructor - || kind === SyntaxKind.SetAccessor; + return kind === SyntaxKind.Constructor || kind === SyntaxKind.SetAccessor; } /** @internal */ -export function canHaveIllegalTypeParameters(node: Node): node is HasIllegalTypeParameters { +export function canHaveIllegalTypeParameters( + node: Node, +): node is HasIllegalTypeParameters { const kind = node.kind; - return kind === SyntaxKind.Constructor - || kind === SyntaxKind.GetAccessor - || kind === SyntaxKind.SetAccessor; + return ( + kind === SyntaxKind.Constructor || + kind === SyntaxKind.GetAccessor || + kind === SyntaxKind.SetAccessor + ); } /** @internal */ -export function canHaveIllegalDecorators(node: Node): node is HasIllegalDecorators { +export function canHaveIllegalDecorators( + node: Node, +): node is HasIllegalDecorators { const kind = node.kind; - return kind === SyntaxKind.PropertyAssignment - || kind === SyntaxKind.ShorthandPropertyAssignment - || kind === SyntaxKind.FunctionDeclaration - || kind === SyntaxKind.Constructor - || kind === SyntaxKind.IndexSignature - || kind === SyntaxKind.ClassStaticBlockDeclaration - || kind === SyntaxKind.MissingDeclaration - || kind === SyntaxKind.VariableStatement - || kind === SyntaxKind.InterfaceDeclaration - || kind === SyntaxKind.TypeAliasDeclaration - || kind === SyntaxKind.EnumDeclaration - || kind === SyntaxKind.ModuleDeclaration - || kind === SyntaxKind.ImportEqualsDeclaration - || kind === SyntaxKind.ImportDeclaration - || kind === SyntaxKind.NamespaceExportDeclaration - || kind === SyntaxKind.ExportDeclaration - || kind === SyntaxKind.ExportAssignment; + return ( + kind === SyntaxKind.PropertyAssignment || + kind === SyntaxKind.ShorthandPropertyAssignment || + kind === SyntaxKind.FunctionDeclaration || + kind === SyntaxKind.Constructor || + kind === SyntaxKind.IndexSignature || + kind === SyntaxKind.ClassStaticBlockDeclaration || + kind === SyntaxKind.MissingDeclaration || + kind === SyntaxKind.VariableStatement || + kind === SyntaxKind.InterfaceDeclaration || + kind === SyntaxKind.TypeAliasDeclaration || + kind === SyntaxKind.EnumDeclaration || + kind === SyntaxKind.ModuleDeclaration || + kind === SyntaxKind.ImportEqualsDeclaration || + kind === SyntaxKind.ImportDeclaration || + kind === SyntaxKind.NamespaceExportDeclaration || + kind === SyntaxKind.ExportDeclaration || + kind === SyntaxKind.ExportAssignment + ); } /** @internal */ -export function canHaveIllegalModifiers(node: Node): node is HasIllegalModifiers { +export function canHaveIllegalModifiers( + node: Node, +): node is HasIllegalModifiers { const kind = node.kind; - return kind === SyntaxKind.ClassStaticBlockDeclaration - || kind === SyntaxKind.PropertyAssignment - || kind === SyntaxKind.ShorthandPropertyAssignment - || kind === SyntaxKind.MissingDeclaration - || kind === SyntaxKind.NamespaceExportDeclaration; + return ( + kind === SyntaxKind.ClassStaticBlockDeclaration || + kind === SyntaxKind.PropertyAssignment || + kind === SyntaxKind.ShorthandPropertyAssignment || + kind === SyntaxKind.MissingDeclaration || + kind === SyntaxKind.NamespaceExportDeclaration + ); } -export function isQuestionOrExclamationToken(node: Node): node is QuestionToken | ExclamationToken { +export function isQuestionOrExclamationToken( + node: Node, +): node is QuestionToken | ExclamationToken { return isQuestionToken(node) || isExclamationToken(node); } -export function isIdentifierOrThisTypeNode(node: Node): node is Identifier | ThisTypeNode { +export function isIdentifierOrThisTypeNode( + node: Node, +): node is Identifier | ThisTypeNode { return isIdentifier(node) || isThisTypeNode(node); } -export function isReadonlyKeywordOrPlusOrMinusToken(node: Node): node is ReadonlyKeyword | PlusToken | MinusToken { +export function isReadonlyKeywordOrPlusOrMinusToken( + node: Node, +): node is ReadonlyKeyword | PlusToken | MinusToken { return isReadonlyKeyword(node) || isPlusToken(node) || isMinusToken(node); } -export function isQuestionOrPlusOrMinusToken(node: Node): node is QuestionToken | PlusToken | MinusToken { +export function isQuestionOrPlusOrMinusToken( + node: Node, +): node is QuestionToken | PlusToken | MinusToken { return isQuestionToken(node) || isPlusToken(node) || isMinusToken(node); } @@ -1182,116 +1608,158 @@ export function isModuleName(node: Node): node is ModuleName { } /** @internal */ -export function isLiteralTypeLikeExpression(node: Node): node is NullLiteral | BooleanLiteral | LiteralExpression | PrefixUnaryExpression { +export function isLiteralTypeLikeExpression( + node: Node, +): node is + | NullLiteral + | BooleanLiteral + | LiteralExpression + | PrefixUnaryExpression +{ const kind = node.kind; - return kind === SyntaxKind.NullKeyword - || kind === SyntaxKind.TrueKeyword - || kind === SyntaxKind.FalseKeyword - || isLiteralExpression(node) - || isPrefixUnaryExpression(node); + return ( + kind === SyntaxKind.NullKeyword || + kind === SyntaxKind.TrueKeyword || + kind === SyntaxKind.FalseKeyword || + isLiteralExpression(node) || + isPrefixUnaryExpression(node) + ); } -function isExponentiationOperator(kind: SyntaxKind): kind is ExponentiationOperator { +function isExponentiationOperator( + kind: SyntaxKind, +): kind is ExponentiationOperator { return kind === SyntaxKind.AsteriskAsteriskToken; } -function isMultiplicativeOperator(kind: SyntaxKind): kind is MultiplicativeOperator { - return kind === SyntaxKind.AsteriskToken - || kind === SyntaxKind.SlashToken - || kind === SyntaxKind.PercentToken; +function isMultiplicativeOperator( + kind: SyntaxKind, +): kind is MultiplicativeOperator { + return ( + kind === SyntaxKind.AsteriskToken || + kind === SyntaxKind.SlashToken || + kind === SyntaxKind.PercentToken + ); } -function isMultiplicativeOperatorOrHigher(kind: SyntaxKind): kind is MultiplicativeOperatorOrHigher { - return isExponentiationOperator(kind) - || isMultiplicativeOperator(kind); +function isMultiplicativeOperatorOrHigher( + kind: SyntaxKind, +): kind is MultiplicativeOperatorOrHigher { + return isExponentiationOperator(kind) || isMultiplicativeOperator(kind); } function isAdditiveOperator(kind: SyntaxKind): kind is AdditiveOperator { - return kind === SyntaxKind.PlusToken - || kind === SyntaxKind.MinusToken; + return kind === SyntaxKind.PlusToken || kind === SyntaxKind.MinusToken; } -function isAdditiveOperatorOrHigher(kind: SyntaxKind): kind is AdditiveOperatorOrHigher { - return isAdditiveOperator(kind) - || isMultiplicativeOperatorOrHigher(kind); +function isAdditiveOperatorOrHigher( + kind: SyntaxKind, +): kind is AdditiveOperatorOrHigher { + return isAdditiveOperator(kind) || isMultiplicativeOperatorOrHigher(kind); } function isShiftOperator(kind: SyntaxKind): kind is ShiftOperator { - return kind === SyntaxKind.LessThanLessThanToken - || kind === SyntaxKind.GreaterThanGreaterThanToken - || kind === SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + return ( + kind === SyntaxKind.LessThanLessThanToken || + kind === SyntaxKind.GreaterThanGreaterThanToken || + kind === SyntaxKind.GreaterThanGreaterThanGreaterThanToken + ); } /** @internal */ -export function isShiftOperatorOrHigher(kind: SyntaxKind): kind is ShiftOperatorOrHigher { - return isShiftOperator(kind) - || isAdditiveOperatorOrHigher(kind); +export function isShiftOperatorOrHigher( + kind: SyntaxKind, +): kind is ShiftOperatorOrHigher { + return isShiftOperator(kind) || isAdditiveOperatorOrHigher(kind); } function isRelationalOperator(kind: SyntaxKind): kind is RelationalOperator { - return kind === SyntaxKind.LessThanToken - || kind === SyntaxKind.LessThanEqualsToken - || kind === SyntaxKind.GreaterThanToken - || kind === SyntaxKind.GreaterThanEqualsToken - || kind === SyntaxKind.InstanceOfKeyword - || kind === SyntaxKind.InKeyword; + return ( + kind === SyntaxKind.LessThanToken || + kind === SyntaxKind.LessThanEqualsToken || + kind === SyntaxKind.GreaterThanToken || + kind === SyntaxKind.GreaterThanEqualsToken || + kind === SyntaxKind.InstanceOfKeyword || + kind === SyntaxKind.InKeyword + ); } -function isRelationalOperatorOrHigher(kind: SyntaxKind): kind is RelationalOperatorOrHigher { - return isRelationalOperator(kind) - || isShiftOperatorOrHigher(kind); +function isRelationalOperatorOrHigher( + kind: SyntaxKind, +): kind is RelationalOperatorOrHigher { + return isRelationalOperator(kind) || isShiftOperatorOrHigher(kind); } function isEqualityOperator(kind: SyntaxKind): kind is EqualityOperator { - return kind === SyntaxKind.EqualsEqualsToken - || kind === SyntaxKind.EqualsEqualsEqualsToken - || kind === SyntaxKind.ExclamationEqualsToken - || kind === SyntaxKind.ExclamationEqualsEqualsToken; + return ( + kind === SyntaxKind.EqualsEqualsToken || + kind === SyntaxKind.EqualsEqualsEqualsToken || + kind === SyntaxKind.ExclamationEqualsToken || + kind === SyntaxKind.ExclamationEqualsEqualsToken + ); } -function isEqualityOperatorOrHigher(kind: SyntaxKind): kind is EqualityOperatorOrHigher { - return isEqualityOperator(kind) - || isRelationalOperatorOrHigher(kind); +function isEqualityOperatorOrHigher( + kind: SyntaxKind, +): kind is EqualityOperatorOrHigher { + return isEqualityOperator(kind) || isRelationalOperatorOrHigher(kind); } function isBitwiseOperator(kind: SyntaxKind): kind is BitwiseOperator { - return kind === SyntaxKind.AmpersandToken - || kind === SyntaxKind.BarToken - || kind === SyntaxKind.CaretToken; + return ( + kind === SyntaxKind.AmpersandToken || + kind === SyntaxKind.BarToken || + kind === SyntaxKind.CaretToken + ); } -function isBitwiseOperatorOrHigher(kind: SyntaxKind): kind is BitwiseOperatorOrHigher { - return isBitwiseOperator(kind) - || isEqualityOperatorOrHigher(kind); +function isBitwiseOperatorOrHigher( + kind: SyntaxKind, +): kind is BitwiseOperatorOrHigher { + return isBitwiseOperator(kind) || isEqualityOperatorOrHigher(kind); } // NOTE: The version in utilities includes ExclamationToken, which is not a binary operator. function isLogicalOperator(kind: SyntaxKind): kind is LogicalOperator { - return kind === SyntaxKind.AmpersandAmpersandToken - || kind === SyntaxKind.BarBarToken; + return ( + kind === SyntaxKind.AmpersandAmpersandToken || + kind === SyntaxKind.BarBarToken + ); } -function isLogicalOperatorOrHigher(kind: SyntaxKind): kind is LogicalOperatorOrHigher { - return isLogicalOperator(kind) - || isBitwiseOperatorOrHigher(kind); +function isLogicalOperatorOrHigher( + kind: SyntaxKind, +): kind is LogicalOperatorOrHigher { + return isLogicalOperator(kind) || isBitwiseOperatorOrHigher(kind); } -function isAssignmentOperatorOrHigher(kind: SyntaxKind): kind is AssignmentOperatorOrHigher { - return kind === SyntaxKind.QuestionQuestionToken - || isLogicalOperatorOrHigher(kind) - || isAssignmentOperator(kind); +function isAssignmentOperatorOrHigher( + kind: SyntaxKind, +): kind is AssignmentOperatorOrHigher { + return ( + kind === SyntaxKind.QuestionQuestionToken || + isLogicalOperatorOrHigher(kind) || + isAssignmentOperator(kind) + ); } function isBinaryOperator(kind: SyntaxKind): kind is BinaryOperator { - return isAssignmentOperatorOrHigher(kind) - || kind === SyntaxKind.CommaToken; + return isAssignmentOperatorOrHigher(kind) || kind === SyntaxKind.CommaToken; } export function isBinaryOperatorToken(node: Node): node is BinaryOperatorToken { return isBinaryOperator(node.kind); } -type BinaryExpressionState = (machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], resultHolder: { value: TResult; }, outerState: TOuterState) => number; +type BinaryExpressionState = ( + machine: BinaryExpressionStateMachine, + stackIndex: number, + stateStack: BinaryExpressionState[], + nodeStack: BinaryExpression[], + userStateStack: TState[], + resultHolder: { value: TResult; }, + outerState: TOuterState, +) => number; namespace BinaryExpressionState { /** @@ -1300,10 +1768,22 @@ namespace BinaryExpressionState { * @param frame The current frame * @returns The new frame */ - export function enter(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult; }, outerState: TOuterState): number { + export function enter( + machine: BinaryExpressionStateMachine, + stackIndex: number, + stateStack: BinaryExpressionState[], + nodeStack: BinaryExpression[], + userStateStack: TState[], + _resultHolder: { value: TResult; }, + outerState: TOuterState, + ): number { const prevUserState = stackIndex > 0 ? userStateStack[stackIndex - 1] : undefined; Debug.assertEqual(stateStack[stackIndex], enter); - userStateStack[stackIndex] = machine.onEnter(nodeStack[stackIndex], prevUserState, outerState); + userStateStack[stackIndex] = machine.onEnter( + nodeStack[stackIndex], + prevUserState, + outerState, + ); stateStack[stackIndex] = nextState(machine, enter); return stackIndex; } @@ -1314,14 +1794,32 @@ namespace BinaryExpressionState { * @param frame The current frame * @returns The new frame */ - export function left(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult; }, _outerState: TOuterState): number { + export function left( + machine: BinaryExpressionStateMachine, + stackIndex: number, + stateStack: BinaryExpressionState[], + nodeStack: BinaryExpression[], + userStateStack: TState[], + _resultHolder: { value: TResult; }, + _outerState: TOuterState, + ): number { Debug.assertEqual(stateStack[stackIndex], left); Debug.assertIsDefined(machine.onLeft); stateStack[stackIndex] = nextState(machine, left); - const nextNode = machine.onLeft(nodeStack[stackIndex].left, userStateStack[stackIndex], nodeStack[stackIndex]); + const nextNode = machine.onLeft( + nodeStack[stackIndex].left, + userStateStack[stackIndex], + nodeStack[stackIndex], + ); if (nextNode) { checkCircularity(stackIndex, nodeStack, nextNode); - return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + return pushStack( + stackIndex, + stateStack, + nodeStack, + userStateStack, + nextNode, + ); } return stackIndex; } @@ -1332,11 +1830,23 @@ namespace BinaryExpressionState { * @param frame The current frame * @returns The new frame */ - export function operator(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult; }, _outerState: TOuterState): number { + export function operator( + machine: BinaryExpressionStateMachine, + stackIndex: number, + stateStack: BinaryExpressionState[], + nodeStack: BinaryExpression[], + userStateStack: TState[], + _resultHolder: { value: TResult; }, + _outerState: TOuterState, + ): number { Debug.assertEqual(stateStack[stackIndex], operator); Debug.assertIsDefined(machine.onOperator); stateStack[stackIndex] = nextState(machine, operator); - machine.onOperator(nodeStack[stackIndex].operatorToken, userStateStack[stackIndex], nodeStack[stackIndex]); + machine.onOperator( + nodeStack[stackIndex].operatorToken, + userStateStack[stackIndex], + nodeStack[stackIndex], + ); return stackIndex; } @@ -1346,14 +1856,32 @@ namespace BinaryExpressionState { * @param frame The current frame * @returns The new frame */ - export function right(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], _resultHolder: { value: TResult; }, _outerState: TOuterState): number { + export function right( + machine: BinaryExpressionStateMachine, + stackIndex: number, + stateStack: BinaryExpressionState[], + nodeStack: BinaryExpression[], + userStateStack: TState[], + _resultHolder: { value: TResult; }, + _outerState: TOuterState, + ): number { Debug.assertEqual(stateStack[stackIndex], right); Debug.assertIsDefined(machine.onRight); stateStack[stackIndex] = nextState(machine, right); - const nextNode = machine.onRight(nodeStack[stackIndex].right, userStateStack[stackIndex], nodeStack[stackIndex]); + const nextNode = machine.onRight( + nodeStack[stackIndex].right, + userStateStack[stackIndex], + nodeStack[stackIndex], + ); if (nextNode) { checkCircularity(stackIndex, nodeStack, nextNode); - return pushStack(stackIndex, stateStack, nodeStack, userStateStack, nextNode); + return pushStack( + stackIndex, + stateStack, + nodeStack, + userStateStack, + nextNode, + ); } return stackIndex; } @@ -1364,15 +1892,30 @@ namespace BinaryExpressionState { * @param frame The current frame * @returns The new frame */ - export function exit(machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], resultHolder: { value: TResult; }, _outerState: TOuterState): number { + export function exit( + machine: BinaryExpressionStateMachine, + stackIndex: number, + stateStack: BinaryExpressionState[], + nodeStack: BinaryExpression[], + userStateStack: TState[], + resultHolder: { value: TResult; }, + _outerState: TOuterState, + ): number { Debug.assertEqual(stateStack[stackIndex], exit); stateStack[stackIndex] = nextState(machine, exit); - const result = machine.onExit(nodeStack[stackIndex], userStateStack[stackIndex]); + const result = machine.onExit( + nodeStack[stackIndex], + userStateStack[stackIndex], + ); if (stackIndex > 0) { stackIndex--; if (machine.foldState) { const side = stateStack[stackIndex] === exit ? "right" : "left"; - userStateStack[stackIndex] = machine.foldState(userStateStack[stackIndex], result, side); + userStateStack[stackIndex] = machine.foldState( + userStateStack[stackIndex], + result, + side, + ); } } else { @@ -1385,22 +1928,33 @@ namespace BinaryExpressionState { * Handles a frame that is already done. * @returns The `done` state. */ - export function done(_machine: BinaryExpressionStateMachine, stackIndex: number, stateStack: BinaryExpressionState[], _nodeStack: BinaryExpression[], _userStateStack: TState[], _resultHolder: { value: TResult; }, _outerState: TOuterState): number { + export function done( + _machine: BinaryExpressionStateMachine, + stackIndex: number, + stateStack: BinaryExpressionState[], + _nodeStack: BinaryExpression[], + _userStateStack: TState[], + _resultHolder: { value: TResult; }, + _outerState: TOuterState, + ): number { Debug.assertEqual(stateStack[stackIndex], done); return stackIndex; } - export function nextState(machine: BinaryExpressionStateMachine, currentState: BinaryExpressionState) { + export function nextState( + machine: BinaryExpressionStateMachine, + currentState: BinaryExpressionState, + ) { switch (currentState) { case enter: if (machine.onLeft) return left; - // falls through + // falls through case left: if (machine.onOperator) return operator; - // falls through + // falls through case operator: if (machine.onRight) return right; - // falls through + // falls through case right: return exit; case exit: @@ -1412,7 +1966,13 @@ namespace BinaryExpressionState { } } - function pushStack(stackIndex: number, stateStack: BinaryExpressionState[], nodeStack: BinaryExpression[], userStateStack: TState[], node: BinaryExpression) { + function pushStack( + stackIndex: number, + stateStack: BinaryExpressionState[], + nodeStack: BinaryExpression[], + userStateStack: TState[], + node: BinaryExpression, + ) { stackIndex++; stateStack[stackIndex] = enter; nodeStack[stackIndex] = node; @@ -1420,10 +1980,17 @@ namespace BinaryExpressionState { return stackIndex; } - function checkCircularity(stackIndex: number, nodeStack: BinaryExpression[], node: BinaryExpression) { + function checkCircularity( + stackIndex: number, + nodeStack: BinaryExpression[], + node: BinaryExpression, + ) { if (Debug.shouldAssert(AssertionLevel.Aggressive)) { while (stackIndex >= 0) { - Debug.assert(nodeStack[stackIndex] !== node, "Circular traversal detected."); + Debug.assert( + nodeStack[stackIndex] !== node, + "Circular traversal detected.", + ); stackIndex--; } } @@ -1435,14 +2002,41 @@ namespace BinaryExpressionState { */ class BinaryExpressionStateMachine { constructor( - readonly onEnter: (node: BinaryExpression, prev: TState | undefined, outerState: TOuterState) => TState, - readonly onLeft: ((left: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, - readonly onOperator: ((operatorToken: BinaryOperatorToken, userState: TState, node: BinaryExpression) => void) | undefined, - readonly onRight: ((right: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + readonly onEnter: ( + node: BinaryExpression, + prev: TState | undefined, + outerState: TOuterState, + ) => TState, + readonly onLeft: + | (( + left: Expression, + userState: TState, + node: BinaryExpression, + ) => BinaryExpression | void) + | undefined, + readonly onOperator: + | (( + operatorToken: BinaryOperatorToken, + userState: TState, + node: BinaryExpression, + ) => void) + | undefined, + readonly onRight: + | (( + right: Expression, + userState: TState, + node: BinaryExpression, + ) => BinaryExpression | void) + | undefined, readonly onExit: (node: BinaryExpression, userState: TState) => TResult, - readonly foldState: ((userState: TState, result: TResult, side: "left" | "right") => TState) | undefined, - ) { - } + readonly foldState: + | (( + userState: TState, + result: TResult, + side: "left" | "right", + ) => TState) + | undefined, + ) {} } /** @@ -1458,11 +2052,35 @@ class BinaryExpressionStateMachine { */ export function createBinaryExpressionTrampoline( onEnter: (node: BinaryExpression, prev: TState | undefined) => TState, - onLeft: ((left: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, - onOperator: ((operatorToken: BinaryOperatorToken, userState: TState, node: BinaryExpression) => void) | undefined, - onRight: ((right: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + onLeft: + | (( + left: Expression, + userState: TState, + node: BinaryExpression, + ) => BinaryExpression | void) + | undefined, + onOperator: + | (( + operatorToken: BinaryOperatorToken, + userState: TState, + node: BinaryExpression, + ) => void) + | undefined, + onRight: + | (( + right: Expression, + userState: TState, + node: BinaryExpression, + ) => BinaryExpression | void) + | undefined, onExit: (node: BinaryExpression, userState: TState) => TResult, - foldState: ((userState: TState, result: TResult, side: "left" | "right") => TState) | undefined, + foldState: + | (( + userState: TState, + result: TResult, + side: "left" | "right", + ) => TState) + | undefined, ): (node: BinaryExpression) => TResult; /** * Creates a state machine that walks a `BinaryExpression` using the heap to reduce call-stack depth on a large tree. @@ -1476,51 +2094,132 @@ export function createBinaryExpressionTrampoline( * @internal */ export function createBinaryExpressionTrampoline( - onEnter: (node: BinaryExpression, prev: TState | undefined, outerState: TOuterState) => TState, - onLeft: ((left: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, - onOperator: ((operatorToken: BinaryOperatorToken, userState: TState, node: BinaryExpression) => void) | undefined, - onRight: ((right: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + onEnter: ( + node: BinaryExpression, + prev: TState | undefined, + outerState: TOuterState, + ) => TState, + onLeft: + | (( + left: Expression, + userState: TState, + node: BinaryExpression, + ) => BinaryExpression | void) + | undefined, + onOperator: + | (( + operatorToken: BinaryOperatorToken, + userState: TState, + node: BinaryExpression, + ) => void) + | undefined, + onRight: + | (( + right: Expression, + userState: TState, + node: BinaryExpression, + ) => BinaryExpression | void) + | undefined, onExit: (node: BinaryExpression, userState: TState) => TResult, - foldState: ((userState: TState, result: TResult, side: "left" | "right") => TState) | undefined, + foldState: + | (( + userState: TState, + result: TResult, + side: "left" | "right", + ) => TState) + | undefined, ): (node: BinaryExpression, outerState: TOuterState) => TResult; /** @internal */ export function createBinaryExpressionTrampoline( - onEnter: (node: BinaryExpression, prev: TState | undefined, outerState: TOuterState) => TState, - onLeft: ((left: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, - onOperator: ((operatorToken: BinaryOperatorToken, userState: TState, node: BinaryExpression) => void) | undefined, - onRight: ((right: Expression, userState: TState, node: BinaryExpression) => BinaryExpression | void) | undefined, + onEnter: ( + node: BinaryExpression, + prev: TState | undefined, + outerState: TOuterState, + ) => TState, + onLeft: + | (( + left: Expression, + userState: TState, + node: BinaryExpression, + ) => BinaryExpression | void) + | undefined, + onOperator: + | (( + operatorToken: BinaryOperatorToken, + userState: TState, + node: BinaryExpression, + ) => void) + | undefined, + onRight: + | (( + right: Expression, + userState: TState, + node: BinaryExpression, + ) => BinaryExpression | void) + | undefined, onExit: (node: BinaryExpression, userState: TState) => TResult, - foldState: ((userState: TState, result: TResult, side: "left" | "right") => TState) | undefined, + foldState: + | (( + userState: TState, + result: TResult, + side: "left" | "right", + ) => TState) + | undefined, ) { - const machine = new BinaryExpressionStateMachine(onEnter, onLeft, onOperator, onRight, onExit, foldState); + const machine = new BinaryExpressionStateMachine( + onEnter, + onLeft, + onOperator, + onRight, + onExit, + foldState, + ); return trampoline; function trampoline(node: BinaryExpression, outerState: TOuterState) { const resultHolder: { value: TResult; } = { value: undefined! }; - const stateStack: BinaryExpressionState[] = [BinaryExpressionState.enter]; + const stateStack: BinaryExpressionState[] = [ + BinaryExpressionState.enter, + ]; const nodeStack: BinaryExpression[] = [node]; const userStateStack: TState[] = [undefined!]; let stackIndex = 0; while (stateStack[stackIndex] !== BinaryExpressionState.done) { - stackIndex = stateStack[stackIndex](machine, stackIndex, stateStack, nodeStack, userStateStack, resultHolder, outerState); + stackIndex = stateStack[stackIndex]( + machine, + stackIndex, + stateStack, + nodeStack, + userStateStack, + resultHolder, + outerState, + ); } Debug.assertEqual(stackIndex, 0); return resultHolder.value; } } -function isExportOrDefaultKeywordKind(kind: SyntaxKind): kind is SyntaxKind.ExportKeyword | SyntaxKind.DefaultKeyword { - return kind === SyntaxKind.ExportKeyword || kind === SyntaxKind.DefaultKeyword; +function isExportOrDefaultKeywordKind( + kind: SyntaxKind, +): kind is SyntaxKind.ExportKeyword | SyntaxKind.DefaultKeyword { + return ( + kind === SyntaxKind.ExportKeyword || kind === SyntaxKind.DefaultKeyword + ); } /** @internal */ -export function isExportOrDefaultModifier(node: Node): node is ExportKeyword | DefaultKeyword { +export function isExportOrDefaultModifier( + node: Node, +): node is ExportKeyword | DefaultKeyword { const kind = node.kind; return isExportOrDefaultKeywordKind(kind); } /** @internal */ -export function isNonExportDefaultModifier(node: Node): node is Exclude { +export function isNonExportDefaultModifier( + node: Node, +): node is Exclude { const kind = node.kind; return isModifierKind(kind) && !isExportOrDefaultKeywordKind(kind); } @@ -1529,14 +2228,26 @@ export function isNonExportDefaultModifier(node: Node): node is Exclude(factory: NodeFactory, nodes: NodeArray): NodeArray; +export function elideNodes( + factory: NodeFactory, + nodes: NodeArray, +): NodeArray; /** @internal */ -export function elideNodes(factory: NodeFactory, nodes: NodeArray | undefined): NodeArray | undefined; +export function elideNodes( + factory: NodeFactory, + nodes: NodeArray | undefined, +): NodeArray | undefined; /** @internal */ -export function elideNodes(factory: NodeFactory, nodes: NodeArray | undefined): NodeArray | undefined { +export function elideNodes( + factory: NodeFactory, + nodes: NodeArray | undefined, +): NodeArray | undefined { if (nodes === undefined) return undefined; if (nodes.length === 0) return nodes; - return setTextRange(factory.createNodeArray([], nodes.hasTrailingComma), nodes); + return setTextRange( + factory.createNodeArray([], nodes.hasTrailingComma), + nodes, + ); } /** @@ -1544,7 +2255,9 @@ export function elideNodes(factory: NodeFactory, nodes: NodeArra * * @internal */ -export function getNodeForGeneratedName(name: GeneratedIdentifier | GeneratedPrivateIdentifier) { +export function getNodeForGeneratedName( + name: GeneratedIdentifier | GeneratedPrivateIdentifier, +) { const autoGenerate = name.emitNode.autoGenerate; if (autoGenerate.flags & GeneratedIdentifierFlags.Node) { const autoGenerateId = autoGenerate.id; @@ -1555,11 +2268,10 @@ export function getNodeForGeneratedName(name: GeneratedIdentifier | GeneratedPri const autoGenerate = node.emitNode?.autoGenerate; // if "node" is a different generated name (having a different "autoGenerateId"), use it and stop traversing. if ( - isMemberName(node) && ( - autoGenerate === undefined || - !!(autoGenerate.flags & GeneratedIdentifierFlags.Node) && - autoGenerate.id !== autoGenerateId - ) + isMemberName(node) && + (autoGenerate === undefined || + (!!(autoGenerate.flags & GeneratedIdentifierFlags.Node) && + autoGenerate.id !== autoGenerateId)) ) { break; } @@ -1583,24 +2295,58 @@ export function formatGeneratedNamePart(part: string | undefined): string; * * @internal */ -export function formatGeneratedNamePart(part: string | GeneratedNamePart | undefined, generateName: (name: GeneratedIdentifier | GeneratedPrivateIdentifier) => string): string; +export function formatGeneratedNamePart( + part: string | GeneratedNamePart | undefined, + generateName: ( + name: GeneratedIdentifier | GeneratedPrivateIdentifier, + ) => string, +): string; /** @internal */ -export function formatGeneratedNamePart(part: string | GeneratedNamePart | undefined, generateName?: (name: GeneratedIdentifier | GeneratedPrivateIdentifier) => string): string { - return typeof part === "object" ? formatGeneratedName(/*privateName*/ false, part.prefix, part.node, part.suffix, generateName!) : - typeof part === "string" ? part.length > 0 && part.charCodeAt(0) === CharacterCodes.hash ? part.slice(1) : part : - ""; -} - -function formatIdentifier(name: string | Identifier | PrivateIdentifier, generateName?: (name: GeneratedIdentifier | GeneratedPrivateIdentifier) => string) { - return typeof name === "string" ? name : - formatIdentifierWorker(name, Debug.checkDefined(generateName)); +export function formatGeneratedNamePart( + part: string | GeneratedNamePart | undefined, + generateName?: ( + name: GeneratedIdentifier | GeneratedPrivateIdentifier, + ) => string, +): string { + return typeof part === "object" + ? formatGeneratedName( + /*privateName*/ false, + part.prefix, + part.node, + part.suffix, + generateName!, + ) + : typeof part === "string" + ? part.length > 0 && part.charCodeAt(0) === CharacterCodes.hash + ? part.slice(1) + : part + : ""; +} + +function formatIdentifier( + name: string | Identifier | PrivateIdentifier, + generateName?: ( + name: GeneratedIdentifier | GeneratedPrivateIdentifier, + ) => string, +) { + return typeof name === "string" + ? name + : formatIdentifierWorker(name, Debug.checkDefined(generateName)); } -function formatIdentifierWorker(node: Identifier | PrivateIdentifier, generateName: (name: GeneratedIdentifier | GeneratedPrivateIdentifier) => string) { - return isGeneratedPrivateIdentifier(node) ? generateName(node).slice(1) : - isGeneratedIdentifier(node) ? generateName(node) : - isPrivateIdentifier(node) ? (node.escapedText as string).slice(1) : - idText(node); +function formatIdentifierWorker( + node: Identifier | PrivateIdentifier, + generateName: ( + name: GeneratedIdentifier | GeneratedPrivateIdentifier, + ) => string, +) { + return isGeneratedPrivateIdentifier(node) + ? generateName(node).slice(1) + : isGeneratedIdentifier(node) + ? generateName(node) + : isPrivateIdentifier(node) + ? (node.escapedText as string).slice(1) + : idText(node); } /** @@ -1612,7 +2358,12 @@ function formatIdentifierWorker(node: Identifier | PrivateIdentifier, generateNa * * @internal */ -export function formatGeneratedName(privateName: boolean, prefix: string | undefined, baseName: string, suffix: string | undefined): string; +export function formatGeneratedName( + privateName: boolean, + prefix: string | undefined, + baseName: string, + suffix: string | undefined, +): string; /** * Formats a generated name. * @param privateName When `true`, inserts a `#` character at the start of the result. @@ -1623,9 +2374,25 @@ export function formatGeneratedName(privateName: boolean, prefix: string | undef * * @internal */ -export function formatGeneratedName(privateName: boolean, prefix: string | GeneratedNamePart | undefined, baseName: string | Identifier | PrivateIdentifier, suffix: string | GeneratedNamePart | undefined, generateName: (name: GeneratedIdentifier | GeneratedPrivateIdentifier) => string): string; +export function formatGeneratedName( + privateName: boolean, + prefix: string | GeneratedNamePart | undefined, + baseName: string | Identifier | PrivateIdentifier, + suffix: string | GeneratedNamePart | undefined, + generateName: ( + name: GeneratedIdentifier | GeneratedPrivateIdentifier, + ) => string, +): string; /** @internal */ -export function formatGeneratedName(privateName: boolean, prefix: string | GeneratedNamePart | undefined, baseName: string | Identifier | PrivateIdentifier, suffix: string | GeneratedNamePart | undefined, generateName?: (name: GeneratedIdentifier | GeneratedPrivateIdentifier) => string) { +export function formatGeneratedName( + privateName: boolean, + prefix: string | GeneratedNamePart | undefined, + baseName: string | Identifier | PrivateIdentifier, + suffix: string | GeneratedNamePart | undefined, + generateName?: ( + name: GeneratedIdentifier | GeneratedPrivateIdentifier, + ) => string, +) { prefix = formatGeneratedNamePart(prefix, generateName!); suffix = formatGeneratedNamePart(suffix, generateName!); baseName = formatIdentifier(baseName, generateName); @@ -1637,11 +2404,20 @@ export function formatGeneratedName(privateName: boolean, prefix: string | Gener * * @internal */ -export function createAccessorPropertyBackingField(factory: NodeFactory, node: PropertyDeclaration, modifiers: ModifiersArray | undefined, initializer: Expression | undefined) { +export function createAccessorPropertyBackingField( + factory: NodeFactory, + node: PropertyDeclaration, + modifiers: ModifiersArray | undefined, + initializer: Expression | undefined, +) { return factory.updatePropertyDeclaration( node, modifiers, - factory.getGeneratedPrivateNameForNode(node.name, /*prefix*/ undefined, "_accessor_storage"), + factory.getGeneratedPrivateNameForNode( + node.name, + /*prefix*/ undefined, + "_accessor_storage", + ), /*questionOrExclamationToken*/ undefined, /*type*/ undefined, initializer, @@ -1653,7 +2429,13 @@ export function createAccessorPropertyBackingField(factory: NodeFactory, node: P * * @internal */ -export function createAccessorPropertyGetRedirector(factory: NodeFactory, node: PropertyDeclaration, modifiers: readonly Modifier[] | undefined, name: PropertyName, receiver: Expression = factory.createThis()): GetAccessorDeclaration { +export function createAccessorPropertyGetRedirector( + factory: NodeFactory, + node: PropertyDeclaration, + modifiers: readonly Modifier[] | undefined, + name: PropertyName, + receiver: Expression = factory.createThis(), +): GetAccessorDeclaration { return factory.createGetAccessorDeclaration( modifiers, name, @@ -1663,7 +2445,11 @@ export function createAccessorPropertyGetRedirector(factory: NodeFactory, node: factory.createReturnStatement( factory.createPropertyAccessExpression( receiver, - factory.getGeneratedPrivateNameForNode(node.name, /*prefix*/ undefined, "_accessor_storage"), + factory.getGeneratedPrivateNameForNode( + node.name, + /*prefix*/ undefined, + "_accessor_storage", + ), ), ), ]), @@ -1675,21 +2461,33 @@ export function createAccessorPropertyGetRedirector(factory: NodeFactory, node: * * @internal */ -export function createAccessorPropertySetRedirector(factory: NodeFactory, node: PropertyDeclaration, modifiers: readonly Modifier[] | undefined, name: PropertyName, receiver: Expression = factory.createThis()) { +export function createAccessorPropertySetRedirector( + factory: NodeFactory, + node: PropertyDeclaration, + modifiers: readonly Modifier[] | undefined, + name: PropertyName, + receiver: Expression = factory.createThis(), +) { return factory.createSetAccessorDeclaration( modifiers, name, - [factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - "value", - )], + [ + factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + "value", + ), + ], factory.createBlock([ factory.createExpressionStatement( factory.createAssignment( factory.createPropertyAccessExpression( receiver, - factory.getGeneratedPrivateNameForNode(node.name, /*prefix*/ undefined, "_accessor_storage"), + factory.getGeneratedPrivateNameForNode( + node.name, + /*prefix*/ undefined, + "_accessor_storage", + ), ), factory.createIdentifier("value"), ), @@ -1699,7 +2497,9 @@ export function createAccessorPropertySetRedirector(factory: NodeFactory, node: } /** @internal */ -export function findComputedPropertyNameCacheAssignment(name: ComputedPropertyName) { +export function findComputedPropertyNameCacheAssignment( + name: ComputedPropertyName, +) { let node = name.expression; while (true) { node = skipOuterExpressions(node); @@ -1713,18 +2513,27 @@ export function findComputedPropertyNameCacheAssignment(name: ComputedPropertyNa continue; } - if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && isGeneratedIdentifier(node.left)) { - return node as AssignmentExpression & { readonly left: GeneratedIdentifier; }; + if ( + isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && + isGeneratedIdentifier(node.left) + ) { + return node as AssignmentExpression & { + readonly left: GeneratedIdentifier; + }; } break; } } -function isSyntheticParenthesizedExpression(node: Expression): node is ParenthesizedExpression { - return isParenthesizedExpression(node) - && nodeIsSynthesized(node) - && !node.emitNode; +function isSyntheticParenthesizedExpression( + node: Expression, +): node is ParenthesizedExpression { + return ( + isParenthesizedExpression(node) && + nodeIsSynthesized(node) && + !node.emitNode + ); } function flattenCommaListWorker(node: Expression, expressions: Expression[]) { @@ -1773,7 +2582,10 @@ export function containsObjectRestOrSpread(node: AssignmentPattern): boolean { for (const element of getElementsOfBindingOrAssignmentPattern(node)) { const target = getTargetOfBindingOrAssignmentElement(element); if (target && isAssignmentPattern(target)) { - if (target.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { + if ( + target.transformFlags & + TransformFlags.ContainsObjectRestOrSpread + ) { return true; } if (target.transformFlags & TransformFlags.ContainsES2018) { diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 7511678393d2b..b4b4393885eb1 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -171,6 +171,7 @@ import { JSDocCallbackTag, JSDocClassTag, JSDocComment, + JSDocContainer, JSDocDeprecatedTag, JSDocEnumTag, JSDocFunctionType, @@ -236,7 +237,6 @@ import { LanguageVariant, lastOrUndefined, LeftHandSideExpression, - LiteralExpression, LiteralLikeNode, LiteralTypeNode, map, @@ -268,6 +268,7 @@ import { NewExpression, Node, NodeArray, + NodeBase, NodeFactory, NodeFactoryFlags, NodeFlags, @@ -366,6 +367,7 @@ import { TokenFlags, tokenIsIdentifierOrKeyword, tokenIsIdentifierOrKeywordOrGreaterThan, + TokenSyntaxKind, tokenToString, tracing, TransformFlags, @@ -413,10 +415,22 @@ const enum SpeculationKind { } let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node; -let TokenConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node; -let IdentifierConstructor: new (kind: SyntaxKind.Identifier, pos: number, end: number) => Node; -let PrivateIdentifierConstructor: new (kind: SyntaxKind.PrivateIdentifier, pos: number, end: number) => Node; -let SourceFileConstructor: new (kind: SyntaxKind.SourceFile, pos: number, end: number) => Node; +let TokenConstructor: new (kind: TKind, pos: number, end: number) => Token; +let IdentifierConstructor: new ( + kind: SyntaxKind.Identifier, + pos: number, + end: number, +) => Node; +let PrivateIdentifierConstructor: new ( + kind: SyntaxKind.PrivateIdentifier, + pos: number, + end: number, +) => Node; +let SourceFileConstructor: new ( + kind: SyntaxKind.SourceFile, + pos: number, + end: number, +) => Node; /** * NOTE: You should not use this, it is only exported to support `createNode` in `~/src/deprecatedCompat/deprecations.ts`. @@ -424,21 +438,52 @@ let SourceFileConstructor: new (kind: SyntaxKind.SourceFile, pos: number, end: n * @internal */ export const parseBaseNodeFactory: BaseNodeFactory = { - createBaseSourceFileNode: kind => new (SourceFileConstructor || (SourceFileConstructor = objectAllocator.getSourceFileConstructor()))(kind, -1, -1), - createBaseIdentifierNode: kind => new (IdentifierConstructor || (IdentifierConstructor = objectAllocator.getIdentifierConstructor()))(kind, -1, -1), - createBasePrivateIdentifierNode: kind => new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1), - createBaseTokenNode: kind => new (TokenConstructor || (TokenConstructor = objectAllocator.getTokenConstructor()))(kind, -1, -1), - createBaseNode: kind => new (NodeConstructor || (NodeConstructor = objectAllocator.getNodeConstructor()))(kind, -1, -1), + createBaseSourceFileNode: kind => + new (SourceFileConstructor || + (SourceFileConstructor = objectAllocator.getSourceFileConstructor()))(kind, -1, -1), + createBaseIdentifierNode: kind => + new (IdentifierConstructor || + (IdentifierConstructor = objectAllocator.getIdentifierConstructor()))(kind, -1, -1), + createBasePrivateIdentifierNode: kind => + new (PrivateIdentifierConstructor || + (PrivateIdentifierConstructor = objectAllocator.getPrivateIdentifierConstructor()))( + kind, + -1, + -1, + ), + createBaseTokenNode: kind => + new (TokenConstructor ||= objectAllocator.getTokenConstructor())( + kind, + -1, + -1, + ), + createBaseNode: kind => + new (NodeConstructor || + (NodeConstructor = objectAllocator.getNodeConstructor()))( + kind, + -1, + -1, + ), }; /** @internal */ -export const parseNodeFactory: NodeFactory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules, parseBaseNodeFactory); - -function visitNode(cbNode: (node: Node) => T, node: Node | undefined): T | undefined { +export const parseNodeFactory: NodeFactory = createNodeFactory( + NodeFactoryFlags.NoParenthesizerRules, + parseBaseNodeFactory, +); + +function visitNode( + cbNode: (node: Node) => T, + node: Node | undefined, +): T | undefined { return node && cbNode(node); } -function visitNodes(cbNode: (node: Node) => T, cbNodes: ((node: NodeArray) => T | undefined) | undefined, nodes: NodeArray | undefined): T | undefined { +function visitNodes( + cbNode: (node: Node) => T, + cbNodes: ((node: NodeArray) => T | undefined) | undefined, + nodes: NodeArray | undefined, +): T | undefined { if (nodes) { if (cbNodes) { return cbNodes(nodes); @@ -454,35 +499,45 @@ function visitNodes(cbNode: (node: Node) => T, cbNodes: ((node: NodeArray = (node: TNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined) => T | undefined; -type ForEachChildTable = { [TNode in ForEachChildNodes as TNode["kind"]]: ForEachChildFunction; }; +type ForEachChildFunction = ( + node: TNode, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +) => T | undefined; +type ForEachChildTable = { + [TNode in ForEachChildNodes as TNode["kind"]]: ForEachChildFunction; +}; const forEachChildTable: ForEachChildTable = { - [SyntaxKind.QualifiedName]: function forEachChildInQualifiedName(node: QualifiedName, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.right); + [SyntaxKind.QualifiedName]: function forEachChildInQualifiedName( + node: QualifiedName, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); }, - [SyntaxKind.TypeParameter]: function forEachChildInTypeParameter(node: TypeParameterDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.TypeParameter]: function forEachChildInTypeParameter( + node: TypeParameterDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.constraint) || visitNode(cbNode, node.default) || - visitNode(cbNode, node.expression); + visitNode(cbNode, node.expression) + ); }, - [SyntaxKind.ShorthandPropertyAssignment]: function forEachChildInShorthandPropertyAssignment(node: ShorthandPropertyAssignment, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.ShorthandPropertyAssignment]: function forEachChildInShorthandPropertyAssignment( + node: ShorthandPropertyAssignment, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.equalsToken) || - visitNode(cbNode, node.objectAssignmentInitializer); + visitNode(cbNode, node.objectAssignmentInitializer) + ); }, - [SyntaxKind.SpreadAssignment]: function forEachChildInSpreadAssignment(node: SpreadAssignment, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.SpreadAssignment]: function forEachChildInSpreadAssignment( + node: SpreadAssignment, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.Parameter]: function forEachChildInParameter(node: ParameterDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.Parameter]: function forEachChildInParameter( + node: ParameterDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); + visitNode(cbNode, node.initializer) + ); }, - [SyntaxKind.PropertyDeclaration]: function forEachChildInPropertyDeclaration(node: PropertyDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.PropertyDeclaration]: function forEachChildInPropertyDeclaration( + node: PropertyDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); + visitNode(cbNode, node.initializer) + ); }, - [SyntaxKind.PropertySignature]: function forEachChildInPropertySignature(node: PropertySignature, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.PropertySignature]: function forEachChildInPropertySignature( + node: PropertySignature, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); + visitNode(cbNode, node.initializer) + ); }, - [SyntaxKind.PropertyAssignment]: function forEachChildInPropertyAssignment(node: PropertyAssignment, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.PropertyAssignment]: function forEachChildInPropertyAssignment< + T, + >( + node: PropertyAssignment, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.exclamationToken) || - visitNode(cbNode, node.initializer); + visitNode(cbNode, node.initializer) + ); }, - [SyntaxKind.VariableDeclaration]: function forEachChildInVariableDeclaration(node: VariableDeclaration, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.name) || + [SyntaxKind.VariableDeclaration]: function forEachChildInVariableDeclaration( + node: VariableDeclaration, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.name) || visitNode(cbNode, node.exclamationToken) || visitNode(cbNode, node.type) || - visitNode(cbNode, node.initializer); + visitNode(cbNode, node.initializer) + ); }, - [SyntaxKind.BindingElement]: function forEachChildInBindingElement(node: BindingElement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.dotDotDotToken) || + [SyntaxKind.BindingElement]: function forEachChildInBindingElement( + node: BindingElement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); + visitNode(cbNode, node.initializer) + ); }, - [SyntaxKind.IndexSignature]: function forEachChildInIndexSignature(node: IndexSignatureDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.IndexSignature]: function forEachChildInIndexSignature( + node: IndexSignatureDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) + ); }, - [SyntaxKind.ConstructorType]: function forEachChildInConstructorType(node: ConstructorTypeNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.ConstructorType]: function forEachChildInConstructorType( + node: ConstructorTypeNode, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) + ); }, - [SyntaxKind.FunctionType]: function forEachChildInFunctionType(node: FunctionTypeNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.FunctionType]: function forEachChildInFunctionType( + node: FunctionTypeNode, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) + ); }, [SyntaxKind.CallSignature]: forEachChildInCallOrConstructSignature, [SyntaxKind.ConstructSignature]: forEachChildInCallOrConstructSignature, - [SyntaxKind.MethodDeclaration]: function forEachChildInMethodDeclaration(node: MethodDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.MethodDeclaration]: function forEachChildInMethodDeclaration( + node: MethodDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || @@ -590,448 +735,959 @@ const forEachChildTable: ForEachChildTable = { visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); + visitNode(cbNode, node.body) + ); }, - [SyntaxKind.MethodSignature]: function forEachChildInMethodSignature(node: MethodSignature, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.MethodSignature]: function forEachChildInMethodSignature( + node: MethodSignature, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) + ); }, - [SyntaxKind.Constructor]: function forEachChildInConstructor(node: ConstructorDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.Constructor]: function forEachChildInConstructor( + node: ConstructorDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); + visitNode(cbNode, node.body) + ); }, - [SyntaxKind.GetAccessor]: function forEachChildInGetAccessor(node: GetAccessorDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.GetAccessor]: function forEachChildInGetAccessor( + node: GetAccessorDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); + visitNode(cbNode, node.body) + ); }, - [SyntaxKind.SetAccessor]: function forEachChildInSetAccessor(node: SetAccessorDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.SetAccessor]: function forEachChildInSetAccessor( + node: SetAccessorDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); + visitNode(cbNode, node.body) + ); }, - [SyntaxKind.FunctionDeclaration]: function forEachChildInFunctionDeclaration(node: FunctionDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.FunctionDeclaration]: function forEachChildInFunctionDeclaration( + node: FunctionDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); + visitNode(cbNode, node.body) + ); }, - [SyntaxKind.FunctionExpression]: function forEachChildInFunctionExpression(node: FunctionExpression, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.FunctionExpression]: function forEachChildInFunctionExpression< + T, + >( + node: FunctionExpression, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.asteriskToken) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || - visitNode(cbNode, node.body); + visitNode(cbNode, node.body) + ); }, - [SyntaxKind.ArrowFunction]: function forEachChildInArrowFunction(node: ArrowFunction, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.ArrowFunction]: function forEachChildInArrowFunction( + node: ArrowFunction, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode(cbNode, node.type) || visitNode(cbNode, node.equalsGreaterThanToken) || - visitNode(cbNode, node.body); + visitNode(cbNode, node.body) + ); }, - [SyntaxKind.ClassStaticBlockDeclaration]: function forEachChildInClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.body); + [SyntaxKind.ClassStaticBlockDeclaration]: function forEachChildInClassStaticBlockDeclaration( + node: ClassStaticBlockDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.body) + ); }, - [SyntaxKind.TypeReference]: function forEachChildInTypeReference(node: TypeReferenceNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.typeName) || - visitNodes(cbNode, cbNodes, node.typeArguments); + [SyntaxKind.TypeReference]: function forEachChildInTypeReference( + node: TypeReferenceNode, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.typeName) || + visitNodes(cbNode, cbNodes, node.typeArguments) + ); }, - [SyntaxKind.TypePredicate]: function forEachChildInTypePredicate(node: TypePredicateNode, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.assertsModifier) || + [SyntaxKind.TypePredicate]: function forEachChildInTypePredicate( + node: TypePredicateNode, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.assertsModifier) || visitNode(cbNode, node.parameterName) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) + ); }, - [SyntaxKind.TypeQuery]: function forEachChildInTypeQuery(node: TypeQueryNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.exprName) || - visitNodes(cbNode, cbNodes, node.typeArguments); + [SyntaxKind.TypeQuery]: function forEachChildInTypeQuery( + node: TypeQueryNode, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.exprName) || + visitNodes(cbNode, cbNodes, node.typeArguments) + ); }, - [SyntaxKind.TypeLiteral]: function forEachChildInTypeLiteral(node: TypeLiteralNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.TypeLiteral]: function forEachChildInTypeLiteral( + node: TypeLiteralNode, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.members); }, - [SyntaxKind.ArrayType]: function forEachChildInArrayType(node: ArrayTypeNode, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.ArrayType]: function forEachChildInArrayType( + node: ArrayTypeNode, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.elementType); }, - [SyntaxKind.TupleType]: function forEachChildInTupleType(node: TupleTypeNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.TupleType]: function forEachChildInTupleType( + node: TupleTypeNode, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.elements); }, [SyntaxKind.UnionType]: forEachChildInUnionOrIntersectionType, [SyntaxKind.IntersectionType]: forEachChildInUnionOrIntersectionType, - [SyntaxKind.ConditionalType]: function forEachChildInConditionalType(node: ConditionalTypeNode, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.checkType) || + [SyntaxKind.ConditionalType]: function forEachChildInConditionalType( + node: ConditionalTypeNode, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.checkType) || visitNode(cbNode, node.extendsType) || visitNode(cbNode, node.trueType) || - visitNode(cbNode, node.falseType); + visitNode(cbNode, node.falseType) + ); }, - [SyntaxKind.InferType]: function forEachChildInInferType(node: InferTypeNode, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.InferType]: function forEachChildInInferType( + node: InferTypeNode, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.typeParameter); }, - [SyntaxKind.ImportType]: function forEachChildInImportType(node: ImportTypeNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.argument) || + [SyntaxKind.ImportType]: function forEachChildInImportType( + node: ImportTypeNode, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.argument) || visitNode(cbNode, node.attributes) || visitNode(cbNode, node.qualifier) || - visitNodes(cbNode, cbNodes, node.typeArguments); + visitNodes(cbNode, cbNodes, node.typeArguments) + ); }, - [SyntaxKind.ImportTypeAssertionContainer]: function forEachChildInImportTypeAssertionContainer(node: ImportTypeAssertionContainer, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.ImportTypeAssertionContainer]: function forEachChildInImportTypeAssertionContainer( + node: ImportTypeAssertionContainer, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.assertClause); }, [SyntaxKind.ParenthesizedType]: forEachChildInParenthesizedTypeOrTypeOperator, [SyntaxKind.TypeOperator]: forEachChildInParenthesizedTypeOrTypeOperator, - [SyntaxKind.IndexedAccessType]: function forEachChildInIndexedAccessType(node: IndexedAccessTypeNode, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.objectType) || - visitNode(cbNode, node.indexType); + [SyntaxKind.IndexedAccessType]: function forEachChildInIndexedAccessType( + node: IndexedAccessTypeNode, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.objectType) || + visitNode(cbNode, node.indexType) + ); }, - [SyntaxKind.MappedType]: function forEachChildInMappedType(node: MappedTypeNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.readonlyToken) || + [SyntaxKind.MappedType]: function forEachChildInMappedType( + node: MappedTypeNode, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.readonlyToken) || visitNode(cbNode, node.typeParameter) || visitNode(cbNode, node.nameType) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.type) || - visitNodes(cbNode, cbNodes, node.members); + visitNodes(cbNode, cbNodes, node.members) + ); }, - [SyntaxKind.LiteralType]: function forEachChildInLiteralType(node: LiteralTypeNode, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.LiteralType]: function forEachChildInLiteralType( + node: LiteralTypeNode, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.literal); }, - [SyntaxKind.NamedTupleMember]: function forEachChildInNamedTupleMember(node: NamedTupleMember, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.dotDotDotToken) || + [SyntaxKind.NamedTupleMember]: function forEachChildInNamedTupleMember( + node: NamedTupleMember, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.dotDotDotToken) || visitNode(cbNode, node.name) || visitNode(cbNode, node.questionToken) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) + ); }, [SyntaxKind.ObjectBindingPattern]: forEachChildInObjectOrArrayBindingPattern, [SyntaxKind.ArrayBindingPattern]: forEachChildInObjectOrArrayBindingPattern, - [SyntaxKind.ArrayLiteralExpression]: function forEachChildInArrayLiteralExpression(node: ArrayLiteralExpression, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.ArrayLiteralExpression]: function forEachChildInArrayLiteralExpression( + node: ArrayLiteralExpression, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.elements); }, - [SyntaxKind.ObjectLiteralExpression]: function forEachChildInObjectLiteralExpression(node: ObjectLiteralExpression, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.ObjectLiteralExpression]: function forEachChildInObjectLiteralExpression( + node: ObjectLiteralExpression, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.properties); }, - [SyntaxKind.PropertyAccessExpression]: function forEachChildInPropertyAccessExpression(node: PropertyAccessExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || + [SyntaxKind.PropertyAccessExpression]: function forEachChildInPropertyAccessExpression( + node: PropertyAccessExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || - visitNode(cbNode, node.name); + visitNode(cbNode, node.name) + ); }, - [SyntaxKind.ElementAccessExpression]: function forEachChildInElementAccessExpression(node: ElementAccessExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || + [SyntaxKind.ElementAccessExpression]: function forEachChildInElementAccessExpression( + node: ElementAccessExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.expression) || visitNode(cbNode, node.questionDotToken) || - visitNode(cbNode, node.argumentExpression); + visitNode(cbNode, node.argumentExpression) + ); }, [SyntaxKind.CallExpression]: forEachChildInCallOrNewExpression, [SyntaxKind.NewExpression]: forEachChildInCallOrNewExpression, - [SyntaxKind.TaggedTemplateExpression]: function forEachChildInTaggedTemplateExpression(node: TaggedTemplateExpression, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tag) || + [SyntaxKind.TaggedTemplateExpression]: function forEachChildInTaggedTemplateExpression( + node: TaggedTemplateExpression, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.tag) || visitNode(cbNode, node.questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || - visitNode(cbNode, node.template); + visitNode(cbNode, node.template) + ); }, - [SyntaxKind.TypeAssertionExpression]: function forEachChildInTypeAssertionExpression(node: TypeAssertion, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.type) || - visitNode(cbNode, node.expression); + [SyntaxKind.TypeAssertionExpression]: function forEachChildInTypeAssertionExpression( + node: TypeAssertion, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.type) || + visitNode(cbNode, node.expression) + ); }, - [SyntaxKind.ParenthesizedExpression]: function forEachChildInParenthesizedExpression(node: ParenthesizedExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.ParenthesizedExpression]: function forEachChildInParenthesizedExpression( + node: ParenthesizedExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.DeleteExpression]: function forEachChildInDeleteExpression(node: DeleteExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.DeleteExpression]: function forEachChildInDeleteExpression( + node: DeleteExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.TypeOfExpression]: function forEachChildInTypeOfExpression(node: TypeOfExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.TypeOfExpression]: function forEachChildInTypeOfExpression( + node: TypeOfExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.VoidExpression]: function forEachChildInVoidExpression(node: VoidExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.VoidExpression]: function forEachChildInVoidExpression( + node: VoidExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.PrefixUnaryExpression]: function forEachChildInPrefixUnaryExpression(node: PrefixUnaryExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.PrefixUnaryExpression]: function forEachChildInPrefixUnaryExpression( + node: PrefixUnaryExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.operand); }, - [SyntaxKind.YieldExpression]: function forEachChildInYieldExpression(node: YieldExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.asteriskToken) || - visitNode(cbNode, node.expression); + [SyntaxKind.YieldExpression]: function forEachChildInYieldExpression( + node: YieldExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.asteriskToken) || + visitNode(cbNode, node.expression) + ); }, - [SyntaxKind.AwaitExpression]: function forEachChildInAwaitExpression(node: AwaitExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.AwaitExpression]: function forEachChildInAwaitExpression( + node: AwaitExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.PostfixUnaryExpression]: function forEachChildInPostfixUnaryExpression(node: PostfixUnaryExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.PostfixUnaryExpression]: function forEachChildInPostfixUnaryExpression( + node: PostfixUnaryExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.operand); }, - [SyntaxKind.BinaryExpression]: function forEachChildInBinaryExpression(node: BinaryExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.left) || + [SyntaxKind.BinaryExpression]: function forEachChildInBinaryExpression( + node: BinaryExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.left) || visitNode(cbNode, node.operatorToken) || - visitNode(cbNode, node.right); + visitNode(cbNode, node.right) + ); }, - [SyntaxKind.AsExpression]: function forEachChildInAsExpression(node: AsExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.type); + [SyntaxKind.AsExpression]: function forEachChildInAsExpression( + node: AsExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.expression) || visitNode(cbNode, node.type) + ); }, - [SyntaxKind.NonNullExpression]: function forEachChildInNonNullExpression(node: NonNullExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.NonNullExpression]: function forEachChildInNonNullExpression( + node: NonNullExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.SatisfiesExpression]: function forEachChildInSatisfiesExpression(node: SatisfiesExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type); + [SyntaxKind.SatisfiesExpression]: function forEachChildInSatisfiesExpression( + node: SatisfiesExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.type) + ); }, - [SyntaxKind.MetaProperty]: function forEachChildInMetaProperty(node: MetaProperty, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.MetaProperty]: function forEachChildInMetaProperty( + node: MetaProperty, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.name); }, - [SyntaxKind.ConditionalExpression]: function forEachChildInConditionalExpression(node: ConditionalExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.condition) || + [SyntaxKind.ConditionalExpression]: function forEachChildInConditionalExpression( + node: ConditionalExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.condition) || visitNode(cbNode, node.questionToken) || visitNode(cbNode, node.whenTrue) || visitNode(cbNode, node.colonToken) || - visitNode(cbNode, node.whenFalse); + visitNode(cbNode, node.whenFalse) + ); }, - [SyntaxKind.SpreadElement]: function forEachChildInSpreadElement(node: SpreadElement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.SpreadElement]: function forEachChildInSpreadElement( + node: SpreadElement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, [SyntaxKind.Block]: forEachChildInBlock, [SyntaxKind.ModuleBlock]: forEachChildInBlock, - [SyntaxKind.SourceFile]: function forEachChildInSourceFile(node: SourceFile, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.statements) || - visitNode(cbNode, node.endOfFileToken); + [SyntaxKind.SourceFile]: function forEachChildInSourceFile( + node: SourceFile, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.statements) || + visitNode(cbNode, node.endOfFileToken) + ); }, - [SyntaxKind.VariableStatement]: function forEachChildInVariableStatement(node: VariableStatement, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.declarationList); + [SyntaxKind.VariableStatement]: function forEachChildInVariableStatement( + node: VariableStatement, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.declarationList) + ); }, - [SyntaxKind.VariableDeclarationList]: function forEachChildInVariableDeclarationList(node: VariableDeclarationList, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.VariableDeclarationList]: function forEachChildInVariableDeclarationList( + node: VariableDeclarationList, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.declarations); }, - [SyntaxKind.ExpressionStatement]: function forEachChildInExpressionStatement(node: ExpressionStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.ExpressionStatement]: function forEachChildInExpressionStatement( + node: ExpressionStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.IfStatement]: function forEachChildInIfStatement(node: IfStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || + [SyntaxKind.IfStatement]: function forEachChildInIfStatement( + node: IfStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.expression) || visitNode(cbNode, node.thenStatement) || - visitNode(cbNode, node.elseStatement); + visitNode(cbNode, node.elseStatement) + ); }, - [SyntaxKind.DoStatement]: function forEachChildInDoStatement(node: DoStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.statement) || - visitNode(cbNode, node.expression); + [SyntaxKind.DoStatement]: function forEachChildInDoStatement( + node: DoStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.statement) || + visitNode(cbNode, node.expression) + ); }, - [SyntaxKind.WhileStatement]: function forEachChildInWhileStatement(node: WhileStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); + [SyntaxKind.WhileStatement]: function forEachChildInWhileStatement( + node: WhileStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement) + ); }, - [SyntaxKind.ForStatement]: function forEachChildInForStatement(node: ForStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.initializer) || + [SyntaxKind.ForStatement]: function forEachChildInForStatement( + node: ForStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.initializer) || visitNode(cbNode, node.condition) || visitNode(cbNode, node.incrementor) || - visitNode(cbNode, node.statement); + visitNode(cbNode, node.statement) + ); }, - [SyntaxKind.ForInStatement]: function forEachChildInForInStatement(node: ForInStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.initializer) || + [SyntaxKind.ForInStatement]: function forEachChildInForInStatement( + node: ForInStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); + visitNode(cbNode, node.statement) + ); }, - [SyntaxKind.ForOfStatement]: function forEachChildInForOfStatement(node: ForOfStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.awaitModifier) || + [SyntaxKind.ForOfStatement]: function forEachChildInForOfStatement( + node: ForOfStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.awaitModifier) || visitNode(cbNode, node.initializer) || visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); + visitNode(cbNode, node.statement) + ); }, [SyntaxKind.ContinueStatement]: forEachChildInContinueOrBreakStatement, [SyntaxKind.BreakStatement]: forEachChildInContinueOrBreakStatement, - [SyntaxKind.ReturnStatement]: function forEachChildInReturnStatement(node: ReturnStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.ReturnStatement]: function forEachChildInReturnStatement( + node: ReturnStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.WithStatement]: function forEachChildInWithStatement(node: WithStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.statement); + [SyntaxKind.WithStatement]: function forEachChildInWithStatement( + node: WithStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.statement) + ); }, - [SyntaxKind.SwitchStatement]: function forEachChildInSwitchStatement(node: SwitchStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.caseBlock); + [SyntaxKind.SwitchStatement]: function forEachChildInSwitchStatement( + node: SwitchStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.caseBlock) + ); }, - [SyntaxKind.CaseBlock]: function forEachChildInCaseBlock(node: CaseBlock, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.CaseBlock]: function forEachChildInCaseBlock( + node: CaseBlock, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.clauses); }, - [SyntaxKind.CaseClause]: function forEachChildInCaseClause(node: CaseClause, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || - visitNodes(cbNode, cbNodes, node.statements); + [SyntaxKind.CaseClause]: function forEachChildInCaseClause( + node: CaseClause, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.statements) + ); }, - [SyntaxKind.DefaultClause]: function forEachChildInDefaultClause(node: DefaultClause, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.DefaultClause]: function forEachChildInDefaultClause( + node: DefaultClause, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.statements); }, - [SyntaxKind.LabeledStatement]: function forEachChildInLabeledStatement(node: LabeledStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.label) || - visitNode(cbNode, node.statement); + [SyntaxKind.LabeledStatement]: function forEachChildInLabeledStatement( + node: LabeledStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.label) || visitNode(cbNode, node.statement) + ); }, - [SyntaxKind.ThrowStatement]: function forEachChildInThrowStatement(node: ThrowStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.ThrowStatement]: function forEachChildInThrowStatement( + node: ThrowStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.TryStatement]: function forEachChildInTryStatement(node: TryStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tryBlock) || + [SyntaxKind.TryStatement]: function forEachChildInTryStatement( + node: TryStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.tryBlock) || visitNode(cbNode, node.catchClause) || - visitNode(cbNode, node.finallyBlock); + visitNode(cbNode, node.finallyBlock) + ); }, - [SyntaxKind.CatchClause]: function forEachChildInCatchClause(node: CatchClause, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.variableDeclaration) || - visitNode(cbNode, node.block); + [SyntaxKind.CatchClause]: function forEachChildInCatchClause( + node: CatchClause, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.variableDeclaration) || + visitNode(cbNode, node.block) + ); }, - [SyntaxKind.Decorator]: function forEachChildInDecorator(node: Decorator, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.Decorator]: function forEachChildInDecorator( + node: Decorator, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, [SyntaxKind.ClassDeclaration]: forEachChildInClassDeclarationOrExpression, [SyntaxKind.ClassExpression]: forEachChildInClassDeclarationOrExpression, - [SyntaxKind.InterfaceDeclaration]: function forEachChildInInterfaceDeclaration(node: InterfaceDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.InterfaceDeclaration]: function forEachChildInInterfaceDeclaration( + node: InterfaceDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || - visitNodes(cbNode, cbNodes, node.members); + visitNodes(cbNode, cbNodes, node.members) + ); }, - [SyntaxKind.TypeAliasDeclaration]: function forEachChildInTypeAliasDeclaration(node: TypeAliasDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.TypeAliasDeclaration]: function forEachChildInTypeAliasDeclaration( + node: TypeAliasDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) + ); }, - [SyntaxKind.EnumDeclaration]: function forEachChildInEnumDeclaration(node: EnumDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.EnumDeclaration]: function forEachChildInEnumDeclaration( + node: EnumDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || - visitNodes(cbNode, cbNodes, node.members); + visitNodes(cbNode, cbNodes, node.members) + ); }, - [SyntaxKind.EnumMember]: function forEachChildInEnumMember(node: EnumMember, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); + [SyntaxKind.EnumMember]: function forEachChildInEnumMember( + node: EnumMember, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer) + ); }, - [SyntaxKind.ModuleDeclaration]: function forEachChildInModuleDeclaration(node: ModuleDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.ModuleDeclaration]: function forEachChildInModuleDeclaration( + node: ModuleDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.body); + visitNode(cbNode, node.body) + ); }, - [SyntaxKind.ImportEqualsDeclaration]: function forEachChildInImportEqualsDeclaration(node: ImportEqualsDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.ImportEqualsDeclaration]: function forEachChildInImportEqualsDeclaration( + node: ImportEqualsDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || - visitNode(cbNode, node.moduleReference); + visitNode(cbNode, node.moduleReference) + ); }, - [SyntaxKind.ImportDeclaration]: function forEachChildInImportDeclaration(node: ImportDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.ImportDeclaration]: function forEachChildInImportDeclaration( + node: ImportDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.importClause) || visitNode(cbNode, node.moduleSpecifier) || - visitNode(cbNode, node.attributes); + visitNode(cbNode, node.attributes) + ); }, - [SyntaxKind.ImportClause]: function forEachChildInImportClause(node: ImportClause, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.namedBindings); + [SyntaxKind.ImportClause]: function forEachChildInImportClause( + node: ImportClause, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.name) || + visitNode(cbNode, node.namedBindings) + ); }, - [SyntaxKind.ImportAttributes]: function forEachChildInImportAttributes(node: ImportAttributes, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.ImportAttributes]: function forEachChildInImportAttributes( + node: ImportAttributes, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.elements); }, - [SyntaxKind.ImportAttribute]: function forEachChildInImportAttribute(node: ImportAttribute, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.value); + [SyntaxKind.ImportAttribute]: function forEachChildInImportAttribute( + node: ImportAttribute, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return visitNode(cbNode, node.name) || visitNode(cbNode, node.value); }, - [SyntaxKind.NamespaceExportDeclaration]: function forEachChildInNamespaceExportDeclaration(node: NamespaceExportDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.name); + [SyntaxKind.NamespaceExportDeclaration]: function forEachChildInNamespaceExportDeclaration( + node: NamespaceExportDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.name) + ); }, - [SyntaxKind.NamespaceImport]: function forEachChildInNamespaceImport(node: NamespaceImport, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.NamespaceImport]: function forEachChildInNamespaceImport( + node: NamespaceImport, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.name); }, - [SyntaxKind.NamespaceExport]: function forEachChildInNamespaceExport(node: NamespaceExport, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.NamespaceExport]: function forEachChildInNamespaceExport( + node: NamespaceExport, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.name); }, [SyntaxKind.NamedImports]: forEachChildInNamedImportsOrExports, [SyntaxKind.NamedExports]: forEachChildInNamedImportsOrExports, - [SyntaxKind.ExportDeclaration]: function forEachChildInExportDeclaration(node: ExportDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || + [SyntaxKind.ExportDeclaration]: function forEachChildInExportDeclaration( + node: ExportDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.exportClause) || visitNode(cbNode, node.moduleSpecifier) || - visitNode(cbNode, node.attributes); + visitNode(cbNode, node.attributes) + ); }, [SyntaxKind.ImportSpecifier]: forEachChildInImportOrExportSpecifier, [SyntaxKind.ExportSpecifier]: forEachChildInImportOrExportSpecifier, - [SyntaxKind.ExportAssignment]: function forEachChildInExportAssignment(node: ExportAssignment, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.expression); + [SyntaxKind.ExportAssignment]: function forEachChildInExportAssignment( + node: ExportAssignment, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || + visitNode(cbNode, node.expression) + ); }, - [SyntaxKind.TemplateExpression]: function forEachChildInTemplateExpression(node: TemplateExpression, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.head) || - visitNodes(cbNode, cbNodes, node.templateSpans); + [SyntaxKind.TemplateExpression]: function forEachChildInTemplateExpression< + T, + >( + node: TemplateExpression, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans) + ); }, - [SyntaxKind.TemplateSpan]: function forEachChildInTemplateSpan(node: TemplateSpan, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || - visitNode(cbNode, node.literal); + [SyntaxKind.TemplateSpan]: function forEachChildInTemplateSpan( + node: TemplateSpan, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.expression) || + visitNode(cbNode, node.literal) + ); }, - [SyntaxKind.TemplateLiteralType]: function forEachChildInTemplateLiteralType(node: TemplateLiteralTypeNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.head) || - visitNodes(cbNode, cbNodes, node.templateSpans); + [SyntaxKind.TemplateLiteralType]: function forEachChildInTemplateLiteralType( + node: TemplateLiteralTypeNode, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.head) || + visitNodes(cbNode, cbNodes, node.templateSpans) + ); }, - [SyntaxKind.TemplateLiteralTypeSpan]: function forEachChildInTemplateLiteralTypeSpan(node: TemplateLiteralTypeSpan, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.type) || - visitNode(cbNode, node.literal); + [SyntaxKind.TemplateLiteralTypeSpan]: function forEachChildInTemplateLiteralTypeSpan( + node: TemplateLiteralTypeSpan, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.type) || visitNode(cbNode, node.literal) + ); }, - [SyntaxKind.ComputedPropertyName]: function forEachChildInComputedPropertyName(node: ComputedPropertyName, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.ComputedPropertyName]: function forEachChildInComputedPropertyName( + node: ComputedPropertyName, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.HeritageClause]: function forEachChildInHeritageClause(node: HeritageClause, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.HeritageClause]: function forEachChildInHeritageClause( + node: HeritageClause, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.types); }, - [SyntaxKind.ExpressionWithTypeArguments]: function forEachChildInExpressionWithTypeArguments(node: ExpressionWithTypeArguments, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || - visitNodes(cbNode, cbNodes, node.typeArguments); + [SyntaxKind.ExpressionWithTypeArguments]: function forEachChildInExpressionWithTypeArguments( + node: ExpressionWithTypeArguments, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.expression) || + visitNodes(cbNode, cbNodes, node.typeArguments) + ); }, - [SyntaxKind.ExternalModuleReference]: function forEachChildInExternalModuleReference(node: ExternalModuleReference, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.ExternalModuleReference]: function forEachChildInExternalModuleReference( + node: ExternalModuleReference, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.MissingDeclaration]: function forEachChildInMissingDeclaration(node: MissingDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.MissingDeclaration]: function forEachChildInMissingDeclaration< + T, + >( + node: MissingDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.modifiers); }, - [SyntaxKind.CommaListExpression]: function forEachChildInCommaListExpression(node: CommaListExpression, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.CommaListExpression]: function forEachChildInCommaListExpression( + node: CommaListExpression, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.elements); }, - [SyntaxKind.JsxElement]: function forEachChildInJsxElement(node: JsxElement, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.openingElement) || + [SyntaxKind.JsxElement]: function forEachChildInJsxElement( + node: JsxElement, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.openingElement) || visitNodes(cbNode, cbNodes, node.children) || - visitNode(cbNode, node.closingElement); + visitNode(cbNode, node.closingElement) + ); }, - [SyntaxKind.JsxFragment]: function forEachChildInJsxFragment(node: JsxFragment, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.openingFragment) || + [SyntaxKind.JsxFragment]: function forEachChildInJsxFragment( + node: JsxFragment, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.openingFragment) || visitNodes(cbNode, cbNodes, node.children) || - visitNode(cbNode, node.closingFragment); + visitNode(cbNode, node.closingFragment) + ); }, [SyntaxKind.JsxSelfClosingElement]: forEachChildInJsxOpeningOrSelfClosingElement, [SyntaxKind.JsxOpeningElement]: forEachChildInJsxOpeningOrSelfClosingElement, - [SyntaxKind.JsxAttributes]: function forEachChildInJsxAttributes(node: JsxAttributes, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.JsxAttributes]: function forEachChildInJsxAttributes( + node: JsxAttributes, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNodes(cbNode, cbNodes, node.properties); }, - [SyntaxKind.JsxAttribute]: function forEachChildInJsxAttribute(node: JsxAttribute, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.name) || - visitNode(cbNode, node.initializer); + [SyntaxKind.JsxAttribute]: function forEachChildInJsxAttribute( + node: JsxAttribute, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer) + ); }, - [SyntaxKind.JsxSpreadAttribute]: function forEachChildInJsxSpreadAttribute(node: JsxSpreadAttribute, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.JsxSpreadAttribute]: function forEachChildInJsxSpreadAttribute< + T, + >( + node: JsxSpreadAttribute, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.expression); }, - [SyntaxKind.JsxExpression]: function forEachChildInJsxExpression(node: JsxExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.dotDotDotToken) || - visitNode(cbNode, node.expression); + [SyntaxKind.JsxExpression]: function forEachChildInJsxExpression( + node: JsxExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.expression) + ); }, - [SyntaxKind.JsxClosingElement]: function forEachChildInJsxClosingElement(node: JsxClosingElement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.JsxClosingElement]: function forEachChildInJsxClosingElement( + node: JsxClosingElement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.tagName); }, - [SyntaxKind.JsxNamespacedName]: function forEachChildInJsxNamespacedName(node: JsxNamespacedName, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.namespace) || - visitNode(cbNode, node.name); + [SyntaxKind.JsxNamespacedName]: function forEachChildInJsxNamespacedName( + node: JsxNamespacedName, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.namespace) || visitNode(cbNode, node.name) + ); }, [SyntaxKind.OptionalType]: forEachChildInOptionalRestOrJSDocParameterModifier, [SyntaxKind.RestType]: forEachChildInOptionalRestOrJSDocParameterModifier, @@ -1040,64 +1696,147 @@ const forEachChildTable: ForEachChildTable = { [SyntaxKind.JSDocNullableType]: forEachChildInOptionalRestOrJSDocParameterModifier, [SyntaxKind.JSDocOptionalType]: forEachChildInOptionalRestOrJSDocParameterModifier, [SyntaxKind.JSDocVariadicType]: forEachChildInOptionalRestOrJSDocParameterModifier, - [SyntaxKind.JSDocFunctionType]: function forEachChildInJSDocFunctionType(node: JSDocFunctionType, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); + [SyntaxKind.JSDocFunctionType]: function forEachChildInJSDocFunctionType( + node: JSDocFunctionType, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.parameters) || + visitNode(cbNode, node.type) + ); }, - [SyntaxKind.JSDoc]: function forEachChildInJSDoc(node: JSDoc, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) - || visitNodes(cbNode, cbNodes, node.tags); + [SyntaxKind.JSDoc]: function forEachChildInJSDoc( + node: JSDoc, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment)) || + visitNodes(cbNode, cbNodes, node.tags) + ); }, - [SyntaxKind.JSDocSeeTag]: function forEachChildInJSDocSeeTag(node: JSDocSeeTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tagName) || + [SyntaxKind.JSDocSeeTag]: function forEachChildInJSDocSeeTag( + node: JSDocSeeTag, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.tagName) || visitNode(cbNode, node.name) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment)) + ); }, - [SyntaxKind.JSDocNameReference]: function forEachChildInJSDocNameReference(node: JSDocNameReference, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.JSDocNameReference]: function forEachChildInJSDocNameReference< + T, + >( + node: JSDocNameReference, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return visitNode(cbNode, node.name); }, - [SyntaxKind.JSDocMemberName]: function forEachChildInJSDocMemberName(node: JSDocMemberName, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.left) || - visitNode(cbNode, node.right); + [SyntaxKind.JSDocMemberName]: function forEachChildInJSDocMemberName( + node: JSDocMemberName, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return visitNode(cbNode, node.left) || visitNode(cbNode, node.right); }, [SyntaxKind.JSDocParameterTag]: forEachChildInJSDocParameterOrPropertyTag, [SyntaxKind.JSDocPropertyTag]: forEachChildInJSDocParameterOrPropertyTag, - [SyntaxKind.JSDocAuthorTag]: function forEachChildInJSDocAuthorTag(node: JSDocAuthorTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tagName) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + [SyntaxKind.JSDocAuthorTag]: function forEachChildInJSDocAuthorTag( + node: JSDocAuthorTag, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.tagName) || + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment)) + ); }, - [SyntaxKind.JSDocImplementsTag]: function forEachChildInJSDocImplementsTag(node: JSDocImplementsTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tagName) || + [SyntaxKind.JSDocImplementsTag]: function forEachChildInJSDocImplementsTag< + T, + >( + node: JSDocImplementsTag, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.tagName) || visitNode(cbNode, node.class) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment)) + ); }, - [SyntaxKind.JSDocAugmentsTag]: function forEachChildInJSDocAugmentsTag(node: JSDocAugmentsTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tagName) || + [SyntaxKind.JSDocAugmentsTag]: function forEachChildInJSDocAugmentsTag( + node: JSDocAugmentsTag, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.tagName) || visitNode(cbNode, node.class) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment)) + ); }, - [SyntaxKind.JSDocTemplateTag]: function forEachChildInJSDocTemplateTag(node: JSDocTemplateTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tagName) || + [SyntaxKind.JSDocTemplateTag]: function forEachChildInJSDocTemplateTag( + node: JSDocTemplateTag, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.tagName) || visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment)) + ); }, - [SyntaxKind.JSDocTypedefTag]: function forEachChildInJSDocTypedefTag(node: JSDocTypedefTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tagName) || + [SyntaxKind.JSDocTypedefTag]: function forEachChildInJSDocTypedefTag( + node: JSDocTypedefTag, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.tagName) || (node.typeExpression && node.typeExpression.kind === SyntaxKind.JSDocTypeExpression ? visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)) + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment)) : visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment))); + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment))) + ); }, - [SyntaxKind.JSDocCallbackTag]: function forEachChildInJSDocCallbackTag(node: JSDocCallbackTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tagName) || + [SyntaxKind.JSDocCallbackTag]: function forEachChildInJSDocCallbackTag( + node: JSDocCallbackTag, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + visitNode(cbNode, node.tagName) || visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment)) + ); }, [SyntaxKind.JSDocReturnTag]: forEachChildInJSDocTypeLikeTag, [SyntaxKind.JSDocTypeTag]: forEachChildInJSDocTypeLikeTag, @@ -1106,15 +1845,25 @@ const forEachChildTable: ForEachChildTable = { [SyntaxKind.JSDocSatisfiesTag]: forEachChildInJSDocTypeLikeTag, [SyntaxKind.JSDocThrowsTag]: forEachChildInJSDocTypeLikeTag, [SyntaxKind.JSDocOverloadTag]: forEachChildInJSDocTypeLikeTag, - [SyntaxKind.JSDocSignature]: function forEachChildInJSDocSignature(node: JSDocSignature, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return forEach(node.typeParameters, cbNode) || + [SyntaxKind.JSDocSignature]: function forEachChildInJSDocSignature( + node: JSDocSignature, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { + return ( + forEach(node.typeParameters, cbNode) || forEach(node.parameters, cbNode) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) + ); }, [SyntaxKind.JSDocLink]: forEachChildInJSDocLinkCodeOrPlain, [SyntaxKind.JSDocLinkCode]: forEachChildInJSDocLinkCodeOrPlain, [SyntaxKind.JSDocLinkPlain]: forEachChildInJSDocLinkCodeOrPlain, - [SyntaxKind.JSDocTypeLiteral]: function forEachChildInJSDocTypeLiteral(node: JSDocTypeLiteral, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { + [SyntaxKind.JSDocTypeLiteral]: function forEachChildInJSDocTypeLiteral( + node: JSDocTypeLiteral, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, + ): T | undefined { return forEach(node.jsDocPropertyTags, cbNode); }, [SyntaxKind.JSDocTag]: forEachChildInJSDocTag, @@ -1130,91 +1879,202 @@ const forEachChildTable: ForEachChildTable = { // shared -function forEachChildInCallOrConstructSignature(node: CallSignatureDeclaration | ConstructSignatureDeclaration, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.typeParameters) || +function forEachChildInCallOrConstructSignature( + node: CallSignatureDeclaration | ConstructSignatureDeclaration, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || - visitNode(cbNode, node.type); + visitNode(cbNode, node.type) + ); } -function forEachChildInUnionOrIntersectionType(node: UnionTypeNode | IntersectionTypeNode, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { +function forEachChildInUnionOrIntersectionType( + node: UnionTypeNode | IntersectionTypeNode, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { return visitNodes(cbNode, cbNodes, node.types); } -function forEachChildInParenthesizedTypeOrTypeOperator(node: ParenthesizedTypeNode | TypeOperatorNode, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { +function forEachChildInParenthesizedTypeOrTypeOperator( + node: ParenthesizedTypeNode | TypeOperatorNode, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { return visitNode(cbNode, node.type); } -function forEachChildInObjectOrArrayBindingPattern(node: BindingPattern, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { +function forEachChildInObjectOrArrayBindingPattern( + node: BindingPattern, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { return visitNodes(cbNode, cbNodes, node.elements); } -function forEachChildInCallOrNewExpression(node: CallExpression | NewExpression, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.expression) || +function forEachChildInCallOrNewExpression( + node: CallExpression | NewExpression, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { + return ( + visitNode(cbNode, node.expression) || // TODO: should we separate these branches out? visitNode(cbNode, (node as CallExpression).questionDotToken) || visitNodes(cbNode, cbNodes, node.typeArguments) || - visitNodes(cbNode, cbNodes, node.arguments); + visitNodes(cbNode, cbNodes, node.arguments) + ); } -function forEachChildInBlock(node: Block | ModuleBlock, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { +function forEachChildInBlock( + node: Block | ModuleBlock, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { return visitNodes(cbNode, cbNodes, node.statements); } -function forEachChildInContinueOrBreakStatement(node: ContinueStatement | BreakStatement, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { +function forEachChildInContinueOrBreakStatement( + node: ContinueStatement | BreakStatement, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { return visitNode(cbNode, node.label); } -function forEachChildInClassDeclarationOrExpression(node: ClassDeclaration | ClassExpression, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNodes(cbNode, cbNodes, node.modifiers) || +function forEachChildInClassDeclarationOrExpression( + node: ClassDeclaration | ClassExpression, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { + return ( + visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, node.name) || visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.heritageClauses) || - visitNodes(cbNode, cbNodes, node.members); + visitNodes(cbNode, cbNodes, node.members) + ); } -function forEachChildInNamedImportsOrExports(node: NamedImports | NamedExports, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { +function forEachChildInNamedImportsOrExports( + node: NamedImports | NamedExports, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { return visitNodes(cbNode, cbNodes, node.elements); } -function forEachChildInImportOrExportSpecifier(node: ImportSpecifier | ExportSpecifier, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.propertyName) || - visitNode(cbNode, node.name); +function forEachChildInImportOrExportSpecifier( + node: ImportSpecifier | ExportSpecifier, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { + return visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name); } -function forEachChildInJsxOpeningOrSelfClosingElement(node: JsxOpeningLikeElement, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tagName) || +function forEachChildInJsxOpeningOrSelfClosingElement( + node: JsxOpeningLikeElement, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { + return ( + visitNode(cbNode, node.tagName) || visitNodes(cbNode, cbNodes, node.typeArguments) || - visitNode(cbNode, node.attributes); + visitNode(cbNode, node.attributes) + ); } -function forEachChildInOptionalRestOrJSDocParameterModifier(node: OptionalTypeNode | RestTypeNode | JSDocTypeExpression | JSDocNullableType | JSDocNonNullableType | JSDocOptionalType | JSDocVariadicType, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { +function forEachChildInOptionalRestOrJSDocParameterModifier( + node: + | OptionalTypeNode + | RestTypeNode + | JSDocTypeExpression + | JSDocNullableType + | JSDocNonNullableType + | JSDocOptionalType + | JSDocVariadicType, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { return visitNode(cbNode, node.type); } -function forEachChildInJSDocParameterOrPropertyTag(node: JSDocParameterTag | JSDocPropertyTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tagName) || +function forEachChildInJSDocParameterOrPropertyTag( + node: JSDocParameterTag | JSDocPropertyTag, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { + return ( + visitNode(cbNode, node.tagName) || (node.isNameFirst - ? visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression) - : visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name)) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + ? visitNode(cbNode, node.name) || + visitNode(cbNode, node.typeExpression) + : visitNode(cbNode, node.typeExpression) || + visitNode(cbNode, node.name)) || + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment)) + ); } -function forEachChildInJSDocTypeLikeTag(node: JSDocReturnTag | JSDocTypeTag | JSDocThisTag | JSDocEnumTag | JSDocThrowsTag | JSDocOverloadTag | JSDocSatisfiesTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tagName) || +function forEachChildInJSDocTypeLikeTag( + node: + | JSDocReturnTag + | JSDocTypeTag + | JSDocThisTag + | JSDocEnumTag + | JSDocThrowsTag + | JSDocOverloadTag + | JSDocSatisfiesTag, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { + return ( + visitNode(cbNode, node.tagName) || visitNode(cbNode, node.typeExpression) || - (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment)) + ); } -function forEachChildInJSDocLinkCodeOrPlain(node: JSDocLink | JSDocLinkCode | JSDocLinkPlain, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { +function forEachChildInJSDocLinkCodeOrPlain( + node: JSDocLink | JSDocLinkCode | JSDocLinkPlain, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { return visitNode(cbNode, node.name); } -function forEachChildInJSDocTag(node: JSDocUnknownTag | JSDocClassTag | JSDocPublicTag | JSDocPrivateTag | JSDocProtectedTag | JSDocReadonlyTag | JSDocDeprecatedTag | JSDocOverrideTag, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { - return visitNode(cbNode, node.tagName) - || (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment)); +function forEachChildInJSDocTag( + node: + | JSDocUnknownTag + | JSDocClassTag + | JSDocPublicTag + | JSDocPrivateTag + | JSDocProtectedTag + | JSDocReadonlyTag + | JSDocDeprecatedTag + | JSDocOverrideTag, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { + return ( + visitNode(cbNode, node.tagName) || + (typeof node.comment === "string" + ? undefined + : visitNodes(cbNode, cbNodes, node.comment)) + ); } -function forEachChildInPartiallyEmittedExpression(node: PartiallyEmittedExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { +function forEachChildInPartiallyEmittedExpression( + node: PartiallyEmittedExpression, + cbNode: (node: Node) => T | undefined, + _cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { return visitNode(cbNode, node.expression); } @@ -1231,11 +2091,17 @@ function forEachChildInPartiallyEmittedExpression(node: PartiallyEmittedExpre * @remarks `forEachChild` must visit the children of a node in the order * that they appear in the source code. The language service depends on this property to locate nodes by position. */ -export function forEachChild(node: Node, cbNode: (node: Node) => T | undefined, cbNodes?: (nodes: NodeArray) => T | undefined): T | undefined { +export function forEachChild( + node: Node, + cbNode: (node: Node) => T | undefined, + cbNodes?: (nodes: NodeArray) => T | undefined, +): T | undefined { if (node === undefined || node.kind <= SyntaxKind.LastToken) { return; } - const fn = (forEachChildTable as Record>)[node.kind]; + const fn = ( + forEachChildTable as Record> + )[node.kind]; return fn === undefined ? undefined : fn(node, cbNode, cbNodes); } @@ -1254,7 +2120,11 @@ export function forEachChild(node: Node, cbNode: (node: Node) => T | undefine * * @internal */ -export function forEachChildRecursively(rootNode: Node, cbNode: (node: Node, parent: Node) => T | "skip" | undefined, cbNodes?: (nodes: NodeArray, parent: Node) => T | "skip" | undefined): T | undefined { +export function forEachChildRecursively( + rootNode: Node, + cbNode: (node: Node, parent: Node) => T | "skip" | undefined, + cbNodes?: (nodes: NodeArray, parent: Node) => T | "skip" | undefined, +): T | undefined { const queue: (Node | NodeArray)[] = gatherPossibleChildren(rootNode); const parents: Node[] = []; // tracks parent references for elements in queue while (parents.length < queue.length) { @@ -1326,8 +2196,19 @@ function setExternalModuleIndicator(sourceFile: SourceFile) { sourceFile.externalModuleIndicator = isFileProbablyExternalModule(sourceFile); } -export function createSourceFile(fileName: string, sourceText: string, languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, setParentNodes = false, scriptKind?: ScriptKind): SourceFile { - tracing?.push(tracing.Phase.Parse, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); +export function createSourceFile( + fileName: string, + sourceText: string, + languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, + setParentNodes = false, + scriptKind?: ScriptKind, +): SourceFile { + tracing?.push( + tracing.Phase.Parse, + "createSourceFile", + { path: fileName }, + /*separateBeginAndEnd*/ true, + ); performance.mark("beforeParse"); let result: SourceFile; @@ -1337,16 +2218,43 @@ export function createSourceFile(fileName: string, sourceText: string, languageV setExternalModuleIndicator: overrideSetExternalModuleIndicator, impliedNodeFormat: format, jsDocParsingMode, - } = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions : ({ languageVersion: languageVersionOrOptions } as CreateSourceFileOptions); + } = typeof languageVersionOrOptions === "object" + ? languageVersionOrOptions + : ({ + languageVersion: languageVersionOrOptions, + } as CreateSourceFileOptions); if (languageVersion === ScriptTarget.JSON) { - result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, ScriptKind.JSON, noop, jsDocParsingMode); + result = Parser.parseSourceFile( + fileName, + sourceText, + languageVersion, + /*syntaxCursor*/ undefined, + setParentNodes, + ScriptKind.JSON, + noop, + jsDocParsingMode, + ); } else { - const setIndicator = format === undefined ? overrideSetExternalModuleIndicator : (file: SourceFile) => { - file.impliedNodeFormat = format; - return (overrideSetExternalModuleIndicator || setExternalModuleIndicator)(file); - }; - result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind, setIndicator, jsDocParsingMode); + const setIndicator = format === undefined + ? overrideSetExternalModuleIndicator + : (file: SourceFile) => { + file.impliedNodeFormat = format; + return ( + overrideSetExternalModuleIndicator || + setExternalModuleIndicator + )(file); + }; + result = Parser.parseSourceFile( + fileName, + sourceText, + languageVersion, + /*syntaxCursor*/ undefined, + setParentNodes, + scriptKind, + setIndicator, + jsDocParsingMode, + ); } perfLogger?.logStopParseSourceFile(); @@ -1356,7 +2264,10 @@ export function createSourceFile(fileName: string, sourceText: string, languageV return result; } -export function parseIsolatedEntityName(text: string, languageVersion: ScriptTarget): EntityName | undefined { +export function parseIsolatedEntityName( + text: string, + languageVersion: ScriptTarget, +): EntityName | undefined { return Parser.parseIsolatedEntityName(text, languageVersion); } @@ -1365,7 +2276,10 @@ export function parseIsolatedEntityName(text: string, languageVersion: ScriptTar * @param fileName * @param sourceText */ -export function parseJsonText(fileName: string, sourceText: string): JsonSourceFile { +export function parseJsonText( + fileName: string, + sourceText: string, +): JsonSourceFile { return Parser.parseJsonText(fileName, sourceText); } @@ -1383,8 +2297,18 @@ export function isExternalModule(file: SourceFile): boolean { // from this SourceFile that are being held onto may change as a result (including // becoming detached from any SourceFile). It is recommended that this SourceFile not // be used once 'update' is called on it. -export function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks = false): SourceFile { - const newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); +export function updateSourceFile( + sourceFile: SourceFile, + newText: string, + textChangeRange: TextChangeRange, + aggressiveChecks = false, +): SourceFile { + const newSourceFile = IncrementalParser.updateSourceFile( + sourceFile, + newText, + textChangeRange, + aggressiveChecks, + ); // Because new source file node is created, it may not have the flag PossiblyContainDynamicImport. This is the case if there is no new edit to add dynamic import. // We will manually port the flag to the new source file. (newSourceFile as Mutable).flags |= sourceFile.flags & NodeFlags.PermanentlySetIncrementalFlags; @@ -1392,8 +2316,16 @@ export function updateSourceFile(sourceFile: SourceFile, newText: string, textCh } /** @internal */ -export function parseIsolatedJSDocComment(content: string, start?: number, length?: number) { - const result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length); +export function parseIsolatedJSDocComment( + content: string, + start?: number, + length?: number, +) { + const result = Parser.JSDocParser.parseIsolatedJSDocComment( + content, + start, + length, + ); if (result && result.jsDoc) { // because the jsDocComment was parsed out of the source file, it might // not be covered by the fixupParentReferences. @@ -1405,8 +2337,16 @@ export function parseIsolatedJSDocComment(content: string, start?: number, lengt /** @internal */ // Exposed only for testing. -export function parseJSDocTypeExpressionForTests(content: string, start?: number, length?: number) { - return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length); +export function parseJSDocTypeExpressionForTests( + content: string, + start?: number, + length?: number, +) { + return Parser.JSDocParser.parseJSDocTypeExpressionForTests( + content, + start, + length, + ); } // Implement the parser as a singleton module. We do this for perf reasons because creating @@ -1424,11 +2364,31 @@ namespace Parser { var disallowInAndDecoratorContext = NodeFlags.DisallowInContext | NodeFlags.DecoratorContext; // capture constructors in 'initializeState' to avoid null checks - var NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node; - var TokenConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node; - var IdentifierConstructor: new (kind: SyntaxKind.Identifier, pos: number, end: number) => Identifier; - var PrivateIdentifierConstructor: new (kind: SyntaxKind.PrivateIdentifier, pos: number, end: number) => PrivateIdentifier; - var SourceFileConstructor: new (kind: SyntaxKind.SourceFile, pos: number, end: number) => SourceFile; + var NodeConstructor: new ( + kind: SyntaxKind, + pos: number, + end: number, + ) => Node; + var TokenConstructor: new ( + kind: TKind, + pos: number, + end: number, + ) => Token; + var IdentifierConstructor: new ( + kind: SyntaxKind.Identifier, + pos: number, + end: number, + ) => Identifier; + var PrivateIdentifierConstructor: new ( + kind: SyntaxKind.PrivateIdentifier, + pos: number, + end: number, + ) => PrivateIdentifier; + var SourceFileConstructor: new ( + kind: SyntaxKind.SourceFile, + pos: number, + end: number, + ) => SourceFile; function countNode(node: Node) { nodeCount++; @@ -1440,12 +2400,20 @@ namespace Parser { var baseNodeFactory: BaseNodeFactory = { createBaseSourceFileNode: kind => countNode(new SourceFileConstructor(kind, /*pos*/ 0, /*end*/ 0)), createBaseIdentifierNode: kind => countNode(new IdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)), - createBasePrivateIdentifierNode: kind => countNode(new PrivateIdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)), + createBasePrivateIdentifierNode: kind => + countNode( + new PrivateIdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0), + ), createBaseTokenNode: kind => countNode(new TokenConstructor(kind, /*pos*/ 0, /*end*/ 0)), createBaseNode: kind => countNode(new NodeConstructor(kind, /*pos*/ 0, /*end*/ 0)), }; - var factory = createNodeFactory(NodeFactoryFlags.NoParenthesizerRules | NodeFactoryFlags.NoNodeConverters | NodeFactoryFlags.NoOriginalNode, baseNodeFactory); + var factory = createNodeFactory( + NodeFactoryFlags.NoParenthesizerRules | + NodeFactoryFlags.NoNodeConverters | + NodeFactoryFlags.NoOriginalNode, + baseNodeFactory, + ); var { createNodeArray: factoryCreateNodeArray, @@ -1590,8 +2558,20 @@ namespace Parser { ): SourceFile { scriptKind = ensureScriptKind(fileName, scriptKind); if (scriptKind === ScriptKind.JSON) { - const result = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - convertToJson(result, result.statements[0]?.expression, result.parseDiagnostics, /*returnValue*/ false, /*jsonConversionNotifier*/ undefined); + const result = parseJsonText( + fileName, + sourceText, + languageVersion, + syntaxCursor, + setParentNodes, + ); + convertToJson( + result, + result.statements[0]?.expression, + result.parseDiagnostics, + /*returnValue*/ false, + /*jsonConversionNotifier*/ undefined, + ); result.referencedFiles = emptyArray; result.typeReferenceDirectives = emptyArray; result.libReferenceDirectives = emptyArray; @@ -1601,18 +2581,41 @@ namespace Parser { return result; } - initializeState(fileName, sourceText, languageVersion, syntaxCursor, scriptKind, jsDocParsingMode); + initializeState( + fileName, + sourceText, + languageVersion, + syntaxCursor, + scriptKind, + jsDocParsingMode, + ); - const result = parseSourceFileWorker(languageVersion, setParentNodes, scriptKind, setExternalModuleIndicatorOverride || setExternalModuleIndicator, jsDocParsingMode); + const result = parseSourceFileWorker( + languageVersion, + setParentNodes, + scriptKind, + setExternalModuleIndicatorOverride || setExternalModuleIndicator, + jsDocParsingMode, + ); clearState(); return result; } - export function parseIsolatedEntityName(content: string, languageVersion: ScriptTarget): EntityName | undefined { + export function parseIsolatedEntityName( + content: string, + languageVersion: ScriptTarget, + ): EntityName | undefined { // Choice of `isDeclarationFile` should be arbitrary - initializeState("", content, languageVersion, /*syntaxCursor*/ undefined, ScriptKind.JS, JSDocParsingMode.ParseAll); + initializeState( + "", + content, + languageVersion, + /*syntaxCursor*/ undefined, + ScriptKind.JS, + JSDocParsingMode.ParseAll, + ); // Prime the scanner. nextToken(); const entityName = parseEntityName(/*allowReservedWords*/ true); @@ -1621,8 +2624,21 @@ namespace Parser { return isValid ? entityName : undefined; } - export function parseJsonText(fileName: string, sourceText: string, languageVersion: ScriptTarget = ScriptTarget.ES2015, syntaxCursor?: IncrementalParser.SyntaxCursor, setParentNodes = false): JsonSourceFile { - initializeState(fileName, sourceText, languageVersion, syntaxCursor, ScriptKind.JSON, JSDocParsingMode.ParseAll); + export function parseJsonText( + fileName: string, + sourceText: string, + languageVersion: ScriptTarget = ScriptTarget.ES2015, + syntaxCursor?: IncrementalParser.SyntaxCursor, + setParentNodes = false, + ): JsonSourceFile { + initializeState( + fileName, + sourceText, + languageVersion, + syntaxCursor, + ScriptKind.JSON, + JSDocParsingMode.ParseAll, + ); sourceFlags = contextFlags; // Prime the scanner. @@ -1646,10 +2662,18 @@ namespace Parser { case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.NullKeyword: - expression = parseTokenNode(); + expression = parseTokenNode< + BooleanLiteral | NullLiteral + >(); break; case SyntaxKind.MinusToken: - if (lookAhead(() => nextToken() === SyntaxKind.NumericLiteral && nextToken() !== SyntaxKind.ColonToken)) { + if ( + lookAhead( + () => + nextToken() === SyntaxKind.NumericLiteral && + nextToken() !== SyntaxKind.ColonToken, + ) + ) { expression = parsePrefixUnaryExpression() as JsonMinusNumericLiteral; } else { @@ -1658,11 +2682,17 @@ namespace Parser { break; case SyntaxKind.NumericLiteral: case SyntaxKind.StringLiteral: - if (lookAhead(() => nextToken() !== SyntaxKind.ColonToken)) { - expression = parseLiteralNode() as StringLiteral | NumericLiteral; + if ( + lookAhead( + () => nextToken() !== SyntaxKind.ColonToken, + ) + ) { + expression = parseLiteralNode() as + | StringLiteral + | NumericLiteral; break; } - // falls through + // falls through default: expression = parseObjectLiteralExpression(); break; @@ -1683,15 +2713,34 @@ namespace Parser { } } - const expression = isArray(expressions) ? finishNode(factoryCreateArrayLiteralExpression(expressions), pos) : Debug.checkDefined(expressions); - const statement = factoryCreateExpressionStatement(expression) as JsonObjectExpressionStatement; + const expression = isArray(expressions) + ? finishNode( + factoryCreateArrayLiteralExpression(expressions), + pos, + ) + : Debug.checkDefined(expressions); + const statement = factoryCreateExpressionStatement( + expression, + ) as JsonObjectExpressionStatement; finishNode(statement, pos); statements = createNodeArray([statement], pos); - endOfFileToken = parseExpectedToken(SyntaxKind.EndOfFileToken, Diagnostics.Unexpected_token) as EndOfFileToken; + endOfFileToken = parseExpectedToken( + SyntaxKind.EndOfFileToken, + Diagnostics.Unexpected_token, + ) as EndOfFileToken; } // Set source file so that errors will be reported with this file name - const sourceFile = createSourceFile(fileName, ScriptTarget.ES2015, ScriptKind.JSON, /*isDeclarationFile*/ false, statements, endOfFileToken, sourceFlags, noop); + const sourceFile = createSourceFile( + fileName, + ScriptTarget.ES2015, + ScriptKind.JSON, + /*isDeclarationFile*/ false, + statements, + endOfFileToken, + sourceFlags, + noop, + ); if (setParentNodes) { fixupParentReferences(sourceFile); @@ -1700,9 +2749,15 @@ namespace Parser { sourceFile.nodeCount = nodeCount; sourceFile.identifierCount = identifierCount; sourceFile.identifiers = identifiers; - sourceFile.parseDiagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); + sourceFile.parseDiagnostics = attachFileToDiagnostics( + parseDiagnostics, + sourceFile, + ); if (jsDocDiagnostics) { - sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile); + sourceFile.jsDocDiagnostics = attachFileToDiagnostics( + jsDocDiagnostics, + sourceFile, + ); } const result = sourceFile as JsonSourceFile; @@ -1710,7 +2765,14 @@ namespace Parser { return result; } - function initializeState(_fileName: string, _sourceText: string, _languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor | undefined, _scriptKind: ScriptKind, _jsDocParsingMode: JSDocParsingMode) { + function initializeState( + _fileName: string, + _sourceText: string, + _languageVersion: ScriptTarget, + _syntaxCursor: IncrementalParser.SyntaxCursor | undefined, + _scriptKind: ScriptKind, + _jsDocParsingMode: JSDocParsingMode, + ) { NodeConstructor = objectAllocator.getNodeConstructor(); TokenConstructor = objectAllocator.getTokenConstructor(); IdentifierConstructor = objectAllocator.getIdentifierConstructor(); @@ -1778,7 +2840,13 @@ namespace Parser { topLevel = true; } - function parseSourceFileWorker(languageVersion: ScriptTarget, setParentNodes: boolean, scriptKind: ScriptKind, setExternalModuleIndicator: (file: SourceFile) => void, jsDocParsingMode: JSDocParsingMode): SourceFile { + function parseSourceFileWorker( + languageVersion: ScriptTarget, + setParentNodes: boolean, + scriptKind: ScriptKind, + setExternalModuleIndicator: (file: SourceFile) => void, + jsDocParsingMode: JSDocParsingMode, + ): SourceFile { const isDeclarationFile = isDeclarationFileName(fileName); if (isDeclarationFile) { contextFlags |= NodeFlags.Ambient; @@ -1789,25 +2857,49 @@ namespace Parser { // Prime the scanner. nextToken(); - const statements = parseList(ParsingContext.SourceElements, parseStatement); + const statements = parseList( + ParsingContext.SourceElements, + parseStatement, + ); Debug.assert(token() === SyntaxKind.EndOfFileToken); const endHasJSDoc = hasPrecedingJSDocComment(); - const endOfFileToken = withJSDoc(parseTokenNode(), endHasJSDoc); + const endOfFileToken = withJSDoc( + parseTokenNode(), + endHasJSDoc, + ); - const sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, sourceFlags, setExternalModuleIndicator); + const sourceFile = createSourceFile( + fileName, + languageVersion, + scriptKind, + isDeclarationFile, + statements, + endOfFileToken, + sourceFlags, + setExternalModuleIndicator, + ); // A member of ReadonlyArray isn't assignable to a member of T[] (and prevents a direct cast) - but this is where we set up those members so they can be readonly in the future processCommentPragmas(sourceFile as {} as PragmaContext, sourceText); - processPragmasIntoFields(sourceFile as {} as PragmaContext, reportPragmaDiagnostic); + processPragmasIntoFields( + sourceFile as {} as PragmaContext, + reportPragmaDiagnostic, + ); sourceFile.commentDirectives = scanner.getCommentDirectives(); sourceFile.nodeCount = nodeCount; sourceFile.identifierCount = identifierCount; sourceFile.identifiers = identifiers; - sourceFile.parseDiagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); + sourceFile.parseDiagnostics = attachFileToDiagnostics( + parseDiagnostics, + sourceFile, + ); sourceFile.jsDocParsingMode = jsDocParsingMode; if (jsDocDiagnostics) { - sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile); + sourceFile.jsDocDiagnostics = attachFileToDiagnostics( + jsDocDiagnostics, + sourceFile, + ); } if (setParentNodes) { @@ -1816,8 +2908,20 @@ namespace Parser { return sourceFile; - function reportPragmaDiagnostic(pos: number, end: number, diagnostic: DiagnosticMessage) { - parseDiagnostics.push(createDetachedDiagnostic(fileName, sourceText, pos, end, diagnostic)); + function reportPragmaDiagnostic( + pos: number, + end: number, + diagnostic: DiagnosticMessage, + ) { + parseDiagnostics.push( + createDetachedDiagnostic( + fileName, + sourceText, + pos, + end, + diagnostic, + ), + ); } } @@ -1828,7 +2932,15 @@ namespace Parser { } Debug.assert(!node.jsDoc); // Should only be called once per node - const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), comment => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); + const jsDoc = mapDefined( + getJSDocCommentRanges(node, sourceText), + comment => + JSDocParser.parseJSDocComment( + node, + comment.pos, + comment.end - comment.pos, + ), + ); if (jsDoc.length) node.jsDoc = jsDoc; if (hasDeprecatedTag) { hasDeprecatedTag = false; @@ -1857,10 +2969,24 @@ namespace Parser { pos = findNextStatementWithoutAwait(sourceFile.statements, start); // append all diagnostics associated with the copied range - const diagnosticStart = findIndex(savedParseDiagnostics, diagnostic => diagnostic.start >= prevStatement.pos); - const diagnosticEnd = diagnosticStart >= 0 ? findIndex(savedParseDiagnostics, diagnostic => diagnostic.start >= nextStatement.pos, diagnosticStart) : -1; + const diagnosticStart = findIndex( + savedParseDiagnostics, + diagnostic => diagnostic.start >= prevStatement.pos, + ); + const diagnosticEnd = diagnosticStart >= 0 + ? findIndex( + savedParseDiagnostics, + diagnostic => diagnostic.start >= nextStatement.pos, + diagnosticStart, + ) + : -1; if (diagnosticStart >= 0) { - addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart, diagnosticEnd >= 0 ? diagnosticEnd : undefined); + addRange( + parseDiagnostics, + savedParseDiagnostics, + diagnosticStart, + diagnosticEnd >= 0 ? diagnosticEnd : undefined, + ); } // reparse all statements between start and pos. We skip existing diagnostics for the same range and allow the parser to generate new ones. @@ -1872,7 +2998,10 @@ namespace Parser { while (token() !== SyntaxKind.EndOfFileToken) { const startPos = scanner.getTokenFullStart(); - const statement = parseListElement(ParsingContext.SourceElements, parseStatement); + const statement = parseListElement( + ParsingContext.SourceElements, + parseStatement, + ); statements.push(statement); if (startPos === scanner.getTokenFullStart()) { nextToken(); @@ -1886,7 +3015,10 @@ namespace Parser { } if (statement.end > nonAwaitStatement.pos) { // we ate into the next statement, so we must reparse it. - pos = findNextStatementWithoutAwait(sourceFile.statements, pos + 1); + pos = findNextStatementWithoutAwait( + sourceFile.statements, + pos + 1, + ); } } } @@ -1895,7 +3027,9 @@ namespace Parser { }, SpeculationKind.Reparse); // find the next statement containing an `await` - start = pos >= 0 ? findNextStatementWithAwait(sourceFile.statements, pos) : -1; + start = pos >= 0 + ? findNextStatementWithAwait(sourceFile.statements, pos) + : -1; } // append all statements between pos and the end of the list @@ -1904,21 +3038,42 @@ namespace Parser { addRange(statements, sourceFile.statements, pos); // append all diagnostics associated with the copied range - const diagnosticStart = findIndex(savedParseDiagnostics, diagnostic => diagnostic.start >= prevStatement.pos); + const diagnosticStart = findIndex( + savedParseDiagnostics, + diagnostic => diagnostic.start >= prevStatement.pos, + ); if (diagnosticStart >= 0) { - addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart); + addRange( + parseDiagnostics, + savedParseDiagnostics, + diagnosticStart, + ); } } syntaxCursor = savedSyntaxCursor; - return factory.updateSourceFile(sourceFile, setTextRange(factoryCreateNodeArray(statements), sourceFile.statements)); + return factory.updateSourceFile( + sourceFile, + setTextRange( + factoryCreateNodeArray(statements), + sourceFile.statements, + ), + ); - function containsPossibleTopLevelAwait(node: Node) { - return !(node.flags & NodeFlags.AwaitContext) - && !!(node.transformFlags & TransformFlags.ContainsPossibleTopLevelAwait); + function containsPossibleTopLevelAwait(node: NodeBase) { + return ( + !(node.flags & NodeFlags.AwaitContext) && + !!( + node.transformFlags & + TransformFlags.ContainsPossibleTopLevelAwait + ) + ); } - function findNextStatementWithAwait(statements: NodeArray, start: number) { + function findNextStatementWithAwait( + statements: NodeArray, + start: number, + ) { for (let i = start; i < statements.length; i++) { if (containsPossibleTopLevelAwait(statements[i])) { return i; @@ -1927,7 +3082,10 @@ namespace Parser { return -1; } - function findNextStatementWithoutAwait(statements: NodeArray, start: number) { + function findNextStatementWithoutAwait( + statements: NodeArray, + start: number, + ) { for (let i = start; i < statements.length; i++) { if (!containsPossibleTopLevelAwait(statements[i])) { return i; @@ -1965,12 +3123,21 @@ namespace Parser { ): SourceFile { // code from createNode is inlined here so createNode won't have to deal with special case of creating source files // this is quite rare comparing to other nodes and createNode should be as fast as possible - let sourceFile = factory.createSourceFile(statements, endOfFileToken, flags); + let sourceFile = factory.createSourceFile( + statements, + endOfFileToken, + flags, + ); setTextRangePosWidth(sourceFile, 0, sourceText.length); setFields(sourceFile); // If we parsed this as an external module, it may contain top-level await - if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & TransformFlags.ContainsPossibleTopLevelAwait) { + if ( + !isDeclarationFile && + isExternalModule(sourceFile) && + sourceFile.transformFlags & + TransformFlags.ContainsPossibleTopLevelAwait + ) { sourceFile = reparseTopLevelAwait(sourceFile); setFields(sourceFile); } @@ -2068,11 +3235,17 @@ namespace Parser { } function allowConditionalTypesAnd(func: () => T): T { - return doOutsideOfContext(NodeFlags.DisallowConditionalTypesContext, func); + return doOutsideOfContext( + NodeFlags.DisallowConditionalTypesContext, + func, + ); } function disallowConditionalTypesAnd(func: () => T): T { - return doInsideOfContext(NodeFlags.DisallowConditionalTypesContext, func); + return doInsideOfContext( + NodeFlags.DisallowConditionalTypesContext, + func, + ); } function doInYieldContext(func: () => T): T { @@ -2092,11 +3265,17 @@ namespace Parser { } function doInYieldAndAwaitContext(func: () => T): T { - return doInsideOfContext(NodeFlags.YieldContext | NodeFlags.AwaitContext, func); + return doInsideOfContext( + NodeFlags.YieldContext | NodeFlags.AwaitContext, + func, + ); } function doOutsideOfYieldAndAwaitContext(func: () => T): T { - return doOutsideOfContext(NodeFlags.YieldContext | NodeFlags.AwaitContext, func); + return doOutsideOfContext( + NodeFlags.YieldContext | NodeFlags.AwaitContext, + func, + ); } function inContext(flags: NodeFlags) { @@ -2123,16 +3302,36 @@ namespace Parser { return inContext(NodeFlags.AwaitContext); } - function parseErrorAtCurrentToken(message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithDetachedLocation | undefined { - return parseErrorAt(scanner.getTokenStart(), scanner.getTokenEnd(), message, ...args); + function parseErrorAtCurrentToken( + message: DiagnosticMessage, + ...args: DiagnosticArguments + ): DiagnosticWithDetachedLocation | undefined { + return parseErrorAt( + scanner.getTokenStart(), + scanner.getTokenEnd(), + message, + ...args, + ); } - function parseErrorAtPosition(start: number, length: number, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithDetachedLocation | undefined { + function parseErrorAtPosition( + start: number, + length: number, + message: DiagnosticMessage, + ...args: DiagnosticArguments + ): DiagnosticWithDetachedLocation | undefined { // Don't report another error if it would just be at the same position as the last error. const lastError = lastOrUndefined(parseDiagnostics); let result: DiagnosticWithDetachedLocation | undefined; if (!lastError || start !== lastError.start) { - result = createDetachedDiagnostic(fileName, sourceText, start, length, message, ...args); + result = createDetachedDiagnostic( + fileName, + sourceText, + start, + length, + message, + ...args, + ); parseDiagnostics.push(result); } @@ -2142,15 +3341,28 @@ namespace Parser { return result; } - function parseErrorAt(start: number, end: number, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithDetachedLocation | undefined { + function parseErrorAt( + start: number, + end: number, + message: DiagnosticMessage, + ...args: DiagnosticArguments + ): DiagnosticWithDetachedLocation | undefined { return parseErrorAtPosition(start, end - start, message, ...args); } - function parseErrorAtRange(range: TextRange, message: DiagnosticMessage, ...args: DiagnosticArguments): void { + function parseErrorAtRange( + range: TextRange, + message: DiagnosticMessage, + ...args: DiagnosticArguments + ): void { parseErrorAt(range.pos, range.end, message, ...args); } - function scanError(message: DiagnosticMessage, length: number, arg0?: any): void { + function scanError( + message: DiagnosticMessage, + length: number, + arg0?: any, + ): void { parseErrorAtPosition(scanner.getTokenEnd(), length, message, arg0); } @@ -2173,7 +3385,7 @@ namespace Parser { } function nextTokenWithoutCheck() { - return currentToken = scanner.scan(); + return (currentToken = scanner.scan()); } function nextTokenAnd(func: () => T): T { @@ -2183,54 +3395,66 @@ namespace Parser { function nextToken(): SyntaxKind { // if the keyword had an escape - if (isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) { + if ( + isKeyword(currentToken) && + (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape()) + ) { // issue a parse error for the escape - parseErrorAt(scanner.getTokenStart(), scanner.getTokenEnd(), Diagnostics.Keywords_cannot_contain_escape_characters); + parseErrorAt( + scanner.getTokenStart(), + scanner.getTokenEnd(), + Diagnostics.Keywords_cannot_contain_escape_characters, + ); } return nextTokenWithoutCheck(); } function nextTokenJSDoc(): JSDocSyntaxKind { - return currentToken = scanner.scanJsDocToken(); + return (currentToken = scanner.scanJsDocToken()); } - function nextJSDocCommentTextToken(inBackticks: boolean): JSDocSyntaxKind | SyntaxKind.JSDocCommentTextToken { - return currentToken = scanner.scanJSDocCommentTextToken(inBackticks); + function nextJSDocCommentTextToken( + inBackticks: boolean, + ): JSDocSyntaxKind | SyntaxKind.JSDocCommentTextToken { + return (currentToken = scanner.scanJSDocCommentTextToken(inBackticks)); } function reScanGreaterToken(): SyntaxKind { - return currentToken = scanner.reScanGreaterToken(); + return (currentToken = scanner.reScanGreaterToken()); } function reScanSlashToken(): SyntaxKind { - return currentToken = scanner.reScanSlashToken(); + return (currentToken = scanner.reScanSlashToken()); } function reScanTemplateToken(isTaggedTemplate: boolean): SyntaxKind { - return currentToken = scanner.reScanTemplateToken(isTaggedTemplate); + return (currentToken = scanner.reScanTemplateToken(isTaggedTemplate)); } function reScanLessThanToken(): SyntaxKind { - return currentToken = scanner.reScanLessThanToken(); + return (currentToken = scanner.reScanLessThanToken()); } function reScanHashToken(): SyntaxKind { - return currentToken = scanner.reScanHashToken(); + return (currentToken = scanner.reScanHashToken()); } function scanJsxIdentifier(): SyntaxKind { - return currentToken = scanner.scanJsxIdentifier(); + return (currentToken = scanner.scanJsxIdentifier()); } function scanJsxText(): SyntaxKind { - return currentToken = scanner.scanJsxToken(); + return (currentToken = scanner.scanJsxToken()); } function scanJsxAttributeValue(): SyntaxKind { - return currentToken = scanner.scanJsxAttributeValue(); + return (currentToken = scanner.scanJsxAttributeValue()); } - function speculationHelper(callback: () => T, speculationKind: SpeculationKind): T { + function speculationHelper( + callback: () => T, + speculationKind: SpeculationKind, + ): T { // Keep track of the state we'll need to rollback to if lookahead fails (or if the // caller asked us to always reset our state). const saveToken = currentToken; @@ -2312,7 +3536,11 @@ namespace Parser { return token() > SyntaxKind.LastReservedWord; } - function parseExpected(kind: PunctuationOrKeywordSyntaxKind, diagnosticMessage?: DiagnosticMessage, shouldAdvance = true): boolean { + function parseExpected( + kind: PunctuationOrKeywordSyntaxKind, + diagnosticMessage?: DiagnosticMessage, + shouldAdvance = true, + ): boolean { if (token() === kind) { if (shouldAdvance) { nextToken(); @@ -2325,12 +3553,17 @@ namespace Parser { parseErrorAtCurrentToken(diagnosticMessage); } else { - parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(kind)); + parseErrorAtCurrentToken( + Diagnostics._0_expected, + tokenToString(kind), + ); } return false; } - const viableKeywordSuggestions = Object.keys(textToKeywordObj).filter(keyword => keyword.length > 2); + const viableKeywordSuggestions = Object.keys(textToKeywordObj).filter( + keyword => keyword.length > 2, + ); /** * Provides a better error message than the generic "';' expected" if possible for @@ -2338,19 +3571,33 @@ namespace Parser { * * @param node Node preceding the expected semicolon location. */ - function parseErrorForMissingSemicolonAfter(node: Expression | PropertyName): void { + function parseErrorForMissingSemicolonAfter( + node: Expression | PropertyName, + ): void { // Tagged template literals are sometimes used in places where only simple strings are allowed, i.e.: // module `M1` { // ^^^^^^^^^^^ This block is parsed as a template literal like module`M1`. if (isTaggedTemplateExpression(node)) { - parseErrorAt(skipTrivia(sourceText, node.template.pos), node.template.end, Diagnostics.Module_declaration_names_may_only_use_or_quoted_strings); + parseErrorAt( + skipTrivia(sourceText, node.template.pos), + node.template.end, + Diagnostics.Module_declaration_names_may_only_use_or_quoted_strings, + ); return; } // Otherwise, if this isn't a well-known keyword-like identifier, give the generic fallback message. - const expressionText = isIdentifierNode(node) ? idText(node) : undefined; - if (!expressionText || !isIdentifierText(expressionText, languageVersion)) { - parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.SemicolonToken)); + const expressionText = isIdentifierNode(node) + ? idText(node) + : undefined; + if ( + !expressionText || + !isIdentifierText(expressionText, languageVersion) + ) { + parseErrorAtCurrentToken( + Diagnostics._0_expected, + tokenToString(SyntaxKind.SemicolonToken), + ); return; } @@ -2361,7 +3608,11 @@ namespace Parser { case "const": case "let": case "var": - parseErrorAt(pos, node.end, Diagnostics.Variable_declaration_not_allowed_at_this_location); + parseErrorAt( + pos, + node.end, + Diagnostics.Variable_declaration_not_allowed_at_this_location, + ); return; case "declare": @@ -2369,27 +3620,52 @@ namespace Parser { return; case "interface": - parseErrorForInvalidName(Diagnostics.Interface_name_cannot_be_0, Diagnostics.Interface_must_be_given_a_name, SyntaxKind.OpenBraceToken); + parseErrorForInvalidName( + Diagnostics.Interface_name_cannot_be_0, + Diagnostics.Interface_must_be_given_a_name, + SyntaxKind.OpenBraceToken, + ); return; case "is": - parseErrorAt(pos, scanner.getTokenStart(), Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); + parseErrorAt( + pos, + scanner.getTokenStart(), + Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods, + ); return; case "module": case "namespace": - parseErrorForInvalidName(Diagnostics.Namespace_name_cannot_be_0, Diagnostics.Namespace_must_be_given_a_name, SyntaxKind.OpenBraceToken); + parseErrorForInvalidName( + Diagnostics.Namespace_name_cannot_be_0, + Diagnostics.Namespace_must_be_given_a_name, + SyntaxKind.OpenBraceToken, + ); return; case "type": - parseErrorForInvalidName(Diagnostics.Type_alias_name_cannot_be_0, Diagnostics.Type_alias_must_be_given_a_name, SyntaxKind.EqualsToken); + parseErrorForInvalidName( + Diagnostics.Type_alias_name_cannot_be_0, + Diagnostics.Type_alias_must_be_given_a_name, + SyntaxKind.EqualsToken, + ); return; } // The user alternatively might have misspelled or forgotten to add a space after a common keyword. - const suggestion = getSpellingSuggestion(expressionText, viableKeywordSuggestions, n => n) ?? getSpaceSuggestion(expressionText); + const suggestion = getSpellingSuggestion( + expressionText, + viableKeywordSuggestions, + n => n, + ) ?? getSpaceSuggestion(expressionText); if (suggestion) { - parseErrorAt(pos, node.end, Diagnostics.Unknown_keyword_or_identifier_Did_you_mean_0, suggestion); + parseErrorAt( + pos, + node.end, + Diagnostics.Unknown_keyword_or_identifier_Did_you_mean_0, + suggestion, + ); return; } @@ -2399,7 +3675,11 @@ namespace Parser { } // Otherwise, we know this some kind of unknown word, not just a missing expected semicolon. - parseErrorAt(pos, node.end, Diagnostics.Unexpected_keyword_or_identifier); + parseErrorAt( + pos, + node.end, + Diagnostics.Unexpected_keyword_or_identifier, + ); } /** @@ -2409,7 +3689,11 @@ namespace Parser { * @param nameDiagnostic Diagnostic to report for all other cases. * @param tokenIfBlankName Current token if the name was invalid for being blank (not provided / skipped). */ - function parseErrorForInvalidName(nameDiagnostic: DiagnosticMessage, blankDiagnostic: DiagnosticMessage, tokenIfBlankName: SyntaxKind) { + function parseErrorForInvalidName( + nameDiagnostic: DiagnosticMessage, + blankDiagnostic: DiagnosticMessage, + tokenIfBlankName: SyntaxKind, + ) { if (token() === tokenIfBlankName) { parseErrorAtCurrentToken(blankDiagnostic); } @@ -2420,7 +3704,10 @@ namespace Parser { function getSpaceSuggestion(expressionText: string) { for (const keyword of viableKeywordSuggestions) { - if (expressionText.length > keyword.length + 2 && startsWith(expressionText, keyword)) { + if ( + expressionText.length > keyword.length + 2 && + startsWith(expressionText, keyword) + ) { return `${keyword} ${expressionText.slice(keyword.length)}`; } } @@ -2428,24 +3715,40 @@ namespace Parser { return undefined; } - function parseSemicolonAfterPropertyName(name: PropertyName, type: TypeNode | undefined, initializer: Expression | undefined) { - if (token() === SyntaxKind.AtToken && !scanner.hasPrecedingLineBreak()) { - parseErrorAtCurrentToken(Diagnostics.Decorators_must_precede_the_name_and_all_keywords_of_property_declarations); + function parseSemicolonAfterPropertyName( + name: PropertyName, + type: TypeNode | undefined, + initializer: Expression | undefined, + ) { + if ( + token() === SyntaxKind.AtToken && + !scanner.hasPrecedingLineBreak() + ) { + parseErrorAtCurrentToken( + Diagnostics.Decorators_must_precede_the_name_and_all_keywords_of_property_declarations, + ); return; } if (token() === SyntaxKind.OpenParenToken) { - parseErrorAtCurrentToken(Diagnostics.Cannot_start_a_function_call_in_a_type_annotation); + parseErrorAtCurrentToken( + Diagnostics.Cannot_start_a_function_call_in_a_type_annotation, + ); nextToken(); return; } if (type && !canParseSemicolon()) { if (initializer) { - parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.SemicolonToken)); + parseErrorAtCurrentToken( + Diagnostics._0_expected, + tokenToString(SyntaxKind.SemicolonToken), + ); } else { - parseErrorAtCurrentToken(Diagnostics.Expected_for_property_initializer); + parseErrorAtCurrentToken( + Diagnostics.Expected_for_property_initializer, + ); } return; } @@ -2455,7 +3758,10 @@ namespace Parser { } if (initializer) { - parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.SemicolonToken)); + parseErrorAtCurrentToken( + Diagnostics._0_expected, + tokenToString(SyntaxKind.SemicolonToken), + ); return; } @@ -2472,19 +3778,35 @@ namespace Parser { return false; } - function parseExpectedMatchingBrackets(openKind: PunctuationSyntaxKind, closeKind: PunctuationSyntaxKind, openParsed: boolean, openPosition: number) { + function parseExpectedMatchingBrackets( + openKind: PunctuationSyntaxKind, + closeKind: PunctuationSyntaxKind, + openParsed: boolean, + openPosition: number, + ) { if (token() === closeKind) { nextToken(); return; } - const lastError = parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(closeKind)); + const lastError = parseErrorAtCurrentToken( + Diagnostics._0_expected, + tokenToString(closeKind), + ); if (!openParsed) { return; } if (lastError) { addRelatedInfo( lastError, - createDetachedDiagnostic(fileName, sourceText, openPosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, tokenToString(openKind), tokenToString(closeKind)), + createDetachedDiagnostic( + fileName, + sourceText, + openPosition, + 1, + Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, + tokenToString(openKind), + tokenToString(closeKind), + ), ); } } @@ -2497,15 +3819,19 @@ namespace Parser { return false; } - function parseOptionalToken(t: TKind): Token; - function parseOptionalToken(t: SyntaxKind): Node | undefined { + function parseOptionalToken( + t: TKind, + ): Token; + function parseOptionalToken(t: TokenSyntaxKind): Node | undefined { if (token() === t) { return parseTokenNode(); } return undefined; } - function parseOptionalTokenJSDoc(t: TKind): Token; + function parseOptionalTokenJSDoc( + t: TKind, + ): Token; function parseOptionalTokenJSDoc(t: JSDocSyntaxKind): Node | undefined { if (token() === t) { return parseTokenNodeJSDoc(); @@ -2513,30 +3839,52 @@ namespace Parser { return undefined; } - function parseExpectedToken(t: TKind, diagnosticMessage?: DiagnosticMessage, arg0?: string): Token; - function parseExpectedToken(t: SyntaxKind, diagnosticMessage?: DiagnosticMessage, arg0?: string): Node { - return parseOptionalToken(t) || - createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || Diagnostics._0_expected, arg0 || tokenToString(t)!); + function parseExpectedToken( + t: TKind, + diagnosticMessage?: DiagnosticMessage, + arg0?: string, + ): Token; + function parseExpectedToken( + t: TokenSyntaxKind, + diagnosticMessage?: DiagnosticMessage, + arg0?: string, + ): Node { + return ( + parseOptionalToken(t) || + createMissingNode( + t, + /*reportAtCurrentPosition*/ false, + diagnosticMessage || Diagnostics._0_expected, + arg0 || tokenToString(t)!, + ) + ); } - function parseExpectedTokenJSDoc(t: TKind): Token; - function parseExpectedTokenJSDoc(t: JSDocSyntaxKind): Node { + function parseExpectedTokenJSDoc( + t: TKind, + ): Token; + function parseExpectedTokenJSDoc(t: JSDocSyntaxKind): Token | Node { const optional = parseOptionalTokenJSDoc(t); if (optional) return optional; Debug.assert(isKeywordOrPunctuation(t)); - return createMissingNode(t, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(t)); + return createMissingNode( + t, + /*reportAtCurrentPosition*/ false, + Diagnostics._0_expected, + tokenToString(t), + ); } function parseTokenNode(): T { const pos = getNodePos(); - const kind = token(); + const kind = token() as TokenSyntaxKind; nextToken(); return finishNode(factoryCreateToken(kind), pos) as T; } function parseTokenNodeJSDoc(): T { const pos = getNodePos(); - const kind = token(); + const kind = token() as JsxTokenSyntaxKind; nextTokenJSDoc(); return finishNode(factoryCreateToken(kind), pos) as T; } @@ -2548,7 +3896,11 @@ namespace Parser { } // We can parse out an optional semicolon in ASI cases in the following cases. - return token() === SyntaxKind.CloseBraceToken || token() === SyntaxKind.EndOfFileToken || scanner.hasPrecedingLineBreak(); + return ( + token() === SyntaxKind.CloseBraceToken || + token() === SyntaxKind.EndOfFileToken || + scanner.hasPrecedingLineBreak() + ); } function tryParseSemicolon() { @@ -2568,7 +3920,12 @@ namespace Parser { return tryParseSemicolon() || parseExpected(SyntaxKind.SemicolonToken); } - function createNodeArray(elements: T[], pos: number, end?: number, hasTrailingComma?: boolean): NodeArray { + function createNodeArray( + elements: T[], + pos: number, + end?: number, + hasTrailingComma?: boolean, + ): NodeArray { const array = factoryCreateNodeArray(elements, hasTrailingComma); setTextRangePosEnd(array, pos, end ?? scanner.getTokenFullStart()); return array; @@ -2591,23 +3948,56 @@ namespace Parser { return node; } - function createMissingNode(kind: T["kind"], reportAtCurrentPosition: false, diagnosticMessage?: DiagnosticMessage, ...args: DiagnosticArguments): T; - function createMissingNode(kind: T["kind"], reportAtCurrentPosition: boolean, diagnosticMessage: DiagnosticMessage, ...args: DiagnosticArguments): T; - function createMissingNode(kind: T["kind"], reportAtCurrentPosition: boolean, diagnosticMessage?: DiagnosticMessage, ...args: DiagnosticArguments): T { + function createMissingNode( + kind: T["kind"], + reportAtCurrentPosition: false, + diagnosticMessage?: DiagnosticMessage, + ...args: DiagnosticArguments + ): T; + function createMissingNode( + kind: T["kind"], + reportAtCurrentPosition: boolean, + diagnosticMessage: DiagnosticMessage, + ...args: DiagnosticArguments + ): T; + function createMissingNode( + kind: T["kind"], + reportAtCurrentPosition: boolean, + diagnosticMessage?: DiagnosticMessage, + ...args: DiagnosticArguments + ): T { if (reportAtCurrentPosition) { - parseErrorAtPosition(scanner.getTokenFullStart(), 0, diagnosticMessage!, ...args); + parseErrorAtPosition( + scanner.getTokenFullStart(), + 0, + diagnosticMessage!, + ...args, + ); } else if (diagnosticMessage) { parseErrorAtCurrentToken(diagnosticMessage, ...args); } const pos = getNodePos(); - const result = kind === SyntaxKind.Identifier ? factoryCreateIdentifier("", /*originalKeywordKind*/ undefined) : - isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) : - kind === SyntaxKind.NumericLiteral ? factoryCreateNumericLiteral("", /*numericLiteralFlags*/ undefined) : - kind === SyntaxKind.StringLiteral ? factoryCreateStringLiteral("", /*isSingleQuote*/ undefined) : - kind === SyntaxKind.MissingDeclaration ? factory.createMissingDeclaration() : - factoryCreateToken(kind); + const result = kind === SyntaxKind.Identifier + ? factoryCreateIdentifier("", /*originalKeywordKind*/ undefined) + : isTemplateLiteralKind(kind) + ? factory.createTemplateLiteralLikeNode( + kind, + "", + "", + /*templateFlags*/ undefined, + ) + : kind === SyntaxKind.NumericLiteral + ? factoryCreateNumericLiteral( + "", + /*numericLiteralFlags*/ undefined, + ) + : kind === SyntaxKind.StringLiteral + ? factoryCreateStringLiteral("", /*isSingleQuote*/ undefined) + : kind === SyntaxKind.MissingDeclaration + ? factory.createMissingDeclaration() + : factoryCreateToken(kind); return finishNode(result, pos) as T; } @@ -2622,7 +4012,11 @@ namespace Parser { // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for // each identifier in order to reduce memory consumption. - function createIdentifier(isIdentifier: boolean, diagnosticMessage?: DiagnosticMessage, privateIdentifierDiagnosticMessage?: DiagnosticMessage): Identifier { + function createIdentifier( + isIdentifier: boolean, + diagnosticMessage?: DiagnosticMessage, + privateIdentifierDiagnosticMessage?: DiagnosticMessage, + ): Identifier { if (isIdentifier) { identifierCount++; const pos = getNodePos(); @@ -2631,15 +4025,30 @@ namespace Parser { const text = internIdentifier(scanner.getTokenValue()); const hasExtendedUnicodeEscape = scanner.hasExtendedUnicodeEscape(); nextTokenWithoutCheck(); - return finishNode(factoryCreateIdentifier(text, originalKeywordKind, hasExtendedUnicodeEscape), pos); + return finishNode( + factoryCreateIdentifier( + text, + originalKeywordKind, + hasExtendedUnicodeEscape, + ), + pos, + ); } if (token() === SyntaxKind.PrivateIdentifier) { - parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); + parseErrorAtCurrentToken( + privateIdentifierDiagnosticMessage || + Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies, + ); return createIdentifier(/*isIdentifier*/ true); } - if (token() === SyntaxKind.Unknown && scanner.tryScan(() => scanner.reScanInvalidIdentifier() === SyntaxKind.Identifier)) { + if ( + token() === SyntaxKind.Unknown && + scanner.tryScan( + () => scanner.reScanInvalidIdentifier() === SyntaxKind.Identifier, + ) + ) { // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser. return createIdentifier(/*isIdentifier*/ true); } @@ -2651,49 +4060,87 @@ namespace Parser { const isReservedWord = scanner.isReservedWord(); const msgArg = scanner.getTokenText(); - const defaultMessage = isReservedWord ? - Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : - Diagnostics.Identifier_expected; + const defaultMessage = isReservedWord + ? Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here + : Diagnostics.Identifier_expected; - return createMissingNode(SyntaxKind.Identifier, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); + return createMissingNode( + SyntaxKind.Identifier, + reportAtCurrentPosition, + diagnosticMessage || defaultMessage, + msgArg, + ); } - function parseBindingIdentifier(privateIdentifierDiagnosticMessage?: DiagnosticMessage) { - return createIdentifier(isBindingIdentifier(), /*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage); + function parseBindingIdentifier( + privateIdentifierDiagnosticMessage?: DiagnosticMessage, + ) { + return createIdentifier( + isBindingIdentifier(), + /*diagnosticMessage*/ undefined, + privateIdentifierDiagnosticMessage, + ); } - function parseIdentifier(diagnosticMessage?: DiagnosticMessage, privateIdentifierDiagnosticMessage?: DiagnosticMessage): Identifier { - return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage); + function parseIdentifier( + diagnosticMessage?: DiagnosticMessage, + privateIdentifierDiagnosticMessage?: DiagnosticMessage, + ): Identifier { + return createIdentifier( + isIdentifier(), + diagnosticMessage, + privateIdentifierDiagnosticMessage, + ); } - function parseIdentifierName(diagnosticMessage?: DiagnosticMessage): Identifier { - return createIdentifier(tokenIsIdentifierOrKeyword(token()), diagnosticMessage); + function parseIdentifierName( + diagnosticMessage?: DiagnosticMessage, + ): Identifier { + return createIdentifier( + tokenIsIdentifierOrKeyword(token()), + diagnosticMessage, + ); } function parseIdentifierNameErrorOnUnicodeEscapeSequence(): Identifier { if (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape()) { - parseErrorAtCurrentToken(Diagnostics.Unicode_escape_sequence_cannot_appear_here); + parseErrorAtCurrentToken( + Diagnostics.Unicode_escape_sequence_cannot_appear_here, + ); } return createIdentifier(tokenIsIdentifierOrKeyword(token())); } function isLiteralPropertyName(): boolean { - return tokenIsIdentifierOrKeyword(token()) || + return ( + tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.StringLiteral || - token() === SyntaxKind.NumericLiteral; + token() === SyntaxKind.NumericLiteral + ); } function isImportAttributeName(): boolean { - return tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.StringLiteral; + return ( + tokenIsIdentifierOrKeyword(token()) || + token() === SyntaxKind.StringLiteral + ); } - function parsePropertyNameWorker(allowComputedPropertyNames: boolean): PropertyName { - if (token() === SyntaxKind.StringLiteral || token() === SyntaxKind.NumericLiteral) { + function parsePropertyNameWorker( + allowComputedPropertyNames: boolean, + ): PropertyName { + if ( + token() === SyntaxKind.StringLiteral || + token() === SyntaxKind.NumericLiteral + ) { const node = parseLiteralNode() as StringLiteral | NumericLiteral; node.text = internIdentifier(node.text); return node; } - if (allowComputedPropertyNames && token() === SyntaxKind.OpenBracketToken) { + if ( + allowComputedPropertyNames && + token() === SyntaxKind.OpenBracketToken + ) { return parseComputedPropertyName(); } if (token() === SyntaxKind.PrivateIdentifier) { @@ -2722,7 +4169,9 @@ namespace Parser { function parsePrivateIdentifier(): PrivateIdentifier { const pos = getNodePos(); - const node = factoryCreatePrivateIdentifier(internIdentifier(scanner.getTokenValue())); + const node = factoryCreatePrivateIdentifier( + internIdentifier(scanner.getTokenValue()), + ); nextToken(); return finishNode(node, pos); } @@ -2766,11 +4215,13 @@ namespace Parser { } function canFollowExportModifier(): boolean { - return token() === SyntaxKind.AtToken - || token() !== SyntaxKind.AsteriskToken - && token() !== SyntaxKind.AsKeyword - && token() !== SyntaxKind.OpenBraceToken - && canFollowModifier(); + return ( + token() === SyntaxKind.AtToken || + (token() !== SyntaxKind.AsteriskToken && + token() !== SyntaxKind.AsKeyword && + token() !== SyntaxKind.OpenBraceToken && + canFollowModifier()) + ); } function nextTokenCanFollowExportModifier(): boolean { @@ -2783,25 +4234,34 @@ namespace Parser { } function canFollowModifier(): boolean { - return token() === SyntaxKind.OpenBracketToken - || token() === SyntaxKind.OpenBraceToken - || token() === SyntaxKind.AsteriskToken - || token() === SyntaxKind.DotDotDotToken - || isLiteralPropertyName(); + return ( + token() === SyntaxKind.OpenBracketToken || + token() === SyntaxKind.OpenBraceToken || + token() === SyntaxKind.AsteriskToken || + token() === SyntaxKind.DotDotDotToken || + isLiteralPropertyName() + ); } function nextTokenCanFollowDefaultKeyword(): boolean { nextToken(); - return token() === SyntaxKind.ClassKeyword - || token() === SyntaxKind.FunctionKeyword - || token() === SyntaxKind.InterfaceKeyword - || token() === SyntaxKind.AtToken - || (token() === SyntaxKind.AbstractKeyword && lookAhead(nextTokenIsClassKeywordOnSameLine)) - || (token() === SyntaxKind.AsyncKeyword && lookAhead(nextTokenIsFunctionKeywordOnSameLine)); + return ( + token() === SyntaxKind.ClassKeyword || + token() === SyntaxKind.FunctionKeyword || + token() === SyntaxKind.InterfaceKeyword || + token() === SyntaxKind.AtToken || + (token() === SyntaxKind.AbstractKeyword && + lookAhead(nextTokenIsClassKeywordOnSameLine)) || + (token() === SyntaxKind.AsyncKeyword && + lookAhead(nextTokenIsFunctionKeywordOnSameLine)) + ); } // True if positioned at the start of a list element - function isListElement(parsingContext: ParsingContext, inErrorRecovery: boolean): boolean { + function isListElement( + parsingContext: ParsingContext, + inErrorRecovery: boolean, + ): boolean { const node = currentNode(parsingContext); if (node) { return true; @@ -2817,9 +4277,16 @@ namespace Parser { // we're parsing. For example, if we have a semicolon in the middle of a class, then // we really don't want to assume the class is over and we're on a statement in the // outer module. We just want to consume and move on. - return !(token() === SyntaxKind.SemicolonToken && inErrorRecovery) && isStartOfStatement(); + return ( + !( + token() === SyntaxKind.SemicolonToken && inErrorRecovery + ) && isStartOfStatement() + ); case ParsingContext.SwitchClauses: - return token() === SyntaxKind.CaseKeyword || token() === SyntaxKind.DefaultKeyword; + return ( + token() === SyntaxKind.CaseKeyword || + token() === SyntaxKind.DefaultKeyword + ); case ParsingContext.TypeMembers: return lookAhead(isTypeMemberStart); case ParsingContext.ClassMembers: @@ -2827,11 +4294,17 @@ namespace Parser { // not in error recovery. If we're in error recovery, we don't want an errant // semicolon to be treated as a class member (since they're almost always used // for statements. - return lookAhead(isClassMemberStart) || (token() === SyntaxKind.SemicolonToken && !inErrorRecovery); + return ( + lookAhead(isClassMemberStart) || + (token() === SyntaxKind.SemicolonToken && !inErrorRecovery) + ); case ParsingContext.EnumMembers: // Include open bracket computed properties. This technically also lets in indexers, // which would be a candidate for improved error reporting. - return token() === SyntaxKind.OpenBracketToken || isLiteralPropertyName(); + return ( + token() === SyntaxKind.OpenBracketToken || + isLiteralPropertyName() + ); case ParsingContext.ObjectLiteralMembers: switch (token()) { case SyntaxKind.OpenBracketToken: @@ -2845,7 +4318,11 @@ namespace Parser { case ParsingContext.RestProperties: return isLiteralPropertyName(); case ParsingContext.ObjectBindingElements: - return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName(); + return ( + token() === SyntaxKind.OpenBracketToken || + token() === SyntaxKind.DotDotDotToken || + isLiteralPropertyName() + ); case ParsingContext.ImportAttributes: return isImportAttributeName(); case ParsingContext.HeritageClauseElement: @@ -2856,29 +4333,46 @@ namespace Parser { } if (!inErrorRecovery) { - return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword(); + return ( + isStartOfLeftHandSideExpression() && + !isHeritageClauseExtendsOrImplementsKeyword() + ); } else { // If we're in error recovery we tighten up what we're willing to match. // That way we don't treat something like "this" as a valid heritage clause // element during recovery. - return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword(); + return ( + isIdentifier() && + !isHeritageClauseExtendsOrImplementsKeyword() + ); } case ParsingContext.VariableDeclarations: return isBindingIdentifierOrPrivateIdentifierOrPattern(); case ParsingContext.ArrayBindingElements: - return token() === SyntaxKind.CommaToken || token() === SyntaxKind.DotDotDotToken || isBindingIdentifierOrPrivateIdentifierOrPattern(); + return ( + token() === SyntaxKind.CommaToken || + token() === SyntaxKind.DotDotDotToken || + isBindingIdentifierOrPrivateIdentifierOrPattern() + ); case ParsingContext.TypeParameters: - return token() === SyntaxKind.InKeyword || token() === SyntaxKind.ConstKeyword || isIdentifier(); + return ( + token() === SyntaxKind.InKeyword || + token() === SyntaxKind.ConstKeyword || + isIdentifier() + ); case ParsingContext.ArrayLiteralMembers: switch (token()) { case SyntaxKind.CommaToken: case SyntaxKind.DotToken: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`) return true; } - // falls through + // falls through case ParsingContext.ArgumentExpressions: - return token() === SyntaxKind.DotDotDotToken || isStartOfExpression(); + return ( + token() === SyntaxKind.DotDotDotToken || + isStartOfExpression() + ); case ParsingContext.Parameters: return isStartOfParameter(/*isJSDocParameter*/ false); case ParsingContext.JSDocParameters: @@ -2891,20 +4385,29 @@ namespace Parser { case ParsingContext.ImportOrExportSpecifiers: // bail out if the next token is [FromKeyword StringLiteral]. // That means we're in something like `import { from "mod"`. Stop here can give better error message. - if (token() === SyntaxKind.FromKeyword && lookAhead(nextTokenIsStringLiteral)) { + if ( + token() === SyntaxKind.FromKeyword && + lookAhead(nextTokenIsStringLiteral) + ) { return false; } return tokenIsIdentifierOrKeyword(token()); case ParsingContext.JsxAttributes: - return tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.OpenBraceToken; - case ParsingContext.JsxChildren: + return ( + tokenIsIdentifierOrKeyword(token()) || + token() === SyntaxKind.OpenBraceToken + ); + case ParsingContext.JsxChildren: return true; case ParsingContext.JSDocComment: return true; case ParsingContext.Count: return Debug.fail("ParsingContext.Count used as a context"); // Not a real context, only a marker. default: - Debug.assertNever(parsingContext, "Non-exhaustive case in 'isListElement'."); + Debug.assertNever( + parsingContext, + "Non-exhaustive case in 'isListElement'.", + ); } } @@ -2920,7 +4423,12 @@ namespace Parser { // extends {} implements const next = nextToken(); - return next === SyntaxKind.CommaToken || next === SyntaxKind.OpenBraceToken || next === SyntaxKind.ExtendsKeyword || next === SyntaxKind.ImplementsKeyword; + return ( + next === SyntaxKind.CommaToken || + next === SyntaxKind.OpenBraceToken || + next === SyntaxKind.ExtendsKeyword || + next === SyntaxKind.ImplementsKeyword + ); } return true; @@ -2981,17 +4489,34 @@ namespace Parser { case ParsingContext.ImportAttributes: return token() === SyntaxKind.CloseBraceToken; case ParsingContext.SwitchClauseStatements: - return token() === SyntaxKind.CloseBraceToken || token() === SyntaxKind.CaseKeyword || token() === SyntaxKind.DefaultKeyword; + return ( + token() === SyntaxKind.CloseBraceToken || + token() === SyntaxKind.CaseKeyword || + token() === SyntaxKind.DefaultKeyword + ); case ParsingContext.HeritageClauseElement: - return token() === SyntaxKind.OpenBraceToken || token() === SyntaxKind.ExtendsKeyword || token() === SyntaxKind.ImplementsKeyword; + return ( + token() === SyntaxKind.OpenBraceToken || + token() === SyntaxKind.ExtendsKeyword || + token() === SyntaxKind.ImplementsKeyword + ); case ParsingContext.VariableDeclarations: return isVariableDeclaratorListTerminator(); case ParsingContext.TypeParameters: // Tokens other than '>' are here for better error recovery - return token() === SyntaxKind.GreaterThanToken || token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.OpenBraceToken || token() === SyntaxKind.ExtendsKeyword || token() === SyntaxKind.ImplementsKeyword; + return ( + token() === SyntaxKind.GreaterThanToken || + token() === SyntaxKind.OpenParenToken || + token() === SyntaxKind.OpenBraceToken || + token() === SyntaxKind.ExtendsKeyword || + token() === SyntaxKind.ImplementsKeyword + ); case ParsingContext.ArgumentExpressions: // Tokens other than ')' are here for better error recovery - return token() === SyntaxKind.CloseParenToken || token() === SyntaxKind.SemicolonToken; + return ( + token() === SyntaxKind.CloseParenToken || + token() === SyntaxKind.SemicolonToken + ); case ParsingContext.ArrayLiteralMembers: case ParsingContext.TupleElementTypes: case ParsingContext.ArrayBindingElements: @@ -3000,16 +4525,29 @@ namespace Parser { case ParsingContext.Parameters: case ParsingContext.RestProperties: // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery - return token() === SyntaxKind.CloseParenToken || token() === SyntaxKind.CloseBracketToken /*|| token === SyntaxKind.OpenBraceToken*/; + return ( + token() === SyntaxKind.CloseParenToken || + token() === + SyntaxKind.CloseBracketToken /*|| token === SyntaxKind.OpenBraceToken*/ + ); case ParsingContext.TypeArguments: // All other tokens should cause the type-argument to terminate except comma token return token() !== SyntaxKind.CommaToken; case ParsingContext.HeritageClauses: - return token() === SyntaxKind.OpenBraceToken || token() === SyntaxKind.CloseBraceToken; + return ( + token() === SyntaxKind.OpenBraceToken || + token() === SyntaxKind.CloseBraceToken + ); case ParsingContext.JsxAttributes: - return token() === SyntaxKind.GreaterThanToken || token() === SyntaxKind.SlashToken; + return ( + token() === SyntaxKind.GreaterThanToken || + token() === SyntaxKind.SlashToken + ); case ParsingContext.JsxChildren: - return token() === SyntaxKind.LessThanToken && lookAhead(nextTokenIsSlash); + return ( + token() === SyntaxKind.LessThanToken && + lookAhead(nextTokenIsSlash) + ); default: return false; } @@ -3047,7 +4585,10 @@ namespace Parser { Debug.assert(parsingContext, "Missing parsing context"); for (let kind = 0; kind < ParsingContext.Count; kind++) { if (parsingContext & (1 << kind)) { - if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) { + if ( + isListElement(kind, /*inErrorRecovery*/ true) || + isListTerminator(kind) + ) { return true; } } @@ -3057,7 +4598,10 @@ namespace Parser { } // Parses a list of elements - function parseList(kind: ParsingContext, parseElement: () => T): NodeArray { + function parseList( + kind: ParsingContext, + parseElement: () => T, + ): NodeArray { const saveParsingContext = parsingContext; parsingContext |= 1 << kind; const list = []; @@ -3079,7 +4623,10 @@ namespace Parser { return createNodeArray(list, listPos); } - function parseListElement(parsingContext: ParsingContext, parseElement: () => T): T { + function parseListElement( + parsingContext: ParsingContext, + parseElement: () => T, + ): T { const node = currentNode(parsingContext); if (node) { return consumeNode(node) as T; @@ -3088,7 +4635,10 @@ namespace Parser { return parseElement(); } - function currentNode(parsingContext: ParsingContext, pos?: number): Node | undefined { + function currentNode( + parsingContext: ParsingContext, + pos?: number, + ): Node | undefined { // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. // // If there is an outstanding parse error that we've encountered, but not attached to @@ -3098,17 +4648,27 @@ namespace Parser { // Note: This may be too conservative. Perhaps we could reuse the node and set the bit // on it (or its leftmost child) as having the error. For now though, being conservative // is nice and likely won't ever affect perf. - if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { + if ( + !syntaxCursor || + !isReusableParsingContext(parsingContext) || + parseErrorBeforeNextFinishedNode + ) { return undefined; } - const node = syntaxCursor.currentNode(pos ?? scanner.getTokenFullStart()); + const node = syntaxCursor.currentNode( + pos ?? scanner.getTokenFullStart(), + ); // Can't reuse a missing node. // Can't reuse a node that intersected the change range. // Can't reuse a node that contains a parse error. This is necessary so that we // produce the same set of errors again. - if (nodeIsMissing(node) || node.intersectsChange || containsParseError(node)) { + if ( + nodeIsMissing(node) || + node.intersectsChange || + containsParseError(node) + ) { return undefined; } @@ -3130,16 +4690,16 @@ namespace Parser { // Ok, we have a node that looks like it could be reused. Now verify that it is valid // in the current list parsing context that we're currently at. - if (!canReuseNode(node, parsingContext)) { + if (!canReuseNode(node as Node, parsingContext)) { return undefined; } - if (canHaveJSDoc(node) && node.jsDoc?.jsDocCache) { + if (canHaveJSDoc(node as Node) && (node as Partial).jsDoc?.jsDocCache) { // jsDocCache may include tags from parent nodes, which might have been modified. - node.jsDoc.jsDocCache = undefined; + (node as Partial).jsDoc!.jsDocCache = undefined; } - return node; + return node as Node; } function consumeNode(node: Node) { @@ -3258,7 +4818,7 @@ namespace Parser { // Method declarations are not necessarily reusable. An object-literal // may have a method calls "constructor(...)" and we must reparse that // into an actual .ConstructorDeclaration. - const methodDeclaration = node as MethodDeclaration; + const methodDeclaration = node; const nameIsConstructor = methodDeclaration.name.kind === SyntaxKind.Identifier && methodDeclaration.name.escapedText === "constructor"; @@ -3358,7 +4918,7 @@ namespace Parser { // // In order to prevent this, we do not allow a variable declarator to be reused if it // has an initializer. - const variableDeclarator = node as VariableDeclaration; + const variableDeclarator = node; return variableDeclarator.initializer === undefined; } @@ -3368,7 +4928,7 @@ namespace Parser { } // See the comment in isReusableVariableDeclaration for why we do this. - const parameter = node as ParameterDeclaration; + const parameter = node; return parameter.initializer === undefined; } @@ -3387,64 +4947,122 @@ namespace Parser { switch (context) { case ParsingContext.SourceElements: return token() === SyntaxKind.DefaultKeyword - ? parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.ExportKeyword)) - : parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected); + ? parseErrorAtCurrentToken( + Diagnostics._0_expected, + tokenToString(SyntaxKind.ExportKeyword), + ) + : parseErrorAtCurrentToken( + Diagnostics.Declaration_or_statement_expected, + ); case ParsingContext.BlockStatements: - return parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected); + return parseErrorAtCurrentToken( + Diagnostics.Declaration_or_statement_expected, + ); case ParsingContext.SwitchClauses: - return parseErrorAtCurrentToken(Diagnostics.case_or_default_expected); + return parseErrorAtCurrentToken( + Diagnostics.case_or_default_expected, + ); case ParsingContext.SwitchClauseStatements: return parseErrorAtCurrentToken(Diagnostics.Statement_expected); case ParsingContext.RestProperties: // fallthrough case ParsingContext.TypeMembers: - return parseErrorAtCurrentToken(Diagnostics.Property_or_signature_expected); + return parseErrorAtCurrentToken( + Diagnostics.Property_or_signature_expected, + ); case ParsingContext.ClassMembers: - return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected); + return parseErrorAtCurrentToken( + Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected, + ); case ParsingContext.EnumMembers: - return parseErrorAtCurrentToken(Diagnostics.Enum_member_expected); + return parseErrorAtCurrentToken( + Diagnostics.Enum_member_expected, + ); case ParsingContext.HeritageClauseElement: - return parseErrorAtCurrentToken(Diagnostics.Expression_expected); + return parseErrorAtCurrentToken( + Diagnostics.Expression_expected, + ); case ParsingContext.VariableDeclarations: return isKeyword(token()) - ? parseErrorAtCurrentToken(Diagnostics._0_is_not_allowed_as_a_variable_declaration_name, tokenToString(token())!) - : parseErrorAtCurrentToken(Diagnostics.Variable_declaration_expected); + ? parseErrorAtCurrentToken( + Diagnostics._0_is_not_allowed_as_a_variable_declaration_name, + tokenToString(token())!, + ) + : parseErrorAtCurrentToken( + Diagnostics.Variable_declaration_expected, + ); case ParsingContext.ObjectBindingElements: - return parseErrorAtCurrentToken(Diagnostics.Property_destructuring_pattern_expected); + return parseErrorAtCurrentToken( + Diagnostics.Property_destructuring_pattern_expected, + ); case ParsingContext.ArrayBindingElements: - return parseErrorAtCurrentToken(Diagnostics.Array_element_destructuring_pattern_expected); + return parseErrorAtCurrentToken( + Diagnostics.Array_element_destructuring_pattern_expected, + ); case ParsingContext.ArgumentExpressions: - return parseErrorAtCurrentToken(Diagnostics.Argument_expression_expected); + return parseErrorAtCurrentToken( + Diagnostics.Argument_expression_expected, + ); case ParsingContext.ObjectLiteralMembers: - return parseErrorAtCurrentToken(Diagnostics.Property_assignment_expected); + return parseErrorAtCurrentToken( + Diagnostics.Property_assignment_expected, + ); case ParsingContext.ArrayLiteralMembers: - return parseErrorAtCurrentToken(Diagnostics.Expression_or_comma_expected); + return parseErrorAtCurrentToken( + Diagnostics.Expression_or_comma_expected, + ); case ParsingContext.JSDocParameters: - return parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected); + return parseErrorAtCurrentToken( + Diagnostics.Parameter_declaration_expected, + ); case ParsingContext.Parameters: return isKeyword(token()) - ? parseErrorAtCurrentToken(Diagnostics._0_is_not_allowed_as_a_parameter_name, tokenToString(token())!) - : parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected); + ? parseErrorAtCurrentToken( + Diagnostics._0_is_not_allowed_as_a_parameter_name, + tokenToString(token())!, + ) + : parseErrorAtCurrentToken( + Diagnostics.Parameter_declaration_expected, + ); case ParsingContext.TypeParameters: - return parseErrorAtCurrentToken(Diagnostics.Type_parameter_declaration_expected); + return parseErrorAtCurrentToken( + Diagnostics.Type_parameter_declaration_expected, + ); case ParsingContext.TypeArguments: - return parseErrorAtCurrentToken(Diagnostics.Type_argument_expected); + return parseErrorAtCurrentToken( + Diagnostics.Type_argument_expected, + ); case ParsingContext.TupleElementTypes: return parseErrorAtCurrentToken(Diagnostics.Type_expected); case ParsingContext.HeritageClauses: - return parseErrorAtCurrentToken(Diagnostics.Unexpected_token_expected); + return parseErrorAtCurrentToken( + Diagnostics.Unexpected_token_expected, + ); case ParsingContext.ImportOrExportSpecifiers: if (token() === SyntaxKind.FromKeyword) { - return parseErrorAtCurrentToken(Diagnostics._0_expected, "}"); + return parseErrorAtCurrentToken( + Diagnostics._0_expected, + "}", + ); } - return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + return parseErrorAtCurrentToken( + Diagnostics.Identifier_expected, + ); case ParsingContext.JsxAttributes: - return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + return parseErrorAtCurrentToken( + Diagnostics.Identifier_expected, + ); case ParsingContext.JsxChildren: - return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + return parseErrorAtCurrentToken( + Diagnostics.Identifier_expected, + ); case ParsingContext.ImportAttributes: - return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected); + return parseErrorAtCurrentToken( + Diagnostics.Identifier_or_string_literal_expected, + ); case ParsingContext.JSDocComment: - return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + return parseErrorAtCurrentToken( + Diagnostics.Identifier_expected, + ); case ParsingContext.Count: return Debug.fail("ParsingContext.Count used as a context"); // Not a real context, only a marker. default: @@ -3453,9 +5071,21 @@ namespace Parser { } // Parses a comma-delimited list of elements - function parseDelimitedList(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimiter?: boolean): NodeArray; - function parseDelimitedList(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimiter?: boolean): NodeArray> | undefined; - function parseDelimitedList(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimiter?: boolean): NodeArray> | undefined { + function parseDelimitedList( + kind: ParsingContext, + parseElement: () => T, + considerSemicolonAsDelimiter?: boolean, + ): NodeArray; + function parseDelimitedList( + kind: ParsingContext, + parseElement: () => T, + considerSemicolonAsDelimiter?: boolean, + ): NodeArray> | undefined; + function parseDelimitedList( + kind: ParsingContext, + parseElement: () => T, + considerSemicolonAsDelimiter?: boolean, + ): NodeArray> | undefined { const saveParsingContext = parsingContext; parsingContext |= 1 << kind; const list: NonNullable[] = []; @@ -3485,14 +5115,21 @@ namespace Parser { // We didn't get a comma, and the list wasn't terminated, explicitly parse // out a comma so we give a good error message. - parseExpected(SyntaxKind.CommaToken, getExpectedCommaDiagnostic(kind)); + parseExpected( + SyntaxKind.CommaToken, + getExpectedCommaDiagnostic(kind), + ); // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of // parse errors. For example, this can happen when people do things like use // a semicolon to delimit object literal members. Note: we'll have already // reported an error when we called parseExpected above. - if (considerSemicolonAsDelimiter && token() === SyntaxKind.SemicolonToken && !scanner.hasPrecedingLineBreak()) { + if ( + considerSemicolonAsDelimiter && + token() === SyntaxKind.SemicolonToken && + !scanner.hasPrecedingLineBreak() + ) { nextToken(); } if (startPos === scanner.getTokenFullStart()) { @@ -3521,11 +5158,18 @@ namespace Parser { // was a trailing comma. // Check if the last token was a comma. // Always preserve a trailing comma by marking it on the NodeArray - return createNodeArray(list, listPos, /*end*/ undefined, commaStart >= 0); + return createNodeArray( + list, + listPos, + /*end*/ undefined, + commaStart >= 0, + ); } function getExpectedCommaDiagnostic(kind: ParsingContext) { - return kind === ParsingContext.EnumMembers ? Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined; + return kind === ParsingContext.EnumMembers + ? Diagnostics.An_enum_member_name_must_be_followed_by_a_or + : undefined; } interface MissingList extends NodeArray { @@ -3542,7 +5186,12 @@ namespace Parser { return !!(arr as MissingList).isMissingList; } - function parseBracketedList(kind: ParsingContext, parseElement: () => T, open: PunctuationSyntaxKind, close: PunctuationSyntaxKind): NodeArray { + function parseBracketedList( + kind: ParsingContext, + parseElement: () => T, + open: PunctuationSyntaxKind, + close: PunctuationSyntaxKind, + ): NodeArray { if (parseExpected(open)) { const result = parseDelimitedList(kind, parseElement); parseExpected(close); @@ -3552,9 +5201,14 @@ namespace Parser { return createMissingList(); } - function parseEntityName(allowReservedWords: boolean, diagnosticMessage?: DiagnosticMessage): EntityName { + function parseEntityName( + allowReservedWords: boolean, + diagnosticMessage?: DiagnosticMessage, + ): EntityName { const pos = getNodePos(); - let entity: EntityName = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage); + let entity: EntityName = allowReservedWords + ? parseIdentifierName(diagnosticMessage) + : parseIdentifier(diagnosticMessage); while (parseOptional(SyntaxKind.DotToken)) { if (token() === SyntaxKind.LessThanToken) { // The entity is part of a JSDoc-style generic. We will use the gap between `typeName` and @@ -3564,7 +5218,11 @@ namespace Parser { entity = finishNode( factory.createQualifiedName( entity, - parseRightSideOfDot(allowReservedWords, /*allowPrivateIdentifiers*/ false, /*allowUnicodeEscapeSequenceInIdentifierName*/ true) as Identifier, + parseRightSideOfDot( + allowReservedWords, + /*allowPrivateIdentifiers*/ false, + /*allowUnicodeEscapeSequenceInIdentifierName*/ true, + ) as Identifier, ), pos, ); @@ -3572,11 +5230,21 @@ namespace Parser { return entity; } - function createQualifiedName(entity: EntityName, name: Identifier): QualifiedName { - return finishNode(factory.createQualifiedName(entity, name), entity.pos); + function createQualifiedName( + entity: EntityName, + name: Identifier, + ): QualifiedName { + return finishNode( + factory.createQualifiedName(entity, name), + entity.pos, + ); } - function parseRightSideOfDot(allowIdentifierNames: boolean, allowPrivateIdentifiers: boolean, allowUnicodeEscapeSequenceInIdentifierName: boolean): Identifier | PrivateIdentifier { + function parseRightSideOfDot( + allowIdentifierNames: boolean, + allowPrivateIdentifiers: boolean, + allowUnicodeEscapeSequenceInIdentifierName: boolean, + ): Identifier | PrivateIdentifier { // Technically a keyword is valid here as all identifiers and keywords are identifier names. // However, often we'll encounter this in error situations when the identifier or keyword // is actually starting another valid construct. @@ -3596,24 +5264,41 @@ namespace Parser { // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword". // In the first case though, ASI will not take effect because there is not a // line terminator after the identifier or keyword. - if (scanner.hasPrecedingLineBreak() && tokenIsIdentifierOrKeyword(token())) { - const matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + if ( + scanner.hasPrecedingLineBreak() && + tokenIsIdentifierOrKeyword(token()) + ) { + const matchesPattern = lookAhead( + nextTokenIsIdentifierOrKeywordOnSameLine, + ); if (matchesPattern) { // Report that we need an identifier. However, report it right after the dot, // and not on the next token. This is because the next token might actually // be an identifier and the error would be quite confusing. - return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Identifier_expected); + return createMissingNode( + SyntaxKind.Identifier, + /*reportAtCurrentPosition*/ true, + Diagnostics.Identifier_expected, + ); } } if (token() === SyntaxKind.PrivateIdentifier) { const node = parsePrivateIdentifier(); - return allowPrivateIdentifiers ? node : createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Identifier_expected); + return allowPrivateIdentifiers + ? node + : createMissingNode( + SyntaxKind.Identifier, + /*reportAtCurrentPosition*/ true, + Diagnostics.Identifier_expected, + ); } if (allowIdentifierNames) { - return allowUnicodeEscapeSequenceInIdentifierName ? parseIdentifierName() : parseIdentifierNameErrorOnUnicodeEscapeSequence(); + return allowUnicodeEscapeSequenceInIdentifierName + ? parseIdentifierName() + : parseIdentifierNameErrorOnUnicodeEscapeSequence(); } return parseIdentifier(); @@ -3631,7 +5316,9 @@ namespace Parser { return createNodeArray(list, pos); } - function parseTemplateExpression(isTaggedTemplate: boolean): TemplateExpression { + function parseTemplateExpression( + isTaggedTemplate: boolean, + ): TemplateExpression { const pos = getNodePos(); return finishNode( factory.createTemplateExpression( @@ -3683,7 +5370,11 @@ namespace Parser { } else { // TODO(rbuckton): Do we need to call `parseExpectedToken` or can we just call `createMissingNode` directly? - return parseExpectedToken(SyntaxKind.TemplateTail, Diagnostics._0_expected, tokenToString(SyntaxKind.CloseBraceToken)) as TemplateTail; + return parseExpectedToken( + SyntaxKind.TemplateTail, + Diagnostics._0_expected, + tokenToString(SyntaxKind.CloseBraceToken), + ) as TemplateTail; } } @@ -3698,43 +5389,76 @@ namespace Parser { ); } - function parseLiteralNode(): LiteralExpression { - return parseLiteralLikeNode(token()) as LiteralExpression; + function parseLiteralNode(): LiteralLikeNode { + return parseLiteralLikeNode(token()); } function parseTemplateHead(isTaggedTemplate: boolean): TemplateHead { - if (!isTaggedTemplate && scanner.getTokenFlags() & TokenFlags.IsInvalid) { + if ( + !isTaggedTemplate && + scanner.getTokenFlags() & TokenFlags.IsInvalid + ) { reScanTemplateToken(/*isTaggedTemplate*/ false); } const fragment = parseLiteralLikeNode(token()); - Debug.assert(fragment.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind"); - return fragment as TemplateHead; + Debug.assert( + fragment.kind === SyntaxKind.TemplateHead, + "Template head has wrong token kind", + ); + return fragment; } - function parseTemplateMiddleOrTemplateTail(): TemplateMiddle | TemplateTail { + function parseTemplateMiddleOrTemplateTail(): + | TemplateMiddle + | TemplateTail + { const fragment = parseLiteralLikeNode(token()); - Debug.assert(fragment.kind === SyntaxKind.TemplateMiddle || fragment.kind === SyntaxKind.TemplateTail, "Template fragment has wrong token kind"); - return fragment as TemplateMiddle | TemplateTail; + Debug.assert( + fragment.kind === SyntaxKind.TemplateMiddle || + fragment.kind === SyntaxKind.TemplateTail, + "Template fragment has wrong token kind", + ); + return fragment; } function getTemplateLiteralRawText(kind: TemplateLiteralToken["kind"]) { - const isLast = kind === SyntaxKind.NoSubstitutionTemplateLiteral || kind === SyntaxKind.TemplateTail; + const isLast = kind === SyntaxKind.NoSubstitutionTemplateLiteral || + kind === SyntaxKind.TemplateTail; const tokenText = scanner.getTokenText(); - return tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2)); + return tokenText.substring( + 1, + tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2), + ); } function parseLiteralLikeNode(kind: SyntaxKind): LiteralLikeNode { const pos = getNodePos(); - const node = isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, scanner.getTokenValue(), getTemplateLiteralRawText(kind), scanner.getTokenFlags() & TokenFlags.TemplateLiteralLikeFlags) : + const node = isTemplateLiteralKind(kind) + ? factory.createTemplateLiteralLikeNode( + kind, + scanner.getTokenValue(), + getTemplateLiteralRawText(kind), + scanner.getTokenFlags() & TokenFlags.TemplateLiteralLikeFlags, + ) // Note that theoretically the following condition would hold true literals like 009, // which is not octal. But because of how the scanner separates the tokens, we would // never get a token like this. Instead, we would get 00 and 9 as two separate tokens. // We also do not need to check for negatives because any prefix operator would be part of a // parent unary expression. - kind === SyntaxKind.NumericLiteral ? factoryCreateNumericLiteral(scanner.getTokenValue(), scanner.getNumericLiteralFlags()) : - kind === SyntaxKind.StringLiteral ? factoryCreateStringLiteral(scanner.getTokenValue(), /*isSingleQuote*/ undefined, scanner.hasExtendedUnicodeEscape()) : - isLiteralKind(kind) ? factoryCreateLiteralLikeNode(kind, scanner.getTokenValue()) : - Debug.fail(); + : kind === SyntaxKind.NumericLiteral + ? factoryCreateNumericLiteral( + scanner.getTokenValue(), + scanner.getNumericLiteralFlags(), + ) + : kind === SyntaxKind.StringLiteral + ? factoryCreateStringLiteral( + scanner.getTokenValue(), + /*isSingleQuote*/ undefined, + scanner.hasExtendedUnicodeEscape(), + ) + : isLiteralKind(kind) + ? factoryCreateLiteralLikeNode(kind, scanner.getTokenValue()) + : Debug.fail(); if (scanner.hasExtendedUnicodeEscape()) { node.hasExtendedUnicodeEscape = true; @@ -3751,12 +5475,23 @@ namespace Parser { // TYPES function parseEntityNameOfTypeReference() { - return parseEntityName(/*allowReservedWords*/ true, Diagnostics.Type_expected); + return parseEntityName( + /*allowReservedWords*/ true, + Diagnostics.Type_expected, + ); } function parseTypeArgumentsOfTypeReference() { - if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === SyntaxKind.LessThanToken) { - return parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken); + if ( + !scanner.hasPrecedingLineBreak() && + reScanLessThanToken() === SyntaxKind.LessThanToken + ) { + return parseBracketedList( + ParsingContext.TypeArguments, + parseType, + SyntaxKind.LessThanToken, + SyntaxKind.GreaterThanToken, + ); } } @@ -3775,14 +5510,19 @@ namespace Parser { function typeHasArrowFunctionBlockingParseError(node: TypeNode): boolean { switch (node.kind) { case SyntaxKind.TypeReference: - return nodeIsMissing((node as TypeReferenceNode).typeName); + return nodeIsMissing(node.typeName); case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: { const { parameters, type } = node as FunctionOrConstructorTypeNode; - return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type); + return ( + isMissingList(parameters) || + typeHasArrowFunctionBlockingParseError(type) + ); } case SyntaxKind.ParenthesizedType: - return typeHasArrowFunctionBlockingParseError((node as ParenthesizedTypeNode).type); + return typeHasArrowFunctionBlockingParseError( + node.type, + ); default: return false; } @@ -3790,7 +5530,14 @@ namespace Parser { function parseThisTypePredicate(lhs: ThisTypeNode): TypePredicateNode { nextToken(); - return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, lhs, parseType()), lhs.pos); + return finishNode( + factory.createTypePredicateNode( + /*assertsModifier*/ undefined, + lhs, + parseType(), + ), + lhs.pos, + ); } function parseThisTypeNode(): ThisTypeNode { @@ -3808,10 +5555,19 @@ namespace Parser { function parseJSDocNonNullableType(): TypeNode { const pos = getNodePos(); nextToken(); - return finishNode(factory.createJSDocNonNullableType(parseNonArrayType(), /*postfix*/ false), pos); + return finishNode( + factory.createJSDocNonNullableType( + parseNonArrayType(), + /*postfix*/ false, + ), + pos, + ); } - function parseJSDocUnknownOrNullableType(): JSDocUnknownType | JSDocNullableType { + function parseJSDocUnknownOrNullableType(): + | JSDocUnknownType + | JSDocNullableType + { const pos = getNodePos(); // skip the ? nextToken(); @@ -3837,7 +5593,10 @@ namespace Parser { return finishNode(factory.createJSDocUnknownType(), pos); } else { - return finishNode(factory.createJSDocNullableType(parseType(), /*postfix*/ false), pos); + return finishNode( + factory.createJSDocNullableType(parseType(), /*postfix*/ false), + pos, + ); } } @@ -3846,17 +5605,37 @@ namespace Parser { const hasJSDoc = hasPrecedingJSDocComment(); if (lookAhead(nextTokenIsOpenParen)) { nextToken(); - const parameters = parseParameters(SignatureFlags.Type | SignatureFlags.JSDoc); - const type = parseReturnType(SyntaxKind.ColonToken, /*isType*/ false); - return withJSDoc(finishNode(factory.createJSDocFunctionType(parameters, type), pos), hasJSDoc); + const parameters = parseParameters( + SignatureFlags.Type | SignatureFlags.JSDoc, + ); + const type = parseReturnType( + SyntaxKind.ColonToken, + /*isType*/ false, + ); + return withJSDoc( + finishNode( + factory.createJSDocFunctionType(parameters, type), + pos, + ), + hasJSDoc, + ); } - return finishNode(factory.createTypeReferenceNode(parseIdentifierName(), /*typeArguments*/ undefined), pos); + return finishNode( + factory.createTypeReferenceNode( + parseIdentifierName(), + /*typeArguments*/ undefined, + ), + pos, + ); } function parseJSDocParameter(): ParameterDeclaration { const pos = getNodePos(); let name: Identifier | undefined; - if (token() === SyntaxKind.ThisKeyword || token() === SyntaxKind.NewKeyword) { + if ( + token() === SyntaxKind.ThisKeyword || + token() === SyntaxKind.NewKeyword + ) { name = parseIdentifierName(); parseExpected(SyntaxKind.ColonToken); } @@ -3879,9 +5658,10 @@ namespace Parser { const pos = getNodePos(); if (parseOptional(SyntaxKind.ModuleKeyword)) { // TODO(rbuckton): We never set the type for a JSDocNamepathType. What should we put here? - const moduleTag = factory.createJSDocNamepathType(/*type*/ undefined!); - terminate: - while (true) { + const moduleTag = factory.createJSDocNamepathType( + /*type*/ undefined!, + ); + terminate: while (true) { switch (token()) { case SyntaxKind.CloseBraceToken: case SyntaxKind.EndOfFileToken: @@ -3915,13 +5695,21 @@ namespace Parser { parseExpected(SyntaxKind.TypeOfKeyword); const entityName = parseEntityName(/*allowReservedWords*/ true); // Make sure we perform ASI to prevent parsing the next line's type arguments as part of an instantiation expression. - const typeArguments = !scanner.hasPrecedingLineBreak() ? tryParseTypeArguments() : undefined; - return finishNode(factory.createTypeQueryNode(entityName, typeArguments), pos); + const typeArguments = !scanner.hasPrecedingLineBreak() + ? tryParseTypeArguments() + : undefined; + return finishNode( + factory.createTypeQueryNode(entityName, typeArguments), + pos, + ); } function parseTypeParameter(): TypeParameterDeclaration { const pos = getNodePos(); - const modifiers = parseModifiers(/*allowDecorators*/ false, /*permitConstAsModifier*/ true); + const modifiers = parseModifiers( + /*allowDecorators*/ false, + /*permitConstAsModifier*/ true, + ); const name = parseIdentifier(); let constraint: TypeNode | undefined; let expression: Expression | undefined; @@ -3945,31 +5733,56 @@ namespace Parser { } } - const defaultType = parseOptional(SyntaxKind.EqualsToken) ? parseType() : undefined; - const node = factory.createTypeParameterDeclaration(modifiers, name, constraint, defaultType); + const defaultType = parseOptional(SyntaxKind.EqualsToken) + ? parseType() + : undefined; + const node = factory.createTypeParameterDeclaration( + modifiers, + name, + constraint, + defaultType, + ); node.expression = expression; return finishNode(node, pos); } - function parseTypeParameters(): NodeArray | undefined { + function parseTypeParameters(): + | NodeArray + | undefined + { if (token() === SyntaxKind.LessThanToken) { - return parseBracketedList(ParsingContext.TypeParameters, parseTypeParameter, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken); + return parseBracketedList( + ParsingContext.TypeParameters, + parseTypeParameter, + SyntaxKind.LessThanToken, + SyntaxKind.GreaterThanToken, + ); } } function isStartOfParameter(isJSDocParameter: boolean): boolean { - return token() === SyntaxKind.DotDotDotToken || + return ( + token() === SyntaxKind.DotDotDotToken || isBindingIdentifierOrPrivateIdentifierOrPattern() || isModifierKind(token()) || token() === SyntaxKind.AtToken || - isStartOfType(/*inStartOfParameter*/ !isJSDocParameter); + isStartOfType(/*inStartOfParameter*/ !isJSDocParameter) + ); } - function parseNameOfParameter(modifiers: NodeArray | undefined) { + function parseNameOfParameter( + modifiers: NodeArray | undefined, + ) { // FormalParameter [Yield,Await]: // BindingElement[?Yield,?Await] - const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_cannot_be_used_as_parameters); - if (getFullWidth(name) === 0 && !some(modifiers) && isModifierKind(token())) { + const name = parseIdentifierOrPattern( + Diagnostics.Private_identifiers_cannot_be_used_as_parameters, + ); + if ( + getFullWidth(name) === 0 && + !some(modifiers) && + isModifierKind(token()) + ) { // in cases like // 'use strict' // function foo(static) @@ -3987,20 +5800,39 @@ namespace Parser { // Be permissive about await and yield by calling isBindingIdentifier instead of isIdentifier; disallowing // them during a speculative parse leads to many more follow-on errors than allowing the function to parse then later // complaining about the use of the keywords. - return isBindingIdentifier() || token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.OpenBraceToken; + return ( + isBindingIdentifier() || + token() === SyntaxKind.OpenBracketToken || + token() === SyntaxKind.OpenBraceToken + ); } - function parseParameter(inOuterAwaitContext: boolean): ParameterDeclaration { + function parseParameter( + inOuterAwaitContext: boolean, + ): ParameterDeclaration { return parseParameterWorker(inOuterAwaitContext); } - function parseParameterForSpeculation(inOuterAwaitContext: boolean): ParameterDeclaration | undefined { - return parseParameterWorker(inOuterAwaitContext, /*allowAmbiguity*/ false); + function parseParameterForSpeculation( + inOuterAwaitContext: boolean, + ): ParameterDeclaration | undefined { + return parseParameterWorker( + inOuterAwaitContext, + /*allowAmbiguity*/ false, + ); } - function parseParameterWorker(inOuterAwaitContext: boolean): ParameterDeclaration; - function parseParameterWorker(inOuterAwaitContext: boolean, allowAmbiguity: false): ParameterDeclaration | undefined; - function parseParameterWorker(inOuterAwaitContext: boolean, allowAmbiguity = true): ParameterDeclaration | undefined { + function parseParameterWorker( + inOuterAwaitContext: boolean, + ): ParameterDeclaration; + function parseParameterWorker( + inOuterAwaitContext: boolean, + allowAmbiguity: false, + ): ParameterDeclaration | undefined; + function parseParameterWorker( + inOuterAwaitContext: boolean, + allowAmbiguity = true, + ): ParameterDeclaration | undefined { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); @@ -4008,9 +5840,9 @@ namespace Parser { // BindingElement[?Yield,?Await] // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. - const modifiers = inOuterAwaitContext ? - doInAwaitContext(() => parseModifiers(/*allowDecorators*/ true)) : - doOutsideOfAwaitContext(() => parseModifiers(/*allowDecorators*/ true)); + const modifiers = inOuterAwaitContext + ? doInAwaitContext(() => parseModifiers(/*allowDecorators*/ true)) + : doOutsideOfAwaitContext(() => parseModifiers(/*allowDecorators*/ true)); if (token() === SyntaxKind.ThisKeyword) { const node = factory.createParameterDeclaration( @@ -4024,7 +5856,10 @@ namespace Parser { const modifier = firstOrUndefined(modifiers); if (modifier) { - parseErrorAtRange(modifier, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters); + parseErrorAtRange( + modifier, + Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters, + ); } return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -4057,15 +5892,27 @@ namespace Parser { return node; } - function parseReturnType(returnToken: SyntaxKind.EqualsGreaterThanToken, isType: boolean): TypeNode; - function parseReturnType(returnToken: SyntaxKind.ColonToken | SyntaxKind.EqualsGreaterThanToken, isType: boolean): TypeNode | undefined; - function parseReturnType(returnToken: SyntaxKind.ColonToken | SyntaxKind.EqualsGreaterThanToken, isType: boolean) { + function parseReturnType( + returnToken: SyntaxKind.EqualsGreaterThanToken, + isType: boolean, + ): TypeNode; + function parseReturnType( + returnToken: SyntaxKind.ColonToken | SyntaxKind.EqualsGreaterThanToken, + isType: boolean, + ): TypeNode | undefined; + function parseReturnType( + returnToken: SyntaxKind.ColonToken | SyntaxKind.EqualsGreaterThanToken, + isType: boolean, + ) { if (shouldParseReturnType(returnToken, isType)) { return allowConditionalTypesAnd(parseTypeOrTypePredicate); } } - function shouldParseReturnType(returnToken: SyntaxKind.ColonToken | SyntaxKind.EqualsGreaterThanToken, isType: boolean): boolean { + function shouldParseReturnType( + returnToken: SyntaxKind.ColonToken | SyntaxKind.EqualsGreaterThanToken, + isType: boolean, + ): boolean { if (returnToken === SyntaxKind.EqualsGreaterThanToken) { parseExpected(returnToken); return true; @@ -4075,16 +5922,28 @@ namespace Parser { } else if (isType && token() === SyntaxKind.EqualsGreaterThanToken) { // This is easy to get backward, especially in type contexts, so parse the type anyway - parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.ColonToken)); + parseErrorAtCurrentToken( + Diagnostics._0_expected, + tokenToString(SyntaxKind.ColonToken), + ); nextToken(); return true; } return false; } - function parseParametersWorker(flags: SignatureFlags, allowAmbiguity: true): NodeArray; - function parseParametersWorker(flags: SignatureFlags, allowAmbiguity: false): NodeArray | undefined; - function parseParametersWorker(flags: SignatureFlags, allowAmbiguity: boolean): NodeArray | undefined { + function parseParametersWorker( + flags: SignatureFlags, + allowAmbiguity: true, + ): NodeArray; + function parseParametersWorker( + flags: SignatureFlags, + allowAmbiguity: false, + ): NodeArray | undefined; + function parseParametersWorker( + flags: SignatureFlags, + allowAmbiguity: boolean, + ): NodeArray | undefined { // FormalParameters [Yield,Await]: (modified) // [empty] // FormalParameterList[?Yield,Await] @@ -4104,9 +5963,15 @@ namespace Parser { setYieldContext(!!(flags & SignatureFlags.Yield)); setAwaitContext(!!(flags & SignatureFlags.Await)); - const parameters = flags & SignatureFlags.JSDoc ? - parseDelimitedList(ParsingContext.JSDocParameters, parseJSDocParameter) : - parseDelimitedList(ParsingContext.Parameters, () => allowAmbiguity ? parseParameter(savedAwaitContext) : parseParameterForSpeculation(savedAwaitContext)); + const parameters = flags & SignatureFlags.JSDoc + ? parseDelimitedList( + ParsingContext.JSDocParameters, + parseJSDocParameter, + ) + : parseDelimitedList(ParsingContext.Parameters, () => + allowAmbiguity + ? parseParameter(savedAwaitContext) + : parseParameterForSpeculation(savedAwaitContext)); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); @@ -4114,7 +5979,9 @@ namespace Parser { return parameters; } - function parseParameters(flags: SignatureFlags): NodeArray { + function parseParameters( + flags: SignatureFlags, + ): NodeArray { // FormalParameters [Yield,Await]: (modified) // [empty] // FormalParameterList[?Yield,Await] @@ -4132,7 +5999,10 @@ namespace Parser { return createMissingList(); } - const parameters = parseParametersWorker(flags, /*allowAmbiguity*/ true); + const parameters = parseParametersWorker( + flags, + /*allowAmbiguity*/ true, + ); parseExpected(SyntaxKind.CloseParenToken); return parameters; } @@ -4148,7 +6018,9 @@ namespace Parser { parseSemicolon(); } - function parseSignatureMember(kind: SyntaxKind.CallSignature | SyntaxKind.ConstructSignature): CallSignatureDeclaration | ConstructSignatureDeclaration { + function parseSignatureMember( + kind: SyntaxKind.CallSignature | SyntaxKind.ConstructSignature, + ): CallSignatureDeclaration | ConstructSignatureDeclaration { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); if (kind === SyntaxKind.ConstructSignature) { @@ -4161,12 +6033,19 @@ namespace Parser { parseTypeMemberSemicolon(); const node = kind === SyntaxKind.CallSignature ? factory.createCallSignature(typeParameters, parameters, type) - : factory.createConstructSignature(typeParameters, parameters, type); + : factory.createConstructSignature( + typeParameters, + parameters, + type, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } function isIndexSignature(): boolean { - return token() === SyntaxKind.OpenBracketToken && lookAhead(isUnambiguouslyIndexSignature); + return ( + token() === SyntaxKind.OpenBracketToken && + lookAhead(isUnambiguouslyIndexSignature) + ); } function isUnambiguouslyIndexSignature() { @@ -4187,7 +6066,10 @@ namespace Parser { // [] // nextToken(); - if (token() === SyntaxKind.DotDotDotToken || token() === SyntaxKind.CloseBracketToken) { + if ( + token() === SyntaxKind.DotDotDotToken || + token() === SyntaxKind.CloseBracketToken + ) { return true; } @@ -4208,7 +6090,10 @@ namespace Parser { // A colon signifies a well formed indexer // A comma should be a badly formed indexer because comma expressions are not allowed // in computed properties. - if (token() === SyntaxKind.ColonToken || token() === SyntaxKind.CommaToken) { + if ( + token() === SyntaxKind.ColonToken || + token() === SyntaxKind.CommaToken + ) { return true; } @@ -4221,32 +6106,67 @@ namespace Parser { // If any of the following tokens are after the question mark, it cannot // be a conditional expression, so treat it as an indexer. nextToken(); - return token() === SyntaxKind.ColonToken || token() === SyntaxKind.CommaToken || token() === SyntaxKind.CloseBracketToken; + return ( + token() === SyntaxKind.ColonToken || + token() === SyntaxKind.CommaToken || + token() === SyntaxKind.CloseBracketToken + ); } - function parseIndexSignatureDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): IndexSignatureDeclaration { - const parameters = parseBracketedList(ParsingContext.Parameters, () => parseParameter(/*inOuterAwaitContext*/ false), SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); + function parseIndexSignatureDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): IndexSignatureDeclaration { + const parameters = parseBracketedList( + ParsingContext.Parameters, + () => parseParameter(/*inOuterAwaitContext*/ false), + SyntaxKind.OpenBracketToken, + SyntaxKind.CloseBracketToken, + ); const type = parseTypeAnnotation(); parseTypeMemberSemicolon(); const node = factory.createIndexSignature(modifiers, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parsePropertyOrMethodSignature(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): PropertySignature | MethodSignature { + function parsePropertyOrMethodSignature( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): PropertySignature | MethodSignature { const name = parsePropertyName(); const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); let node: PropertySignature | MethodSignature; - if (token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken) { + if ( + token() === SyntaxKind.OpenParenToken || + token() === SyntaxKind.LessThanToken + ) { // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] const typeParameters = parseTypeParameters(); const parameters = parseParameters(SignatureFlags.Type); - const type = parseReturnType(SyntaxKind.ColonToken, /*isType*/ true); - node = factory.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type); + const type = parseReturnType( + SyntaxKind.ColonToken, + /*isType*/ true, + ); + node = factory.createMethodSignature( + modifiers, + name, + questionToken, + typeParameters, + parameters, + type, + ); } else { const type = parseTypeAnnotation(); - node = factory.createPropertySignature(modifiers, name, questionToken, type); + node = factory.createPropertySignature( + modifiers, + name, + questionToken, + type, + ); // Although type literal properties cannot not have initializers, we attempt // to parse an initializer so we can report in the checker that an interface // property or type literal property cannot have an initializer. @@ -4284,32 +6204,52 @@ namespace Parser { // If we were able to get any potential identifier, check that it is // the start of a member declaration if (idToken) { - return token() === SyntaxKind.OpenParenToken || + return ( + token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken || token() === SyntaxKind.QuestionToken || token() === SyntaxKind.ColonToken || token() === SyntaxKind.CommaToken || - canParseSemicolon(); + canParseSemicolon() + ); } return false; } function parseTypeMember(): TypeElement { - if (token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken) { + if ( + token() === SyntaxKind.OpenParenToken || + token() === SyntaxKind.LessThanToken + ) { return parseSignatureMember(SyntaxKind.CallSignature); } - if (token() === SyntaxKind.NewKeyword && lookAhead(nextTokenIsOpenParenOrLessThan)) { + if ( + token() === SyntaxKind.NewKeyword && + lookAhead(nextTokenIsOpenParenOrLessThan) + ) { return parseSignatureMember(SyntaxKind.ConstructSignature); } const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers(/*allowDecorators*/ false); if (parseContextualModifier(SyntaxKind.GetKeyword)) { - return parseAccessorDeclaration(pos, hasJSDoc, modifiers, SyntaxKind.GetAccessor, SignatureFlags.Type); + return parseAccessorDeclaration( + pos, + hasJSDoc, + modifiers, + SyntaxKind.GetAccessor, + SignatureFlags.Type, + ); } if (parseContextualModifier(SyntaxKind.SetKeyword)) { - return parseAccessorDeclaration(pos, hasJSDoc, modifiers, SyntaxKind.SetAccessor, SignatureFlags.Type); + return parseAccessorDeclaration( + pos, + hasJSDoc, + modifiers, + SyntaxKind.SetAccessor, + SignatureFlags.Type, + ); } if (isIndexSignature()) { @@ -4320,7 +6260,10 @@ namespace Parser { function nextTokenIsOpenParenOrLessThan() { nextToken(); - return token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken; + return ( + token() === SyntaxKind.OpenParenToken || + token() === SyntaxKind.LessThanToken + ); } function nextTokenIsDot() { @@ -4339,7 +6282,10 @@ namespace Parser { function parseTypeLiteral(): TypeLiteralNode { const pos = getNodePos(); - return finishNode(factory.createTypeLiteralNode(parseObjectTypeMembers()), pos); + return finishNode( + factory.createTypeLiteralNode(parseObjectTypeMembers()), + pos, + ); } function parseObjectTypeMembers(): NodeArray { @@ -4357,13 +6303,20 @@ namespace Parser { function isStartOfMappedType() { nextToken(); - if (token() === SyntaxKind.PlusToken || token() === SyntaxKind.MinusToken) { + if ( + token() === SyntaxKind.PlusToken || + token() === SyntaxKind.MinusToken + ) { return nextToken() === SyntaxKind.ReadonlyKeyword; } if (token() === SyntaxKind.ReadonlyKeyword) { nextToken(); } - return token() === SyntaxKind.OpenBracketToken && nextTokenIsIdentifier() && nextToken() === SyntaxKind.InKeyword; + return ( + token() === SyntaxKind.OpenBracketToken && + nextTokenIsIdentifier() && + nextToken() === SyntaxKind.InKeyword + ); } function parseMappedTypeParameter() { @@ -4371,26 +6324,48 @@ namespace Parser { const name = parseIdentifierName(); parseExpected(SyntaxKind.InKeyword); const type = parseType(); - return finishNode(factory.createTypeParameterDeclaration(/*modifiers*/ undefined, name, type, /*defaultType*/ undefined), pos); + return finishNode( + factory.createTypeParameterDeclaration( + /*modifiers*/ undefined, + name, + type, + /*defaultType*/ undefined, + ), + pos, + ); } function parseMappedType() { const pos = getNodePos(); parseExpected(SyntaxKind.OpenBraceToken); let readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined; - if (token() === SyntaxKind.ReadonlyKeyword || token() === SyntaxKind.PlusToken || token() === SyntaxKind.MinusToken) { - readonlyToken = parseTokenNode(); + if ( + token() === SyntaxKind.ReadonlyKeyword || + token() === SyntaxKind.PlusToken || + token() === SyntaxKind.MinusToken + ) { + readonlyToken = parseTokenNode< + ReadonlyKeyword | PlusToken | MinusToken + >(); if (readonlyToken.kind !== SyntaxKind.ReadonlyKeyword) { parseExpected(SyntaxKind.ReadonlyKeyword); } } parseExpected(SyntaxKind.OpenBracketToken); const typeParameter = parseMappedTypeParameter(); - const nameType = parseOptional(SyntaxKind.AsKeyword) ? parseType() : undefined; + const nameType = parseOptional(SyntaxKind.AsKeyword) + ? parseType() + : undefined; parseExpected(SyntaxKind.CloseBracketToken); let questionToken: QuestionToken | PlusToken | MinusToken | undefined; - if (token() === SyntaxKind.QuestionToken || token() === SyntaxKind.PlusToken || token() === SyntaxKind.MinusToken) { - questionToken = parseTokenNode(); + if ( + token() === SyntaxKind.QuestionToken || + token() === SyntaxKind.PlusToken || + token() === SyntaxKind.MinusToken + ) { + questionToken = parseTokenNode< + QuestionToken | PlusToken | MinusToken + >(); if (questionToken.kind !== SyntaxKind.QuestionToken) { parseExpected(SyntaxKind.QuestionToken); } @@ -4399,7 +6374,17 @@ namespace Parser { parseSemicolon(); const members = parseList(ParsingContext.TypeMembers, parseTypeMember); parseExpected(SyntaxKind.CloseBraceToken); - return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos); + return finishNode( + factory.createMappedTypeNode( + readonlyToken, + typeParameter, + nameType, + questionToken, + type, + members, + ), + pos, + ); } function parseTupleElementType() { @@ -4418,26 +6403,43 @@ namespace Parser { } function isNextTokenColonOrQuestionColon() { - return nextToken() === SyntaxKind.ColonToken || (token() === SyntaxKind.QuestionToken && nextToken() === SyntaxKind.ColonToken); + return ( + nextToken() === SyntaxKind.ColonToken || + (token() === SyntaxKind.QuestionToken && + nextToken() === SyntaxKind.ColonToken) + ); } function isTupleElementName() { if (token() === SyntaxKind.DotDotDotToken) { - return tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon(); + return ( + tokenIsIdentifierOrKeyword(nextToken()) && + isNextTokenColonOrQuestionColon() + ); } - return tokenIsIdentifierOrKeyword(token()) && isNextTokenColonOrQuestionColon(); + return ( + tokenIsIdentifierOrKeyword(token()) && + isNextTokenColonOrQuestionColon() + ); } function parseTupleElementNameOrTupleElementType() { if (lookAhead(isTupleElementName)) { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - const dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken); + const dotDotDotToken = parseOptionalToken( + SyntaxKind.DotDotDotToken, + ); const name = parseIdentifierName(); const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); parseExpected(SyntaxKind.ColonToken); const type = parseTupleElementType(); - const node = factory.createNamedTupleMember(dotDotDotToken, name, questionToken, type); + const node = factory.createNamedTupleMember( + dotDotDotToken, + name, + questionToken, + type, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } return parseTupleElementType(); @@ -4447,7 +6449,12 @@ namespace Parser { const pos = getNodePos(); return finishNode( factory.createTupleTypeNode( - parseBracketedList(ParsingContext.TupleElementTypes, parseTupleElementNameOrTupleElementType, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken), + parseBracketedList( + ParsingContext.TupleElementTypes, + parseTupleElementNameOrTupleElementType, + SyntaxKind.OpenBracketToken, + SyntaxKind.CloseBracketToken, + ), ), pos, ); @@ -4461,12 +6468,18 @@ namespace Parser { return finishNode(factory.createParenthesizedType(type), pos); } - function parseModifiersForConstructorType(): NodeArray | undefined { + function parseModifiersForConstructorType(): + | NodeArray + | undefined + { let modifiers: NodeArray | undefined; if (token() === SyntaxKind.AbstractKeyword) { const pos = getNodePos(); nextToken(); - const modifier = finishNode(factoryCreateToken(SyntaxKind.AbstractKeyword), pos); + const modifier = finishNode( + factoryCreateToken(SyntaxKind.AbstractKeyword), + pos, + ); modifiers = createNodeArray([modifier], pos); } return modifiers; @@ -4477,12 +6490,23 @@ namespace Parser { const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiersForConstructorType(); const isConstructorType = parseOptional(SyntaxKind.NewKeyword); - Debug.assert(!modifiers || isConstructorType, "Per isStartOfFunctionOrConstructorType, a function type cannot have modifiers."); + Debug.assert( + !modifiers || isConstructorType, + "Per isStartOfFunctionOrConstructorType, a function type cannot have modifiers.", + ); const typeParameters = parseTypeParameters(); const parameters = parseParameters(SignatureFlags.Type); - const type = parseReturnType(SyntaxKind.EqualsGreaterThanToken, /*isType*/ false); + const type = parseReturnType( + SyntaxKind.EqualsGreaterThanToken, + /*isType*/ false, + ); const node = isConstructorType - ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, type) + ? factory.createConstructorTypeNode( + modifiers, + typeParameters, + parameters, + type, + ) : factory.createFunctionTypeNode(typeParameters, parameters, type); return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -4497,11 +6521,19 @@ namespace Parser { if (negative) { nextToken(); } - let expression: BooleanLiteral | NullLiteral | LiteralExpression | PrefixUnaryExpression = token() === SyntaxKind.TrueKeyword || token() === SyntaxKind.FalseKeyword || token() === SyntaxKind.NullKeyword ? - parseTokenNode() : - parseLiteralLikeNode(token()) as LiteralExpression; + let expression = token() === SyntaxKind.TrueKeyword || + token() === SyntaxKind.FalseKeyword || + token() === SyntaxKind.NullKeyword + ? parseTokenNode() + : (parseLiteralLikeNode(token())); if (negative) { - expression = finishNode(factory.createPrefixUnaryExpression(SyntaxKind.MinusToken, expression), pos); + expression = finishNode( + factory.createPrefixUnaryExpression( + SyntaxKind.MinusToken, + expression, + ), + pos, + ); } return finishNode(factory.createLiteralTypeNode(expression), pos); } @@ -4523,33 +6555,69 @@ namespace Parser { const openBracePosition = scanner.getTokenStart(); parseExpected(SyntaxKind.OpenBraceToken); const currentToken = token(); - if (currentToken === SyntaxKind.WithKeyword || currentToken === SyntaxKind.AssertKeyword) { + if ( + currentToken === SyntaxKind.WithKeyword || + currentToken === SyntaxKind.AssertKeyword + ) { nextToken(); } else { - parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(SyntaxKind.WithKeyword)); + parseErrorAtCurrentToken( + Diagnostics._0_expected, + tokenToString(SyntaxKind.WithKeyword), + ); } parseExpected(SyntaxKind.ColonToken); - attributes = parseImportAttributes(currentToken as SyntaxKind.WithKeyword | SyntaxKind.AssertKeyword, /*skipKeyword*/ true); + attributes = parseImportAttributes( + currentToken as + | SyntaxKind.WithKeyword + | SyntaxKind.AssertKeyword, + /*skipKeyword*/ true, + ); if (!parseExpected(SyntaxKind.CloseBraceToken)) { const lastError = lastOrUndefined(parseDiagnostics); - if (lastError && lastError.code === Diagnostics._0_expected.code) { + if ( + lastError && + lastError.code === Diagnostics._0_expected.code + ) { addRelatedInfo( lastError, - createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}"), + createDetachedDiagnostic( + fileName, + sourceText, + openBracePosition, + 1, + Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, + "{", + "}", + ), ); } } } parseExpected(SyntaxKind.CloseParenToken); - const qualifier = parseOptional(SyntaxKind.DotToken) ? parseEntityNameOfTypeReference() : undefined; + const qualifier = parseOptional(SyntaxKind.DotToken) + ? parseEntityNameOfTypeReference() + : undefined; const typeArguments = parseTypeArgumentsOfTypeReference(); - return finishNode(factory.createImportTypeNode(type, attributes, qualifier, typeArguments, isTypeOf), pos); + return finishNode( + factory.createImportTypeNode( + type, + attributes, + qualifier, + typeArguments, + isTypeOf, + ), + pos, + ); } function nextTokenIsNumericOrBigIntLiteral() { nextToken(); - return token() === SyntaxKind.NumericLiteral || token() === SyntaxKind.BigIntLiteral; + return ( + token() === SyntaxKind.NumericLiteral || + token() === SyntaxKind.BigIntLiteral + ); } function parseNonArrayType(): TypeNode { @@ -4569,13 +6637,13 @@ namespace Parser { case SyntaxKind.AsteriskEqualsToken: // If there is '*=', treat it as * followed by postfix = scanner.reScanAsteriskEqualsToken(); - // falls through + // falls through case SyntaxKind.AsteriskToken: return parseJSDocAllType(); case SyntaxKind.QuestionQuestionToken: // If there is '??', treat it as prefix-'?' in JSDoc type. scanner.reScanQuestionToken(); - // falls through + // falls through case SyntaxKind.QuestionToken: return parseJSDocUnknownOrNullableType(); case SyntaxKind.FunctionKeyword: @@ -4591,12 +6659,17 @@ namespace Parser { case SyntaxKind.NullKeyword: return parseLiteralTypeNode(); case SyntaxKind.MinusToken: - return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference(); + return lookAhead(nextTokenIsNumericOrBigIntLiteral) + ? parseLiteralTypeNode(/*negative*/ true) + : parseTypeReference(); case SyntaxKind.VoidKeyword: return parseTokenNode(); case SyntaxKind.ThisKeyword: { const thisKeyword = parseThisTypeNode(); - if (token() === SyntaxKind.IsKeyword && !scanner.hasPrecedingLineBreak()) { + if ( + token() === SyntaxKind.IsKeyword && + !scanner.hasPrecedingLineBreak() + ) { return parseThisTypePredicate(thisKeyword); } else { @@ -4604,9 +6677,13 @@ namespace Parser { } } case SyntaxKind.TypeOfKeyword: - return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery(); + return lookAhead(isStartOfTypeOfImportType) + ? parseImportType() + : parseTypeQuery(); case SyntaxKind.OpenBraceToken: - return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral(); + return lookAhead(isStartOfMappedType) + ? parseMappedType() + : parseTypeLiteral(); case SyntaxKind.OpenBracketToken: return parseTupleType(); case SyntaxKind.OpenParenToken: @@ -4614,7 +6691,9 @@ namespace Parser { case SyntaxKind.ImportKeyword: return parseImportType(); case SyntaxKind.AssertsKeyword: - return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference(); + return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) + ? parseAssertsTypePredicate() + : parseTypeReference(); case SyntaxKind.TemplateHead: return parseTemplateType(); default: @@ -4664,11 +6743,17 @@ namespace Parser { case SyntaxKind.FunctionKeyword: return !inStartOfParameter; case SyntaxKind.MinusToken: - return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral); + return ( + !inStartOfParameter && + lookAhead(nextTokenIsNumericOrBigIntLiteral) + ); case SyntaxKind.OpenParenToken: // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier, // or something that starts a type. We don't want to consider things like '(1)' a type. - return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType); + return ( + !inStartOfParameter && + lookAhead(isStartOfParenthesizedOrFunctionType) + ); default: return isIdentifier(); } @@ -4676,7 +6761,11 @@ namespace Parser { function isStartOfParenthesizedOrFunctionType() { nextToken(); - return token() === SyntaxKind.CloseParenToken || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType(); + return ( + token() === SyntaxKind.CloseParenToken || + isStartOfParameter(/*isJSDocParameter*/ false) || + isStartOfType() + ); } function parsePostfixTypeOrHigher(): TypeNode { @@ -4686,7 +6775,13 @@ namespace Parser { switch (token()) { case SyntaxKind.ExclamationToken: nextToken(); - type = finishNode(factory.createJSDocNonNullableType(type, /*postfix*/ true), pos); + type = finishNode( + factory.createJSDocNonNullableType( + type, + /*postfix*/ true, + ), + pos, + ); break; case SyntaxKind.QuestionToken: // If next token is start of a type we have a conditional type @@ -4694,18 +6789,30 @@ namespace Parser { return type; } nextToken(); - type = finishNode(factory.createJSDocNullableType(type, /*postfix*/ true), pos); + type = finishNode( + factory.createJSDocNullableType(type, /*postfix*/ true), + pos, + ); break; case SyntaxKind.OpenBracketToken: parseExpected(SyntaxKind.OpenBracketToken); if (isStartOfType()) { const indexType = parseType(); parseExpected(SyntaxKind.CloseBracketToken); - type = finishNode(factory.createIndexedAccessTypeNode(type, indexType), pos); + type = finishNode( + factory.createIndexedAccessTypeNode( + type, + indexType, + ), + pos, + ); } else { parseExpected(SyntaxKind.CloseBracketToken); - type = finishNode(factory.createArrayTypeNode(type), pos); + type = finishNode( + factory.createArrayTypeNode(type), + pos, + ); } break; default: @@ -4715,16 +6822,30 @@ namespace Parser { return type; } - function parseTypeOperator(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword) { + function parseTypeOperator( + operator: + | SyntaxKind.KeyOfKeyword + | SyntaxKind.UniqueKeyword + | SyntaxKind.ReadonlyKeyword, + ) { const pos = getNodePos(); parseExpected(operator); - return finishNode(factory.createTypeOperatorNode(operator, parseTypeOperatorOrHigher()), pos); + return finishNode( + factory.createTypeOperatorNode( + operator, + parseTypeOperatorOrHigher(), + ), + pos, + ); } function tryParseConstraintOfInferType() { if (parseOptional(SyntaxKind.ExtendsKeyword)) { const constraint = disallowConditionalTypesAnd(parseType); - if (inDisallowConditionalTypesContext() || token() !== SyntaxKind.QuestionToken) { + if ( + inDisallowConditionalTypesContext() || + token() !== SyntaxKind.QuestionToken + ) { return constraint; } } @@ -4734,14 +6855,21 @@ namespace Parser { const pos = getNodePos(); const name = parseIdentifier(); const constraint = tryParse(tryParseConstraintOfInferType); - const node = factory.createTypeParameterDeclaration(/*modifiers*/ undefined, name, constraint); + const node = factory.createTypeParameterDeclaration( + /*modifiers*/ undefined, + name, + constraint, + ); return finishNode(node, pos); } function parseInferType(): InferTypeNode { const pos = getNodePos(); parseExpected(SyntaxKind.InferKeyword); - return finishNode(factory.createInferTypeNode(parseTypeParameterOfInferType()), pos); + return finishNode( + factory.createInferTypeNode(parseTypeParameterOfInferType()), + pos, + ); } function parseTypeOperatorOrHigher(): TypeNode { @@ -4785,17 +6913,23 @@ namespace Parser { function parseUnionOrIntersectionType( operator: SyntaxKind.BarToken | SyntaxKind.AmpersandToken, parseConstituentType: () => TypeNode, - createTypeNode: (types: NodeArray) => UnionOrIntersectionTypeNode, + createTypeNode: ( + types: NodeArray, + ) => UnionOrIntersectionTypeNode, ): TypeNode { const pos = getNodePos(); const isUnionType = operator === SyntaxKind.BarToken; const hasLeadingOperator = parseOptional(operator); - let type = hasLeadingOperator && parseFunctionOrConstructorTypeToError(isUnionType) - || parseConstituentType(); + let type = (hasLeadingOperator && + parseFunctionOrConstructorTypeToError(isUnionType)) || + parseConstituentType(); if (token() === operator || hasLeadingOperator) { const types = [type]; while (parseOptional(operator)) { - types.push(parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType()); + types.push( + parseFunctionOrConstructorTypeToError(isUnionType) || + parseConstituentType(), + ); } type = finishNode(createTypeNode(createNodeArray(types, pos)), pos); } @@ -4803,11 +6937,19 @@ namespace Parser { } function parseIntersectionTypeOrHigher(): TypeNode { - return parseUnionOrIntersectionType(SyntaxKind.AmpersandToken, parseTypeOperatorOrHigher, factory.createIntersectionTypeNode); + return parseUnionOrIntersectionType( + SyntaxKind.AmpersandToken, + parseTypeOperatorOrHigher, + factory.createIntersectionTypeNode, + ); } function parseUnionTypeOrHigher(): TypeNode { - return parseUnionOrIntersectionType(SyntaxKind.BarToken, parseIntersectionTypeOrHigher, factory.createUnionTypeNode); + return parseUnionOrIntersectionType( + SyntaxKind.BarToken, + parseIntersectionTypeOrHigher, + factory.createUnionTypeNode, + ); } function nextTokenIsNewKeyword(): boolean { @@ -4819,11 +6961,17 @@ namespace Parser { if (token() === SyntaxKind.LessThanToken) { return true; } - if (token() === SyntaxKind.OpenParenToken && lookAhead(isUnambiguouslyStartOfFunctionType)) { + if ( + token() === SyntaxKind.OpenParenToken && + lookAhead(isUnambiguouslyStartOfFunctionType) + ) { return true; } - return token() === SyntaxKind.NewKeyword || - token() === SyntaxKind.AbstractKeyword && lookAhead(nextTokenIsNewKeyword); + return ( + token() === SyntaxKind.NewKeyword || + (token() === SyntaxKind.AbstractKeyword && + lookAhead(nextTokenIsNewKeyword)) + ); } function skipParameterStart(): boolean { @@ -4835,7 +6983,10 @@ namespace Parser { nextToken(); return true; } - if (token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.OpenBraceToken) { + if ( + token() === SyntaxKind.OpenBracketToken || + token() === SyntaxKind.OpenBraceToken + ) { // Return true if we can parse an array or object binding pattern with no errors const previousErrorCount = parseDiagnostics.length; parseIdentifierOrPattern(); @@ -4846,7 +6997,10 @@ namespace Parser { function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === SyntaxKind.CloseParenToken || token() === SyntaxKind.DotDotDotToken) { + if ( + token() === SyntaxKind.CloseParenToken || + token() === SyntaxKind.DotDotDotToken + ) { // ( ) // ( ... return true; @@ -4855,8 +7009,10 @@ namespace Parser { // We successfully skipped modifiers (if any) and an identifier or binding pattern, // now see if we have something that indicates a parameter declaration if ( - token() === SyntaxKind.ColonToken || token() === SyntaxKind.CommaToken || - token() === SyntaxKind.QuestionToken || token() === SyntaxKind.EqualsToken + token() === SyntaxKind.ColonToken || + token() === SyntaxKind.CommaToken || + token() === SyntaxKind.QuestionToken || + token() === SyntaxKind.EqualsToken ) { // ( xxx : // ( xxx , @@ -4880,7 +7036,14 @@ namespace Parser { const typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix); const type = parseType(); if (typePredicateVariable) { - return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, typePredicateVariable, type), pos); + return finishNode( + factory.createTypePredicateNode( + /*assertsModifier*/ undefined, + typePredicateVariable, + type, + ), + pos, + ); } else { return type; @@ -4889,7 +7052,10 @@ namespace Parser { function parseTypePredicatePrefix() { const id = parseIdentifier(); - if (token() === SyntaxKind.IsKeyword && !scanner.hasPrecedingLineBreak()) { + if ( + token() === SyntaxKind.IsKeyword && + !scanner.hasPrecedingLineBreak() + ) { nextToken(); return id; } @@ -4898,9 +7064,20 @@ namespace Parser { function parseAssertsTypePredicate(): TypeNode { const pos = getNodePos(); const assertsModifier = parseExpectedToken(SyntaxKind.AssertsKeyword); - const parameterName = token() === SyntaxKind.ThisKeyword ? parseThisTypeNode() : parseIdentifier(); - const type = parseOptional(SyntaxKind.IsKeyword) ? parseType() : undefined; - return finishNode(factory.createTypePredicateNode(assertsModifier, parameterName, type), pos); + const parameterName = token() === SyntaxKind.ThisKeyword + ? parseThisTypeNode() + : parseIdentifier(); + const type = parseOptional(SyntaxKind.IsKeyword) + ? parseType() + : undefined; + return finishNode( + factory.createTypePredicateNode( + assertsModifier, + parameterName, + type, + ), + pos, + ); } function parseType(): TypeNode { @@ -4912,17 +7089,29 @@ namespace Parser { } const pos = getNodePos(); const type = parseUnionTypeOrHigher(); - if (!inDisallowConditionalTypesContext() && !scanner.hasPrecedingLineBreak() && parseOptional(SyntaxKind.ExtendsKeyword)) { + if ( + !inDisallowConditionalTypesContext() && + !scanner.hasPrecedingLineBreak() && + parseOptional(SyntaxKind.ExtendsKeyword) + ) { // The type following 'extends' is not permitted to be another conditional type const extendsType = disallowConditionalTypesAnd(parseType); parseExpected(SyntaxKind.QuestionToken); const trueType = allowConditionalTypesAnd(parseType); parseExpected(SyntaxKind.ColonToken); const falseType = allowConditionalTypesAnd(parseType); - return finishNode(factory.createConditionalTypeNode(type, extendsType, trueType, falseType), pos); - } - return type; - } + return finishNode( + factory.createConditionalTypeNode( + type, + extendsType, + trueType, + falseType, + ), + pos, + ); + } + return type; + } function parseTypeAnnotation(): TypeNode | undefined { return parseOptional(SyntaxKind.ColonToken) ? parseType() : undefined; @@ -4997,11 +7186,13 @@ namespace Parser { function isStartOfExpressionStatement(): boolean { // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement. - return token() !== SyntaxKind.OpenBraceToken && + return ( + token() !== SyntaxKind.OpenBraceToken && token() !== SyntaxKind.FunctionKeyword && token() !== SyntaxKind.ClassKeyword && token() !== SyntaxKind.AtToken && - isStartOfExpression(); + isStartOfExpression() + ); } function parseExpression(): Expression { @@ -5016,10 +7207,19 @@ namespace Parser { } const pos = getNodePos(); - let expr = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); + let expr = parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ); let operatorToken: BinaryOperatorToken; while ((operatorToken = parseOptionalToken(SyntaxKind.CommaToken))) { - expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true), pos); + expr = makeBinaryExpression( + expr, + operatorToken, + parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ), + pos, + ); } if (saveDecoratorContext) { @@ -5029,10 +7229,16 @@ namespace Parser { } function parseInitializer(): Expression | undefined { - return parseOptional(SyntaxKind.EqualsToken) ? parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true) : undefined; + return parseOptional(SyntaxKind.EqualsToken) + ? parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ) + : undefined; } - function parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction: boolean): Expression { + function parseAssignmentExpressionOrHigher( + allowReturnTypeInArrowFunction: boolean, + ): Expression { // AssignmentExpression[in,yield]: // 1) ConditionalExpression[?in,?yield] // 2) LeftHandSideExpression = AssignmentExpression[?in,?yield] @@ -5060,7 +7266,12 @@ namespace Parser { // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. - const arrowExpression = tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) || tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction); + const arrowExpression = tryParseParenthesizedArrowFunctionExpression( + allowReturnTypeInArrowFunction, + ) || + tryParseAsyncSimpleArrowFunctionExpression( + allowReturnTypeInArrowFunction, + ); if (arrowExpression) { return arrowExpression; } @@ -5081,8 +7292,17 @@ namespace Parser { // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single // identifier and the current token is an arrow. - if (expr.kind === SyntaxKind.Identifier && token() === SyntaxKind.EqualsGreaterThanToken) { - return parseSimpleArrowFunctionExpression(pos, expr as Identifier, allowReturnTypeInArrowFunction, hasJSDoc, /*asyncModifier*/ undefined); + if ( + expr.kind === SyntaxKind.Identifier && + token() === SyntaxKind.EqualsGreaterThanToken + ) { + return parseSimpleArrowFunctionExpression( + pos, + expr, + allowReturnTypeInArrowFunction, + hasJSDoc, + /*asyncModifier*/ undefined, + ); } // Now see if we might be in cases '2' or '3'. @@ -5091,12 +7311,26 @@ namespace Parser { // // Note: we call reScanGreaterToken so that we get an appropriately merged token // for cases like `> > =` becoming `>>=` - if (isLeftHandSideExpression(expr) && isAssignmentOperator(reScanGreaterToken())) { - return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction), pos); + if ( + isLeftHandSideExpression(expr) && + isAssignmentOperator(reScanGreaterToken()) + ) { + return makeBinaryExpression( + expr, + parseTokenNode(), + parseAssignmentExpressionOrHigher( + allowReturnTypeInArrowFunction, + ), + pos, + ); } // It wasn't an assignment or a lambda. This is a conditional expression: - return parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction); + return parseConditionalExpressionRest( + expr, + pos, + allowReturnTypeInArrowFunction, + ); } function isYieldExpression(): boolean { @@ -5148,7 +7382,9 @@ namespace Parser { return finishNode( factory.createYieldExpression( parseOptionalToken(SyntaxKind.AsteriskToken), - parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true), + parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ), ), pos, ); @@ -5156,12 +7392,27 @@ namespace Parser { else { // if the next token is not on the same line as yield. or we don't have an '*' or // the start of an expression, then this is just a simple "yield" expression. - return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos); + return finishNode( + factory.createYieldExpression( + /*asteriskToken*/ undefined, + /*expression*/ undefined, + ), + pos, + ); } } - function parseSimpleArrowFunctionExpression(pos: number, identifier: Identifier, allowReturnTypeInArrowFunction: boolean, hasJSDoc: boolean, asyncModifier?: NodeArray | undefined): ArrowFunction { - Debug.assert(token() === SyntaxKind.EqualsGreaterThanToken, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); + function parseSimpleArrowFunctionExpression( + pos: number, + identifier: Identifier, + allowReturnTypeInArrowFunction: boolean, + hasJSDoc: boolean, + asyncModifier?: NodeArray | undefined, + ): ArrowFunction { + Debug.assert( + token() === SyntaxKind.EqualsGreaterThanToken, + "parseSimpleArrowFunctionExpression should only have been called if we had a =>", + ); const parameter = factory.createParameterDeclaration( /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, @@ -5172,14 +7423,32 @@ namespace Parser { ); finishNode(parameter, identifier.pos); - const parameters = createNodeArray([parameter], parameter.pos, parameter.end); - const equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken); - const body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier, allowReturnTypeInArrowFunction); - const node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body); + const parameters = createNodeArray( + [parameter], + parameter.pos, + parameter.end, + ); + const equalsGreaterThanToken = parseExpectedToken( + SyntaxKind.EqualsGreaterThanToken, + ); + const body = parseArrowFunctionExpressionBody( + /*isAsync*/ !!asyncModifier, + allowReturnTypeInArrowFunction, + ); + const node = factory.createArrowFunction( + asyncModifier, + /*typeParameters*/ undefined, + parameters, + /*type*/ undefined, + equalsGreaterThanToken, + body, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction: boolean): Expression | undefined { + function tryParseParenthesizedArrowFunctionExpression( + allowReturnTypeInArrowFunction: boolean, + ): Expression | undefined { const triState = isParenthesizedArrowFunctionExpression(); if (triState === Tristate.False) { // It's definitely not a parenthesized arrow function expression. @@ -5190,9 +7459,16 @@ namespace Parser { // following => or { token. Otherwise, we *might* have an arrow function. Try to parse // it out, but don't allow any ambiguity, and return 'undefined' if this could be an // expression instead. - return triState === Tristate.True ? - parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true, /*allowReturnTypeInArrowFunction*/ true) : - tryParse(() => parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction)); + return triState === Tristate.True + ? parseParenthesizedArrowFunctionExpression( + /*allowAmbiguity*/ true, + /*allowReturnTypeInArrowFunction*/ true, + ) + : tryParse(() => + parsePossibleParenthesizedArrowFunctionExpression( + allowReturnTypeInArrowFunction, + ) + ); } // True -> We definitely expect a parenthesized arrow function here. @@ -5200,7 +7476,11 @@ namespace Parser { // Unknown -> There *might* be a parenthesized arrow function here. // Speculatively look ahead to be sure, and rollback if not. function isParenthesizedArrowFunctionExpression(): Tristate { - if (token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken || token() === SyntaxKind.AsyncKeyword) { + if ( + token() === SyntaxKind.OpenParenToken || + token() === SyntaxKind.LessThanToken || + token() === SyntaxKind.AsyncKeyword + ) { return lookAhead(isParenthesizedArrowFunctionExpressionWorker); } @@ -5220,7 +7500,10 @@ namespace Parser { if (scanner.hasPrecedingLineBreak()) { return Tristate.False; } - if (token() !== SyntaxKind.OpenParenToken && token() !== SyntaxKind.LessThanToken) { + if ( + token() !== SyntaxKind.OpenParenToken && + token() !== SyntaxKind.LessThanToken + ) { return Tristate.False; } } @@ -5251,7 +7534,10 @@ namespace Parser { // ({ x }) => { } // ([ x ]) // ({ x }) - if (second === SyntaxKind.OpenBracketToken || second === SyntaxKind.OpenBraceToken) { + if ( + second === SyntaxKind.OpenBracketToken || + second === SyntaxKind.OpenBraceToken + ) { return Tristate.Unknown; } @@ -5264,7 +7550,11 @@ namespace Parser { // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This // isn't actually allowed, but we want to treat it as a lambda so we can provide // a good error message. - if (isModifierKind(second) && second !== SyntaxKind.AsyncKeyword && lookAhead(nextTokenIsIdentifier)) { + if ( + isModifierKind(second) && + second !== SyntaxKind.AsyncKeyword && + lookAhead(nextTokenIsIdentifier) + ) { if (nextToken() === SyntaxKind.AsKeyword) { // https://github.com/microsoft/TypeScript/issues/44466 return Tristate.False; @@ -5287,7 +7577,12 @@ namespace Parser { case SyntaxKind.QuestionToken: nextToken(); // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. - if (token() === SyntaxKind.ColonToken || token() === SyntaxKind.CommaToken || token() === SyntaxKind.EqualsToken || token() === SyntaxKind.CloseParenToken) { + if ( + token() === SyntaxKind.ColonToken || + token() === SyntaxKind.CommaToken || + token() === SyntaxKind.EqualsToken || + token() === SyntaxKind.CloseParenToken + ) { return Tristate.True; } // Otherwise it is definitely not a lambda. @@ -5326,7 +7621,10 @@ namespace Parser { return true; } } - else if (third === SyntaxKind.CommaToken || third === SyntaxKind.EqualsToken) { + else if ( + third === SyntaxKind.CommaToken || + third === SyntaxKind.EqualsToken + ) { return true; } return false; @@ -5344,29 +7642,49 @@ namespace Parser { } } - function parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction: boolean): ArrowFunction | undefined { + function parsePossibleParenthesizedArrowFunctionExpression( + allowReturnTypeInArrowFunction: boolean, + ): ArrowFunction | undefined { const tokenPos = scanner.getTokenStart(); if (notParenthesizedArrow?.has(tokenPos)) { return undefined; } - const result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false, allowReturnTypeInArrowFunction); + const result = parseParenthesizedArrowFunctionExpression( + /*allowAmbiguity*/ false, + allowReturnTypeInArrowFunction, + ); if (!result) { - (notParenthesizedArrow || (notParenthesizedArrow = new Set())).add(tokenPos); + (notParenthesizedArrow || (notParenthesizedArrow = new Set())).add( + tokenPos, + ); } return result; } - function tryParseAsyncSimpleArrowFunctionExpression(allowReturnTypeInArrowFunction: boolean): ArrowFunction | undefined { + function tryParseAsyncSimpleArrowFunctionExpression( + allowReturnTypeInArrowFunction: boolean, + ): ArrowFunction | undefined { // We do a check here so that we won't be doing unnecessarily call to "lookAhead" if (token() === SyntaxKind.AsyncKeyword) { - if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === Tristate.True) { + if ( + lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === + Tristate.True + ) { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); const asyncModifier = parseModifiersForArrowFunction(); - const expr = parseBinaryExpressionOrHigher(OperatorPrecedence.Lowest); - return parseSimpleArrowFunctionExpression(pos, expr as Identifier, allowReturnTypeInArrowFunction, hasJSDoc, asyncModifier); + const expr = parseBinaryExpressionOrHigher( + OperatorPrecedence.Lowest, + ); + return parseSimpleArrowFunctionExpression( + pos, + expr as Identifier, + allowReturnTypeInArrowFunction, + hasJSDoc, + asyncModifier, + ); } } return undefined; @@ -5380,12 +7698,21 @@ namespace Parser { nextToken(); // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher" - if (scanner.hasPrecedingLineBreak() || token() === SyntaxKind.EqualsGreaterThanToken) { + if ( + scanner.hasPrecedingLineBreak() || + token() === SyntaxKind.EqualsGreaterThanToken + ) { return Tristate.False; } // Check for un-parenthesized AsyncArrowFunction - const expr = parseBinaryExpressionOrHigher(OperatorPrecedence.Lowest); - if (!scanner.hasPrecedingLineBreak() && expr.kind === SyntaxKind.Identifier && token() === SyntaxKind.EqualsGreaterThanToken) { + const expr = parseBinaryExpressionOrHigher( + OperatorPrecedence.Lowest, + ); + if ( + !scanner.hasPrecedingLineBreak() && + expr.kind === SyntaxKind.Identifier && + token() === SyntaxKind.EqualsGreaterThanToken + ) { return Tristate.True; } } @@ -5393,11 +7720,16 @@ namespace Parser { return Tristate.False; } - function parseParenthesizedArrowFunctionExpression(allowAmbiguity: boolean, allowReturnTypeInArrowFunction: boolean): ArrowFunction | undefined { + function parseParenthesizedArrowFunctionExpression( + allowAmbiguity: boolean, + allowReturnTypeInArrowFunction: boolean, + ): ArrowFunction | undefined { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiersForArrowFunction(); - const isAsync = some(modifiers, isAsyncModifier) ? SignatureFlags.Await : SignatureFlags.None; + const isAsync = some(modifiers, isAsyncModifier) + ? SignatureFlags.Await + : SignatureFlags.None; // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -5416,7 +7748,10 @@ namespace Parser { } else { if (!allowAmbiguity) { - const maybeParameters = parseParametersWorker(isAsync, allowAmbiguity); + const maybeParameters = parseParametersWorker( + isAsync, + allowAmbiguity, + ); if (!maybeParameters) { return undefined; } @@ -5432,7 +7767,11 @@ namespace Parser { const hasReturnColon = token() === SyntaxKind.ColonToken; const type = parseReturnType(SyntaxKind.ColonToken, /*isType*/ false); - if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) { + if ( + type && + !allowAmbiguity && + typeHasArrowFunctionBlockingParseError(type) + ) { return undefined; } @@ -5449,11 +7788,15 @@ namespace Parser { let unwrappedType = type; while (unwrappedType?.kind === SyntaxKind.ParenthesizedType) { - unwrappedType = (unwrappedType as ParenthesizedTypeNode).type; // Skip parens if need be + unwrappedType = unwrappedType.type; // Skip parens if need be } const hasJSDocFunctionType = unwrappedType && isJSDocFunctionType(unwrappedType); - if (!allowAmbiguity && token() !== SyntaxKind.EqualsGreaterThanToken && (hasJSDocFunctionType || token() !== SyntaxKind.OpenBraceToken)) { + if ( + !allowAmbiguity && + token() !== SyntaxKind.EqualsGreaterThanToken && + (hasJSDocFunctionType || token() !== SyntaxKind.OpenBraceToken) + ) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; } @@ -5461,9 +7804,15 @@ namespace Parser { // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. const lastToken = token(); - const equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken); - const body = (lastToken === SyntaxKind.EqualsGreaterThanToken || lastToken === SyntaxKind.OpenBraceToken) - ? parseArrowFunctionExpressionBody(some(modifiers, isAsyncModifier), allowReturnTypeInArrowFunction) + const equalsGreaterThanToken = parseExpectedToken( + SyntaxKind.EqualsGreaterThanToken, + ); + const body = lastToken === SyntaxKind.EqualsGreaterThanToken || + lastToken === SyntaxKind.OpenBraceToken + ? parseArrowFunctionExpressionBody( + some(modifiers, isAsyncModifier), + allowReturnTypeInArrowFunction, + ) : parseIdentifier(); // Given: @@ -5492,13 +7841,25 @@ namespace Parser { } } - const node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body); + const node = factory.createArrowFunction( + modifiers, + typeParameters, + parameters, + type, + equalsGreaterThanToken, + body, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseArrowFunctionExpressionBody(isAsync: boolean, allowReturnTypeInArrowFunction: boolean): Block | Expression { + function parseArrowFunctionExpressionBody( + isAsync: boolean, + allowReturnTypeInArrowFunction: boolean, + ): Block | Expression { if (token() === SyntaxKind.OpenBraceToken) { - return parseFunctionBlock(isAsync ? SignatureFlags.Await : SignatureFlags.None); + return parseFunctionBlock( + isAsync ? SignatureFlags.Await : SignatureFlags.None, + ); } if ( @@ -5522,19 +7883,34 @@ namespace Parser { // up preemptively closing the containing construct. // // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error. - return parseFunctionBlock(SignatureFlags.IgnoreMissingOpenBrace | (isAsync ? SignatureFlags.Await : SignatureFlags.None)); + return parseFunctionBlock( + SignatureFlags.IgnoreMissingOpenBrace | + (isAsync ? SignatureFlags.Await : SignatureFlags.None), + ); } const savedTopLevel = topLevel; topLevel = false; const node = isAsync - ? doInAwaitContext(() => parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction)) - : doOutsideOfAwaitContext(() => parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction)); + ? doInAwaitContext(() => + parseAssignmentExpressionOrHigher( + allowReturnTypeInArrowFunction, + ) + ) + : doOutsideOfAwaitContext(() => + parseAssignmentExpressionOrHigher( + allowReturnTypeInArrowFunction, + ) + ); topLevel = savedTopLevel; return node; } - function parseConditionalExpressionRest(leftOperand: Expression, pos: number, allowReturnTypeInArrowFunction: boolean): Expression { + function parseConditionalExpressionRest( + leftOperand: Expression, + pos: number, + allowReturnTypeInArrowFunction: boolean, + ): Expression { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (!questionToken) { @@ -5548,17 +7924,29 @@ namespace Parser { factory.createConditionalExpression( leftOperand, questionToken, - doOutsideOfContext(disallowInAndDecoratorContext, () => parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ false)), + doOutsideOfContext(disallowInAndDecoratorContext, () => + parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ false, + )), colonToken = parseExpectedToken(SyntaxKind.ColonToken), nodeIsPresent(colonToken) - ? parseAssignmentExpressionOrHigher(allowReturnTypeInArrowFunction) - : createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, tokenToString(SyntaxKind.ColonToken)), + ? parseAssignmentExpressionOrHigher( + allowReturnTypeInArrowFunction, + ) + : createMissingNode( + SyntaxKind.Identifier, + /*reportAtCurrentPosition*/ false, + Diagnostics._0_expected, + tokenToString(SyntaxKind.ColonToken), + ), ), pos, ); } - function parseBinaryExpressionOrHigher(precedence: OperatorPrecedence): Expression { + function parseBinaryExpressionOrHigher( + precedence: OperatorPrecedence, + ): Expression { const pos = getNodePos(); const leftOperand = parseUnaryExpressionOrHigher(); return parseBinaryExpressionRest(precedence, leftOperand, pos); @@ -5568,7 +7956,11 @@ namespace Parser { return t === SyntaxKind.InKeyword || t === SyntaxKind.OfKeyword; } - function parseBinaryExpressionRest(precedence: OperatorPrecedence, leftOperand: Expression, pos: number): Expression { + function parseBinaryExpressionRest( + precedence: OperatorPrecedence, + leftOperand: Expression, + pos: number, + ): Expression { while (true) { // We either have a binary operator here, or we're finished. We call // reScanGreaterToken so that we merge token sequences like > and = into >= @@ -5597,9 +7989,9 @@ namespace Parser { // ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand // a ** b - c // ^token; leftOperand = b. Return b to the caller as a rightOperand - const consumeCurrentOperator = token() === SyntaxKind.AsteriskAsteriskToken ? - newPrecedence >= precedence : - newPrecedence > precedence; + const consumeCurrentOperator = token() === SyntaxKind.AsteriskAsteriskToken + ? newPrecedence >= precedence + : newPrecedence > precedence; if (!consumeCurrentOperator) { break; @@ -5609,7 +8001,10 @@ namespace Parser { break; } - if (token() === SyntaxKind.AsKeyword || token() === SyntaxKind.SatisfiesKeyword) { + if ( + token() === SyntaxKind.AsKeyword || + token() === SyntaxKind.SatisfiesKeyword + ) { // Make sure we *do* perform ASI for constructs like this: // var x = foo // as (Bar) @@ -5621,12 +8016,18 @@ namespace Parser { else { const keywordKind = token(); nextToken(); - leftOperand = keywordKind === SyntaxKind.SatisfiesKeyword ? makeSatisfiesExpression(leftOperand, parseType()) : - makeAsExpression(leftOperand, parseType()); + leftOperand = keywordKind === SyntaxKind.SatisfiesKeyword + ? makeSatisfiesExpression(leftOperand, parseType()) + : makeAsExpression(leftOperand, parseType()); } } else { - leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence), pos); + leftOperand = makeBinaryExpression( + leftOperand, + parseTokenNode(), + parseBinaryExpressionOrHigher(newPrecedence), + pos, + ); } } @@ -5641,12 +8042,26 @@ namespace Parser { return getBinaryOperatorPrecedence(token()) > 0; } - function makeSatisfiesExpression(left: Expression, right: TypeNode): SatisfiesExpression { - return finishNode(factory.createSatisfiesExpression(left, right), left.pos); + function makeSatisfiesExpression( + left: Expression, + right: TypeNode, + ): SatisfiesExpression { + return finishNode( + factory.createSatisfiesExpression(left, right), + left.pos, + ); } - function makeBinaryExpression(left: Expression, operatorToken: BinaryOperatorToken, right: Expression, pos: number): BinaryExpression { - return finishNode(factory.createBinaryExpression(left, operatorToken, right), pos); + function makeBinaryExpression( + left: Expression, + operatorToken: BinaryOperatorToken, + right: Expression, + pos: number, + ): BinaryExpression { + return finishNode( + factory.createBinaryExpression(left, operatorToken, right), + pos, + ); } function makeAsExpression(left: Expression, right: TypeNode): AsExpression { @@ -5655,22 +8070,43 @@ namespace Parser { function parsePrefixUnaryExpression() { const pos = getNodePos(); - return finishNode(factory.createPrefixUnaryExpression(token() as PrefixUnaryOperator, nextTokenAnd(parseSimpleUnaryExpression)), pos); + return finishNode( + factory.createPrefixUnaryExpression( + token() as PrefixUnaryOperator, + nextTokenAnd(parseSimpleUnaryExpression), + ), + pos, + ); } function parseDeleteExpression() { const pos = getNodePos(); - return finishNode(factory.createDeleteExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos); + return finishNode( + factory.createDeleteExpression( + nextTokenAnd(parseSimpleUnaryExpression), + ), + pos, + ); } function parseTypeOfExpression() { const pos = getNodePos(); - return finishNode(factory.createTypeOfExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos); + return finishNode( + factory.createTypeOfExpression( + nextTokenAnd(parseSimpleUnaryExpression), + ), + pos, + ); } function parseVoidExpression() { const pos = getNodePos(); - return finishNode(factory.createVoidExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos); + return finishNode( + factory.createVoidExpression( + nextTokenAnd(parseSimpleUnaryExpression), + ), + pos, + ); } function isAwaitExpression(): boolean { @@ -5688,7 +8124,12 @@ namespace Parser { function parseAwaitExpression() { const pos = getNodePos(); - return finishNode(factory.createAwaitExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos); + return finishNode( + factory.createAwaitExpression( + nextTokenAnd(parseSimpleUnaryExpression), + ), + pos, + ); } /** @@ -5698,7 +8139,11 @@ namespace Parser { * 1) UnaryExpression[?Yield] * 2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield] */ - function parseUnaryExpressionOrHigher(): UnaryExpression | BinaryExpression { + function parseUnaryExpressionOrHigher(): + | UnaryExpression + | BinaryExpression + | UpdateExpression + { /** * ES7 UpdateExpression: * 1) LeftHandSideExpression[?Yield] @@ -5710,9 +8155,13 @@ namespace Parser { if (isUpdateExpression()) { const pos = getNodePos(); const updateExpression = parseUpdateExpression(); - return token() === SyntaxKind.AsteriskAsteriskToken ? - parseBinaryExpressionRest(getBinaryOperatorPrecedence(token()), updateExpression, pos) as BinaryExpression : - updateExpression; + return token() === SyntaxKind.AsteriskAsteriskToken + ? (parseBinaryExpressionRest( + getBinaryOperatorPrecedence(token()), + updateExpression, + pos, + ) as BinaryExpression) + : updateExpression; } /** @@ -5731,12 +8180,24 @@ namespace Parser { if (token() === SyntaxKind.AsteriskAsteriskToken) { const pos = skipTrivia(sourceText, simpleUnaryExpression.pos); const { end } = simpleUnaryExpression; - if (simpleUnaryExpression.kind === SyntaxKind.TypeAssertionExpression) { - parseErrorAt(pos, end, Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); + if ( + simpleUnaryExpression.kind === + SyntaxKind.TypeAssertionExpression + ) { + parseErrorAt( + pos, + end, + Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, + ); } else { Debug.assert(isKeywordOrPunctuation(unaryOperator)); - parseErrorAt(pos, end, Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, tokenToString(unaryOperator)); + parseErrorAt( + pos, + end, + Diagnostics.An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses, + tokenToString(unaryOperator), + ); } } return simpleUnaryExpression; @@ -5773,7 +8234,12 @@ namespace Parser { // Just like in parseUpdateExpression, we need to avoid parsing type assertions when // in JSX and we see an expression like "+ bar". if (languageVariant === LanguageVariant.JSX) { - return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true, /*topInvalidNodePosition*/ undefined, /*openingTag*/ undefined, /*mustBeUnary*/ true); + return parseJsxElementOrSelfClosingElementOrFragment( + /*inExpressionContext*/ true, + /*topInvalidNodePosition*/ undefined, + /*openingTag*/ undefined, + /*mustBeUnary*/ true, + ); } // This is modified UnaryExpression grammar in TypeScript // UnaryExpression (modified): @@ -5783,7 +8249,7 @@ namespace Parser { if (isAwaitExpression()) { return parseAwaitExpression(); } - // falls through + // falls through default: return parseUpdateExpression(); } @@ -5817,8 +8283,8 @@ namespace Parser { if (languageVariant !== LanguageVariant.JSX) { return false; } - // We are in JSX context and the token is part of JSXElement. - // falls through + // We are in JSX context and the token is part of JSXElement. + // falls through default: return true; } @@ -5836,22 +8302,44 @@ namespace Parser { * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression */ function parseUpdateExpression(): UpdateExpression { - if (token() === SyntaxKind.PlusPlusToken || token() === SyntaxKind.MinusMinusToken) { + if ( + token() === SyntaxKind.PlusPlusToken || + token() === SyntaxKind.MinusMinusToken + ) { const pos = getNodePos(); - return finishNode(factory.createPrefixUnaryExpression(token() as PrefixUnaryOperator, nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos); + return finishNode( + factory.createPrefixUnaryExpression( + token() as PrefixUnaryOperator, + nextTokenAnd(parseLeftHandSideExpressionOrHigher), + ), + pos, + ); } - else if (languageVariant === LanguageVariant.JSX && token() === SyntaxKind.LessThanToken && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) { + else if ( + languageVariant === LanguageVariant.JSX && + token() === SyntaxKind.LessThanToken && + lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan) + ) { // JSXElement is part of primaryExpression - return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + return parseJsxElementOrSelfClosingElementOrFragment( + /*inExpressionContext*/ true, + ); } const expression = parseLeftHandSideExpressionOrHigher(); Debug.assert(isLeftHandSideExpression(expression)); - if ((token() === SyntaxKind.PlusPlusToken || token() === SyntaxKind.MinusMinusToken) && !scanner.hasPrecedingLineBreak()) { + if ( + (token() === SyntaxKind.PlusPlusToken || + token() === SyntaxKind.MinusMinusToken) && + !scanner.hasPrecedingLineBreak() + ) { const operator = token() as PostfixUnaryOperator; nextToken(); - return finishNode(factory.createPostfixUnaryExpression(expression, operator), expression.pos); + return finishNode( + factory.createPostfixUnaryExpression(expression, operator), + expression.pos, + ); } return expression; @@ -5899,13 +8387,19 @@ namespace Parser { // import * as foo1 from "module-from-node // We want this import to be a statement rather than import call expression sourceFlags |= NodeFlags.PossiblyContainsDynamicImport; - expression = parseTokenNode(); + expression = parseTokenNode(); } else if (lookAhead(nextTokenIsDot)) { // This is an 'import.*' metaproperty (i.e. 'import.meta') nextToken(); // advance past the 'import' nextToken(); // advance past the dot - expression = finishNode(factory.createMetaProperty(SyntaxKind.ImportKeyword, parseIdentifierName()), pos); + expression = finishNode( + factory.createMetaProperty( + SyntaxKind.ImportKeyword, + parseIdentifierName(), + ), + pos, + ); sourceFlags |= NodeFlags.PossiblyContainsImportMeta; } else { @@ -5913,7 +8407,9 @@ namespace Parser { } } else { - expression = token() === SyntaxKind.SuperKeyword ? parseSuperExpression() : parseMemberExpressionOrHigher(); + expression = token() === SyntaxKind.SuperKeyword + ? parseSuperExpression() + : parseMemberExpressionOrHigher(); } // Now, we *may* be complete. However, we might have consumed the start of a @@ -5972,7 +8468,11 @@ namespace Parser { // of the recursion immediately. So we parse out a primary expression to start with. const pos = getNodePos(); const expression = parsePrimaryExpression(); - return parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true); + return parseMemberExpressionRest( + pos, + expression, + /*allowOptionalChain*/ true, + ); } function parseSuperExpression(): MemberExpression { @@ -5982,27 +8482,58 @@ namespace Parser { const startPos = getNodePos(); const typeArguments = tryParse(parseTypeArgumentsInExpression); if (typeArguments !== undefined) { - parseErrorAt(startPos, getNodePos(), Diagnostics.super_may_not_use_type_arguments); + parseErrorAt( + startPos, + getNodePos(), + Diagnostics.super_may_not_use_type_arguments, + ); if (!isTemplateStartOfTaggedTemplate()) { - expression = factory.createExpressionWithTypeArguments(expression, typeArguments); + expression = factory.createExpressionWithTypeArguments( + expression, + typeArguments, + ); } } } - if (token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.DotToken || token() === SyntaxKind.OpenBracketToken) { + if ( + token() === SyntaxKind.OpenParenToken || + token() === SyntaxKind.DotToken || + token() === SyntaxKind.OpenBracketToken + ) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - parseExpectedToken(SyntaxKind.DotToken, Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); + parseExpectedToken( + SyntaxKind.DotToken, + Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access, + ); // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic - return finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true, /*allowUnicodeEscapeSequenceInIdentifierName*/ true)), pos); + return finishNode( + factoryCreatePropertyAccessExpression( + expression, + parseRightSideOfDot( + /*allowIdentifierNames*/ true, + /*allowPrivateIdentifiers*/ true, + /*allowUnicodeEscapeSequenceInIdentifierName*/ true, + ), + ), + pos, + ); } - function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext: boolean, topInvalidNodePosition?: number, openingTag?: JsxOpeningElement | JsxOpeningFragment, mustBeUnary = false): JsxElement | JsxSelfClosingElement | JsxFragment { + function parseJsxElementOrSelfClosingElementOrFragment( + inExpressionContext: boolean, + topInvalidNodePosition?: number, + openingTag?: JsxOpeningElement | JsxOpeningFragment, + mustBeUnary = false, + ): JsxElement | JsxSelfClosingElement | JsxFragment { const pos = getNodePos(); - const opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext); + const opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment( + inExpressionContext, + ); let result: JsxElement | JsxSelfClosingElement | JsxFragment; if (opening.kind === SyntaxKind.JsxOpeningElement) { let children = parseJsxChildren(opening); @@ -6010,9 +8541,15 @@ namespace Parser { const lastChild: JsxChild | undefined = children[children.length - 1]; if ( - lastChild?.kind === SyntaxKind.JsxElement - && !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName) - && tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName) + lastChild?.kind === SyntaxKind.JsxElement && + !tagNamesAreEquivalent( + lastChild.openingElement.tagName, + lastChild.closingElement.tagName, + ) && + tagNamesAreEquivalent( + opening.tagName, + lastChild.closingElement.tagName, + ) ) { // when an unclosed JsxOpeningElement incorrectly parses its parent's JsxClosingElement, // restructure (
(......
)) --> (
(......)
) @@ -6022,32 +8559,85 @@ namespace Parser { factory.createJsxElement( lastChild.openingElement, lastChild.children, - finishNode(factory.createJsxClosingElement(finishNode(factoryCreateIdentifier(""), end, end)), end, end), + finishNode( + factory.createJsxClosingElement( + finishNode( + factoryCreateIdentifier(""), + end, + end, + ), + ), + end, + end, + ), ), lastChild.openingElement.pos, end, ); - children = createNodeArray([...children.slice(0, children.length - 1), newLast], children.pos, end); + children = createNodeArray( + [...children.slice(0, children.length - 1), newLast], + children.pos, + end, + ); closingElement = lastChild.closingElement; } else { - closingElement = parseJsxClosingElement(opening, inExpressionContext); - if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) { - if (openingTag && isJsxOpeningElement(openingTag) && tagNamesAreEquivalent(closingElement.tagName, openingTag.tagName)) { + closingElement = parseJsxClosingElement( + opening, + inExpressionContext, + ); + if ( + !tagNamesAreEquivalent( + opening.tagName, + closingElement.tagName, + ) + ) { + if ( + openingTag && + isJsxOpeningElement(openingTag) && + tagNamesAreEquivalent( + closingElement.tagName, + openingTag.tagName, + ) + ) { // opening incorrectly matched with its parent's closing -- put error on opening - parseErrorAtRange(opening.tagName, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, opening.tagName)); + parseErrorAtRange( + opening.tagName, + Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, + getTextOfNodeFromSourceText( + sourceText, + opening.tagName, + ), + ); } else { // other opening/closing mismatches -- put error on closing - parseErrorAtRange(closingElement.tagName, Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, getTextOfNodeFromSourceText(sourceText, opening.tagName)); + parseErrorAtRange( + closingElement.tagName, + Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, + getTextOfNodeFromSourceText( + sourceText, + opening.tagName, + ), + ); } } } - result = finishNode(factory.createJsxElement(opening, children, closingElement), pos); + result = finishNode( + factory.createJsxElement(opening, children, closingElement), + pos, + ); } else if (opening.kind === SyntaxKind.JsxOpeningFragment) { - result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos); + result = finishNode( + factory.createJsxFragment( + opening, + parseJsxChildren(opening), + parseJsxClosingFragment(inExpressionContext), + ), + pos, + ); } else { Debug.assert(opening.kind === SyntaxKind.JsxSelfClosingElement); @@ -6064,14 +8654,39 @@ namespace Parser { // of one sort or another. // If we are in a unary context, we can't do this recovery; the binary expression we return here is not // a valid UnaryExpression and will cause problems later. - if (!mustBeUnary && inExpressionContext && token() === SyntaxKind.LessThanToken) { - const topBadPos = typeof topInvalidNodePosition === "undefined" ? result.pos : topInvalidNodePosition; - const invalidElement = tryParse(() => parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true, topBadPos)); + if ( + !mustBeUnary && + inExpressionContext && + token() === SyntaxKind.LessThanToken + ) { + const topBadPos = typeof topInvalidNodePosition === "undefined" + ? result.pos + : topInvalidNodePosition; + const invalidElement = tryParse(() => + parseJsxElementOrSelfClosingElementOrFragment( + /*inExpressionContext*/ true, + topBadPos, + ) + ); if (invalidElement) { - const operatorToken = createMissingNode(SyntaxKind.CommaToken, /*reportAtCurrentPosition*/ false); + const operatorToken = createMissingNode( + SyntaxKind.CommaToken, + /*reportAtCurrentPosition*/ false, + ); setTextRangePosWidth(operatorToken, invalidElement.pos, 0); - parseErrorAt(skipTrivia(sourceText, topBadPos), invalidElement.end, Diagnostics.JSX_expressions_must_have_one_parent_element); - return finishNode(factory.createBinaryExpression(result, operatorToken as Token, invalidElement), pos) as Node as JsxElement; + parseErrorAt( + skipTrivia(sourceText, topBadPos), + invalidElement.end, + Diagnostics.JSX_expressions_must_have_one_parent_element, + ); + return finishNode( + factory.createBinaryExpression( + result, + operatorToken as Token, + invalidElement, + ), + pos, + ) as Node as JsxElement; } } @@ -6080,25 +8695,45 @@ namespace Parser { function parseJsxText(): JsxText { const pos = getNodePos(); - const node = factory.createJsxText(scanner.getTokenValue(), currentToken === SyntaxKind.JsxTextAllWhiteSpaces); + const node = factory.createJsxText( + scanner.getTokenValue(), + currentToken === SyntaxKind.JsxTextAllWhiteSpaces, + ); currentToken = scanner.scanJsxToken(); return finishNode(node, pos); } - function parseJsxChild(openingTag: JsxOpeningElement | JsxOpeningFragment, token: JsxTokenSyntaxKind): JsxChild | undefined { + function parseJsxChild( + openingTag: JsxOpeningElement | JsxOpeningFragment, + token: JsxTokenSyntaxKind, + ): JsxChild | undefined { switch (token) { case SyntaxKind.EndOfFileToken: // If we hit EOF, issue the error at the tag that lacks the closing element // rather than at the end of the file (which is useless) if (isJsxOpeningFragment(openingTag)) { - parseErrorAtRange(openingTag, Diagnostics.JSX_fragment_has_no_corresponding_closing_tag); + parseErrorAtRange( + openingTag, + Diagnostics.JSX_fragment_has_no_corresponding_closing_tag, + ); } else { // We want the error span to cover only 'Foo.Bar' in < Foo.Bar > // or to cover only 'Foo' in < Foo > const tag = openingTag.tagName; - const start = Math.min(skipTrivia(sourceText, tag.pos), tag.end); - parseErrorAt(start, tag.end, Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, getTextOfNodeFromSourceText(sourceText, openingTag.tagName)); + const start = Math.min( + skipTrivia(sourceText, tag.pos), + tag.end, + ); + parseErrorAt( + start, + tag.end, + Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, + getTextOfNodeFromSourceText( + sourceText, + openingTag.tagName, + ), + ); } return undefined; case SyntaxKind.LessThanSlashToken: @@ -6110,27 +8745,42 @@ namespace Parser { case SyntaxKind.OpenBraceToken: return parseJsxExpression(/*inExpressionContext*/ false); case SyntaxKind.LessThanToken: - return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false, /*topInvalidNodePosition*/ undefined, openingTag); + return parseJsxElementOrSelfClosingElementOrFragment( + /*inExpressionContext*/ false, + /*topInvalidNodePosition*/ undefined, + openingTag, + ); default: return Debug.assertNever(token); } } - function parseJsxChildren(openingTag: JsxOpeningElement | JsxOpeningFragment): NodeArray { + function parseJsxChildren( + openingTag: JsxOpeningElement | JsxOpeningFragment, + ): NodeArray { const list = []; const listPos = getNodePos(); const saveParsingContext = parsingContext; parsingContext |= 1 << ParsingContext.JsxChildren; while (true) { - const child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); + const child = parseJsxChild( + openingTag, + currentToken = scanner.reScanJsxToken(), + ); if (!child) break; list.push(child); if ( - isJsxOpeningElement(openingTag) - && child?.kind === SyntaxKind.JsxElement - && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName) - && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName) + isJsxOpeningElement(openingTag) && + child?.kind === SyntaxKind.JsxElement && + !tagNamesAreEquivalent( + child.openingElement.tagName, + child.closingElement.tagName, + ) && + tagNamesAreEquivalent( + openingTag.tagName, + child.closingElement.tagName, + ) ) { // stop after parsing a mismatched child like
...(
) in order to reattach the
higher break; @@ -6143,10 +8793,17 @@ namespace Parser { function parseJsxAttributes(): JsxAttributes { const pos = getNodePos(); - return finishNode(factory.createJsxAttributes(parseList(ParsingContext.JsxAttributes, parseJsxAttribute)), pos); + return finishNode( + factory.createJsxAttributes( + parseList(ParsingContext.JsxAttributes, parseJsxAttribute), + ), + pos, + ); } - function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext: boolean): JsxOpeningElement | JsxSelfClosingElement | JsxOpeningFragment { + function parseJsxOpeningOrSelfClosingElementOrOpeningFragment( + inExpressionContext: boolean, + ): JsxOpeningElement | JsxSelfClosingElement | JsxOpeningFragment { const pos = getNodePos(); parseExpected(SyntaxKind.LessThanToken); @@ -6157,7 +8814,9 @@ namespace Parser { return finishNode(factory.createJsxOpeningFragment(), pos); } const tagName = parseJsxElementName(); - const typeArguments = (contextFlags & NodeFlags.JavaScriptFile) === 0 ? tryParseTypeArguments() : undefined; + const typeArguments = (contextFlags & NodeFlags.JavaScriptFile) === 0 + ? tryParseTypeArguments() + : undefined; const attributes = parseJsxAttributes(); let node: JsxOpeningLikeElement; @@ -6167,11 +8826,21 @@ namespace Parser { // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate // scanning errors scanJsxText(); - node = factory.createJsxOpeningElement(tagName, typeArguments, attributes); + node = factory.createJsxOpeningElement( + tagName, + typeArguments, + attributes, + ); } else { parseExpected(SyntaxKind.SlashToken); - if (parseExpected(SyntaxKind.GreaterThanToken, /*diagnosticMessage*/ undefined, /*shouldAdvance*/ false)) { + if ( + parseExpected( + SyntaxKind.GreaterThanToken, + /*diagnosticMessage*/ undefined, + /*shouldAdvance*/ false, + ) + ) { // manually advance the scanner in order to look for jsx text inside jsx if (inExpressionContext) { nextToken(); @@ -6180,7 +8849,11 @@ namespace Parser { scanJsxText(); } } - node = factory.createJsxSelfClosingElement(tagName, typeArguments, attributes); + node = factory.createJsxSelfClosingElement( + tagName, + typeArguments, + attributes, + ); } return finishNode(node, pos); @@ -6199,12 +8872,26 @@ namespace Parser { } let expression: PropertyAccessExpression | Identifier | ThisExpression = initialExpression; while (parseOptional(SyntaxKind.DotToken)) { - expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false, /*allowUnicodeEscapeSequenceInIdentifierName*/ false)), pos); + expression = finishNode( + factoryCreatePropertyAccessExpression( + expression, + parseRightSideOfDot( + /*allowIdentifierNames*/ true, + /*allowPrivateIdentifiers*/ false, + /*allowUnicodeEscapeSequenceInIdentifierName*/ false, + ), + ), + pos, + ); } return expression as JsxTagNameExpression; } - function parseJsxTagName(): Identifier | JsxNamespacedName | ThisExpression { + function parseJsxTagName(): + | Identifier + | JsxNamespacedName + | ThisExpression + { const pos = getNodePos(); scanJsxIdentifier(); @@ -6212,12 +8899,22 @@ namespace Parser { const tagName = parseIdentifierNameErrorOnUnicodeEscapeSequence(); if (parseOptional(SyntaxKind.ColonToken)) { scanJsxIdentifier(); - return finishNode(factory.createJsxNamespacedName(tagName, parseIdentifierNameErrorOnUnicodeEscapeSequence()), pos); + return finishNode( + factory.createJsxNamespacedName( + tagName, + parseIdentifierNameErrorOnUnicodeEscapeSequence(), + ), + pos, + ); } - return isThis ? finishNode(factory.createToken(SyntaxKind.ThisKeyword), pos) : tagName; + return isThis + ? finishNode(factory.createToken(SyntaxKind.ThisKeyword), pos) + : tagName; } - function parseJsxExpression(inExpressionContext: boolean): JsxExpression | undefined { + function parseJsxExpression( + inExpressionContext: boolean, + ): JsxExpression | undefined { const pos = getNodePos(); if (!parseExpected(SyntaxKind.OpenBraceToken)) { return undefined; @@ -6238,12 +8935,21 @@ namespace Parser { parseExpected(SyntaxKind.CloseBraceToken); } else { - if (parseExpected(SyntaxKind.CloseBraceToken, /*diagnosticMessage*/ undefined, /*shouldAdvance*/ false)) { + if ( + parseExpected( + SyntaxKind.CloseBraceToken, + /*diagnosticMessage*/ undefined, + /*shouldAdvance*/ false, + ) + ) { scanJsxText(); } } - return finishNode(factory.createJsxExpression(dotDotDotToken, expression), pos); + return finishNode( + factory.createJsxExpression(dotDotDotToken, expression), + pos, + ); } function parseJsxAttribute(): JsxAttribute | JsxSpreadAttribute { @@ -6252,7 +8958,13 @@ namespace Parser { } const pos = getNodePos(); - return finishNode(factory.createJsxAttribute(parseJsxAttributeName(), parseJsxAttributeValue()), pos); + return finishNode( + factory.createJsxAttribute( + parseJsxAttributeName(), + parseJsxAttributeValue(), + ), + pos, + ); } function parseJsxAttributeValue(): JsxAttributeValue | undefined { @@ -6264,7 +8976,9 @@ namespace Parser { return parseJsxExpression(/*inExpressionContext*/ true); } if (token() === SyntaxKind.LessThanToken) { - return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); + return parseJsxElementOrSelfClosingElementOrFragment( + /*inExpressionContext*/ true, + ); } parseErrorAtCurrentToken(Diagnostics.or_JSX_element_expected); } @@ -6278,7 +8992,13 @@ namespace Parser { const attrName = parseIdentifierNameErrorOnUnicodeEscapeSequence(); if (parseOptional(SyntaxKind.ColonToken)) { scanJsxIdentifier(); - return finishNode(factory.createJsxNamespacedName(attrName, parseIdentifierNameErrorOnUnicodeEscapeSequence()), pos); + return finishNode( + factory.createJsxNamespacedName( + attrName, + parseIdentifierNameErrorOnUnicodeEscapeSequence(), + ), + pos, + ); } return attrName; } @@ -6292,13 +9012,25 @@ namespace Parser { return finishNode(factory.createJsxSpreadAttribute(expression), pos); } - function parseJsxClosingElement(open: JsxOpeningElement, inExpressionContext: boolean): JsxClosingElement { + function parseJsxClosingElement( + open: JsxOpeningElement, + inExpressionContext: boolean, + ): JsxClosingElement { const pos = getNodePos(); parseExpected(SyntaxKind.LessThanSlashToken); const tagName = parseJsxElementName(); - if (parseExpected(SyntaxKind.GreaterThanToken, /*diagnosticMessage*/ undefined, /*shouldAdvance*/ false)) { + if ( + parseExpected( + SyntaxKind.GreaterThanToken, + /*diagnosticMessage*/ undefined, + /*shouldAdvance*/ false, + ) + ) { // manually advance the scanner in order to look for jsx text inside jsx - if (inExpressionContext || !tagNamesAreEquivalent(open.tagName, tagName)) { + if ( + inExpressionContext || + !tagNamesAreEquivalent(open.tagName, tagName) + ) { nextToken(); } else { @@ -6308,10 +9040,18 @@ namespace Parser { return finishNode(factory.createJsxClosingElement(tagName), pos); } - function parseJsxClosingFragment(inExpressionContext: boolean): JsxClosingFragment { + function parseJsxClosingFragment( + inExpressionContext: boolean, + ): JsxClosingFragment { const pos = getNodePos(); parseExpected(SyntaxKind.LessThanSlashToken); - if (parseExpected(SyntaxKind.GreaterThanToken, Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment, /*shouldAdvance*/ false)) { + if ( + parseExpected( + SyntaxKind.GreaterThanToken, + Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment, + /*shouldAdvance*/ false, + ) + ) { // manually advance the scanner in order to look for jsx text inside jsx if (inExpressionContext) { nextToken(); @@ -6324,7 +9064,10 @@ namespace Parser { } function parseTypeAssertion(): TypeAssertion { - Debug.assert(languageVariant !== LanguageVariant.JSX, "Type assertions should never be parsed in JSX; they should be parsed as comparisons or JSX elements/fragments."); + Debug.assert( + languageVariant !== LanguageVariant.JSX, + "Type assertions should never be parsed in JSX; they should be parsed as comparisons or JSX elements/fragments.", + ); const pos = getNodePos(); parseExpected(SyntaxKind.LessThanToken); const type = parseType(); @@ -6335,14 +9078,18 @@ namespace Parser { function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() { nextToken(); - return tokenIsIdentifierOrKeyword(token()) - || token() === SyntaxKind.OpenBracketToken - || isTemplateStartOfTaggedTemplate(); + return ( + tokenIsIdentifierOrKeyword(token()) || + token() === SyntaxKind.OpenBracketToken || + isTemplateStartOfTaggedTemplate() + ); } function isStartOfOptionalPropertyOrElementAccessChain() { - return token() === SyntaxKind.QuestionDotToken - && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate); + return ( + token() === SyntaxKind.QuestionDotToken && + lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate) + ); } function tryReparseOptionalChain(node: Expression) { @@ -6352,7 +9099,10 @@ namespace Parser { // check for an optional chain in a non-null expression if (isNonNullExpression(node)) { let expr = node.expression; - while (isNonNullExpression(expr) && !(expr.flags & NodeFlags.OptionalChain)) { + while ( + isNonNullExpression(expr) && + !(expr.flags & NodeFlags.OptionalChain) + ) { expr = expr.expression; } if (expr.flags & NodeFlags.OptionalChain) { @@ -6367,27 +9117,57 @@ namespace Parser { return false; } - function parsePropertyAccessExpressionRest(pos: number, expression: LeftHandSideExpression, questionDotToken: QuestionDotToken | undefined) { - const name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true, /*allowUnicodeEscapeSequenceInIdentifierName*/ true); + function parsePropertyAccessExpressionRest( + pos: number, + expression: LeftHandSideExpression, + questionDotToken: QuestionDotToken | undefined, + ) { + const name = parseRightSideOfDot( + /*allowIdentifierNames*/ true, + /*allowPrivateIdentifiers*/ true, + /*allowUnicodeEscapeSequenceInIdentifierName*/ true, + ); const isOptionalChain = questionDotToken || tryReparseOptionalChain(expression); - const propertyAccess = isOptionalChain ? - factoryCreatePropertyAccessChain(expression, questionDotToken, name) : - factoryCreatePropertyAccessExpression(expression, name); + const propertyAccess = isOptionalChain + ? factoryCreatePropertyAccessChain( + expression, + questionDotToken, + name, + ) + : factoryCreatePropertyAccessExpression(expression, name); if (isOptionalChain && isPrivateIdentifier(propertyAccess.name)) { - parseErrorAtRange(propertyAccess.name, Diagnostics.An_optional_chain_cannot_contain_private_identifiers); + parseErrorAtRange( + propertyAccess.name, + Diagnostics.An_optional_chain_cannot_contain_private_identifiers, + ); } - if (isExpressionWithTypeArguments(expression) && expression.typeArguments) { + if ( + isExpressionWithTypeArguments(expression) && + expression.typeArguments + ) { const pos = expression.typeArguments.pos - 1; const end = skipTrivia(sourceText, expression.typeArguments.end) + 1; - parseErrorAt(pos, end, Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access); + parseErrorAt( + pos, + end, + Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access, + ); } return finishNode(propertyAccess, pos); } - function parseElementAccessExpressionRest(pos: number, expression: LeftHandSideExpression, questionDotToken: QuestionDotToken | undefined) { + function parseElementAccessExpressionRest( + pos: number, + expression: LeftHandSideExpression, + questionDotToken: QuestionDotToken | undefined, + ) { let argumentExpression: Expression; if (token() === SyntaxKind.CloseBracketToken) { - argumentExpression = createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.An_element_access_expression_should_take_an_argument); + argumentExpression = createMissingNode( + SyntaxKind.Identifier, + /*reportAtCurrentPosition*/ true, + Diagnostics.An_element_access_expression_should_take_an_argument, + ); } else { const argument = allowInAnd(parseExpression); @@ -6399,18 +9179,34 @@ namespace Parser { parseExpected(SyntaxKind.CloseBracketToken); - const indexedAccess = questionDotToken || tryReparseOptionalChain(expression) ? - factoryCreateElementAccessChain(expression, questionDotToken, argumentExpression) : - factoryCreateElementAccessExpression(expression, argumentExpression); + const indexedAccess = questionDotToken || tryReparseOptionalChain(expression) + ? factoryCreateElementAccessChain( + expression, + questionDotToken, + argumentExpression, + ) + : factoryCreateElementAccessExpression( + expression, + argumentExpression, + ); return finishNode(indexedAccess, pos); } - function parseMemberExpressionRest(pos: number, expression: LeftHandSideExpression, allowOptionalChain: boolean): MemberExpression { + function parseMemberExpressionRest( + pos: number, + expression: LeftHandSideExpression, + allowOptionalChain: boolean, + ): MemberExpression { while (true) { let questionDotToken: QuestionDotToken | undefined; let isPropertyAccess = false; - if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) { - questionDotToken = parseExpectedToken(SyntaxKind.QuestionDotToken); + if ( + allowOptionalChain && + isStartOfOptionalPropertyOrElementAccessChain() + ) { + questionDotToken = parseExpectedToken( + SyntaxKind.QuestionDotToken, + ); isPropertyAccess = tokenIsIdentifierOrKeyword(token()); } else { @@ -6418,33 +9214,69 @@ namespace Parser { } if (isPropertyAccess) { - expression = parsePropertyAccessExpressionRest(pos, expression, questionDotToken); + expression = parsePropertyAccessExpressionRest( + pos, + expression, + questionDotToken, + ); continue; } // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName - if ((questionDotToken || !inDecoratorContext()) && parseOptional(SyntaxKind.OpenBracketToken)) { - expression = parseElementAccessExpressionRest(pos, expression, questionDotToken); + if ( + (questionDotToken || !inDecoratorContext()) && + parseOptional(SyntaxKind.OpenBracketToken) + ) { + expression = parseElementAccessExpressionRest( + pos, + expression, + questionDotToken, + ); continue; } if (isTemplateStartOfTaggedTemplate()) { // Absorb type arguments into TemplateExpression when preceding expression is ExpressionWithTypeArguments - expression = !questionDotToken && expression.kind === SyntaxKind.ExpressionWithTypeArguments ? - parseTaggedTemplateRest(pos, (expression as ExpressionWithTypeArguments).expression, questionDotToken, (expression as ExpressionWithTypeArguments).typeArguments) : - parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ undefined); + expression = !questionDotToken && + expression.kind === SyntaxKind.ExpressionWithTypeArguments + ? parseTaggedTemplateRest( + pos, + expression + .expression, + questionDotToken, + expression + .typeArguments, + ) + : parseTaggedTemplateRest( + pos, + expression, + questionDotToken, + /*typeArguments*/ undefined, + ); continue; } if (!questionDotToken) { - if (token() === SyntaxKind.ExclamationToken && !scanner.hasPrecedingLineBreak()) { + if ( + token() === SyntaxKind.ExclamationToken && + !scanner.hasPrecedingLineBreak() + ) { nextToken(); - expression = finishNode(factory.createNonNullExpression(expression), pos); + expression = finishNode( + factory.createNonNullExpression(expression), + pos, + ); continue; } const typeArguments = tryParse(parseTypeArgumentsInExpression); if (typeArguments) { - expression = finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos); + expression = finishNode( + factory.createExpressionWithTypeArguments( + expression, + typeArguments, + ), + pos, + ); continue; } } @@ -6454,16 +9286,24 @@ namespace Parser { } function isTemplateStartOfTaggedTemplate() { - return token() === SyntaxKind.NoSubstitutionTemplateLiteral || token() === SyntaxKind.TemplateHead; + return ( + token() === SyntaxKind.NoSubstitutionTemplateLiteral || + token() === SyntaxKind.TemplateHead + ); } - function parseTaggedTemplateRest(pos: number, tag: LeftHandSideExpression, questionDotToken: QuestionDotToken | undefined, typeArguments: NodeArray | undefined) { + function parseTaggedTemplateRest( + pos: number, + tag: LeftHandSideExpression, + questionDotToken: QuestionDotToken | undefined, + typeArguments: NodeArray | undefined, + ) { const tagExpression = factory.createTaggedTemplateExpression( tag, typeArguments, - token() === SyntaxKind.NoSubstitutionTemplateLiteral ? - (reScanTemplateToken(/*isTaggedTemplate*/ true), parseLiteralNode() as NoSubstitutionTemplateLiteral) : - parseTemplateExpression(/*isTaggedTemplate*/ true), + token() === SyntaxKind.NoSubstitutionTemplateLiteral + ? (reScanTemplateToken(/*isTaggedTemplate*/ true), parseLiteralNode() as NoSubstitutionTemplateLiteral) + : parseTemplateExpression(/*isTaggedTemplate*/ true), ); if (questionDotToken || tag.flags & NodeFlags.OptionalChain) { (tagExpression as Mutable).flags |= NodeFlags.OptionalChain; @@ -6472,35 +9312,74 @@ namespace Parser { return finishNode(tagExpression, pos); } - function parseCallExpressionRest(pos: number, expression: LeftHandSideExpression): LeftHandSideExpression { + function parseCallExpressionRest( + pos: number, + expression: LeftHandSideExpression, + ): LeftHandSideExpression { while (true) { - expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true); + expression = parseMemberExpressionRest( + pos, + expression, + /*allowOptionalChain*/ true, + ); let typeArguments: NodeArray | undefined; - const questionDotToken = parseOptionalToken(SyntaxKind.QuestionDotToken); + const questionDotToken = parseOptionalToken( + SyntaxKind.QuestionDotToken, + ); if (questionDotToken) { typeArguments = tryParse(parseTypeArgumentsInExpression); if (isTemplateStartOfTaggedTemplate()) { - expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments); + expression = parseTaggedTemplateRest( + pos, + expression, + questionDotToken, + typeArguments, + ); continue; } } if (typeArguments || token() === SyntaxKind.OpenParenToken) { // Absorb type arguments into CallExpression when preceding expression is ExpressionWithTypeArguments - if (!questionDotToken && expression.kind === SyntaxKind.ExpressionWithTypeArguments) { - typeArguments = (expression as ExpressionWithTypeArguments).typeArguments; - expression = (expression as ExpressionWithTypeArguments).expression; + if ( + !questionDotToken && + expression.kind === SyntaxKind.ExpressionWithTypeArguments + ) { + typeArguments = expression + .typeArguments; + expression = expression + .expression; } const argumentList = parseArgumentList(); - const callExpr = questionDotToken || tryReparseOptionalChain(expression) ? - factoryCreateCallChain(expression, questionDotToken, typeArguments, argumentList) : - factoryCreateCallExpression(expression, typeArguments, argumentList); + const callExpr = questionDotToken || tryReparseOptionalChain(expression) + ? factoryCreateCallChain( + expression, + questionDotToken, + typeArguments, + argumentList, + ) + : factoryCreateCallExpression( + expression, + typeArguments, + argumentList, + ); expression = finishNode(callExpr, pos); continue; } if (questionDotToken) { // We parsed `?.` but then failed to parse anything, so report a missing identifier here. - const name = createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ false, Diagnostics.Identifier_expected); - expression = finishNode(factoryCreatePropertyAccessChain(expression, questionDotToken, name), pos); + const name = createMissingNode( + SyntaxKind.Identifier, + /*reportAtCurrentPosition*/ false, + Diagnostics.Identifier_expected, + ); + expression = finishNode( + factoryCreatePropertyAccessChain( + expression, + questionDotToken, + name, + ), + pos, + ); } break; } @@ -6509,7 +9388,10 @@ namespace Parser { function parseArgumentList() { parseExpected(SyntaxKind.OpenParenToken); - const result = parseDelimitedList(ParsingContext.ArgumentExpressions, parseArgumentExpression); + const result = parseDelimitedList( + ParsingContext.ArgumentExpressions, + parseArgumentExpression, + ); parseExpected(SyntaxKind.CloseParenToken); return result; } @@ -6525,7 +9407,10 @@ namespace Parser { } nextToken(); - const typeArguments = parseDelimitedList(ParsingContext.TypeArguments, parseType); + const typeArguments = parseDelimitedList( + ParsingContext.TypeArguments, + parseType, + ); if (reScanGreaterToken() !== SyntaxKind.GreaterThanToken) { // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; @@ -6536,7 +9421,9 @@ namespace Parser { // treat it as such. If the type argument list is followed by `(` or a template literal, as in // `f(42)`, we favor the type argument interpretation even though JavaScript would view // it as a relational expression. - return typeArguments && canFollowTypeArgumentsInExpression() ? typeArguments : undefined; + return typeArguments && canFollowTypeArgumentsInExpression() + ? typeArguments + : undefined; } function canFollowTypeArgumentsInExpression(): boolean { @@ -6557,7 +9444,11 @@ namespace Parser { } // We favor the type argument list interpretation when it is immediately followed by // a line break, a binary operator, or something that can't start an expression. - return scanner.hasPrecedingLineBreak() || isBinaryOperator() || !isStartOfExpression(); + return ( + scanner.hasPrecedingLineBreak() || + isBinaryOperator() || + !isStartOfExpression() + ); } function parsePrimaryExpression(): PrimaryExpression { @@ -6602,7 +9493,9 @@ namespace Parser { return parseNewExpressionOrNewDotTarget(); case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: - if (reScanSlashToken() === SyntaxKind.RegularExpressionLiteral) { + if ( + reScanSlashToken() === SyntaxKind.RegularExpressionLiteral + ) { return parseLiteralNode(); } break; @@ -6621,24 +9514,36 @@ namespace Parser { parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); - return withJSDoc(finishNode(factoryCreateParenthesizedExpression(expression), pos), hasJSDoc); + return withJSDoc( + finishNode(factoryCreateParenthesizedExpression(expression), pos), + hasJSDoc, + ); } function parseSpreadElement(): Expression { const pos = getNodePos(); parseExpected(SyntaxKind.DotDotDotToken); - const expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); + const expression = parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ); return finishNode(factory.createSpreadElement(expression), pos); } function parseArgumentOrArrayLiteralElement(): Expression { - return token() === SyntaxKind.DotDotDotToken ? parseSpreadElement() : - token() === SyntaxKind.CommaToken ? finishNode(factory.createOmittedExpression(), getNodePos()) : - parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); + return token() === SyntaxKind.DotDotDotToken + ? parseSpreadElement() + : token() === SyntaxKind.CommaToken + ? finishNode(factory.createOmittedExpression(), getNodePos()) + : parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ); } function parseArgumentExpression(): Expression { - return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement); + return doOutsideOfContext( + disallowInAndDecoratorContext, + parseArgumentOrArrayLiteralElement, + ); } function parseArrayLiteralExpression(): ArrayLiteralExpression { @@ -6646,9 +9551,20 @@ namespace Parser { const openBracketPosition = scanner.getTokenStart(); const openBracketParsed = parseExpected(SyntaxKind.OpenBracketToken); const multiLine = scanner.hasPrecedingLineBreak(); - const elements = parseDelimitedList(ParsingContext.ArrayLiteralMembers, parseArgumentOrArrayLiteralElement); - parseExpectedMatchingBrackets(SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken, openBracketParsed, openBracketPosition); - return finishNode(factoryCreateArrayLiteralExpression(elements, multiLine), pos); + const elements = parseDelimitedList( + ParsingContext.ArrayLiteralMembers, + parseArgumentOrArrayLiteralElement, + ); + parseExpectedMatchingBrackets( + SyntaxKind.OpenBracketToken, + SyntaxKind.CloseBracketToken, + openBracketParsed, + openBracketPosition, + ); + return finishNode( + factoryCreateArrayLiteralExpression(elements, multiLine), + pos, + ); } function parseObjectLiteralElement(): ObjectLiteralElementLike { @@ -6656,16 +9572,33 @@ namespace Parser { const hasJSDoc = hasPrecedingJSDocComment(); if (parseOptionalToken(SyntaxKind.DotDotDotToken)) { - const expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); - return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc); + const expression = parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ); + return withJSDoc( + finishNode(factory.createSpreadAssignment(expression), pos), + hasJSDoc, + ); } const modifiers = parseModifiers(/*allowDecorators*/ true); if (parseContextualModifier(SyntaxKind.GetKeyword)) { - return parseAccessorDeclaration(pos, hasJSDoc, modifiers, SyntaxKind.GetAccessor, SignatureFlags.None); + return parseAccessorDeclaration( + pos, + hasJSDoc, + modifiers, + SyntaxKind.GetAccessor, + SignatureFlags.None, + ); } if (parseContextualModifier(SyntaxKind.SetKeyword)) { - return parseAccessorDeclaration(pos, hasJSDoc, modifiers, SyntaxKind.SetAccessor, SignatureFlags.None); + return parseAccessorDeclaration( + pos, + hasJSDoc, + modifiers, + SyntaxKind.SetAccessor, + SignatureFlags.None, + ); } const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); @@ -6674,10 +9607,24 @@ namespace Parser { // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); - const exclamationToken = parseOptionalToken(SyntaxKind.ExclamationToken); + const exclamationToken = parseOptionalToken( + SyntaxKind.ExclamationToken, + ); - if (asteriskToken || token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken) { - return parseMethodDeclaration(pos, hasJSDoc, modifiers, asteriskToken, name, questionToken, exclamationToken); + if ( + asteriskToken || + token() === SyntaxKind.OpenParenToken || + token() === SyntaxKind.LessThanToken + ) { + return parseMethodDeclaration( + pos, + hasJSDoc, + modifiers, + asteriskToken, + name, + questionToken, + exclamationToken, + ); } // check if it is short-hand property assignment or normal property assignment @@ -6686,18 +9633,31 @@ namespace Parser { // IdentifierReference[?Yield] Initializer[In, ?Yield] // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern let node: Mutable; - const isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== SyntaxKind.ColonToken); + const isShorthandPropertyAssignment = tokenIsIdentifier && token() !== SyntaxKind.ColonToken; if (isShorthandPropertyAssignment) { const equalsToken = parseOptionalToken(SyntaxKind.EqualsToken); - const objectAssignmentInitializer = equalsToken ? allowInAnd(() => parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)) : undefined; - node = factory.createShorthandPropertyAssignment(name as Identifier, objectAssignmentInitializer); + const objectAssignmentInitializer = equalsToken + ? allowInAnd(() => + parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ) + ) + : undefined; + node = factory.createShorthandPropertyAssignment( + name as Identifier, + objectAssignmentInitializer, + ); // Save equals token for error reporting. // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful. node.equalsToken = equalsToken; } else { parseExpected(SyntaxKind.ColonToken); - const initializer = allowInAnd(() => parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)); + const initializer = allowInAnd(() => + parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ) + ); node = factory.createPropertyAssignment(name, initializer); } // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker @@ -6712,9 +9672,21 @@ namespace Parser { const openBracePosition = scanner.getTokenStart(); const openBraceParsed = parseExpected(SyntaxKind.OpenBraceToken); const multiLine = scanner.hasPrecedingLineBreak(); - const properties = parseDelimitedList(ParsingContext.ObjectLiteralMembers, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true); - parseExpectedMatchingBrackets(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, openBraceParsed, openBracePosition); - return finishNode(factoryCreateObjectLiteralExpression(properties, multiLine), pos); + const properties = parseDelimitedList( + ParsingContext.ObjectLiteralMembers, + parseObjectLiteralElement, + /*considerSemicolonAsDelimiter*/ true, + ); + parseExpectedMatchingBrackets( + SyntaxKind.OpenBraceToken, + SyntaxKind.CloseBraceToken, + openBraceParsed, + openBracePosition, + ); + return finishNode( + factoryCreateObjectLiteralExpression(properties, multiLine), + pos, + ); } function parseFunctionExpression(): FunctionExpression { @@ -6731,12 +9703,19 @@ namespace Parser { const modifiers = parseModifiers(/*allowDecorators*/ false); parseExpected(SyntaxKind.FunctionKeyword); const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); - const isGenerator = asteriskToken ? SignatureFlags.Yield : SignatureFlags.None; - const isAsync = some(modifiers, isAsyncModifier) ? SignatureFlags.Await : SignatureFlags.None; - const name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) : - isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) : - isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) : - parseOptionalBindingIdentifier(); + const isGenerator = asteriskToken + ? SignatureFlags.Yield + : SignatureFlags.None; + const isAsync = some(modifiers, isAsyncModifier) + ? SignatureFlags.Await + : SignatureFlags.None; + const name = isGenerator && isAsync + ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) + : isGenerator + ? doInYieldContext(parseOptionalBindingIdentifier) + : isAsync + ? doInAwaitContext(parseOptionalBindingIdentifier) + : parseOptionalBindingIdentifier(); const typeParameters = parseTypeParameters(); const parameters = parseParameters(isGenerator | isAsync); @@ -6745,7 +9724,15 @@ namespace Parser { setDecoratorContext(savedDecoratorContext); - const node = factory.createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + const node = factory.createFunctionExpression( + modifiers, + asteriskToken, + name, + typeParameters, + parameters, + type, + body, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -6758,36 +9745,71 @@ namespace Parser { parseExpected(SyntaxKind.NewKeyword); if (parseOptional(SyntaxKind.DotToken)) { const name = parseIdentifierName(); - return finishNode(factory.createMetaProperty(SyntaxKind.NewKeyword, name), pos); + return finishNode( + factory.createMetaProperty(SyntaxKind.NewKeyword, name), + pos, + ); } const expressionPos = getNodePos(); - let expression: LeftHandSideExpression = parseMemberExpressionRest(expressionPos, parsePrimaryExpression(), /*allowOptionalChain*/ false); + let expression: LeftHandSideExpression = parseMemberExpressionRest( + expressionPos, + parsePrimaryExpression(), + /*allowOptionalChain*/ false, + ); let typeArguments: NodeArray | undefined; // Absorb type arguments into NewExpression when preceding expression is ExpressionWithTypeArguments if (expression.kind === SyntaxKind.ExpressionWithTypeArguments) { - typeArguments = (expression as ExpressionWithTypeArguments).typeArguments; - expression = (expression as ExpressionWithTypeArguments).expression; + typeArguments = expression + .typeArguments; + expression = expression.expression; } if (token() === SyntaxKind.QuestionDotToken) { - parseErrorAtCurrentToken(Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, getTextOfNodeFromSourceText(sourceText, expression)); + parseErrorAtCurrentToken( + Diagnostics.Invalid_optional_chain_from_new_expression_Did_you_mean_to_call_0, + getTextOfNodeFromSourceText(sourceText, expression), + ); } - const argumentList = token() === SyntaxKind.OpenParenToken ? parseArgumentList() : undefined; - return finishNode(factoryCreateNewExpression(expression, typeArguments, argumentList), pos); + const argumentList = token() === SyntaxKind.OpenParenToken + ? parseArgumentList() + : undefined; + return finishNode( + factoryCreateNewExpression(expression, typeArguments, argumentList), + pos, + ); } // STATEMENTS - function parseBlock(ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block { + function parseBlock( + ignoreMissingOpenBrace: boolean, + diagnosticMessage?: DiagnosticMessage, + ): Block { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); const openBracePosition = scanner.getTokenStart(); - const openBraceParsed = parseExpected(SyntaxKind.OpenBraceToken, diagnosticMessage); + const openBraceParsed = parseExpected( + SyntaxKind.OpenBraceToken, + diagnosticMessage, + ); if (openBraceParsed || ignoreMissingOpenBrace) { const multiLine = scanner.hasPrecedingLineBreak(); - const statements = parseList(ParsingContext.BlockStatements, parseStatement); - parseExpectedMatchingBrackets(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken, openBraceParsed, openBracePosition); - const result = withJSDoc(finishNode(factoryCreateBlock(statements, multiLine), pos), hasJSDoc); + const statements = parseList( + ParsingContext.BlockStatements, + parseStatement, + ); + parseExpectedMatchingBrackets( + SyntaxKind.OpenBraceToken, + SyntaxKind.CloseBraceToken, + openBraceParsed, + openBracePosition, + ); + const result = withJSDoc( + finishNode(factoryCreateBlock(statements, multiLine), pos), + hasJSDoc, + ); if (token() === SyntaxKind.EqualsToken) { - parseErrorAtCurrentToken(Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_whole_assignment_in_parentheses); + parseErrorAtCurrentToken( + Diagnostics.Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_whole_assignment_in_parentheses, + ); nextToken(); } @@ -6795,11 +9817,20 @@ namespace Parser { } else { const statements = createMissingList(); - return withJSDoc(finishNode(factoryCreateBlock(statements, /*multiLine*/ undefined), pos), hasJSDoc); + return withJSDoc( + finishNode( + factoryCreateBlock(statements, /*multiLine*/ undefined), + pos, + ), + hasJSDoc, + ); } } - function parseFunctionBlock(flags: SignatureFlags, diagnosticMessage?: DiagnosticMessage): Block { + function parseFunctionBlock( + flags: SignatureFlags, + diagnosticMessage?: DiagnosticMessage, + ): Block { const savedYieldContext = inYieldContext(); setYieldContext(!!(flags & SignatureFlags.Yield)); @@ -6816,7 +9847,10 @@ namespace Parser { setDecoratorContext(/*val*/ false); } - const block = parseBlock(!!(flags & SignatureFlags.IgnoreMissingOpenBrace), diagnosticMessage); + const block = parseBlock( + !!(flags & SignatureFlags.IgnoreMissingOpenBrace), + diagnosticMessage, + ); if (saveDecoratorContext) { setDecoratorContext(/*val*/ true); @@ -6833,7 +9867,10 @@ namespace Parser { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.SemicolonToken); - return withJSDoc(finishNode(factory.createEmptyStatement(), pos), hasJSDoc); + return withJSDoc( + finishNode(factory.createEmptyStatement(), pos), + hasJSDoc, + ); } function parseIfStatement(): IfStatement { @@ -6843,10 +9880,27 @@ namespace Parser { const openParenPosition = scanner.getTokenStart(); const openParenParsed = parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, openParenParsed, openParenPosition); + parseExpectedMatchingBrackets( + SyntaxKind.OpenParenToken, + SyntaxKind.CloseParenToken, + openParenParsed, + openParenPosition, + ); const thenStatement = parseStatement(); - const elseStatement = parseOptional(SyntaxKind.ElseKeyword) ? parseStatement() : undefined; - return withJSDoc(finishNode(factoryCreateIfStatement(expression, thenStatement, elseStatement), pos), hasJSDoc); + const elseStatement = parseOptional(SyntaxKind.ElseKeyword) + ? parseStatement() + : undefined; + return withJSDoc( + finishNode( + factoryCreateIfStatement( + expression, + thenStatement, + elseStatement, + ), + pos, + ), + hasJSDoc, + ); } function parseDoStatement(): DoStatement { @@ -6858,14 +9912,22 @@ namespace Parser { const openParenPosition = scanner.getTokenStart(); const openParenParsed = parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, openParenParsed, openParenPosition); + parseExpectedMatchingBrackets( + SyntaxKind.OpenParenToken, + SyntaxKind.CloseParenToken, + openParenParsed, + openParenPosition, + ); // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby // do;while(0)x will have a semicolon inserted before x. parseOptional(SyntaxKind.SemicolonToken); - return withJSDoc(finishNode(factory.createDoStatement(statement, expression), pos), hasJSDoc); + return withJSDoc( + finishNode(factory.createDoStatement(statement, expression), pos), + hasJSDoc, + ); } function parseWhileStatement(): WhileStatement { @@ -6875,9 +9937,17 @@ namespace Parser { const openParenPosition = scanner.getTokenStart(); const openParenParsed = parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, openParenParsed, openParenPosition); + parseExpectedMatchingBrackets( + SyntaxKind.OpenParenToken, + SyntaxKind.CloseParenToken, + openParenParsed, + openParenPosition, + ); const statement = parseStatement(); - return withJSDoc(finishNode(factoryCreateWhileStatement(expression, statement), pos), hasJSDoc); + return withJSDoc( + finishNode(factoryCreateWhileStatement(expression, statement), pos), + hasJSDoc, + ); } function parseForOrForInOrForOfStatement(): Statement { @@ -6890,11 +9960,21 @@ namespace Parser { let initializer!: VariableDeclarationList | Expression; if (token() !== SyntaxKind.SemicolonToken) { if ( - token() === SyntaxKind.VarKeyword || token() === SyntaxKind.LetKeyword || token() === SyntaxKind.ConstKeyword || - token() === SyntaxKind.UsingKeyword && lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf) || - token() === SyntaxKind.AwaitKeyword && lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf) + token() === SyntaxKind.VarKeyword || + token() === SyntaxKind.LetKeyword || + token() === SyntaxKind.ConstKeyword || + (token() === SyntaxKind.UsingKeyword && + lookAhead( + nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf, + )) || + (token() === SyntaxKind.AwaitKeyword && + lookAhead( + nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf, + )) ) { - initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + initializer = parseVariableDeclarationList( + /*inForStatementInitializer*/ true, + ); } else { initializer = disallowInAnd(parseExpression); @@ -6902,19 +9982,37 @@ namespace Parser { } let node: IterationStatement; - if (awaitToken ? parseExpected(SyntaxKind.OfKeyword) : parseOptional(SyntaxKind.OfKeyword)) { - const expression = allowInAnd(() => parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true)); + if ( + awaitToken + ? parseExpected(SyntaxKind.OfKeyword) + : parseOptional(SyntaxKind.OfKeyword) + ) { + const expression = allowInAnd(() => + parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ) + ); parseExpected(SyntaxKind.CloseParenToken); - node = factoryCreateForOfStatement(awaitToken, initializer, expression, parseStatement()); + node = factoryCreateForOfStatement( + awaitToken, + initializer, + expression, + parseStatement(), + ); } else if (parseOptional(SyntaxKind.InKeyword)) { const expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); - node = factory.createForInStatement(initializer, expression, parseStatement()); + node = factory.createForInStatement( + initializer, + expression, + parseStatement(), + ); } else { parseExpected(SyntaxKind.SemicolonToken); - const condition = token() !== SyntaxKind.SemicolonToken && token() !== SyntaxKind.CloseParenToken + const condition = token() !== SyntaxKind.SemicolonToken && + token() !== SyntaxKind.CloseParenToken ? allowInAnd(parseExpression) : undefined; parseExpected(SyntaxKind.SemicolonToken); @@ -6922,17 +10020,31 @@ namespace Parser { ? allowInAnd(parseExpression) : undefined; parseExpected(SyntaxKind.CloseParenToken); - node = factoryCreateForStatement(initializer, condition, incrementor, parseStatement()); + node = factoryCreateForStatement( + initializer, + condition, + incrementor, + parseStatement(), + ); } - return withJSDoc(finishNode(node, pos) as ForStatement | ForInOrOfStatement, hasJSDoc); + return withJSDoc( + finishNode(node, pos) as ForStatement | ForInOrOfStatement, + hasJSDoc, + ); } - function parseBreakOrContinueStatement(kind: SyntaxKind): BreakOrContinueStatement { + function parseBreakOrContinueStatement( + kind: SyntaxKind, + ): BreakOrContinueStatement { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - parseExpected(kind === SyntaxKind.BreakStatement ? SyntaxKind.BreakKeyword : SyntaxKind.ContinueKeyword); + parseExpected( + kind === SyntaxKind.BreakStatement + ? SyntaxKind.BreakKeyword + : SyntaxKind.ContinueKeyword, + ); const label = canParseSemicolon() ? undefined : parseIdentifier(); parseSemicolon(); @@ -6946,9 +10058,14 @@ namespace Parser { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.ReturnKeyword); - const expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression); + const expression = canParseSemicolon() + ? undefined + : allowInAnd(parseExpression); parseSemicolon(); - return withJSDoc(finishNode(factory.createReturnStatement(expression), pos), hasJSDoc); + return withJSDoc( + finishNode(factory.createReturnStatement(expression), pos), + hasJSDoc, + ); } function parseWithStatement(): WithStatement { @@ -6958,9 +10075,20 @@ namespace Parser { const openParenPosition = scanner.getTokenStart(); const openParenParsed = parseExpected(SyntaxKind.OpenParenToken); const expression = allowInAnd(parseExpression); - parseExpectedMatchingBrackets(SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, openParenParsed, openParenPosition); - const statement = doInsideOfContext(NodeFlags.InWithStatement, parseStatement); - return withJSDoc(finishNode(factory.createWithStatement(expression, statement), pos), hasJSDoc); + parseExpectedMatchingBrackets( + SyntaxKind.OpenParenToken, + SyntaxKind.CloseParenToken, + openParenParsed, + openParenPosition, + ); + const statement = doInsideOfContext( + NodeFlags.InWithStatement, + parseStatement, + ); + return withJSDoc( + finishNode(factory.createWithStatement(expression, statement), pos), + hasJSDoc, + ); } function parseCaseClause(): CaseClause { @@ -6969,26 +10097,40 @@ namespace Parser { parseExpected(SyntaxKind.CaseKeyword); const expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.ColonToken); - const statements = parseList(ParsingContext.SwitchClauseStatements, parseStatement); - return withJSDoc(finishNode(factory.createCaseClause(expression, statements), pos), hasJSDoc); + const statements = parseList( + ParsingContext.SwitchClauseStatements, + parseStatement, + ); + return withJSDoc( + finishNode(factory.createCaseClause(expression, statements), pos), + hasJSDoc, + ); } function parseDefaultClause(): DefaultClause { const pos = getNodePos(); parseExpected(SyntaxKind.DefaultKeyword); parseExpected(SyntaxKind.ColonToken); - const statements = parseList(ParsingContext.SwitchClauseStatements, parseStatement); + const statements = parseList( + ParsingContext.SwitchClauseStatements, + parseStatement, + ); return finishNode(factory.createDefaultClause(statements), pos); } function parseCaseOrDefaultClause(): CaseOrDefaultClause { - return token() === SyntaxKind.CaseKeyword ? parseCaseClause() : parseDefaultClause(); + return token() === SyntaxKind.CaseKeyword + ? parseCaseClause() + : parseDefaultClause(); } function parseCaseBlock(): CaseBlock { const pos = getNodePos(); parseExpected(SyntaxKind.OpenBraceToken); - const clauses = parseList(ParsingContext.SwitchClauses, parseCaseOrDefaultClause); + const clauses = parseList( + ParsingContext.SwitchClauses, + parseCaseOrDefaultClause, + ); parseExpected(SyntaxKind.CloseBraceToken); return finishNode(factory.createCaseBlock(clauses), pos); } @@ -7001,7 +10143,13 @@ namespace Parser { const expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); const caseBlock = parseCaseBlock(); - return withJSDoc(finishNode(factory.createSwitchStatement(expression, caseBlock), pos), hasJSDoc); + return withJSDoc( + finishNode( + factory.createSwitchStatement(expression, caseBlock), + pos, + ), + hasJSDoc, + ); } function parseThrowStatement(): ThrowStatement { @@ -7017,7 +10165,9 @@ namespace Parser { // directly as that might consume an expression on the following line. // Instead, we create a "missing" identifier, but don't report an error. The actual error // will be reported in the grammar walker. - let expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); + let expression = scanner.hasPrecedingLineBreak() + ? undefined + : allowInAnd(parseExpression); if (expression === undefined) { identifierCount++; expression = finishNode(factoryCreateIdentifier(""), getNodePos()); @@ -7025,7 +10175,10 @@ namespace Parser { if (!tryParseSemicolon()) { parseErrorForMissingSemicolonAfter(expression); } - return withJSDoc(finishNode(factory.createThrowStatement(expression), pos), hasJSDoc); + return withJSDoc( + finishNode(factory.createThrowStatement(expression), pos), + hasJSDoc, + ); } // TODO: Review for error recovery @@ -7035,17 +10188,28 @@ namespace Parser { parseExpected(SyntaxKind.TryKeyword); const tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); - const catchClause = token() === SyntaxKind.CatchKeyword ? parseCatchClause() : undefined; + const catchClause = token() === SyntaxKind.CatchKeyword + ? parseCatchClause() + : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. let finallyBlock: Block | undefined; if (!catchClause || token() === SyntaxKind.FinallyKeyword) { - parseExpected(SyntaxKind.FinallyKeyword, Diagnostics.catch_or_finally_expected); + parseExpected( + SyntaxKind.FinallyKeyword, + Diagnostics.catch_or_finally_expected, + ); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } - return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); + return withJSDoc( + finishNode( + factory.createTryStatement(tryBlock, catchClause, finallyBlock), + pos, + ), + hasJSDoc, + ); } function parseCatchClause(): CatchClause { @@ -7063,7 +10227,10 @@ namespace Parser { } const block = parseBlock(/*ignoreMissingOpenBrace*/ false); - return finishNode(factory.createCatchClause(variableDeclaration, block), pos); + return finishNode( + factory.createCatchClause(variableDeclaration, block), + pos, + ); } function parseDebuggerStatement(): Statement { @@ -7071,10 +10238,16 @@ namespace Parser { const hasJSDoc = hasPrecedingJSDocComment(); parseExpected(SyntaxKind.DebuggerKeyword); parseSemicolon(); - return withJSDoc(finishNode(factory.createDebuggerStatement(), pos), hasJSDoc); + return withJSDoc( + finishNode(factory.createDebuggerStatement(), pos), + hasJSDoc, + ); } - function parseExpressionOrLabeledStatement(): ExpressionStatement | LabeledStatement { + function parseExpressionOrLabeledStatement(): + | ExpressionStatement + | LabeledStatement + { // Avoiding having to do the lookahead for a labeled statement by just trying to parse // out an expression, seeing if it is identifier and then seeing if it is followed by // a colon. @@ -7083,7 +10256,10 @@ namespace Parser { let node: ExpressionStatement | LabeledStatement; const hasParen = token() === SyntaxKind.OpenParenToken; const expression = allowInAnd(parseExpression); - if (isIdentifierNode(expression) && parseOptional(SyntaxKind.ColonToken)) { + if ( + isIdentifierNode(expression) && + parseOptional(SyntaxKind.ColonToken) + ) { node = factory.createLabeledStatement(expression, parseStatement()); } else { @@ -7101,22 +10277,37 @@ namespace Parser { function nextTokenIsIdentifierOrKeywordOnSameLine() { nextToken(); - return tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak(); + return ( + tokenIsIdentifierOrKeyword(token()) && + !scanner.hasPrecedingLineBreak() + ); } function nextTokenIsClassKeywordOnSameLine() { nextToken(); - return token() === SyntaxKind.ClassKeyword && !scanner.hasPrecedingLineBreak(); + return ( + token() === SyntaxKind.ClassKeyword && + !scanner.hasPrecedingLineBreak() + ); } function nextTokenIsFunctionKeywordOnSameLine() { nextToken(); - return token() === SyntaxKind.FunctionKeyword && !scanner.hasPrecedingLineBreak(); + return ( + token() === SyntaxKind.FunctionKeyword && + !scanner.hasPrecedingLineBreak() + ); } function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() { nextToken(); - return (tokenIsIdentifierOrKeyword(token()) || token() === SyntaxKind.NumericLiteral || token() === SyntaxKind.BigIntLiteral || token() === SyntaxKind.StringLiteral) && !scanner.hasPrecedingLineBreak(); + return ( + (tokenIsIdentifierOrKeyword(token()) || + token() === SyntaxKind.NumericLiteral || + token() === SyntaxKind.BigIntLiteral || + token() === SyntaxKind.StringLiteral) && + !scanner.hasPrecedingLineBreak() + ); } function isDeclaration(): boolean { @@ -7175,7 +10366,10 @@ namespace Parser { if (scanner.hasPrecedingLineBreak()) { return false; } - if (previousToken === SyntaxKind.DeclareKeyword && token() === SyntaxKind.TypeKeyword) { + if ( + previousToken === SyntaxKind.DeclareKeyword && + token() === SyntaxKind.TypeKeyword + ) { // If we see 'declare type', then commit to parsing a type alias. parseTypeAliasDeclaration will // report Line_break_not_permitted_here if needed. return true; @@ -7184,21 +10378,32 @@ namespace Parser { case SyntaxKind.GlobalKeyword: nextToken(); - return token() === SyntaxKind.OpenBraceToken || token() === SyntaxKind.Identifier || token() === SyntaxKind.ExportKeyword; + return ( + token() === SyntaxKind.OpenBraceToken || + token() === SyntaxKind.Identifier || + token() === SyntaxKind.ExportKeyword + ); case SyntaxKind.ImportKeyword: nextToken(); - return token() === SyntaxKind.StringLiteral || token() === SyntaxKind.AsteriskToken || - token() === SyntaxKind.OpenBraceToken || tokenIsIdentifierOrKeyword(token()); + return ( + token() === SyntaxKind.StringLiteral || + token() === SyntaxKind.AsteriskToken || + token() === SyntaxKind.OpenBraceToken || + tokenIsIdentifierOrKeyword(token()) + ); case SyntaxKind.ExportKeyword: let currentToken = nextToken(); if (currentToken === SyntaxKind.TypeKeyword) { currentToken = lookAhead(nextToken); } if ( - currentToken === SyntaxKind.EqualsToken || currentToken === SyntaxKind.AsteriskToken || - currentToken === SyntaxKind.OpenBraceToken || currentToken === SyntaxKind.DefaultKeyword || - currentToken === SyntaxKind.AsKeyword || currentToken === SyntaxKind.AtToken + currentToken === SyntaxKind.EqualsToken || + currentToken === SyntaxKind.AsteriskToken || + currentToken === SyntaxKind.OpenBraceToken || + currentToken === SyntaxKind.DefaultKeyword || + currentToken === SyntaxKind.AsKeyword || + currentToken === SyntaxKind.AtToken ) { return true; } @@ -7249,7 +10454,10 @@ namespace Parser { return true; case SyntaxKind.ImportKeyword: - return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot); + return ( + isStartOfDeclaration() || + lookAhead(nextTokenIsOpenParenOrLessThanOrDot) + ); case SyntaxKind.ConstKeyword: case SyntaxKind.ExportKeyword: @@ -7273,7 +10481,10 @@ namespace Parser { case SyntaxKind.ReadonlyKeyword: // When these don't start a declaration, they may be the start of a class member if an identifier // immediately follows. Otherwise they're an identifier in an expression statement. - return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + return ( + isStartOfDeclaration() || + !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) + ); default: return isStartOfExpression(); @@ -7282,7 +10493,11 @@ namespace Parser { function nextTokenIsBindingIdentifierOrStartOfDestructuring() { nextToken(); - return isBindingIdentifier() || token() === SyntaxKind.OpenBraceToken || token() === SyntaxKind.OpenBracketToken; + return ( + isBindingIdentifier() || + token() === SyntaxKind.OpenBraceToken || + token() === SyntaxKind.OpenBracketToken + ); } function isLetDeclaration() { @@ -7292,29 +10507,44 @@ namespace Parser { } function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf() { - return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(/*disallowOf*/ true); + return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine( + /*disallowOf*/ true, + ); } - function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf?: boolean) { + function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine( + disallowOf?: boolean, + ) { nextToken(); if (disallowOf && token() === SyntaxKind.OfKeyword) return false; - return (isBindingIdentifier() || token() === SyntaxKind.OpenBraceToken) && !scanner.hasPrecedingLineBreak(); + return ( + (isBindingIdentifier() || token() === SyntaxKind.OpenBraceToken) && + !scanner.hasPrecedingLineBreak() + ); } function isUsingDeclaration() { // 'using' always starts a lexical declaration if followed by an identifier. We also eagerly parse // |ObjectBindingPattern| so that we can report a grammar error during check. We don't parse out // |ArrayBindingPattern| since it potentially conflicts with element access (i.e., `using[x]`). - return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine); + return lookAhead( + nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine, + ); } function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf() { - return nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine(/*disallowOf*/ true); + return nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine( + /*disallowOf*/ true, + ); } - function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine(disallowOf?: boolean) { + function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine( + disallowOf?: boolean, + ) { if (nextToken() === SyntaxKind.UsingKeyword) { - return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf); + return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine( + disallowOf, + ); } return false; } @@ -7323,7 +10553,9 @@ namespace Parser { // 'await using' always starts a lexical declaration if followed by an identifier. We also eagerly parse // |ObjectBindingPattern| so that we can report a grammar error during check. We don't parse out // |ArrayBindingPattern| since it potentially conflicts with element access (i.e., `await using[x]`). - return lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine); + return lookAhead( + nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine, + ); } function parseStatement(): Statement { @@ -7333,26 +10565,50 @@ namespace Parser { case SyntaxKind.OpenBraceToken: return parseBlock(/*ignoreMissingOpenBrace*/ false); case SyntaxKind.VarKeyword: - return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); + return parseVariableStatement( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ undefined, + ); case SyntaxKind.LetKeyword: if (isLetDeclaration()) { - return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); + return parseVariableStatement( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ undefined, + ); } break; case SyntaxKind.AwaitKeyword: if (isAwaitUsingDeclaration()) { - return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); + return parseVariableStatement( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ undefined, + ); } break; case SyntaxKind.UsingKeyword: if (isUsingDeclaration()) { - return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); + return parseVariableStatement( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ undefined, + ); } break; case SyntaxKind.FunctionKeyword: - return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); + return parseFunctionDeclaration( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ undefined, + ); case SyntaxKind.ClassKeyword: - return parseClassDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); + return parseClassDeclaration( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ undefined, + ); case SyntaxKind.IfKeyword: return parseIfStatement(); case SyntaxKind.DoKeyword: @@ -7362,7 +10618,9 @@ namespace Parser { case SyntaxKind.ForKeyword: return parseForOrForInOrForOfStatement(); case SyntaxKind.ContinueKeyword: - return parseBreakOrContinueStatement(SyntaxKind.ContinueStatement); + return parseBreakOrContinueStatement( + SyntaxKind.ContinueStatement, + ); case SyntaxKind.BreakKeyword: return parseBreakOrContinueStatement(SyntaxKind.BreakStatement); case SyntaxKind.ReturnKeyword: @@ -7448,7 +10706,11 @@ namespace Parser { }); } - function parseDeclarationWorker(pos: number, hasJSDoc: boolean, modifiersIn: NodeArray | undefined): Statement { + function parseDeclarationWorker( + pos: number, + hasJSDoc: boolean, + modifiersIn: NodeArray | undefined, + ): Statement { switch (token()) { case SyntaxKind.VarKeyword: case SyntaxKind.LetKeyword: @@ -7471,23 +10733,43 @@ namespace Parser { case SyntaxKind.NamespaceKeyword: return parseModuleDeclaration(pos, hasJSDoc, modifiersIn); case SyntaxKind.ImportKeyword: - return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, modifiersIn); + return parseImportDeclarationOrImportEqualsDeclaration( + pos, + hasJSDoc, + modifiersIn, + ); case SyntaxKind.ExportKeyword: nextToken(); switch (token()) { case SyntaxKind.DefaultKeyword: case SyntaxKind.EqualsToken: - return parseExportAssignment(pos, hasJSDoc, modifiersIn); + return parseExportAssignment( + pos, + hasJSDoc, + modifiersIn, + ); case SyntaxKind.AsKeyword: - return parseNamespaceExportDeclaration(pos, hasJSDoc, modifiersIn); + return parseNamespaceExportDeclaration( + pos, + hasJSDoc, + modifiersIn, + ); default: - return parseExportDeclaration(pos, hasJSDoc, modifiersIn); + return parseExportDeclaration( + pos, + hasJSDoc, + modifiersIn, + ); } default: if (modifiersIn) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - const missing = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); + const missing = createMissingNode( + SyntaxKind.MissingDeclaration, + /*reportAtCurrentPosition*/ true, + Diagnostics.Declaration_expected, + ); setTextRangePos(missing, pos); (missing as Mutable).modifiers = modifiersIn; return missing; @@ -7501,10 +10783,16 @@ namespace Parser { } function nextTokenIsIdentifierOrStringLiteralOnSameLine() { nextToken(); - return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === SyntaxKind.StringLiteral); + return ( + !scanner.hasPrecedingLineBreak() && + (isIdentifier() || token() === SyntaxKind.StringLiteral) + ); } - function parseFunctionBlockOrSemicolon(flags: SignatureFlags, diagnosticMessage?: DiagnosticMessage): Block | undefined { + function parseFunctionBlockOrSemicolon( + flags: SignatureFlags, + diagnosticMessage?: DiagnosticMessage, + ): Block | undefined { if (token() !== SyntaxKind.OpenBraceToken) { if (flags & SignatureFlags.Type) { parseTypeMemberSemicolon(); @@ -7528,7 +10816,15 @@ namespace Parser { const dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken); const name = parseIdentifierOrPattern(); const initializer = parseInitializer(); - return finishNode(factory.createBindingElement(dotDotDotToken, /*propertyName*/ undefined, name, initializer), pos); + return finishNode( + factory.createBindingElement( + dotDotDotToken, + /*propertyName*/ undefined, + name, + initializer, + ), + pos, + ); } function parseObjectBindingElement(): BindingElement { @@ -7546,13 +10842,26 @@ namespace Parser { name = parseIdentifierOrPattern(); } const initializer = parseInitializer(); - return finishNode(factory.createBindingElement(dotDotDotToken, propertyName, name, initializer), pos); + return finishNode( + factory.createBindingElement( + dotDotDotToken, + propertyName, + name, + initializer, + ), + pos, + ); } function parseObjectBindingPattern(): ObjectBindingPattern { const pos = getNodePos(); parseExpected(SyntaxKind.OpenBraceToken); - const elements = allowInAnd(() => parseDelimitedList(ParsingContext.ObjectBindingElements, parseObjectBindingElement)); + const elements = allowInAnd(() => + parseDelimitedList( + ParsingContext.ObjectBindingElements, + parseObjectBindingElement, + ) + ); parseExpected(SyntaxKind.CloseBraceToken); return finishNode(factory.createObjectBindingPattern(elements), pos); } @@ -7560,19 +10869,28 @@ namespace Parser { function parseArrayBindingPattern(): ArrayBindingPattern { const pos = getNodePos(); parseExpected(SyntaxKind.OpenBracketToken); - const elements = allowInAnd(() => parseDelimitedList(ParsingContext.ArrayBindingElements, parseArrayBindingElement)); + const elements = allowInAnd(() => + parseDelimitedList( + ParsingContext.ArrayBindingElements, + parseArrayBindingElement, + ) + ); parseExpected(SyntaxKind.CloseBracketToken); return finishNode(factory.createArrayBindingPattern(elements), pos); } function isBindingIdentifierOrPrivateIdentifierOrPattern() { - return token() === SyntaxKind.OpenBraceToken - || token() === SyntaxKind.OpenBracketToken - || token() === SyntaxKind.PrivateIdentifier - || isBindingIdentifier(); + return ( + token() === SyntaxKind.OpenBraceToken || + token() === SyntaxKind.OpenBracketToken || + token() === SyntaxKind.PrivateIdentifier || + isBindingIdentifier() + ); } - function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage?: DiagnosticMessage): Identifier | BindingPattern { + function parseIdentifierOrPattern( + privateIdentifierDiagnosticMessage?: DiagnosticMessage, + ): Identifier | BindingPattern { if (token() === SyntaxKind.OpenBracketToken) { return parseArrayBindingPattern(); } @@ -7586,24 +10904,39 @@ namespace Parser { return parseVariableDeclaration(/*allowExclamation*/ true); } - function parseVariableDeclaration(allowExclamation?: boolean): VariableDeclaration { + function parseVariableDeclaration( + allowExclamation?: boolean, + ): VariableDeclaration { const pos = getNodePos(); const hasJSDoc = hasPrecedingJSDocComment(); - const name = parseIdentifierOrPattern(Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations); + const name = parseIdentifierOrPattern( + Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations, + ); let exclamationToken: ExclamationToken | undefined; if ( - allowExclamation && name.kind === SyntaxKind.Identifier && - token() === SyntaxKind.ExclamationToken && !scanner.hasPrecedingLineBreak() + allowExclamation && + name.kind === SyntaxKind.Identifier && + token() === SyntaxKind.ExclamationToken && + !scanner.hasPrecedingLineBreak() ) { exclamationToken = parseTokenNode>(); } const type = parseTypeAnnotation(); - const initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer(); - const node = factoryCreateVariableDeclaration(name, exclamationToken, type, initializer); + const initializer = isInOrOfKeyword(token()) + ? undefined + : parseInitializer(); + const node = factoryCreateVariableDeclaration( + name, + exclamationToken, + type, + initializer, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseVariableDeclarationList(inForStatementInitializer: boolean): VariableDeclarationList { + function parseVariableDeclarationList( + inForStatementInitializer: boolean, + ): VariableDeclarationList { const pos = getNodePos(); let flags: NodeFlags = 0; @@ -7640,7 +10973,10 @@ namespace Parser { // this context. // The checker will then give an error that there is an empty declaration list. let declarations: readonly VariableDeclaration[]; - if (token() === SyntaxKind.OfKeyword && lookAhead(canFollowContextualOfKeyword)) { + if ( + token() === SyntaxKind.OfKeyword && + lookAhead(canFollowContextualOfKeyword) + ) { declarations = createMissingList(); } else { @@ -7649,42 +10985,77 @@ namespace Parser { declarations = parseDelimitedList( ParsingContext.VariableDeclarations, - inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation, + inForStatementInitializer + ? parseVariableDeclaration + : parseVariableDeclarationAllowExclamation, ); setDisallowInContext(savedDisallowIn); } - return finishNode(factoryCreateVariableDeclarationList(declarations, flags), pos); + return finishNode( + factoryCreateVariableDeclarationList(declarations, flags), + pos, + ); } function canFollowContextualOfKeyword(): boolean { - return nextTokenIsIdentifier() && nextToken() === SyntaxKind.CloseParenToken; + return ( + nextTokenIsIdentifier() && + nextToken() === SyntaxKind.CloseParenToken + ); } - function parseVariableStatement(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): VariableStatement { - const declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); + function parseVariableStatement( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): VariableStatement { + const declarationList = parseVariableDeclarationList( + /*inForStatementInitializer*/ false, + ); parseSemicolon(); const node = factoryCreateVariableStatement(modifiers, declarationList); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseFunctionDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): FunctionDeclaration { + function parseFunctionDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): FunctionDeclaration { const savedAwaitContext = inAwaitContext(); const modifierFlags = modifiersToFlags(modifiers); parseExpected(SyntaxKind.FunctionKeyword); const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); // We don't parse the name here in await context, instead we will report a grammar error in the checker. - const name = modifierFlags & ModifierFlags.Default ? parseOptionalBindingIdentifier() : parseBindingIdentifier(); - const isGenerator = asteriskToken ? SignatureFlags.Yield : SignatureFlags.None; - const isAsync = modifierFlags & ModifierFlags.Async ? SignatureFlags.Await : SignatureFlags.None; + const name = modifierFlags & ModifierFlags.Default + ? parseOptionalBindingIdentifier() + : parseBindingIdentifier(); + const isGenerator = asteriskToken + ? SignatureFlags.Yield + : SignatureFlags.None; + const isAsync = modifierFlags & ModifierFlags.Async + ? SignatureFlags.Await + : SignatureFlags.None; const typeParameters = parseTypeParameters(); if (modifierFlags & ModifierFlags.Export) setAwaitContext(/*value*/ true); const parameters = parseParameters(isGenerator | isAsync); const type = parseReturnType(SyntaxKind.ColonToken, /*isType*/ false); - const body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, Diagnostics.or_expected); + const body = parseFunctionBlockOrSemicolon( + isGenerator | isAsync, + Diagnostics.or_expected, + ); setAwaitContext(savedAwaitContext); - const node = factory.createFunctionDeclaration(modifiers, asteriskToken, name, typeParameters, parameters, type, body); + const node = factory.createFunctionDeclaration( + modifiers, + asteriskToken, + name, + typeParameters, + parameters, + type, + body, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -7692,22 +11063,41 @@ namespace Parser { if (token() === SyntaxKind.ConstructorKeyword) { return parseExpected(SyntaxKind.ConstructorKeyword); } - if (token() === SyntaxKind.StringLiteral && lookAhead(nextToken) === SyntaxKind.OpenParenToken) { + if ( + token() === SyntaxKind.StringLiteral && + lookAhead(nextToken) === SyntaxKind.OpenParenToken + ) { return tryParse(() => { const literalNode = parseLiteralNode(); - return literalNode.text === "constructor" ? literalNode : undefined; + return literalNode.text === "constructor" + ? literalNode + : undefined; }); } } - function tryParseConstructorDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): ConstructorDeclaration | undefined { + function tryParseConstructorDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): ConstructorDeclaration | undefined { return tryParse(() => { if (parseConstructorName()) { const typeParameters = parseTypeParameters(); const parameters = parseParameters(SignatureFlags.None); - const type = parseReturnType(SyntaxKind.ColonToken, /*isType*/ false); - const body = parseFunctionBlockOrSemicolon(SignatureFlags.None, Diagnostics.or_expected); - const node = factory.createConstructorDeclaration(modifiers, parameters, body); + const type = parseReturnType( + SyntaxKind.ColonToken, + /*isType*/ false, + ); + const body = parseFunctionBlockOrSemicolon( + SignatureFlags.None, + Diagnostics.or_expected, + ); + const node = factory.createConstructorDeclaration( + modifiers, + parameters, + body, + ); // Attach invalid nodes if they exist so that we can report them in the grammar checker. (node as Mutable).typeParameters = typeParameters; @@ -7727,12 +11117,19 @@ namespace Parser { exclamationToken: ExclamationToken | undefined, diagnosticMessage?: DiagnosticMessage, ): MethodDeclaration { - const isGenerator = asteriskToken ? SignatureFlags.Yield : SignatureFlags.None; - const isAsync = some(modifiers, isAsyncModifier) ? SignatureFlags.Await : SignatureFlags.None; + const isGenerator = asteriskToken + ? SignatureFlags.Yield + : SignatureFlags.None; + const isAsync = some(modifiers, isAsyncModifier) + ? SignatureFlags.Await + : SignatureFlags.None; const typeParameters = parseTypeParameters(); const parameters = parseParameters(isGenerator | isAsync); const type = parseReturnType(SyntaxKind.ColonToken, /*isType*/ false); - const body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage); + const body = parseFunctionBlockOrSemicolon( + isGenerator | isAsync, + diagnosticMessage, + ); const node = factory.createMethodDeclaration( modifiers, asteriskToken, @@ -7756,9 +11153,16 @@ namespace Parser { name: PropertyName, questionToken: QuestionToken | undefined, ): PropertyDeclaration { - const exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(SyntaxKind.ExclamationToken) : undefined; + const exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() + ? parseOptionalToken(SyntaxKind.ExclamationToken) + : undefined; const type = parseTypeAnnotation(); - const initializer = doOutsideOfContext(NodeFlags.YieldContext | NodeFlags.AwaitContext | NodeFlags.DisallowInContext, parseInitializer); + const initializer = doOutsideOfContext( + NodeFlags.YieldContext | + NodeFlags.AwaitContext | + NodeFlags.DisallowInContext, + parseInitializer, + ); parseSemicolonAfterPropertyName(name, type, initializer); const node = factory.createPropertyDeclaration( modifiers, @@ -7780,21 +11184,57 @@ namespace Parser { // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); - if (asteriskToken || token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken) { - return parseMethodDeclaration(pos, hasJSDoc, modifiers, asteriskToken, name, questionToken, /*exclamationToken*/ undefined, Diagnostics.or_expected); + if ( + asteriskToken || + token() === SyntaxKind.OpenParenToken || + token() === SyntaxKind.LessThanToken + ) { + return parseMethodDeclaration( + pos, + hasJSDoc, + modifiers, + asteriskToken, + name, + questionToken, + /*exclamationToken*/ undefined, + Diagnostics.or_expected, + ); } - return parsePropertyDeclaration(pos, hasJSDoc, modifiers, name, questionToken); + return parsePropertyDeclaration( + pos, + hasJSDoc, + modifiers, + name, + questionToken, + ); } - function parseAccessorDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined, kind: AccessorDeclaration["kind"], flags: SignatureFlags): AccessorDeclaration { + function parseAccessorDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + kind: AccessorDeclaration["kind"], + flags: SignatureFlags, + ): AccessorDeclaration { const name = parsePropertyName(); const typeParameters = parseTypeParameters(); const parameters = parseParameters(SignatureFlags.None); const type = parseReturnType(SyntaxKind.ColonToken, /*isType*/ false); const body = parseFunctionBlockOrSemicolon(flags); const node = kind === SyntaxKind.GetAccessor - ? factory.createGetAccessorDeclaration(modifiers, name, parameters, type, body) - : factory.createSetAccessorDeclaration(modifiers, name, parameters, body); + ? factory.createGetAccessorDeclaration( + modifiers, + name, + parameters, + type, + body, + ) + : factory.createSetAccessorDeclaration( + modifiers, + name, + parameters, + body, + ); // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors (node as Mutable).typeParameters = typeParameters; if (isSetAccessorDeclaration(node)) (node as Mutable).type = type; @@ -7843,7 +11283,11 @@ namespace Parser { // If we were able to get any potential identifier... if (idToken !== undefined) { // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse. - if (!isKeyword(idToken) || idToken === SyntaxKind.SetKeyword || idToken === SyntaxKind.GetKeyword) { + if ( + !isKeyword(idToken) || + idToken === SyntaxKind.SetKeyword || + idToken === SyntaxKind.GetKeyword + ) { return true; } @@ -7870,10 +11314,17 @@ namespace Parser { return false; } - function parseClassStaticBlockDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): ClassStaticBlockDeclaration { + function parseClassStaticBlockDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): ClassStaticBlockDeclaration { parseExpectedToken(SyntaxKind.StaticKeyword); const body = parseClassStaticBlockBody(); - const node = withJSDoc(finishNode(factory.createClassStaticBlockDeclaration(body), pos), hasJSDoc); + const node = withJSDoc( + finishNode(factory.createClassStaticBlockDeclaration(body), pos), + hasJSDoc, + ); (node as Mutable).modifiers = modifiers; return node; } @@ -7898,9 +11349,15 @@ namespace Parser { // `@await` is is disallowed in an [Await] context, but can cause parsing to go off the rails // This simply parses the missing identifier and moves on. const pos = getNodePos(); - const awaitExpression = parseIdentifier(Diagnostics.Expression_expected); + const awaitExpression = parseIdentifier( + Diagnostics.Expression_expected, + ); nextToken(); - const memberExpression = parseMemberExpressionRest(pos, awaitExpression, /*allowOptionalChain*/ true); + const memberExpression = parseMemberExpressionRest( + pos, + awaitExpression, + /*allowOptionalChain*/ true, + ); return parseCallExpressionRest(pos, memberExpression); } return parseLeftHandSideExpressionOrHigher(); @@ -7915,7 +11372,11 @@ namespace Parser { return finishNode(factory.createDecorator(expression), pos); } - function tryParseModifier(hasSeenStaticModifier: boolean, permitConstAsModifier?: boolean, stopOnStartOfClassStaticBlock?: boolean): Modifier | undefined { + function tryParseModifier( + hasSeenStaticModifier: boolean, + permitConstAsModifier?: boolean, + stopOnStartOfClassStaticBlock?: boolean, + ): Modifier | undefined { const pos = getNodePos(); const kind = token(); @@ -7926,10 +11387,17 @@ namespace Parser { return undefined; } } - else if (stopOnStartOfClassStaticBlock && token() === SyntaxKind.StaticKeyword && lookAhead(nextTokenIsOpenBrace)) { + else if ( + stopOnStartOfClassStaticBlock && + token() === SyntaxKind.StaticKeyword && + lookAhead(nextTokenIsOpenBrace) + ) { return undefined; } - else if (hasSeenStaticModifier && token() === SyntaxKind.StaticKeyword) { + else if ( + hasSeenStaticModifier && + token() === SyntaxKind.StaticKeyword + ) { return undefined; } else { @@ -7948,12 +11416,28 @@ namespace Parser { * * In such situations, 'permitConstAsModifier' should be set to true. */ - function parseModifiers(allowDecorators: false, permitConstAsModifier?: boolean, stopOnStartOfClassStaticBlock?: boolean): NodeArray | undefined; - function parseModifiers(allowDecorators: true, permitConstAsModifier?: boolean, stopOnStartOfClassStaticBlock?: boolean): NodeArray | undefined; - function parseModifiers(allowDecorators: boolean, permitConstAsModifier?: boolean, stopOnStartOfClassStaticBlock?: boolean): NodeArray | undefined { + function parseModifiers( + allowDecorators: false, + permitConstAsModifier?: boolean, + stopOnStartOfClassStaticBlock?: boolean, + ): NodeArray | undefined; + function parseModifiers( + allowDecorators: true, + permitConstAsModifier?: boolean, + stopOnStartOfClassStaticBlock?: boolean, + ): NodeArray | undefined; + function parseModifiers( + allowDecorators: boolean, + permitConstAsModifier?: boolean, + stopOnStartOfClassStaticBlock?: boolean, + ): NodeArray | undefined { const pos = getNodePos(); let list: ModifierLike[] | undefined; - let decorator, modifier, hasSeenStaticModifier = false, hasLeadingModifier = false, hasTrailingDecorator = false; + let decorator, + modifier, + hasSeenStaticModifier = false, + hasLeadingModifier = false, + hasTrailingDecorator = false; // Decorators should be contiguous in a list of modifiers but can potentially appear in two places (i.e., `[...leadingDecorators, ...leadingModifiers, ...trailingDecorators, ...trailingModifiers]`). // The leading modifiers *should* only contain `export` and `default` when trailingDecorators are present, but we'll handle errors for any other leading modifiers in the checker. @@ -7961,21 +11445,31 @@ namespace Parser { // parse leading decorators if (allowDecorators && token() === SyntaxKind.AtToken) { - while (decorator = tryParseDecorator()) { + while ((decorator = tryParseDecorator())) { list = append(list, decorator); } } // parse leading modifiers - while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) { + while ( + (modifier = tryParseModifier( + hasSeenStaticModifier, + permitConstAsModifier, + stopOnStartOfClassStaticBlock, + )) + ) { if (modifier.kind === SyntaxKind.StaticKeyword) hasSeenStaticModifier = true; list = append(list, modifier); hasLeadingModifier = true; } // parse trailing decorators, but only if we parsed any leading modifiers - if (hasLeadingModifier && allowDecorators && token() === SyntaxKind.AtToken) { - while (decorator = tryParseDecorator()) { + if ( + hasLeadingModifier && + allowDecorators && + token() === SyntaxKind.AtToken + ) { + while ((decorator = tryParseDecorator())) { list = append(list, decorator); hasTrailingDecorator = true; } @@ -7983,7 +11477,13 @@ namespace Parser { // parse trailing modifiers, but only if we parsed any trailing decorators if (hasTrailingDecorator) { - while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) { + while ( + (modifier = tryParseModifier( + hasSeenStaticModifier, + permitConstAsModifier, + stopOnStartOfClassStaticBlock, + )) + ) { if (modifier.kind === SyntaxKind.StaticKeyword) hasSeenStaticModifier = true; list = append(list, modifier); } @@ -7997,7 +11497,10 @@ namespace Parser { if (token() === SyntaxKind.AsyncKeyword) { const pos = getNodePos(); nextToken(); - const modifier = finishNode(factoryCreateToken(SyntaxKind.AsyncKeyword), pos); + const modifier = finishNode( + factoryCreateToken(SyntaxKind.AsyncKeyword), + pos, + ); modifiers = createNodeArray([modifier], pos); } return modifiers; @@ -8008,24 +11511,53 @@ namespace Parser { const hasJSDoc = hasPrecedingJSDocComment(); if (token() === SyntaxKind.SemicolonToken) { nextToken(); - return withJSDoc(finishNode(factory.createSemicolonClassElement(), pos), hasJSDoc); + return withJSDoc( + finishNode(factory.createSemicolonClassElement(), pos), + hasJSDoc, + ); } - const modifiers = parseModifiers(/*allowDecorators*/ true, /*permitConstAsModifier*/ true, /*stopOnStartOfClassStaticBlock*/ true); - if (token() === SyntaxKind.StaticKeyword && lookAhead(nextTokenIsOpenBrace)) { + const modifiers = parseModifiers( + /*allowDecorators*/ true, + /*permitConstAsModifier*/ true, + /*stopOnStartOfClassStaticBlock*/ true, + ); + if ( + token() === SyntaxKind.StaticKeyword && + lookAhead(nextTokenIsOpenBrace) + ) { return parseClassStaticBlockDeclaration(pos, hasJSDoc, modifiers); } if (parseContextualModifier(SyntaxKind.GetKeyword)) { - return parseAccessorDeclaration(pos, hasJSDoc, modifiers, SyntaxKind.GetAccessor, SignatureFlags.None); + return parseAccessorDeclaration( + pos, + hasJSDoc, + modifiers, + SyntaxKind.GetAccessor, + SignatureFlags.None, + ); } if (parseContextualModifier(SyntaxKind.SetKeyword)) { - return parseAccessorDeclaration(pos, hasJSDoc, modifiers, SyntaxKind.SetAccessor, SignatureFlags.None); + return parseAccessorDeclaration( + pos, + hasJSDoc, + modifiers, + SyntaxKind.SetAccessor, + SignatureFlags.None, + ); } - if (token() === SyntaxKind.ConstructorKeyword || token() === SyntaxKind.StringLiteral) { - const constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, modifiers); + if ( + token() === SyntaxKind.ConstructorKeyword || + token() === SyntaxKind.StringLiteral + ) { + const constructorDeclaration = tryParseConstructorDeclaration( + pos, + hasJSDoc, + modifiers, + ); if (constructorDeclaration) { return constructorDeclaration; } @@ -8052,18 +11584,34 @@ namespace Parser { return doInsideOfContext(NodeFlags.Ambient, () => parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers)); } else { - return parsePropertyOrMethodDeclaration(pos, hasJSDoc, modifiers); + return parsePropertyOrMethodDeclaration( + pos, + hasJSDoc, + modifiers, + ); } } if (modifiers) { // treat this as a property declaration with a missing name. - const name = createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); - return parsePropertyDeclaration(pos, hasJSDoc, modifiers, name, /*questionToken*/ undefined); + const name = createMissingNode( + SyntaxKind.Identifier, + /*reportAtCurrentPosition*/ true, + Diagnostics.Declaration_expected, + ); + return parsePropertyDeclaration( + pos, + hasJSDoc, + modifiers, + name, + /*questionToken*/ undefined, + ); } // 'isClassMemberStart' should have hinted not to attempt parsing. - return Debug.fail("Should not have attempted to parse class member declaration."); + return Debug.fail( + "Should not have attempted to parse class member declaration.", + ); } function parseDecoratedExpression(): PrimaryExpression { @@ -8071,24 +11619,52 @@ namespace Parser { const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers(/*allowDecorators*/ true); if (token() === SyntaxKind.ClassKeyword) { - return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, SyntaxKind.ClassExpression) as ClassExpression; + return parseClassDeclarationOrExpression( + pos, + hasJSDoc, + modifiers, + SyntaxKind.ClassExpression, + ) as ClassExpression; } - const missing = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Expression_expected); + const missing = createMissingNode( + SyntaxKind.MissingDeclaration, + /*reportAtCurrentPosition*/ true, + Diagnostics.Expression_expected, + ); setTextRangePos(missing, pos); (missing as Mutable).modifiers = modifiers; return missing; } function parseClassExpression(): ClassExpression { - return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined, SyntaxKind.ClassExpression) as ClassExpression; + return parseClassDeclarationOrExpression( + getNodePos(), + hasPrecedingJSDocComment(), + /*modifiers*/ undefined, + SyntaxKind.ClassExpression, + ) as ClassExpression; } - function parseClassDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): ClassDeclaration { - return parseClassDeclarationOrExpression(pos, hasJSDoc, modifiers, SyntaxKind.ClassDeclaration) as ClassDeclaration; + function parseClassDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): ClassDeclaration { + return parseClassDeclarationOrExpression( + pos, + hasJSDoc, + modifiers, + SyntaxKind.ClassDeclaration, + ) as ClassDeclaration; } - function parseClassDeclarationOrExpression(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined, kind: ClassLikeDeclaration["kind"]): ClassLikeDeclaration { + function parseClassDeclarationOrExpression( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + kind: ClassLikeDeclaration["kind"], + ): ClassLikeDeclaration { const savedAwaitContext = inAwaitContext(); parseExpected(SyntaxKind.ClassKeyword); @@ -8110,8 +11686,20 @@ namespace Parser { } setAwaitContext(savedAwaitContext); const node = kind === SyntaxKind.ClassDeclaration - ? factory.createClassDeclaration(modifiers, name, typeParameters, heritageClauses, members) - : factory.createClassExpression(modifiers, name, typeParameters, heritageClauses, members); + ? factory.createClassDeclaration( + modifiers, + name, + typeParameters, + heritageClauses, + members, + ) + : factory.createClassExpression( + modifiers, + name, + typeParameters, + heritageClauses, + members, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -8127,7 +11715,10 @@ namespace Parser { } function isImplementsClause() { - return token() === SyntaxKind.ImplementsKeyword && lookAhead(nextTokenIsIdentifierOrKeyword); + return ( + token() === SyntaxKind.ImplementsKeyword && + lookAhead(nextTokenIsIdentifierOrKeyword) + ); } function parseHeritageClauses(): NodeArray | undefined { @@ -8135,7 +11726,10 @@ namespace Parser { // ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt } if (isHeritageClause()) { - return parseList(ParsingContext.HeritageClauses, parseHeritageClause); + return parseList( + ParsingContext.HeritageClauses, + parseHeritageClause, + ); } return undefined; @@ -8144,9 +11738,15 @@ namespace Parser { function parseHeritageClause(): HeritageClause { const pos = getNodePos(); const tok = token(); - Debug.assert(tok === SyntaxKind.ExtendsKeyword || tok === SyntaxKind.ImplementsKeyword); // isListElement() should ensure this. + Debug.assert( + tok === SyntaxKind.ExtendsKeyword || + tok === SyntaxKind.ImplementsKeyword, + ); // isListElement() should ensure this. nextToken(); - const types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseExpressionWithTypeArguments); + const types = parseDelimitedList( + ParsingContext.HeritageClauseElement, + parseExpressionWithTypeArguments, + ); return finishNode(factory.createHeritageClause(tok, types), pos); } @@ -8154,36 +11754,65 @@ namespace Parser { const pos = getNodePos(); const expression = parseLeftHandSideExpressionOrHigher(); if (expression.kind === SyntaxKind.ExpressionWithTypeArguments) { - return expression as ExpressionWithTypeArguments; + return expression; } const typeArguments = tryParseTypeArguments(); - return finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos); + return finishNode( + factory.createExpressionWithTypeArguments( + expression, + typeArguments, + ), + pos, + ); } function tryParseTypeArguments(): NodeArray | undefined { - return token() === SyntaxKind.LessThanToken ? - parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken) : undefined; + return token() === SyntaxKind.LessThanToken + ? parseBracketedList( + ParsingContext.TypeArguments, + parseType, + SyntaxKind.LessThanToken, + SyntaxKind.GreaterThanToken, + ) + : undefined; } function isHeritageClause(): boolean { - return token() === SyntaxKind.ExtendsKeyword || token() === SyntaxKind.ImplementsKeyword; + return ( + token() === SyntaxKind.ExtendsKeyword || + token() === SyntaxKind.ImplementsKeyword + ); } function parseClassMembers(): NodeArray { return parseList(ParsingContext.ClassMembers, parseClassElement); } - function parseInterfaceDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): InterfaceDeclaration { + function parseInterfaceDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): InterfaceDeclaration { parseExpected(SyntaxKind.InterfaceKeyword); const name = parseIdentifier(); const typeParameters = parseTypeParameters(); const heritageClauses = parseHeritageClauses(); const members = parseObjectTypeMembers(); - const node = factory.createInterfaceDeclaration(modifiers, name, typeParameters, heritageClauses, members); + const node = factory.createInterfaceDeclaration( + modifiers, + name, + typeParameters, + heritageClauses, + members, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseTypeAliasDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): TypeAliasDeclaration { + function parseTypeAliasDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): TypeAliasDeclaration { parseExpected(SyntaxKind.TypeKeyword); if (scanner.hasPrecedingLineBreak()) { parseErrorAtCurrentToken(Diagnostics.Line_break_not_permitted_here); @@ -8191,9 +11820,16 @@ namespace Parser { const name = parseIdentifier(); const typeParameters = parseTypeParameters(); parseExpected(SyntaxKind.EqualsToken); - const type = token() === SyntaxKind.IntrinsicKeyword && tryParse(parseKeywordAndNoDot) || parseType(); + const type = (token() === SyntaxKind.IntrinsicKeyword && + tryParse(parseKeywordAndNoDot)) || + parseType(); parseSemicolon(); - const node = factory.createTypeAliasDeclaration(modifiers, name, typeParameters, type); + const node = factory.createTypeAliasDeclaration( + modifiers, + name, + typeParameters, + type, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } @@ -8206,10 +11842,17 @@ namespace Parser { const hasJSDoc = hasPrecedingJSDocComment(); const name = parsePropertyName(); const initializer = allowInAnd(parseInitializer); - return withJSDoc(finishNode(factory.createEnumMember(name, initializer), pos), hasJSDoc); + return withJSDoc( + finishNode(factory.createEnumMember(name, initializer), pos), + hasJSDoc, + ); } - function parseEnumDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): EnumDeclaration { + function parseEnumDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): EnumDeclaration { parseExpected(SyntaxKind.EnumKeyword); const name = parseIdentifier(); let members; @@ -8228,7 +11871,10 @@ namespace Parser { const pos = getNodePos(); let statements; if (parseExpected(SyntaxKind.OpenBraceToken)) { - statements = parseList(ParsingContext.BlockStatements, parseStatement); + statements = parseList( + ParsingContext.BlockStatements, + parseStatement, + ); parseExpected(SyntaxKind.CloseBraceToken); } else { @@ -8237,19 +11883,40 @@ namespace Parser { return finishNode(factory.createModuleBlock(statements), pos); } - function parseModuleOrNamespaceDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined, flags: NodeFlags): ModuleDeclaration { + function parseModuleOrNamespaceDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + flags: NodeFlags, + ): ModuleDeclaration { // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. const namespaceFlag = flags & NodeFlags.Namespace; - const name = flags & NodeFlags.NestedNamespace ? parseIdentifierName() : parseIdentifier(); + const name = flags & NodeFlags.NestedNamespace + ? parseIdentifierName() + : parseIdentifier(); const body = parseOptional(SyntaxKind.DotToken) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*modifiers*/ undefined, NodeFlags.NestedNamespace | namespaceFlag) as NamespaceDeclaration + ? (parseModuleOrNamespaceDeclaration( + getNodePos(), + /*hasJSDoc*/ false, + /*modifiers*/ undefined, + NodeFlags.NestedNamespace | namespaceFlag, + ) as NamespaceDeclaration) : parseModuleBlock(); - const node = factory.createModuleDeclaration(modifiers, name, body, flags); + const node = factory.createModuleDeclaration( + modifiers, + name, + body, + flags, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseAmbientExternalModuleDeclaration(pos: number, hasJSDoc: boolean, modifiersIn: NodeArray | undefined): ModuleDeclaration { + function parseAmbientExternalModuleDeclaration( + pos: number, + hasJSDoc: boolean, + modifiersIn: NodeArray | undefined, + ): ModuleDeclaration { let flags: NodeFlags = 0; let name; if (token() === SyntaxKind.GlobalKeyword) { @@ -8268,15 +11935,28 @@ namespace Parser { else { parseSemicolon(); } - const node = factory.createModuleDeclaration(modifiersIn, name, body, flags); + const node = factory.createModuleDeclaration( + modifiersIn, + name, + body, + flags, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseModuleDeclaration(pos: number, hasJSDoc: boolean, modifiersIn: NodeArray | undefined): ModuleDeclaration { + function parseModuleDeclaration( + pos: number, + hasJSDoc: boolean, + modifiersIn: NodeArray | undefined, + ): ModuleDeclaration { let flags: NodeFlags = 0; if (token() === SyntaxKind.GlobalKeyword) { // global augmentation - return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn); + return parseAmbientExternalModuleDeclaration( + pos, + hasJSDoc, + modifiersIn, + ); } else if (parseOptional(SyntaxKind.NamespaceKeyword)) { flags |= NodeFlags.Namespace; @@ -8284,15 +11964,26 @@ namespace Parser { else { parseExpected(SyntaxKind.ModuleKeyword); if (token() === SyntaxKind.StringLiteral) { - return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, modifiersIn); + return parseAmbientExternalModuleDeclaration( + pos, + hasJSDoc, + modifiersIn, + ); } } - return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, modifiersIn, flags); + return parseModuleOrNamespaceDeclaration( + pos, + hasJSDoc, + modifiersIn, + flags, + ); } function isExternalModuleReference() { - return token() === SyntaxKind.RequireKeyword && - lookAhead(nextTokenIsOpenParen); + return ( + token() === SyntaxKind.RequireKeyword && + lookAhead(nextTokenIsOpenParen) + ); } function nextTokenIsOpenParen() { @@ -8307,7 +11998,11 @@ namespace Parser { return nextToken() === SyntaxKind.SlashToken; } - function parseNamespaceExportDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): NamespaceExportDeclaration { + function parseNamespaceExportDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): NamespaceExportDeclaration { parseExpected(SyntaxKind.AsKeyword); parseExpected(SyntaxKind.NamespaceKeyword); const name = parseIdentifier(); @@ -8318,7 +12013,11 @@ namespace Parser { return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseImportDeclarationOrImportEqualsDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): ImportEqualsDeclaration | ImportDeclaration { + function parseImportDeclarationOrImportEqualsDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): ImportEqualsDeclaration | ImportDeclaration { parseExpected(SyntaxKind.ImportKeyword); const afterImportPos = scanner.getTokenFullStart(); @@ -8333,14 +12032,24 @@ namespace Parser { if ( token() !== SyntaxKind.FromKeyword && identifier?.escapedText === "type" && - (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration()) + (isIdentifier() || + tokenAfterImportDefinitelyProducesImportDeclaration()) ) { isTypeOnly = true; identifier = isIdentifier() ? parseIdentifier() : undefined; } - if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) { - return parseImportEqualsDeclaration(pos, hasJSDoc, modifiers, identifier, isTypeOnly); + if ( + identifier && + !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() + ) { + return parseImportEqualsDeclaration( + pos, + hasJSDoc, + modifiers, + identifier, + isTypeOnly, + ); } // ImportDeclaration: @@ -8352,29 +12061,49 @@ namespace Parser { token() === SyntaxKind.AsteriskToken || // import * token() === SyntaxKind.OpenBraceToken // import { ) { - importClause = parseImportClause(identifier, afterImportPos, isTypeOnly); + importClause = parseImportClause( + identifier, + afterImportPos, + isTypeOnly, + ); parseExpected(SyntaxKind.FromKeyword); } const moduleSpecifier = parseModuleSpecifier(); const currentToken = token(); let attributes: ImportAttributes | undefined; - if ((currentToken === SyntaxKind.WithKeyword || currentToken === SyntaxKind.AssertKeyword) && !scanner.hasPrecedingLineBreak()) { + if ( + (currentToken === SyntaxKind.WithKeyword || + currentToken === SyntaxKind.AssertKeyword) && + !scanner.hasPrecedingLineBreak() + ) { attributes = parseImportAttributes(currentToken); } parseSemicolon(); - const node = factory.createImportDeclaration(modifiers, importClause, moduleSpecifier, attributes); + const node = factory.createImportDeclaration( + modifiers, + importClause, + moduleSpecifier, + attributes, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } function parseImportAttribute() { const pos = getNodePos(); - const name = tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(SyntaxKind.StringLiteral) as StringLiteral; + const name = tokenIsIdentifierOrKeyword(token()) + ? parseIdentifierName() + : (parseLiteralLikeNode(SyntaxKind.StringLiteral) as StringLiteral); parseExpected(SyntaxKind.ColonToken); - const value = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); + const value = parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ); return finishNode(factory.createImportAttribute(name, value), pos); } - function parseImportAttributes(token: SyntaxKind.AssertKeyword | SyntaxKind.WithKeyword, skipKeyword?: true) { + function parseImportAttributes( + token: SyntaxKind.AssertKeyword | SyntaxKind.WithKeyword, + skipKeyword?: true, + ) { const pos = getNodePos(); if (!skipKeyword) { parseExpected(token); @@ -8382,44 +12111,95 @@ namespace Parser { const openBracePosition = scanner.getTokenStart(); if (parseExpected(SyntaxKind.OpenBraceToken)) { const multiLine = scanner.hasPrecedingLineBreak(); - const elements = parseDelimitedList(ParsingContext.ImportAttributes, parseImportAttribute, /*considerSemicolonAsDelimiter*/ true); + const elements = parseDelimitedList( + ParsingContext.ImportAttributes, + parseImportAttribute, + /*considerSemicolonAsDelimiter*/ true, + ); if (!parseExpected(SyntaxKind.CloseBraceToken)) { const lastError = lastOrUndefined(parseDiagnostics); - if (lastError && lastError.code === Diagnostics._0_expected.code) { + if ( + lastError && + lastError.code === Diagnostics._0_expected.code + ) { addRelatedInfo( lastError, - createDetachedDiagnostic(fileName, sourceText, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, "{", "}"), + createDetachedDiagnostic( + fileName, + sourceText, + openBracePosition, + 1, + Diagnostics.The_parser_expected_to_find_a_1_to_match_the_0_token_here, + "{", + "}", + ), ); } } - return finishNode(factory.createImportAttributes(elements, multiLine, token), pos); + return finishNode( + factory.createImportAttributes(elements, multiLine, token), + pos, + ); } else { - const elements = createNodeArray([], getNodePos(), /*end*/ undefined, /*hasTrailingComma*/ false); - return finishNode(factory.createImportAttributes(elements, /*multiLine*/ false, token), pos); + const elements = createNodeArray( + [], + getNodePos(), + /*end*/ undefined, + /*hasTrailingComma*/ false, + ); + return finishNode( + factory.createImportAttributes( + elements, + /*multiLine*/ false, + token, + ), + pos, + ); } } function tokenAfterImportDefinitelyProducesImportDeclaration() { - return token() === SyntaxKind.AsteriskToken || token() === SyntaxKind.OpenBraceToken; + return ( + token() === SyntaxKind.AsteriskToken || + token() === SyntaxKind.OpenBraceToken + ); } function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() { // In `import id ___`, the current token decides whether to produce // an ImportDeclaration or ImportEqualsDeclaration. - return token() === SyntaxKind.CommaToken || token() === SyntaxKind.FromKeyword; + return ( + token() === SyntaxKind.CommaToken || + token() === SyntaxKind.FromKeyword + ); } - function parseImportEqualsDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined, identifier: Identifier, isTypeOnly: boolean): ImportEqualsDeclaration { + function parseImportEqualsDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + identifier: Identifier, + isTypeOnly: boolean, + ): ImportEqualsDeclaration { parseExpected(SyntaxKind.EqualsToken); const moduleReference = parseModuleReference(); parseSemicolon(); - const node = factory.createImportEqualsDeclaration(modifiers, isTypeOnly, identifier, moduleReference); + const node = factory.createImportEqualsDeclaration( + modifiers, + isTypeOnly, + identifier, + moduleReference, + ); const finished = withJSDoc(finishNode(node, pos), hasJSDoc); return finished; } - function parseImportClause(identifier: Identifier | undefined, pos: number, isTypeOnly: boolean) { + function parseImportClause( + identifier: Identifier | undefined, + pos: number, + isTypeOnly: boolean, + ) { // ImportClause: // ImportedDefaultBinding // NameSpaceImport @@ -8430,14 +12210,16 @@ namespace Parser { // If there was no default import or if there is comma token after default import // parse namespace or named imports let namedBindings: NamespaceImport | NamedImports | undefined; - if ( - !identifier || - parseOptional(SyntaxKind.CommaToken) - ) { - namedBindings = token() === SyntaxKind.AsteriskToken ? parseNamespaceImport() : parseNamedImportsOrExports(SyntaxKind.NamedImports); + if (!identifier || parseOptional(SyntaxKind.CommaToken)) { + namedBindings = token() === SyntaxKind.AsteriskToken + ? parseNamespaceImport() + : parseNamedImportsOrExports(SyntaxKind.NamedImports); } - return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos); + return finishNode( + factory.createImportClause(isTypeOnly, identifier, namedBindings), + pos, + ); } function parseModuleReference() { @@ -8452,7 +12234,10 @@ namespace Parser { parseExpected(SyntaxKind.OpenParenToken); const expression = parseModuleSpecifier(); parseExpected(SyntaxKind.CloseParenToken); - return finishNode(factory.createExternalModuleReference(expression), pos); + return finishNode( + factory.createExternalModuleReference(expression), + pos, + ); } function parseModuleSpecifier(): Expression { @@ -8479,9 +12264,15 @@ namespace Parser { return finishNode(factory.createNamespaceImport(name), pos); } - function parseNamedImportsOrExports(kind: SyntaxKind.NamedImports): NamedImports; - function parseNamedImportsOrExports(kind: SyntaxKind.NamedExports): NamedExports; - function parseNamedImportsOrExports(kind: SyntaxKind): NamedImportsOrExports { + function parseNamedImportsOrExports( + kind: SyntaxKind.NamedImports, + ): NamedImports; + function parseNamedImportsOrExports( + kind: SyntaxKind.NamedExports, + ): NamedExports; + function parseNamedImportsOrExports( + kind: SyntaxKind, + ): NamedImportsOrExports { const pos = getNodePos(); // NamedImports: @@ -8493,21 +12284,44 @@ namespace Parser { // ImportSpecifier // ImportsList, ImportSpecifier const node = kind === SyntaxKind.NamedImports - ? factory.createNamedImports(parseBracketedList(ParsingContext.ImportOrExportSpecifiers, parseImportSpecifier, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken)) - : factory.createNamedExports(parseBracketedList(ParsingContext.ImportOrExportSpecifiers, parseExportSpecifier, SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken)); + ? factory.createNamedImports( + parseBracketedList( + ParsingContext.ImportOrExportSpecifiers, + parseImportSpecifier, + SyntaxKind.OpenBraceToken, + SyntaxKind.CloseBraceToken, + ), + ) + : factory.createNamedExports( + parseBracketedList( + ParsingContext.ImportOrExportSpecifiers, + parseExportSpecifier, + SyntaxKind.OpenBraceToken, + SyntaxKind.CloseBraceToken, + ), + ); return finishNode(node, pos); } function parseExportSpecifier() { const hasJSDoc = hasPrecedingJSDocComment(); - return withJSDoc(parseImportOrExportSpecifier(SyntaxKind.ExportSpecifier) as ExportSpecifier, hasJSDoc); + return withJSDoc( + parseImportOrExportSpecifier( + SyntaxKind.ExportSpecifier, + ) as ExportSpecifier, + hasJSDoc, + ); } function parseImportSpecifier() { - return parseImportOrExportSpecifier(SyntaxKind.ImportSpecifier) as ImportSpecifier; + return parseImportOrExportSpecifier( + SyntaxKind.ImportSpecifier, + ) as ImportSpecifier; } - function parseImportOrExportSpecifier(kind: SyntaxKind): ImportOrExportSpecifier { + function parseImportOrExportSpecifier( + kind: SyntaxKind, + ): ImportOrExportSpecifier { const pos = getNodePos(); // ImportSpecifier: // BindingIdentifier @@ -8575,7 +12389,11 @@ namespace Parser { name = parseNameWithKeywordCheck(); } if (kind === SyntaxKind.ImportSpecifier && checkIdentifierIsKeyword) { - parseErrorAt(checkIdentifierStart, checkIdentifierEnd, Diagnostics.Identifier_expected); + parseErrorAt( + checkIdentifierStart, + checkIdentifierEnd, + Diagnostics.Identifier_expected, + ); } const node = kind === SyntaxKind.ImportSpecifier ? factory.createImportSpecifier(isTypeOnly, propertyName, name) @@ -8591,10 +12409,17 @@ namespace Parser { } function parseNamespaceExport(pos: number): NamespaceExport { - return finishNode(factory.createNamespaceExport(parseIdentifierName()), pos); + return finishNode( + factory.createNamespaceExport(parseIdentifierName()), + pos, + ); } - function parseExportDeclaration(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): ExportDeclaration { + function parseExportDeclaration( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): ExportDeclaration { const savedAwaitContext = inAwaitContext(); setAwaitContext(/*value*/ true); let exportClause: NamedExportBindings | undefined; @@ -8614,22 +12439,41 @@ namespace Parser { // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. - if (token() === SyntaxKind.FromKeyword || (token() === SyntaxKind.StringLiteral && !scanner.hasPrecedingLineBreak())) { + if ( + token() === SyntaxKind.FromKeyword || + (token() === SyntaxKind.StringLiteral && + !scanner.hasPrecedingLineBreak()) + ) { parseExpected(SyntaxKind.FromKeyword); moduleSpecifier = parseModuleSpecifier(); } } const currentToken = token(); - if (moduleSpecifier && (currentToken === SyntaxKind.WithKeyword || currentToken === SyntaxKind.AssertKeyword) && !scanner.hasPrecedingLineBreak()) { + if ( + moduleSpecifier && + (currentToken === SyntaxKind.WithKeyword || + currentToken === SyntaxKind.AssertKeyword) && + !scanner.hasPrecedingLineBreak() + ) { attributes = parseImportAttributes(currentToken); } parseSemicolon(); setAwaitContext(savedAwaitContext); - const node = factory.createExportDeclaration(modifiers, isTypeOnly, exportClause, moduleSpecifier, attributes); + const node = factory.createExportDeclaration( + modifiers, + isTypeOnly, + exportClause, + moduleSpecifier, + attributes, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } - function parseExportAssignment(pos: number, hasJSDoc: boolean, modifiers: NodeArray | undefined): ExportAssignment { + function parseExportAssignment( + pos: number, + hasJSDoc: boolean, + modifiers: NodeArray | undefined, + ): ExportAssignment { const savedAwaitContext = inAwaitContext(); setAwaitContext(/*value*/ true); let isExportEquals: boolean | undefined; @@ -8639,42 +12483,48 @@ namespace Parser { else { parseExpected(SyntaxKind.DefaultKeyword); } - const expression = parseAssignmentExpressionOrHigher(/*allowReturnTypeInArrowFunction*/ true); + const expression = parseAssignmentExpressionOrHigher( + /*allowReturnTypeInArrowFunction*/ true, + ); parseSemicolon(); setAwaitContext(savedAwaitContext); - const node = factory.createExportAssignment(modifiers, isExportEquals, expression); + const node = factory.createExportAssignment( + modifiers, + isExportEquals, + expression, + ); return withJSDoc(finishNode(node, pos), hasJSDoc); } // dprint-ignore const enum ParsingContext { - SourceElements, // Elements in source file - BlockStatements, // Statements in block - SwitchClauses, // Clauses in switch statement - SwitchClauseStatements, // Statements in switch clause - TypeMembers, // Members in interface or type literal - ClassMembers, // Members in class declaration - EnumMembers, // Members in enum declaration - HeritageClauseElement, // Elements in a heritage clause - VariableDeclarations, // Variable declarations in variable statement - ObjectBindingElements, // Binding elements in object binding list - ArrayBindingElements, // Binding elements in array binding list - ArgumentExpressions, // Expressions in argument list - ObjectLiteralMembers, // Members in object literal - JsxAttributes, // Attributes in jsx element - JsxChildren, // Things between opening and closing JSX tags - ArrayLiteralMembers, // Members in array literal - Parameters, // Parameters in parameter list - JSDocParameters, // JSDoc parameters in parameter list of JSDoc function type - RestProperties, // Property names in a rest type list - TypeParameters, // Type parameters in type parameter list - TypeArguments, // Type arguments in type argument list - TupleElementTypes, // Element types in tuple element type list - HeritageClauses, // Heritage clauses for a class or interface declaration. - ImportOrExportSpecifiers, // Named import clause's import specifier list, - ImportAttributes, // Import attributes - JSDocComment, // Parsing via JSDocParser - Count, // Number of parsing contexts + SourceElements, // Elements in source file + BlockStatements, // Statements in block + SwitchClauses, // Clauses in switch statement + SwitchClauseStatements, // Statements in switch clause + TypeMembers, // Members in interface or type literal + ClassMembers, // Members in class declaration + EnumMembers, // Members in enum declaration + HeritageClauseElement, // Elements in a heritage clause + VariableDeclarations, // Variable declarations in variable statement + ObjectBindingElements, // Binding elements in object binding list + ArrayBindingElements, // Binding elements in array binding list + ArgumentExpressions, // Expressions in argument list + ObjectLiteralMembers, // Members in object literal + JsxAttributes, // Attributes in jsx element + JsxChildren, // Things between opening and closing JSX tags + ArrayLiteralMembers, // Members in array literal + Parameters, // Parameters in parameter list + JSDocParameters, // JSDoc parameters in parameter list of JSDoc function type + RestProperties, // Property names in a rest type list + TypeParameters, // Type parameters in type parameter list + TypeArguments, // Type arguments in type argument list + TupleElementTypes, // Element types in tuple element type list + HeritageClauses, // Heritage clauses for a class or interface declaration. + ImportOrExportSpecifiers, // Named import clause's import specifier list, + ImportAttributes, // Import attributes + JSDocComment, // Parsing via JSDocParser + Count, // Number of parsing contexts } const enum Tristate { @@ -8684,27 +12534,65 @@ namespace Parser { } export namespace JSDocParser { - export function parseJSDocTypeExpressionForTests(content: string, start: number | undefined, length: number | undefined): { jsDocTypeExpression: JSDocTypeExpression; diagnostics: Diagnostic[]; } | undefined { - initializeState("file.js", content, ScriptTarget.Latest, /*syntaxCursor*/ undefined, ScriptKind.JS, JSDocParsingMode.ParseAll); + export function parseJSDocTypeExpressionForTests( + content: string, + start: number | undefined, + length: number | undefined, + ): + | { + jsDocTypeExpression: JSDocTypeExpression; + diagnostics: Diagnostic[]; + } + | undefined + { + initializeState( + "file.js", + content, + ScriptTarget.Latest, + /*syntaxCursor*/ undefined, + ScriptKind.JS, + JSDocParsingMode.ParseAll, + ); scanner.setText(content, start, length); currentToken = scanner.scan(); const jsDocTypeExpression = parseJSDocTypeExpression(); - const sourceFile = createSourceFile("file.js", ScriptTarget.Latest, ScriptKind.JS, /*isDeclarationFile*/ false, [], factoryCreateToken(SyntaxKind.EndOfFileToken), NodeFlags.None, noop); - const diagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); + const sourceFile = createSourceFile( + "file.js", + ScriptTarget.Latest, + ScriptKind.JS, + /*isDeclarationFile*/ false, + [], + factoryCreateToken(SyntaxKind.EndOfFileToken), + NodeFlags.None, + noop, + ); + const diagnostics = attachFileToDiagnostics( + parseDiagnostics, + sourceFile, + ); if (jsDocDiagnostics) { - sourceFile.jsDocDiagnostics = attachFileToDiagnostics(jsDocDiagnostics, sourceFile); + sourceFile.jsDocDiagnostics = attachFileToDiagnostics( + jsDocDiagnostics, + sourceFile, + ); } clearState(); - return jsDocTypeExpression ? { jsDocTypeExpression, diagnostics } : undefined; + return jsDocTypeExpression + ? { jsDocTypeExpression, diagnostics } + : undefined; } // Parses out a JSDoc type expression. - export function parseJSDocTypeExpression(mayOmitBraces?: boolean): JSDocTypeExpression { + export function parseJSDocTypeExpression( + mayOmitBraces?: boolean, + ): JSDocTypeExpression { const pos = getNodePos(); - const hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(SyntaxKind.OpenBraceToken); + const hasBrace = (mayOmitBraces ? parseOptional : parseExpected)( + SyntaxKind.OpenBraceToken, + ); const type = doInsideOfContext(NodeFlags.JSDoc, parseJSDocType); if (!mayOmitBraces || hasBrace) { parseExpectedJSDoc(SyntaxKind.CloseBraceToken); @@ -8719,11 +12607,19 @@ namespace Parser { const pos = getNodePos(); const hasBrace = parseOptional(SyntaxKind.OpenBraceToken); const p2 = getNodePos(); - let entityName: EntityName | JSDocMemberName = parseEntityName(/*allowReservedWords*/ false); + let entityName: EntityName | JSDocMemberName = parseEntityName( + /*allowReservedWords*/ false, + ); while (token() === SyntaxKind.PrivateIdentifier) { reScanHashToken(); // rescan #id as # id nextTokenJSDoc(); // then skip the # - entityName = finishNode(factory.createJSDocMemberName(entityName, parseIdentifier()), p2); + entityName = finishNode( + factory.createJSDocMemberName( + entityName, + parseIdentifier(), + ), + p2, + ); } if (hasBrace) { parseExpectedJSDoc(SyntaxKind.CloseBraceToken); @@ -8734,18 +12630,39 @@ namespace Parser { return finishNode(result, pos); } - export function parseIsolatedJSDocComment(content: string, start: number | undefined, length: number | undefined): { jsDoc: JSDoc; diagnostics: Diagnostic[]; } | undefined { - initializeState("", content, ScriptTarget.Latest, /*syntaxCursor*/ undefined, ScriptKind.JS, JSDocParsingMode.ParseAll); + export function parseIsolatedJSDocComment( + content: string, + start: number | undefined, + length: number | undefined, + ): { jsDoc: JSDoc; diagnostics: Diagnostic[]; } | undefined { + initializeState( + "", + content, + ScriptTarget.Latest, + /*syntaxCursor*/ undefined, + ScriptKind.JS, + JSDocParsingMode.ParseAll, + ); const jsDoc = doInsideOfContext(NodeFlags.JSDoc, () => parseJSDocCommentWorker(start, length)); - const sourceFile = { languageVariant: LanguageVariant.Standard, text: content } as SourceFile; - const diagnostics = attachFileToDiagnostics(parseDiagnostics, sourceFile); + const sourceFile = { + languageVariant: LanguageVariant.Standard, + text: content, + } as SourceFile; + const diagnostics = attachFileToDiagnostics( + parseDiagnostics, + sourceFile, + ); clearState(); return jsDoc ? { jsDoc, diagnostics } : undefined; } - export function parseJSDocComment(parent: HasJSDoc, start: number, length: number): JSDoc | undefined { + export function parseJSDocComment( + parent: HasJSDoc, + start: number, + length: number, + ): JSDoc | undefined { const saveToken = currentToken; const saveParseDiagnosticsLength = parseDiagnostics.length; const saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; @@ -8778,7 +12695,10 @@ namespace Parser { CallbackParameter = 1 << 2, } - function parseJSDocCommentWorker(start = 0, length: number | undefined): JSDoc | undefined { + function parseJSDocCommentWorker( + start = 0, + length: number | undefined, + ): JSDoc | undefined { const content = sourceText; const end = length === undefined ? content.length : start + length; length = end - start; @@ -8804,7 +12724,11 @@ namespace Parser { parsingContext |= 1 << ParsingContext.JSDocComment; // + 3 for leading /**, - 5 in total for /** */ - const result = scanner.scanRange(start + 3, length - 5, doJSDocScan); + const result = scanner.scanRange( + start + 3, + length - 5, + doJSDocScan, + ); parsingContext = saveParsingContext; return result; @@ -8830,8 +12754,7 @@ namespace Parser { state = JSDocState.BeginningOfLine; indent = 0; } - loop: - while (true) { + loop: while (true) { switch (token()) { case SyntaxKind.AtToken: removeTrailingWhitespace(comments); @@ -8856,18 +12779,28 @@ namespace Parser { pushComment(asterisk); } else { - Debug.assert(state === JSDocState.BeginningOfLine); + Debug.assert( + state === JSDocState.BeginningOfLine, + ); // Ignore the first asterisk on a line state = JSDocState.SawAsterisk; indent += asterisk.length; } break; case SyntaxKind.WhitespaceTrivia: - Debug.assert(state !== JSDocState.SavingComments, "whitespace shouldn't come from the scanner while saving top-level comment text"); + Debug.assert( + state !== JSDocState.SavingComments, + "whitespace shouldn't come from the scanner while saving top-level comment text", + ); // only collect whitespace if we're already saving comments or have just crossed the comment indent margin const whitespace = scanner.getTokenText(); - if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent)); + if ( + margin !== undefined && + indent + whitespace.length > margin + ) { + comments.push( + whitespace.slice(margin - indent), + ); } indent += whitespace.length; break; @@ -8886,13 +12819,21 @@ namespace Parser { if (!linkEnd) { removeLeadingNewlines(comments); } - parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd ?? start, commentEnd)); + parts.push( + finishNode( + factory.createJSDocText( + comments.join(""), + ), + linkEnd ?? start, + commentEnd, + ), + ); parts.push(link); comments = []; linkEnd = scanner.getTokenEnd(); break; } - // fallthrough if it's not a {@link sequence + // fallthrough if it's not a {@link sequence default: // Anything else is doc comment text. We just save it. Because it // wasn't a tag, we can no longer parse a tag on this line until we hit the next @@ -8910,15 +12851,40 @@ namespace Parser { } const trimmedComments = comments.join("").trimEnd(); if (parts.length && trimmedComments.length) { - parts.push(finishNode(factory.createJSDocText(trimmedComments), linkEnd ?? start, commentsPos)); + parts.push( + finishNode( + factory.createJSDocText(trimmedComments), + linkEnd ?? start, + commentsPos, + ), + ); + } + if (parts.length && tags) { + Debug.assertIsDefined( + commentsPos, + "having parsed tags implies that the end of the comment span should be set", + ); } - if (parts.length && tags) Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); - return finishNode(factory.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : trimmedComments.length ? trimmedComments : undefined, tagsArray), start, end); + return finishNode( + factory.createJSDocComment( + parts.length + ? createNodeArray(parts, start, commentsPos) + : trimmedComments.length + ? trimmedComments + : undefined, + tagsArray, + ), + start, + end, + ); } function removeLeadingNewlines(comments: string[]) { - while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) { + while ( + comments.length && + (comments[0] === "\n" || comments[0] === "\r") + ) { comments.shift(); } } @@ -8929,7 +12895,9 @@ namespace Parser { if (trimmed === "") { comments.pop(); } - else if (trimmed.length < comments[comments.length - 1].length) { + else if ( + trimmed.length < comments[comments.length - 1].length + ) { comments[comments.length - 1] = trimmed; break; } @@ -8946,25 +12914,39 @@ namespace Parser { if (token() === SyntaxKind.EndOfFileToken) { return true; } - if (!(token() === SyntaxKind.WhitespaceTrivia || token() === SyntaxKind.NewLineTrivia)) { + if ( + !( + token() === SyntaxKind.WhitespaceTrivia || + token() === SyntaxKind.NewLineTrivia + ) + ) { return false; } } } function skipWhitespace(): void { - if (token() === SyntaxKind.WhitespaceTrivia || token() === SyntaxKind.NewLineTrivia) { + if ( + token() === SyntaxKind.WhitespaceTrivia || + token() === SyntaxKind.NewLineTrivia + ) { if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range } } - while (token() === SyntaxKind.WhitespaceTrivia || token() === SyntaxKind.NewLineTrivia) { + while ( + token() === SyntaxKind.WhitespaceTrivia || + token() === SyntaxKind.NewLineTrivia + ) { nextTokenJSDoc(); } } function skipWhitespaceOrAsterisk(): string { - if (token() === SyntaxKind.WhitespaceTrivia || token() === SyntaxKind.NewLineTrivia) { + if ( + token() === SyntaxKind.WhitespaceTrivia || + token() === SyntaxKind.NewLineTrivia + ) { if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range } @@ -8973,7 +12955,12 @@ namespace Parser { let precedingLineBreak = scanner.hasPrecedingLineBreak(); let seenLineBreak = false; let indentText = ""; - while ((precedingLineBreak && token() === SyntaxKind.AsteriskToken) || token() === SyntaxKind.WhitespaceTrivia || token() === SyntaxKind.NewLineTrivia) { + while ( + (precedingLineBreak && + token() === SyntaxKind.AsteriskToken) || + token() === SyntaxKind.WhitespaceTrivia || + token() === SyntaxKind.NewLineTrivia + ) { indentText += scanner.getTokenText(); if (token() === SyntaxKind.NewLineTrivia) { precedingLineBreak = true; @@ -8999,37 +12986,94 @@ namespace Parser { let tag: JSDocTag | undefined; switch (tagName.escapedText) { case "author": - tag = parseAuthorTag(start, tagName, margin, indentText); + tag = parseAuthorTag( + start, + tagName, + margin, + indentText, + ); break; case "implements": - tag = parseImplementsTag(start, tagName, margin, indentText); + tag = parseImplementsTag( + start, + tagName, + margin, + indentText, + ); break; case "augments": case "extends": - tag = parseAugmentsTag(start, tagName, margin, indentText); + tag = parseAugmentsTag( + start, + tagName, + margin, + indentText, + ); break; case "class": case "constructor": - tag = parseSimpleTag(start, factory.createJSDocClassTag, tagName, margin, indentText); + tag = parseSimpleTag( + start, + factory.createJSDocClassTag, + tagName, + margin, + indentText, + ); break; case "public": - tag = parseSimpleTag(start, factory.createJSDocPublicTag, tagName, margin, indentText); + tag = parseSimpleTag( + start, + factory.createJSDocPublicTag, + tagName, + margin, + indentText, + ); break; case "private": - tag = parseSimpleTag(start, factory.createJSDocPrivateTag, tagName, margin, indentText); + tag = parseSimpleTag( + start, + factory.createJSDocPrivateTag, + tagName, + margin, + indentText, + ); break; case "protected": - tag = parseSimpleTag(start, factory.createJSDocProtectedTag, tagName, margin, indentText); + tag = parseSimpleTag( + start, + factory.createJSDocProtectedTag, + tagName, + margin, + indentText, + ); break; case "readonly": - tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText); + tag = parseSimpleTag( + start, + factory.createJSDocReadonlyTag, + tagName, + margin, + indentText, + ); break; case "override": - tag = parseSimpleTag(start, factory.createJSDocOverrideTag, tagName, margin, indentText); + tag = parseSimpleTag( + start, + factory.createJSDocOverrideTag, + tagName, + margin, + indentText, + ); break; case "deprecated": hasDeprecatedTag = true; - tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText); + tag = parseSimpleTag( + start, + factory.createJSDocDeprecatedTag, + tagName, + margin, + indentText, + ); break; case "this": tag = parseThisTag(start, tagName, margin, indentText); @@ -9040,44 +13084,94 @@ namespace Parser { case "arg": case "argument": case "param": - return parseParameterOrPropertyTag(start, tagName, PropertyLikeParse.Parameter, margin); + return parseParameterOrPropertyTag( + start, + tagName, + PropertyLikeParse.Parameter, + margin, + ); case "return": case "returns": - tag = parseReturnTag(start, tagName, margin, indentText); + tag = parseReturnTag( + start, + tagName, + margin, + indentText, + ); break; case "template": - tag = parseTemplateTag(start, tagName, margin, indentText); + tag = parseTemplateTag( + start, + tagName, + margin, + indentText, + ); break; case "type": tag = parseTypeTag(start, tagName, margin, indentText); break; case "typedef": - tag = parseTypedefTag(start, tagName, margin, indentText); + tag = parseTypedefTag( + start, + tagName, + margin, + indentText, + ); break; case "callback": - tag = parseCallbackTag(start, tagName, margin, indentText); + tag = parseCallbackTag( + start, + tagName, + margin, + indentText, + ); break; case "overload": - tag = parseOverloadTag(start, tagName, margin, indentText); + tag = parseOverloadTag( + start, + tagName, + margin, + indentText, + ); break; case "satisfies": - tag = parseSatisfiesTag(start, tagName, margin, indentText); + tag = parseSatisfiesTag( + start, + tagName, + margin, + indentText, + ); break; case "see": tag = parseSeeTag(start, tagName, margin, indentText); break; case "exception": case "throws": - tag = parseThrowsTag(start, tagName, margin, indentText); + tag = parseThrowsTag( + start, + tagName, + margin, + indentText, + ); break; default: - tag = parseUnknownTag(start, tagName, margin, indentText); + tag = parseUnknownTag( + start, + tagName, + margin, + indentText, + ); break; } return tag; } - function parseTrailingTagComments(pos: number, end: number, margin: number, indentText: string) { + function parseTrailingTagComments( + pos: number, + end: number, + margin: number, + indentText: string, + ) { // some tags, like typedef and callback, have already parsed their comments earlier if (!indentText) { margin += end - pos; @@ -9085,7 +13179,10 @@ namespace Parser { return parseTagComments(margin, indentText.slice(margin)); } - function parseTagComments(indent: number, initialMargin?: string): string | NodeArray | undefined { + function parseTagComments( + indent: number, + initialMargin?: string, + ): string | NodeArray | undefined { const commentsPos = getNodePos(); let comments: string[] = []; const parts: JSDocComment[] = []; @@ -9106,9 +13203,10 @@ namespace Parser { } state = JSDocState.SawAsterisk; } - let tok = token() as JSDocSyntaxKind | SyntaxKind.JSDocCommentTextToken; - loop: - while (true) { + let tok = token() as + | JSDocSyntaxKind + | SyntaxKind.JSDocCommentTextToken; + loop: while (true) { switch (tok) { case SyntaxKind.NewLineTrivia: state = JSDocState.BeginningOfLine; @@ -9123,11 +13221,20 @@ namespace Parser { // Done break loop; case SyntaxKind.WhitespaceTrivia: - Debug.assert(state !== JSDocState.SavingComments && state !== JSDocState.SavingBackticks, "whitespace shouldn't come from the scanner while saving comment text"); + Debug.assert( + state !== JSDocState.SavingComments && + state !== JSDocState.SavingBackticks, + "whitespace shouldn't come from the scanner while saving comment text", + ); const whitespace = scanner.getTokenText(); // if the whitespace crosses the margin, take only the whitespace that passes the margin - if (margin !== undefined && indent + whitespace.length > margin) { - comments.push(whitespace.slice(margin - indent)); + if ( + margin !== undefined && + indent + whitespace.length > margin + ) { + comments.push( + whitespace.slice(margin - indent), + ); state = JSDocState.SavingComments; } indent += whitespace.length; @@ -9138,7 +13245,15 @@ namespace Parser { const linkStart = scanner.getTokenEnd() - 1; const link = parseJSDocLink(linkStart); if (link) { - parts.push(finishNode(factory.createJSDocText(comments.join("")), linkEnd ?? commentsPos, commentEnd)); + parts.push( + finishNode( + factory.createJSDocText( + comments.join(""), + ), + linkEnd ?? commentsPos, + commentEnd, + ), + ); parts.push(link); comments = []; linkEnd = scanner.getTokenEnd(); @@ -9169,8 +13284,8 @@ namespace Parser { indent += 1; break; } - // record the * as a comment - // falls through + // record the * as a comment + // falls through default: if (state !== JSDocState.SavingBackticks) { state = JSDocState.SavingComments; // leading identifiers start recording as well @@ -9178,8 +13293,13 @@ namespace Parser { pushComment(scanner.getTokenText()); break; } - if (state === JSDocState.SavingComments || state === JSDocState.SavingBackticks) { - tok = nextJSDocCommentTextToken(state === JSDocState.SavingBackticks); + if ( + state === JSDocState.SavingComments || + state === JSDocState.SavingBackticks + ) { + tok = nextJSDocCommentTextToken( + state === JSDocState.SavingBackticks, + ); } else { tok = nextTokenJSDoc(); @@ -9190,9 +13310,18 @@ namespace Parser { const trimmedComments = comments.join("").trimEnd(); if (parts.length) { if (trimmedComments.length) { - parts.push(finishNode(factory.createJSDocText(trimmedComments), linkEnd ?? commentsPos)); + parts.push( + finishNode( + factory.createJSDocText(trimmedComments), + linkEnd ?? commentsPos, + ), + ); } - return createNodeArray(parts, commentsPos, scanner.getTokenEnd()); + return createNodeArray( + parts, + commentsPos, + scanner.getTokenEnd(), + ); } else if (trimmedComments.length) { return trimmedComments; @@ -9215,26 +13344,42 @@ namespace Parser { while (token() === SyntaxKind.PrivateIdentifier) { reScanHashToken(); // rescan #id as # id nextTokenJSDoc(); // then skip the # - name = finishNode(factory.createJSDocMemberName(name, parseIdentifier()), p2); + name = finishNode( + factory.createJSDocMemberName( + name, + parseIdentifier(), + ), + p2, + ); } } const text = []; - while (token() !== SyntaxKind.CloseBraceToken && token() !== SyntaxKind.NewLineTrivia && token() !== SyntaxKind.EndOfFileToken) { + while ( + token() !== SyntaxKind.CloseBraceToken && + token() !== SyntaxKind.NewLineTrivia && + token() !== SyntaxKind.EndOfFileToken + ) { text.push(scanner.getTokenText()); nextTokenJSDoc(); } - const create = linkType === "link" ? factory.createJSDocLink - : linkType === "linkcode" ? factory.createJSDocLinkCode + const create = linkType === "link" + ? factory.createJSDocLink + : linkType === "linkcode" + ? factory.createJSDocLinkCode : factory.createJSDocLinkPlain; - return finishNode(create(name, text.join("")), start, scanner.getTokenEnd()); + return finishNode( + create(name, text.join("")), + start, + scanner.getTokenEnd(), + ); } function parseJSDocLinkPrefix() { skipWhitespaceOrAsterisk(); if ( - token() === SyntaxKind.OpenBraceToken - && nextTokenJSDoc() === SyntaxKind.AtToken - && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) + token() === SyntaxKind.OpenBraceToken && + nextTokenJSDoc() === SyntaxKind.AtToken && + tokenIsIdentifierOrKeyword(nextTokenJSDoc()) ) { const kind = scanner.getTokenValue(); if (isJSDocLinkTag(kind)) return kind; @@ -9242,11 +13387,31 @@ namespace Parser { } function isJSDocLinkTag(kind: string) { - return kind === "link" || kind === "linkcode" || kind === "linkplain"; + return ( + kind === "link" || + kind === "linkcode" || + kind === "linkplain" + ); } - function parseUnknownTag(start: number, tagName: Identifier, indent: number, indentText: string) { - return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); + function parseUnknownTag( + start: number, + tagName: Identifier, + indent: number, + indentText: string, + ) { + return finishNode( + factory.createJSDocUnknownTag( + tagName, + parseTrailingTagComments( + start, + getNodePos(), + indent, + indentText, + ), + ), + start, + ); } function addTag(tag: JSDocTag | undefined): void { @@ -9265,17 +13430,26 @@ namespace Parser { function tryParseTypeExpression(): JSDocTypeExpression | undefined { skipWhitespaceOrAsterisk(); - return token() === SyntaxKind.OpenBraceToken ? parseJSDocTypeExpression() : undefined; + return token() === SyntaxKind.OpenBraceToken + ? parseJSDocTypeExpression() + : undefined; } - function parseBracketNameInPropertyAndParamTag(): { name: EntityName; isBracketed: boolean; } { + function parseBracketNameInPropertyAndParamTag(): { + name: EntityName; + isBracketed: boolean; + } { // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar' - const isBracketed = parseOptionalJsdoc(SyntaxKind.OpenBracketToken); + const isBracketed = parseOptionalJsdoc( + SyntaxKind.OpenBracketToken, + ); if (isBracketed) { skipWhitespace(); } // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild - const isBackquoted = parseOptionalJsdoc(SyntaxKind.BacktickToken); + const isBackquoted = parseOptionalJsdoc( + SyntaxKind.BacktickToken, + ); const name = parseJSDocEntityName(); if (isBackquoted) { parseExpectedTokenJSDoc(SyntaxKind.BacktickToken); @@ -9293,18 +13467,32 @@ namespace Parser { return { name, isBracketed }; } - function isObjectOrObjectArrayTypeReference(node: TypeNode): boolean { + function isObjectOrObjectArrayTypeReference( + node: TypeNode, + ): boolean { switch (node.kind) { case SyntaxKind.ObjectKeyword: return true; case SyntaxKind.ArrayType: - return isObjectOrObjectArrayTypeReference((node as ArrayTypeNode).elementType); + return isObjectOrObjectArrayTypeReference( + node.elementType, + ); default: - return isTypeReferenceNode(node) && isIdentifierNode(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments; + return ( + isTypeReferenceNode(node) && + isIdentifierNode(node.typeName) && + node.typeName.escapedText === "Object" && + !node.typeArguments + ); } } - function parseParameterOrPropertyTag(start: number, tagName: Identifier, target: PropertyLikeParse, indent: number): JSDocParameterTag | JSDocPropertyTag { + function parseParameterOrPropertyTag( + start: number, + tagName: Identifier, + target: PropertyLikeParse, + indent: number, + ): JSDocParameterTag | JSDocPropertyTag { let typeExpression = tryParseTypeExpression(); let isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -9316,98 +13504,280 @@ namespace Parser { typeExpression = tryParseTypeExpression(); } - const comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); + const comment = parseTrailingTagComments( + start, + getNodePos(), + indent, + indentText, + ); - const nestedTypeLiteral = parseNestedTypeLiteral(typeExpression, name, target, indent); + const nestedTypeLiteral = parseNestedTypeLiteral( + typeExpression, + name, + target, + indent, + ); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; } const result = target === PropertyLikeParse.Property - ? factory.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) - : factory.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); + ? factory.createJSDocPropertyTag( + tagName, + name, + isBracketed, + typeExpression, + isNameFirst, + comment, + ) + : factory.createJSDocParameterTag( + tagName, + name, + isBracketed, + typeExpression, + isNameFirst, + comment, + ); return finishNode(result, start); } - function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression | undefined, name: EntityName, target: PropertyLikeParse, indent: number) { - if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { + function parseNestedTypeLiteral( + typeExpression: JSDocTypeExpression | undefined, + name: EntityName, + target: PropertyLikeParse, + indent: number, + ) { + if ( + typeExpression && + isObjectOrObjectArrayTypeReference(typeExpression.type) + ) { const pos = getNodePos(); - let child: JSDocPropertyLikeTag | JSDocTypeTag | JSDocTemplateTag | false; + let child: + | JSDocPropertyLikeTag + | JSDocTypeTag + | JSDocTemplateTag + | false; let children: JSDocPropertyLikeTag[] | undefined; - while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent, name))) { - if (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) { + while ( + (child = tryParse(() => + parseChildParameterOrPropertyTag( + target, + indent, + name, + ) + )) + ) { + if ( + child.kind === SyntaxKind.JSDocParameterTag || + child.kind === SyntaxKind.JSDocPropertyTag + ) { children = append(children, child); } else if (child.kind === SyntaxKind.JSDocTemplateTag) { - parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); + parseErrorAtRange( + child.tagName, + Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag, + ); } } if (children) { - const literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === SyntaxKind.ArrayType), pos); - return finishNode(factory.createJSDocTypeExpression(literal), pos); + const literal = finishNode( + factory.createJSDocTypeLiteral( + children, + typeExpression.type.kind === + SyntaxKind.ArrayType, + ), + pos, + ); + return finishNode( + factory.createJSDocTypeExpression(literal), + pos, + ); } } } - function parseReturnTag(start: number, tagName: Identifier, indent: number, indentText: string): JSDocReturnTag { + function parseReturnTag( + start: number, + tagName: Identifier, + indent: number, + indentText: string, + ): JSDocReturnTag { if (some(tags, isJSDocReturnTag)) { - parseErrorAt(tagName.pos, scanner.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.escapedText)); + parseErrorAt( + tagName.pos, + scanner.getTokenStart(), + Diagnostics._0_tag_already_specified, + unescapeLeadingUnderscores(tagName.escapedText), + ); } const typeExpression = tryParseTypeExpression(); - return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); + return finishNode( + factory.createJSDocReturnTag( + tagName, + typeExpression, + parseTrailingTagComments( + start, + getNodePos(), + indent, + indentText, + ), + ), + start, + ); } - function parseTypeTag(start: number, tagName: Identifier, indent?: number, indentText?: string): JSDocTypeTag { + function parseTypeTag( + start: number, + tagName: Identifier, + indent?: number, + indentText?: string, + ): JSDocTypeTag { if (some(tags, isJSDocTypeTag)) { - parseErrorAt(tagName.pos, scanner.getTokenStart(), Diagnostics._0_tag_already_specified, unescapeLeadingUnderscores(tagName.escapedText)); + parseErrorAt( + tagName.pos, + scanner.getTokenStart(), + Diagnostics._0_tag_already_specified, + unescapeLeadingUnderscores(tagName.escapedText), + ); } - const typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); - const comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; - return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start); + const typeExpression = parseJSDocTypeExpression( + /*mayOmitBraces*/ true, + ); + const comments = indent !== undefined && indentText !== undefined + ? parseTrailingTagComments( + start, + getNodePos(), + indent, + indentText, + ) + : undefined; + return finishNode( + factory.createJSDocTypeTag( + tagName, + typeExpression, + comments, + ), + start, + ); } - function parseSeeTag(start: number, tagName: Identifier, indent?: number, indentText?: string): JSDocSeeTag { - const isMarkdownOrJSDocLink = token() === SyntaxKind.OpenBracketToken - || lookAhead(() => nextTokenJSDoc() === SyntaxKind.AtToken && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && isJSDocLinkTag(scanner.getTokenValue())); - const nameExpression = isMarkdownOrJSDocLink ? undefined : parseJSDocNameReference(); - const comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined; - return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start); + function parseSeeTag( + start: number, + tagName: Identifier, + indent?: number, + indentText?: string, + ): JSDocSeeTag { + const isMarkdownOrJSDocLink = token() === SyntaxKind.OpenBracketToken || + lookAhead( + () => + nextTokenJSDoc() === SyntaxKind.AtToken && + tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && + isJSDocLinkTag(scanner.getTokenValue()), + ); + const nameExpression = isMarkdownOrJSDocLink + ? undefined + : parseJSDocNameReference(); + const comments = indent !== undefined && indentText !== undefined + ? parseTrailingTagComments( + start, + getNodePos(), + indent, + indentText, + ) + : undefined; + return finishNode( + factory.createJSDocSeeTag( + tagName, + nameExpression, + comments, + ), + start, + ); } - function parseThrowsTag(start: number, tagName: Identifier, indent: number, indentText: string): JSDocThrowsTag { + function parseThrowsTag( + start: number, + tagName: Identifier, + indent: number, + indentText: string, + ): JSDocThrowsTag { const typeExpression = tryParseTypeExpression(); - const comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); - return finishNode(factory.createJSDocThrowsTag(tagName, typeExpression, comment), start); + const comment = parseTrailingTagComments( + start, + getNodePos(), + indent, + indentText, + ); + return finishNode( + factory.createJSDocThrowsTag( + tagName, + typeExpression, + comment, + ), + start, + ); } - function parseAuthorTag(start: number, tagName: Identifier, indent: number, indentText: string): JSDocAuthorTag { + function parseAuthorTag( + start: number, + tagName: Identifier, + indent: number, + indentText: string, + ): JSDocAuthorTag { const commentStart = getNodePos(); const textOnly = parseAuthorNameAndEmail(); let commentEnd = scanner.getTokenFullStart(); - const comments = parseTrailingTagComments(start, commentEnd, indent, indentText); + const comments = parseTrailingTagComments( + start, + commentEnd, + indent, + indentText, + ); if (!comments) { commentEnd = scanner.getTokenFullStart(); } const allParts = typeof comments !== "string" - ? createNodeArray(concatenate([finishNode(textOnly, commentStart, commentEnd)], comments) as JSDocComment[], commentStart) // cast away readonly + ? createNodeArray( + concatenate( + [ + finishNode( + textOnly, + commentStart, + commentEnd, + ), + ], + comments, + ) as JSDocComment[], + commentStart, + ) // cast away readonly : textOnly.text + comments; - return finishNode(factory.createJSDocAuthorTag(tagName, allParts), start); + return finishNode( + factory.createJSDocAuthorTag(tagName, allParts), + start, + ); } function parseAuthorNameAndEmail(): JSDocText { const comments: string[] = []; let inEmail = false; let token = scanner.getToken(); - while (token !== SyntaxKind.EndOfFileToken && token !== SyntaxKind.NewLineTrivia) { + while ( + token !== SyntaxKind.EndOfFileToken && + token !== SyntaxKind.NewLineTrivia + ) { if (token === SyntaxKind.LessThanToken) { inEmail = true; } else if (token === SyntaxKind.AtToken && !inEmail) { break; } - else if (token === SyntaxKind.GreaterThanToken && inEmail) { + else if ( + token === SyntaxKind.GreaterThanToken && + inEmail + ) { comments.push(scanner.getTokenText()); scanner.resetTokenState(scanner.getTokenEnd()); break; @@ -9419,30 +13789,92 @@ namespace Parser { return factory.createJSDocText(comments.join("")); } - function parseImplementsTag(start: number, tagName: Identifier, margin: number, indentText: string): JSDocImplementsTag { + function parseImplementsTag( + start: number, + tagName: Identifier, + margin: number, + indentText: string, + ): JSDocImplementsTag { const className = parseExpressionWithTypeArgumentsForAugments(); - return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); + return finishNode( + factory.createJSDocImplementsTag( + tagName, + className, + parseTrailingTagComments( + start, + getNodePos(), + margin, + indentText, + ), + ), + start, + ); } - function parseAugmentsTag(start: number, tagName: Identifier, margin: number, indentText: string): JSDocAugmentsTag { + function parseAugmentsTag( + start: number, + tagName: Identifier, + margin: number, + indentText: string, + ): JSDocAugmentsTag { const className = parseExpressionWithTypeArgumentsForAugments(); - return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); + return finishNode( + factory.createJSDocAugmentsTag( + tagName, + className, + parseTrailingTagComments( + start, + getNodePos(), + margin, + indentText, + ), + ), + start, + ); } - function parseSatisfiesTag(start: number, tagName: Identifier, margin: number, indentText: string): JSDocSatisfiesTag { - const typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ false); - const comments = margin !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), margin, indentText) : undefined; - return finishNode(factory.createJSDocSatisfiesTag(tagName, typeExpression, comments), start); + function parseSatisfiesTag( + start: number, + tagName: Identifier, + margin: number, + indentText: string, + ): JSDocSatisfiesTag { + const typeExpression = parseJSDocTypeExpression( + /*mayOmitBraces*/ false, + ); + const comments = margin !== undefined && indentText !== undefined + ? parseTrailingTagComments( + start, + getNodePos(), + margin, + indentText, + ) + : undefined; + return finishNode( + factory.createJSDocSatisfiesTag( + tagName, + typeExpression, + comments, + ), + start, + ); } - function parseExpressionWithTypeArgumentsForAugments(): ExpressionWithTypeArguments & { expression: Identifier | PropertyAccessEntityNameExpression; } { + function parseExpressionWithTypeArgumentsForAugments(): ExpressionWithTypeArguments & { + expression: Identifier | PropertyAccessEntityNameExpression; + } { const usedBrace = parseOptional(SyntaxKind.OpenBraceToken); const pos = getNodePos(); const expression = parsePropertyAccessEntityNameExpression(); scanner.setInJSDocType(true); const typeArguments = tryParseTypeArguments(); scanner.setInJSDocType(false); - const node = factory.createExpressionWithTypeArguments(expression, typeArguments) as ExpressionWithTypeArguments & { expression: Identifier | PropertyAccessEntityNameExpression; }; + const node = factory.createExpressionWithTypeArguments( + expression, + typeArguments, + ) as ExpressionWithTypeArguments & { + expression: Identifier | PropertyAccessEntityNameExpression; + }; const res = finishNode(node, pos); if (usedBrace) { parseExpected(SyntaxKind.CloseBraceToken); @@ -9455,29 +13887,98 @@ namespace Parser { let node: Identifier | PropertyAccessEntityNameExpression = parseJSDocIdentifierName(); while (parseOptional(SyntaxKind.DotToken)) { const name = parseJSDocIdentifierName(); - node = finishNode(factoryCreatePropertyAccessExpression(node, name), pos) as PropertyAccessEntityNameExpression; + node = finishNode( + factoryCreatePropertyAccessExpression(node, name), + pos, + ) as PropertyAccessEntityNameExpression; } return node; } - function parseSimpleTag(start: number, createTag: (tagName: Identifier | undefined, comment?: string | NodeArray) => JSDocTag, tagName: Identifier, margin: number, indentText: string): JSDocTag { - return finishNode(createTag(tagName, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); + function parseSimpleTag( + start: number, + createTag: ( + tagName: Identifier | undefined, + comment?: string | NodeArray, + ) => JSDocTag, + tagName: Identifier, + margin: number, + indentText: string, + ): JSDocTag { + return finishNode( + createTag( + tagName, + parseTrailingTagComments( + start, + getNodePos(), + margin, + indentText, + ), + ), + start, + ); } - function parseThisTag(start: number, tagName: Identifier, margin: number, indentText: string): JSDocThisTag { - const typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + function parseThisTag( + start: number, + tagName: Identifier, + margin: number, + indentText: string, + ): JSDocThisTag { + const typeExpression = parseJSDocTypeExpression( + /*mayOmitBraces*/ true, + ); skipWhitespace(); - return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); + return finishNode( + factory.createJSDocThisTag( + tagName, + typeExpression, + parseTrailingTagComments( + start, + getNodePos(), + margin, + indentText, + ), + ), + start, + ); } - function parseEnumTag(start: number, tagName: Identifier, margin: number, indentText: string): JSDocEnumTag { - const typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true); + function parseEnumTag( + start: number, + tagName: Identifier, + margin: number, + indentText: string, + ): JSDocEnumTag { + const typeExpression = parseJSDocTypeExpression( + /*mayOmitBraces*/ true, + ); skipWhitespace(); - return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, getNodePos(), margin, indentText)), start); + return finishNode( + factory.createJSDocEnumTag( + tagName, + typeExpression, + parseTrailingTagComments( + start, + getNodePos(), + margin, + indentText, + ), + ), + start, + ); } - function parseTypedefTag(start: number, tagName: Identifier, indent: number, indentText: string): JSDocTypedefTag { - let typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined = tryParseTypeExpression(); + function parseTypedefTag( + start: number, + tagName: Identifier, + indent: number, + indentText: string, + ): JSDocTypedefTag { + let typeExpression: + | JSDocTypeExpression + | JSDocTypeLiteral + | undefined = tryParseTypeExpression(); skipWhitespaceOrAsterisk(); const fullName = parseJSDocTypeNameWithNamespace(); @@ -9485,21 +13986,41 @@ namespace Parser { let comment = parseTagComments(indent); let end: number | undefined; - if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) { - let child: JSDocTypeTag | JSDocPropertyTag | JSDocTemplateTag | false; + if ( + !typeExpression || + isObjectOrObjectArrayTypeReference(typeExpression.type) + ) { + let child: + | JSDocTypeTag + | JSDocPropertyTag + | JSDocTemplateTag + | false; let childTypeTag: JSDocTypeTag | undefined; let jsDocPropertyTags: JSDocPropertyTag[] | undefined; let hasChildren = false; - while (child = tryParse(() => parseChildPropertyTag(indent))) { + while ( + (child = tryParse(() => parseChildPropertyTag(indent))) + ) { if (child.kind === SyntaxKind.JSDocTemplateTag) { break; } hasChildren = true; if (child.kind === SyntaxKind.JSDocTypeTag) { if (childTypeTag) { - const lastError = parseErrorAtCurrentToken(Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags); + const lastError = parseErrorAtCurrentToken( + Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags, + ); if (lastError) { - addRelatedInfo(lastError, createDetachedDiagnostic(fileName, sourceText, 0, 0, Diagnostics.The_tag_was_first_specified_here)); + addRelatedInfo( + lastError, + createDetachedDiagnostic( + fileName, + sourceText, + 0, + 0, + Diagnostics.The_tag_was_first_specified_here, + ), + ); } break; } @@ -9508,29 +14029,50 @@ namespace Parser { } } else { - jsDocPropertyTags = append(jsDocPropertyTags, child); + jsDocPropertyTags = append( + jsDocPropertyTags, + child, + ); } } if (hasChildren) { - const isArrayType = typeExpression && typeExpression.type.kind === SyntaxKind.ArrayType; - const jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType); - typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ? - childTypeTag.typeExpression : - finishNode(jsdocTypeLiteral, start); + const isArrayType = typeExpression && + typeExpression.type.kind === SyntaxKind.ArrayType; + const jsdocTypeLiteral = factory.createJSDocTypeLiteral( + jsDocPropertyTags, + isArrayType, + ); + typeExpression = childTypeTag && + childTypeTag.typeExpression && + !isObjectOrObjectArrayTypeReference( + childTypeTag.typeExpression.type, + ) + ? childTypeTag.typeExpression + : finishNode(jsdocTypeLiteral, start); end = typeExpression.end; } } // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace - end = end || comment !== undefined ? - getNodePos() : - (fullName ?? typeExpression ?? tagName).end; + end = end || comment !== undefined + ? getNodePos() + : (fullName ?? typeExpression ?? tagName).end; if (!comment) { - comment = parseTrailingTagComments(start, end, indent, indentText); + comment = parseTrailingTagComments( + start, + end, + indent, + indentText, + ); } - const typedefTag = factory.createJSDocTypedefTag(tagName, typeExpression, fullName, comment); + const typedefTag = factory.createJSDocTypedefTag( + tagName, + typeExpression, + fullName, + comment, + ); return finishNode(typedefTag, start, end); } @@ -9541,7 +14083,9 @@ namespace Parser { } const typeNameOrNamespaceName = parseJSDocIdentifierName(); if (parseOptional(SyntaxKind.DotToken)) { - const body = parseJSDocTypeNameWithNamespace(/*nested*/ true); + const body = parseJSDocTypeNameWithNamespace( + /*nested*/ true, + ); const jsDocNamespaceNode = factory.createModuleDeclaration( /*modifiers*/ undefined, typeNameOrNamespaceName, @@ -9561,9 +14105,20 @@ namespace Parser { const pos = getNodePos(); let child: JSDocParameterTag | JSDocTemplateTag | false; let parameters; - while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.CallbackParameter, indent) as JSDocParameterTag | JSDocTemplateTag)) { + while ( + (child = tryParse( + () => + parseChildParameterOrPropertyTag( + PropertyLikeParse.CallbackParameter, + indent, + ) as JSDocParameterTag | JSDocTemplateTag, + )) + ) { if (child.kind === SyntaxKind.JSDocTemplateTag) { - parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); + parseErrorAtRange( + child.tagName, + Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag, + ); break; } parameters = append(parameters, child); @@ -9571,45 +14126,96 @@ namespace Parser { return createNodeArray(parameters || [], pos); } - function parseJSDocSignature(start: number, indent: number): JSDocSignature { + function parseJSDocSignature( + start: number, + indent: number, + ): JSDocSignature { const parameters = parseCallbackTagParameters(indent); const returnTag = tryParse(() => { if (parseOptionalJsdoc(SyntaxKind.AtToken)) { const tag = parseTag(indent); if (tag && tag.kind === SyntaxKind.JSDocReturnTag) { - return tag as JSDocReturnTag; + return tag; } } }); - return finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start); + return finishNode( + factory.createJSDocSignature( + /*typeParameters*/ undefined, + parameters, + returnTag, + ), + start, + ); } - function parseCallbackTag(start: number, tagName: Identifier, indent: number, indentText: string): JSDocCallbackTag { + function parseCallbackTag( + start: number, + tagName: Identifier, + indent: number, + indentText: string, + ): JSDocCallbackTag { const fullName = parseJSDocTypeNameWithNamespace(); skipWhitespace(); let comment = parseTagComments(indent); const typeExpression = parseJSDocSignature(start, indent); if (!comment) { - comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); + comment = parseTrailingTagComments( + start, + getNodePos(), + indent, + indentText, + ); } const end = comment !== undefined ? getNodePos() : typeExpression.end; - return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end); + return finishNode( + factory.createJSDocCallbackTag( + tagName, + typeExpression, + fullName, + comment, + ), + start, + end, + ); } - function parseOverloadTag(start: number, tagName: Identifier, indent: number, indentText: string): JSDocOverloadTag { + function parseOverloadTag( + start: number, + tagName: Identifier, + indent: number, + indentText: string, + ): JSDocOverloadTag { skipWhitespace(); let comment = parseTagComments(indent); const typeExpression = parseJSDocSignature(start, indent); if (!comment) { - comment = parseTrailingTagComments(start, getNodePos(), indent, indentText); + comment = parseTrailingTagComments( + start, + getNodePos(), + indent, + indentText, + ); } const end = comment !== undefined ? getNodePos() : typeExpression.end; - return finishNode(factory.createJSDocOverloadTag(tagName, typeExpression, comment), start, end); + return finishNode( + factory.createJSDocOverloadTag( + tagName, + typeExpression, + comment, + ), + start, + end, + ); } function escapedTextsEqual(a: EntityName, b: EntityName): boolean { while (!isIdentifierNode(a) || !isIdentifierNode(b)) { - if (!isIdentifierNode(a) && !isIdentifierNode(b) && a.right.escapedText === b.right.escapedText) { + if ( + !isIdentifierNode(a) && + !isIdentifierNode(b) && + a.right.escapedText === b.right.escapedText + ) { a = a.left; b = b.left; } @@ -9621,10 +14227,23 @@ namespace Parser { } function parseChildPropertyTag(indent: number) { - return parseChildParameterOrPropertyTag(PropertyLikeParse.Property, indent) as JSDocTypeTag | JSDocPropertyTag | JSDocTemplateTag | false; - } - - function parseChildParameterOrPropertyTag(target: PropertyLikeParse, indent: number, name?: EntityName): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | JSDocTemplateTag | false { + return parseChildParameterOrPropertyTag( + PropertyLikeParse.Property, + indent, + ) as JSDocTypeTag | JSDocPropertyTag | JSDocTemplateTag | false; + } + + function parseChildParameterOrPropertyTag( + target: PropertyLikeParse, + indent: number, + name?: EntityName, + ): + | JSDocTypeTag + | JSDocPropertyTag + | JSDocParameterTag + | JSDocTemplateTag + | false + { let canParseTag = true; let seenAsterisk = false; while (true) { @@ -9633,8 +14252,17 @@ namespace Parser { if (canParseTag) { const child = tryParseChildTag(target, indent); if ( - child && (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) && - name && (isIdentifierNode(child.name) || !escapedTextsEqual(name, child.name.left)) + child && + (child.kind === + SyntaxKind.JSDocParameterTag || + child.kind === + SyntaxKind.JSDocPropertyTag) && + name && + (isIdentifierNode(child.name) || + !escapedTextsEqual( + name, + child.name.left, + )) ) { return false; } @@ -9661,7 +14289,16 @@ namespace Parser { } } - function tryParseChildTag(target: PropertyLikeParse, indent: number): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | JSDocTemplateTag | false { + function tryParseChildTag( + target: PropertyLikeParse, + indent: number, + ): + | JSDocTypeTag + | JSDocPropertyTag + | JSDocParameterTag + | JSDocTemplateTag + | false + { Debug.assert(token() === SyntaxKind.AtToken); const start = scanner.getTokenFullStart(); nextTokenJSDoc(); @@ -9671,7 +14308,10 @@ namespace Parser { let t: PropertyLikeParse; switch (tagName.escapedText) { case "type": - return target === PropertyLikeParse.Property && parseTypeTag(start, tagName); + return ( + target === PropertyLikeParse.Property && + parseTypeTag(start, tagName) + ); case "prop": case "property": t = PropertyLikeParse.Property; @@ -9679,39 +14319,65 @@ namespace Parser { case "arg": case "argument": case "param": - t = PropertyLikeParse.Parameter | PropertyLikeParse.CallbackParameter; + t = PropertyLikeParse.Parameter | + PropertyLikeParse.CallbackParameter; break; case "template": - return parseTemplateTag(start, tagName, indent, indentText); + return parseTemplateTag( + start, + tagName, + indent, + indentText, + ); default: return false; } if (!(target & t)) { return false; } - return parseParameterOrPropertyTag(start, tagName, target, indent); + return parseParameterOrPropertyTag( + start, + tagName, + target, + indent, + ); } function parseTemplateTagTypeParameter() { const typeParameterPos = getNodePos(); - const isBracketed = parseOptionalJsdoc(SyntaxKind.OpenBracketToken); + const isBracketed = parseOptionalJsdoc( + SyntaxKind.OpenBracketToken, + ); if (isBracketed) { skipWhitespace(); } - const name = parseJSDocIdentifierName(Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces); + const name = parseJSDocIdentifierName( + Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces, + ); let defaultType: TypeNode | undefined; if (isBracketed) { skipWhitespace(); parseExpected(SyntaxKind.EqualsToken); - defaultType = doInsideOfContext(NodeFlags.JSDoc, parseJSDocType); + defaultType = doInsideOfContext( + NodeFlags.JSDoc, + parseJSDocType, + ); parseExpected(SyntaxKind.CloseBracketToken); } if (nodeIsMissing(name)) { return undefined; } - return finishNode(factory.createTypeParameterDeclaration(/*modifiers*/ undefined, name, /*constraint*/ undefined, defaultType), typeParameterPos); + return finishNode( + factory.createTypeParameterDeclaration( + /*modifiers*/ undefined, + name, + /*constraint*/ undefined, + defaultType, + ), + typeParameterPos, + ); } function parseTemplateTagTypeParameters() { @@ -9729,7 +14395,12 @@ namespace Parser { return createNodeArray(typeParameters, pos); } - function parseTemplateTag(start: number, tagName: Identifier, indent: number, indentText: string): JSDocTemplateTag { + function parseTemplateTag( + start: number, + tagName: Identifier, + indent: number, + indentText: string, + ): JSDocTemplateTag { // The template tag looks like one of the following: // @template T,U,V // @template {Constraint} T @@ -9741,9 +14412,24 @@ namespace Parser { // TODO: Determine whether we should enforce this in the checker. // TODO: Consider moving the `constraint` to the first type parameter as we could then remove `getEffectiveConstraintOfTypeParameter`. // TODO: Consider only parsing a single type parameter if there is a constraint. - const constraint = token() === SyntaxKind.OpenBraceToken ? parseJSDocTypeExpression() : undefined; + const constraint = token() === SyntaxKind.OpenBraceToken + ? parseJSDocTypeExpression() + : undefined; const typeParameters = parseTemplateTagTypeParameters(); - return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start); + return finishNode( + factory.createJSDocTemplateTag( + tagName, + constraint, + typeParameters, + parseTrailingTagComments( + start, + getNodePos(), + indent, + indentText, + ), + ), + start, + ); } function parseOptionalJsdoc(t: JSDocSyntaxKind): boolean { @@ -9772,9 +14458,15 @@ namespace Parser { return entity; } - function parseJSDocIdentifierName(message?: DiagnosticMessage): Identifier { + function parseJSDocIdentifierName( + message?: DiagnosticMessage, + ): Identifier { if (!tokenIsIdentifierOrKeyword(token())) { - return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ !message, message || Diagnostics.Identifier_expected); + return createMissingNode( + SyntaxKind.Identifier, + /*reportAtCurrentPosition*/ !message, + message || Diagnostics.Identifier_expected, + ); } identifierCount++; @@ -9782,7 +14474,11 @@ namespace Parser { const end = scanner.getTokenEnd(); const originalKeywordKind = token(); const text = internIdentifier(scanner.getTokenValue()); - const result = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start, end); + const result = finishNode( + factoryCreateIdentifier(text, originalKeywordKind), + start, + end, + ); nextTokenJSDoc(); return result; } @@ -9791,10 +14487,20 @@ namespace Parser { } namespace IncrementalParser { - export function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks: boolean): SourceFile { + export function updateSourceFile( + sourceFile: SourceFile, + newText: string, + textChangeRange: TextChangeRange, + aggressiveChecks: boolean, + ): SourceFile { aggressiveChecks = aggressiveChecks || Debug.shouldAssert(AssertionLevel.Aggressive); - checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks); + checkChangeRange( + sourceFile, + newText, + textChangeRange, + aggressiveChecks, + ); if (textChangeRangeIsUnchanged(textChangeRange)) { // if the text didn't change, then we can just return our current source file as-is. return sourceFile; @@ -9803,7 +14509,16 @@ namespace IncrementalParser { if (sourceFile.statements.length === 0) { // If we don't have any statements in the current source file, then there's no real // way to incrementally parse. So just do a full parse instead. - return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind, sourceFile.setExternalModuleIndicator, sourceFile.jsDocParsingMode); + return Parser.parseSourceFile( + sourceFile.fileName, + newText, + sourceFile.languageVersion, + /*syntaxCursor*/ undefined, + /*setParentNodes*/ true, + sourceFile.scriptKind, + sourceFile.setExternalModuleIndicator, + sourceFile.jsDocParsingMode, + ); } // Make sure we're not trying to incrementally update a source file more than once. Once @@ -9815,7 +14530,7 @@ namespace IncrementalParser { const incrementalSourceFile = sourceFile as Node as IncrementalNode; Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); incrementalSourceFile.hasBeenIncrementallyParsed = true; - Parser.fixupParentReferences(incrementalSourceFile); + Parser.fixupParentReferences(incrementalSourceFile as Node); const oldText = sourceFile.text; const syntaxCursor = createSyntaxCursor(sourceFile); @@ -9827,13 +14542,19 @@ namespace IncrementalParser { // Ensure that extending the affected range only moved the start of the change range // earlier in the file. Debug.assert(changeRange.span.start <= textChangeRange.span.start); - Debug.assert(textSpanEnd(changeRange.span) === textSpanEnd(textChangeRange.span)); - Debug.assert(textSpanEnd(textChangeRangeNewSpan(changeRange)) === textSpanEnd(textChangeRangeNewSpan(textChangeRange))); + Debug.assert( + textSpanEnd(changeRange.span) === textSpanEnd(textChangeRange.span), + ); + Debug.assert( + textSpanEnd(textChangeRangeNewSpan(changeRange)) === + textSpanEnd(textChangeRangeNewSpan(textChangeRange)), + ); // The is the amount the nodes after the edit range need to be adjusted. It can be // positive (if the edit added characters), negative (if the edit deleted characters) // or zero (if this was a pure overwrite with nothing added/removed). - const delta = textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + const delta = textChangeRangeNewSpan(changeRange).length - + changeRange.span.length; // If we added or removed characters during the edit, then we need to go and adjust all // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they @@ -9854,7 +14575,16 @@ namespace IncrementalParser { // // Also, mark any syntax elements that intersect the changed span. We know, up front, // that we cannot reuse these elements. - updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, textSpanEnd(changeRange.span), textSpanEnd(textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks); + updateTokenPositionsAndMarkElements( + incrementalSourceFile, + changeRange.span.start, + textSpanEnd(changeRange.span), + textSpanEnd(textChangeRangeNewSpan(changeRange)), + delta, + oldText, + newText, + aggressiveChecks, + ); // Now that we've set up our internal incremental state just proceed and parse the // source file in the normal fashion. When possible the parser will retrieve and @@ -9866,7 +14596,16 @@ namespace IncrementalParser { // inconsistent tree. Setting the parents on the new tree should be very fast. We // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. - const result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind, sourceFile.setExternalModuleIndicator, sourceFile.jsDocParsingMode); + const result = Parser.parseSourceFile( + sourceFile.fileName, + newText, + sourceFile.languageVersion, + syntaxCursor, + /*setParentNodes*/ true, + sourceFile.scriptKind, + sourceFile.setExternalModuleIndicator, + sourceFile.jsDocParsingMode, + ); result.commentDirectives = getNewCommentDirectives( sourceFile.commentDirectives, result.commentDirectives, @@ -9910,7 +14649,13 @@ namespace IncrementalParser { }; commentDirectives = append(commentDirectives, updatedDirective); if (aggressiveChecks) { - Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end)); + Debug.assert( + oldText.substring(range.pos, range.end) === + newText.substring( + updatedDirective.range.pos, + updatedDirective.range.end, + ), + ); } } // Ignore ranges that fall in change range @@ -9930,9 +14675,30 @@ namespace IncrementalParser { } } - function moveElementEntirelyPastChangeRange(element: IncrementalNode, isArray: false, delta: number, oldText: string, newText: string, aggressiveChecks: boolean): void; - function moveElementEntirelyPastChangeRange(element: IncrementalNodeArray, isArray: true, delta: number, oldText: string, newText: string, aggressiveChecks: boolean): void; - function moveElementEntirelyPastChangeRange(element: IncrementalNode | IncrementalNodeArray, isArray: boolean, delta: number, oldText: string, newText: string, aggressiveChecks: boolean) { + function moveElementEntirelyPastChangeRange( + element: IncrementalNode, + isArray: false, + delta: number, + oldText: string, + newText: string, + aggressiveChecks: boolean, + ): void; + function moveElementEntirelyPastChangeRange( + element: IncrementalNodeArray, + isArray: true, + delta: number, + oldText: string, + newText: string, + aggressiveChecks: boolean, + ): void; + function moveElementEntirelyPastChangeRange( + element: IncrementalNode | IncrementalNodeArray, + isArray: boolean, + delta: number, + oldText: string, + newText: string, + aggressiveChecks: boolean, + ) { if (isArray) { visitArray(element as IncrementalNodeArray); } @@ -9959,7 +14725,11 @@ namespace IncrementalParser { Debug.assert(text === newText.substring(node.pos, node.end)); } - forEachChild(node, visitNode as (node: Node) => void, visitArray as (nodes: NodeArray) => void); + forEachChild( + node, + visitNode as (node: Node) => void, + visitArray as (nodes: NodeArray) => void, + ); if (hasJSDocNodes(node)) { for (const jsDocComment of node.jsDoc!) { visitNode(jsDocComment as Node as IncrementalNode); @@ -9978,7 +14748,7 @@ namespace IncrementalParser { } } - function shouldCheckNode(node: Node) { + function shouldCheckNode(node: IncrementalNode | Node) { switch (node.kind) { case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: @@ -9989,9 +14759,21 @@ namespace IncrementalParser { return false; } - function adjustIntersectingElement(element: IncrementalElement, changeStart: number, changeRangeOldEnd: number, changeRangeNewEnd: number, delta: number) { - Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); - Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + function adjustIntersectingElement( + element: IncrementalElement, + changeStart: number, + changeRangeOldEnd: number, + changeRangeNewEnd: number, + delta: number, + ) { + Debug.assert( + element.end >= changeStart, + "Adjusting an element that was entirely before the change range", + ); + Debug.assert( + element.pos <= changeRangeOldEnd, + "Adjusting an element that was entirely after the change range", + ); Debug.assert(element.pos <= element.end); // We have an element that intersects the change range in some way. It may have its @@ -10047,12 +14829,12 @@ namespace IncrementalParser { // However any element that ended after that will have their pos adjusted to be // at the end of the new range. i.e. any node that ended in the 'Y' range will // be adjusted to have their end at the end of the 'Z' range. - const end = element.end >= changeRangeOldEnd ? + const end = element.end >= changeRangeOldEnd // Element ends after the change range. Always adjust the end pos. - element.end + delta : + ? element.end + delta // Element ends in the change range. The element will keep its position if // possible. Or Move backward to the new-end if it's in the 'Y' range. - Math.min(element.end, changeRangeNewEnd); + : Math.min(element.end, changeRangeNewEnd); Debug.assert(pos <= end); if (element.parent) { @@ -10098,7 +14880,14 @@ namespace IncrementalParser { if (child.pos > changeRangeOldEnd) { // Node is entirely past the change range. We need to move both its pos and // end, forward or backward appropriately. - moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks); + moveElementEntirelyPastChangeRange( + child, + /*isArray*/ false, + delta, + oldText, + newText, + aggressiveChecks, + ); return; } @@ -10111,8 +14900,18 @@ namespace IncrementalParser { child._children = undefined; // Adjust the pos or end (or both) of the intersecting element accordingly. - adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - forEachChild(child, visitNode as (node: Node) => void, visitArray as (nodes: NodeArray) => void); + adjustIntersectingElement( + child, + changeStart, + changeRangeOldEnd, + changeRangeNewEnd, + delta, + ); + forEachChild( + child, + visitNode as (node: Node) => void, + visitArray as (nodes: NodeArray) => void, + ); if (hasJSDocNodes(child)) { for (const jsDocComment of child.jsDoc!) { visitNode(jsDocComment as Node as IncrementalNode); @@ -10131,7 +14930,14 @@ namespace IncrementalParser { if (array.pos > changeRangeOldEnd) { // Array is entirely after the change range. We need to move it, and move any of // its children. - moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks); + moveElementEntirelyPastChangeRange( + array, + /*isArray*/ true, + delta, + oldText, + newText, + aggressiveChecks, + ); return; } @@ -10144,7 +14950,13 @@ namespace IncrementalParser { array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. - adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + adjustIntersectingElement( + array, + changeStart, + changeRangeOldEnd, + changeRangeNewEnd, + delta, + ); for (const node of array) { visitNode(node); } @@ -10156,7 +14968,10 @@ namespace IncrementalParser { } } - function extendToAffectedRange(sourceFile: SourceFile, changeRange: TextChangeRange): TextChangeRange { + function extendToAffectedRange( + sourceFile: SourceFile, + changeRange: TextChangeRange, + ): TextChangeRange { // Consider the following code: // void foo() { /; } // @@ -10175,27 +14990,38 @@ namespace IncrementalParser { // the left by maxLookahead tokens. We only need to do this as long as we're not at the // start of the tree. for (let i = 0; start > 0 && i <= maxLookahead; i++) { - const nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + const nearestNode = findNearestNodeStartingBeforeOrAtPosition( + sourceFile, + start, + ); Debug.assert(nearestNode.pos <= start); const position = nearestNode.pos; start = Math.max(0, position - 1); } - const finalSpan = createTextSpanFromBounds(start, textSpanEnd(changeRange.span)); + const finalSpan = createTextSpanFromBounds( + start, + textSpanEnd(changeRange.span), + ); const finalLength = changeRange.newLength + (changeRange.span.start - start); return createTextChangeRange(finalSpan, finalLength); } - function findNearestNodeStartingBeforeOrAtPosition(sourceFile: SourceFile, position: number): Node { + function findNearestNodeStartingBeforeOrAtPosition( + sourceFile: SourceFile, + position: number, + ): Node { let bestResult: Node = sourceFile; let lastNodeEntirelyBeforePosition: Node | undefined; forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - const lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition); + const lastChildOfLastEntireNodeBeforePosition = getLastDescendant( + lastNodeEntirelyBeforePosition, + ); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } @@ -10273,18 +15099,43 @@ namespace IncrementalParser { } } - function checkChangeRange(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks: boolean) { + function checkChangeRange( + sourceFile: SourceFile, + newText: string, + textChangeRange: TextChangeRange, + aggressiveChecks: boolean, + ) { const oldText = sourceFile.text; if (textChangeRange) { - Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); + Debug.assert( + oldText.length - + textChangeRange.span.length + + textChangeRange.newLength === + newText.length, + ); - if (aggressiveChecks || Debug.shouldAssert(AssertionLevel.VeryAggressive)) { - const oldTextPrefix = oldText.substr(0, textChangeRange.span.start); - const newTextPrefix = newText.substr(0, textChangeRange.span.start); + if ( + aggressiveChecks || + Debug.shouldAssert(AssertionLevel.VeryAggressive) + ) { + const oldTextPrefix = oldText.substr( + 0, + textChangeRange.span.start, + ); + const newTextPrefix = newText.substr( + 0, + textChangeRange.span.start, + ); Debug.assert(oldTextPrefix === newTextPrefix); - const oldTextSuffix = oldText.substring(textSpanEnd(textChangeRange.span), oldText.length); - const newTextSuffix = newText.substring(textSpanEnd(textChangeRangeNewSpan(textChangeRange)), newText.length); + const oldTextSuffix = oldText.substring( + textSpanEnd(textChangeRange.span), + oldText.length, + ); + const newTextSuffix = newText.substring( + textSpanEnd(textChangeRangeNewSpan(textChangeRange)), + newText.length, + ); Debug.assert(oldTextSuffix === newTextSuffix); } } @@ -10297,7 +15148,7 @@ namespace IncrementalParser { _children: Node[] | undefined; } - export interface IncrementalNode extends Node, IncrementalElement { + export interface IncrementalNode extends NodeBase, IncrementalElement { hasBeenIncrementallyParsed: boolean; } @@ -10330,7 +15181,11 @@ namespace IncrementalParser { // Much of the time the parser will need the very next node in the array that // we just returned a node from.So just simply check for that case and move // forward in the array instead of searching for the node again. - if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) { + if ( + current && + current.end === position && + currentArrayIndex < currentArray.length - 1 + ) { currentArrayIndex++; current = currentArray[currentArrayIndex]; } @@ -10396,7 +15251,10 @@ namespace IncrementalParser { return true; } else { - if (child.pos < position && position < child.end) { + if ( + child.pos < position && + position < child.end + ) { // Position in somewhere within this child. Search in it and // stop searching in this array. forEachChild(child, visitNode, visitArray); @@ -10420,10 +15278,19 @@ namespace IncrementalParser { /** @internal */ export function isDeclarationFileName(fileName: string): boolean { - return fileExtensionIsOneOf(fileName, supportedDeclarationExtensions) || (fileExtensionIs(fileName, Extension.Ts) && getBaseFileName(fileName).includes(".d.")); + return ( + fileExtensionIsOneOf(fileName, supportedDeclarationExtensions) || + (fileExtensionIs(fileName, Extension.Ts) && + getBaseFileName(fileName).includes(".d.")) + ); } -function parseResolutionMode(mode: string | undefined, pos: number, end: number, reportDiagnostic: PragmaDiagnosticReporter): ResolutionMode { +function parseResolutionMode( + mode: string | undefined, + pos: number, + end: number, + reportDiagnostic: PragmaDiagnosticReporter, +): ResolutionMode { if (!mode) { return undefined; } @@ -10433,12 +15300,19 @@ function parseResolutionMode(mode: string | undefined, pos: number, end: number, if (mode === "require") { return ModuleKind.CommonJS; } - reportDiagnostic(pos, end - pos, Diagnostics.resolution_mode_should_be_either_require_or_import); + reportDiagnostic( + pos, + end - pos, + Diagnostics.resolution_mode_should_be_either_require_or_import, + ); return undefined; } /** @internal */ -export function processCommentPragmas(context: PragmaContext, sourceText: string): void { +export function processCommentPragmas( + context: PragmaContext, + sourceText: string, +): void { const pragmas: PragmaPseudoMapEntry[] = []; for (const range of getLeadingCommentRanges(sourceText, 0) || emptyArray) { @@ -10463,17 +15337,25 @@ export function processCommentPragmas(context: PragmaContext, sourceText: string } /** @internal */ -export type PragmaDiagnosticReporter = (pos: number, length: number, message: DiagnosticMessage) => void; +export type PragmaDiagnosticReporter = ( + pos: number, + length: number, + message: DiagnosticMessage, +) => void; /** @internal */ -export function processPragmasIntoFields(context: PragmaContext, reportDiagnostic: PragmaDiagnosticReporter): void { +export function processPragmasIntoFields( + context: PragmaContext, + reportDiagnostic: PragmaDiagnosticReporter, +): void { context.checkJsDirective = undefined; context.referencedFiles = []; context.typeReferenceDirectives = []; context.libReferenceDirectives = []; context.amdDependencies = []; context.hasNoDefaultLib = false; - context.pragmas!.forEach((entryOrList, key) => { // TODO: GH#18217 + context.pragmas!.forEach((entryOrList, key) => { + // TODO: GH#18217 // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :( switch (key) { @@ -10481,25 +15363,55 @@ export function processPragmasIntoFields(context: PragmaContext, reportDiagnosti const referencedFiles = context.referencedFiles; const typeReferenceDirectives = context.typeReferenceDirectives; const libReferenceDirectives = context.libReferenceDirectives; - forEach(toArray(entryOrList) as PragmaPseudoMap["reference"][], arg => { - const { types, lib, path, ["resolution-mode"]: res } = arg.arguments; - if (arg.arguments["no-default-lib"]) { - context.hasNoDefaultLib = true; - } - else if (types) { - const parsed = parseResolutionMode(res, types.pos, types.end, reportDiagnostic); - typeReferenceDirectives.push({ pos: types.pos, end: types.end, fileName: types.value, ...(parsed ? { resolutionMode: parsed } : {}) }); - } - else if (lib) { - libReferenceDirectives.push({ pos: lib.pos, end: lib.end, fileName: lib.value }); - } - else if (path) { - referencedFiles.push({ pos: path.pos, end: path.end, fileName: path.value }); - } - else { - reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, Diagnostics.Invalid_reference_directive_syntax); - } - }); + forEach( + toArray(entryOrList) as PragmaPseudoMap["reference"][], + arg => { + const { + types, + lib, + path, + ["resolution-mode"]: res, + } = arg.arguments; + if (arg.arguments["no-default-lib"]) { + context.hasNoDefaultLib = true; + } + else if (types) { + const parsed = parseResolutionMode( + res, + types.pos, + types.end, + reportDiagnostic, + ); + typeReferenceDirectives.push({ + pos: types.pos, + end: types.end, + fileName: types.value, + ...(parsed ? { resolutionMode: parsed } : {}), + }); + } + else if (lib) { + libReferenceDirectives.push({ + pos: lib.pos, + end: lib.end, + fileName: lib.value, + }); + } + else if (path) { + referencedFiles.push({ + pos: path.pos, + end: path.end, + fileName: path.value, + }); + } + else { + reportDiagnostic( + arg.range.pos, + arg.range.end - arg.range.pos, + Diagnostics.Invalid_reference_directive_syntax, + ); + } + }, + ); break; } case "amd-dependency": { @@ -10514,13 +15426,21 @@ export function processPragmasIntoFields(context: PragmaContext, reportDiagnosti for (const entry of entryOrList) { if (context.moduleName) { // TODO: It's probably fine to issue this diagnostic on all instances of the pragma - reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments); + reportDiagnostic( + entry.range.pos, + entry.range.end - entry.range.pos, + Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments, + ); } - context.moduleName = (entry as PragmaPseudoMap["amd-module"]).arguments.name; + context.moduleName = ( + entry as PragmaPseudoMap["amd-module"] + ).arguments.name; } } else { - context.moduleName = (entryOrList as PragmaPseudoMap["amd-module"]).arguments.name; + context.moduleName = ( + entryOrList as PragmaPseudoMap["amd-module"] + ).arguments.name; } break; } @@ -10528,7 +15448,10 @@ export function processPragmasIntoFields(context: PragmaContext, reportDiagnosti case "ts-check": { // _last_ of either nocheck or check in a file is the "winner" forEach(toArray(entryOrList), entry => { - if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) { + if ( + !context.checkJsDirective || + entry.range.pos > context.checkJsDirective.pos + ) { context.checkJsDirective = { enabled: key === "ts-check", end: entry.range.end, @@ -10554,15 +15477,23 @@ function getNamedArgRegEx(name: string): RegExp { if (namedArgRegExCache.has(name)) { return namedArgRegExCache.get(name)!; } - const result = new RegExp(`(\\s${name}\\s*=\\s*)(?:(?:'([^']*)')|(?:"([^"]*)"))`, "im"); + const result = new RegExp( + `(\\s${name}\\s*=\\s*)(?:(?:'([^']*)')|(?:"([^"]*)"))`, + "im", + ); namedArgRegExCache.set(name, result); return result; } const tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; const singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)(.*)\s*$/im; -function extractPragmas(pragmas: PragmaPseudoMapEntry[], range: CommentRange, text: string) { - const tripleSlash = range.kind === SyntaxKind.SingleLineCommentTrivia && tripleSlashXMLCommentStartRegEx.exec(text); +function extractPragmas( + pragmas: PragmaPseudoMapEntry[], + range: CommentRange, + text: string, +) { + const tripleSlash = range.kind === SyntaxKind.SingleLineCommentTrivia && + tripleSlashXMLCommentStartRegEx.exec(text); if (tripleSlash) { const name = tripleSlash[1].toLowerCase() as keyof PragmaPseudoMap; // Technically unsafe cast, but we do it so the below check to make it safe typechecks const pragma = commentPragmas[name] as PragmaDefinition; @@ -10570,7 +15501,11 @@ function extractPragmas(pragmas: PragmaPseudoMapEntry[], range: CommentRange, te return; } if (pragma.args) { - const argument: { [index: string]: string | { value: string; pos: number; end: number; }; } = {}; + const argument: { + [index: string]: + | string + | { value: string; pos: number; end: number; }; + } = {}; for (const arg of pragma.args) { const matcher = getNamedArgRegEx(arg.name); const matchResult = matcher.exec(text); @@ -10580,7 +15515,10 @@ function extractPragmas(pragmas: PragmaPseudoMapEntry[], range: CommentRange, te else if (matchResult) { const value = matchResult[2] || matchResult[3]; if (arg.captureSpan) { - const startPos = range.pos + matchResult.index + matchResult[1].length + 1; + const startPos = range.pos + + matchResult.index + + matchResult[1].length + + 1; argument[arg.name] = { value, pos: startPos, @@ -10592,29 +15530,51 @@ function extractPragmas(pragmas: PragmaPseudoMapEntry[], range: CommentRange, te } } } - pragmas.push({ name, args: { arguments: argument, range } } as PragmaPseudoMapEntry); + pragmas.push({ + name, + args: { arguments: argument, range }, + } as PragmaPseudoMapEntry); } else { - pragmas.push({ name, args: { arguments: {}, range } } as PragmaPseudoMapEntry); + pragmas.push({ + name, + args: { arguments: {}, range }, + } as PragmaPseudoMapEntry); } return; } - const singleLine = range.kind === SyntaxKind.SingleLineCommentTrivia && singleLinePragmaRegEx.exec(text); + const singleLine = range.kind === SyntaxKind.SingleLineCommentTrivia && + singleLinePragmaRegEx.exec(text); if (singleLine) { - return addPragmaForMatch(pragmas, range, PragmaKindFlags.SingleLine, singleLine); + return addPragmaForMatch( + pragmas, + range, + PragmaKindFlags.SingleLine, + singleLine, + ); } if (range.kind === SyntaxKind.MultiLineCommentTrivia) { const multiLinePragmaRegEx = /@(\S+)(\s+.*)?$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating) let multiLineMatch: RegExpExecArray | null; - while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { - addPragmaForMatch(pragmas, range, PragmaKindFlags.MultiLine, multiLineMatch); + while ((multiLineMatch = multiLinePragmaRegEx.exec(text))) { + addPragmaForMatch( + pragmas, + range, + PragmaKindFlags.MultiLine, + multiLineMatch, + ); } } } -function addPragmaForMatch(pragmas: PragmaPseudoMapEntry[], range: CommentRange, kind: PragmaKindFlags, match: RegExpExecArray) { +function addPragmaForMatch( + pragmas: PragmaPseudoMapEntry[], + range: CommentRange, + kind: PragmaKindFlags, + match: RegExpExecArray, +) { if (!match) return; const name = match[1].toLowerCase() as keyof PragmaPseudoMap; // Technically unsafe cast, but we do it so they below check to make it safe typechecks const pragma = commentPragmas[name] as PragmaDefinition; @@ -10624,11 +15584,17 @@ function addPragmaForMatch(pragmas: PragmaPseudoMapEntry[], range: CommentRange, const args = match[2]; // Split on spaces and match up positionally with definition const argument = getNamedPragmaArguments(pragma, args); if (argument === "fail") return; // Missing required argument, fail to parse it - pragmas.push({ name, args: { arguments: argument, range } } as PragmaPseudoMapEntry); + pragmas.push({ + name, + args: { arguments: argument, range }, + } as PragmaPseudoMapEntry); return; } -function getNamedPragmaArguments(pragma: PragmaDefinition, text: string | undefined): { [index: string]: string; } | "fail" { +function getNamedPragmaArguments( + pragma: PragmaDefinition, + text: string | undefined, +): { [index: string]: string; } | "fail" { if (!text) return {}; if (!pragma.args) return {}; const args = text.trim().split(/\s+/); @@ -10639,7 +15605,9 @@ function getNamedPragmaArguments(pragma: PragmaDefinition, text: string | undefi return "fail"; } if (argument.captureSpan) { - return Debug.fail("Capture spans not yet implemented for non-xml pragmas"); + return Debug.fail( + "Capture spans not yet implemented for non-xml pragmas", + ); } argMap[argument.name] = args[i]; } @@ -10647,7 +15615,10 @@ function getNamedPragmaArguments(pragma: PragmaDefinition, text: string | undefi } /** @internal */ -export function tagNamesAreEquivalent(lhs: JsxTagNameExpression, rhs: JsxTagNameExpression): boolean { +export function tagNamesAreEquivalent( + lhs: JsxTagNameExpression, + rhs: JsxTagNameExpression, +): boolean { if (lhs.kind !== rhs.kind) { return false; } @@ -10661,13 +15632,23 @@ export function tagNamesAreEquivalent(lhs: JsxTagNameExpression, rhs: JsxTagName } if (lhs.kind === SyntaxKind.JsxNamespacedName) { - return lhs.namespace.escapedText === (rhs as JsxNamespacedName).namespace.escapedText && - lhs.name.escapedText === (rhs as JsxNamespacedName).name.escapedText; + return ( + lhs.namespace.escapedText === + (rhs as JsxNamespacedName).namespace.escapedText && + lhs.name.escapedText === (rhs as JsxNamespacedName).name.escapedText + ); } // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element - return (lhs as PropertyAccessExpression).name.escapedText === (rhs as PropertyAccessExpression).name.escapedText && - tagNamesAreEquivalent((lhs as PropertyAccessExpression).expression as JsxTagNameExpression, (rhs as PropertyAccessExpression).expression as JsxTagNameExpression); + return ( + (lhs as PropertyAccessExpression).name.escapedText === + (rhs as PropertyAccessExpression).name.escapedText && + tagNamesAreEquivalent( + (lhs as PropertyAccessExpression) + .expression as JsxTagNameExpression, + (rhs as PropertyAccessExpression).expression as JsxTagNameExpression, + ) + ); } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 04fc89a37d0f0..dd2a2b90584c7 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -6,7 +6,6 @@ import { append, arrayFrom, arrayIsEqualTo, - AsExpression, BuilderProgram, CancellationToken, canHaveDecorators, @@ -75,7 +74,6 @@ import { equateStringsCaseInsensitive, equateStringsCaseSensitive, explainIfFileIsRedirectAndImpliedFormat, - ExportAssignment, ExportDeclaration, Extension, extensionFromPath, @@ -163,11 +161,9 @@ import { hasProperty, hasSyntacticModifier, hasZeroOrOneAsteriskCharacter, - HeritageClause, Identifier, identity, ImportAttributes, - ImportClause, ImportDeclaration, ImportOrExportSpecifier, InputFiles, @@ -218,7 +214,6 @@ import { mapDefinedIterator, maybeBind, memoize, - MethodDeclaration, ModeAwareCache, ModeAwareCacheKey, ModifierFlags, @@ -283,7 +278,6 @@ import { resolveTypeReferenceDirective, returnFalse, returnUndefined, - SatisfiesExpression, ScriptKind, ScriptTarget, setParent, @@ -2988,7 +2982,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg case SyntaxKind.Parameter: case SyntaxKind.PropertyDeclaration: case SyntaxKind.MethodDeclaration: - if ((parent as ParameterDeclaration | PropertyDeclaration | MethodDeclaration).questionToken === node) { + if (parent.questionToken === node) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); return "skip"; } @@ -3010,13 +3004,13 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg switch (node.kind) { case SyntaxKind.ImportClause: - if ((node as ImportClause).isTypeOnly) { + if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(parent, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type")); return "skip"; } break; case SyntaxKind.ExportDeclaration: - if ((node as ExportDeclaration).isTypeOnly) { + if (node.isTypeOnly) { diagnostics.push(createDiagnosticForNode(node, Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type")); return "skip"; } @@ -3032,13 +3026,13 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg diagnostics.push(createDiagnosticForNode(node, Diagnostics.import_can_only_be_used_in_TypeScript_files)); return "skip"; case SyntaxKind.ExportAssignment: - if ((node as ExportAssignment).isExportEquals) { + if (node.isExportEquals) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.export_can_only_be_used_in_TypeScript_files)); return "skip"; } break; case SyntaxKind.HeritageClause: - const heritageClause = node as HeritageClause; + const heritageClause = node; if (heritageClause.token === SyntaxKind.ImplementsKeyword) { diagnostics.push(createDiagnosticForNode(node, Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files)); return "skip"; @@ -3073,10 +3067,10 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg diagnostics.push(createDiagnosticForNode(node, Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files)); return "skip"; case SyntaxKind.AsExpression: - diagnostics.push(createDiagnosticForNode((node as AsExpression).type, Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); + diagnostics.push(createDiagnosticForNode(node.type, Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files)); return "skip"; case SyntaxKind.SatisfiesExpression: - diagnostics.push(createDiagnosticForNode((node as SatisfiesExpression).type, Diagnostics.Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files)); + diagnostics.push(createDiagnosticForNode(node.type, Diagnostics.Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files)); return "skip"; case SyntaxKind.TypeAssertionExpression: Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX. @@ -3146,7 +3140,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg break; case SyntaxKind.PropertyDeclaration: // Check modifiers of property declaration - if (nodes === (parent as PropertyDeclaration).modifiers) { + if (nodes === parent.modifiers) { for (const modifier of nodes as NodeArray) { if ( isModifier(modifier) @@ -3161,7 +3155,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg break; case SyntaxKind.Parameter: // Check modifiers of parameter declaration - if (nodes === (parent as ParameterDeclaration).modifiers && some(nodes, isModifier)) { + if (nodes === parent.modifiers && some(nodes, isModifier)) { diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files)); return "skip"; } @@ -3436,7 +3430,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg } }; while (true) { - const child = isJavaScriptFile && hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild); + const child: Node | undefined = isJavaScriptFile && hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild); if (!child) { return current; } diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index 3a37fe0f2d3f4..0e1dd4ec5367a 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -353,8 +353,8 @@ export function transformNodes(resolver: EmitResolver | undefine diagnostics, }; - function transformRoot(node: T) { - return node && (!isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node; + function transformRoot(node: Node): T { + return (node && (!isSourceFile(node) || !node.isDeclarationFile) ? (transformation(node as T)) : node) as T; } /** diff --git a/src/compiler/transformers/classFields.ts b/src/compiler/transformers/classFields.ts index ede44357f242d..2c5f85e63a7c8 100644 --- a/src/compiler/transformers/classFields.ts +++ b/src/compiler/transformers/classFields.ts @@ -338,8 +338,15 @@ const enum ClassFacts { WillHoistInitializersToConstructor = 1 << 4, } -type LexicalEnv = LexicalEnvironment; -type PrivateEnv = PrivateEnvironment; +type LexicalEnv = LexicalEnvironment< + ClassLexicalEnvironment | undefined, + PrivateEnvironmentData, + PrivateIdentifierInfo +>; +type PrivateEnv = PrivateEnvironment< + PrivateEnvironmentData, + PrivateIdentifierInfo +>; /** * Transforms ECMAScript Class Syntax. @@ -350,7 +357,9 @@ type PrivateEnv = PrivateEnvironment SourceFile | Bundle { +export function transformClassFields( + context: TransformationContext, +): (x: SourceFile | Bundle) => SourceFile | Bundle { const { factory, getEmitHelperFactory: emitHelpers, @@ -371,16 +380,19 @@ export function transformClassFields(context: TransformationContext): (x: Source // Transform field initializers using Define semantics when `useDefineForClassFields: true` and target < ES2022. const shouldTransformInitializersUsingDefine = useDefineForClassFields && languageVersion < ScriptTarget.ES2022; - const shouldTransformInitializers = shouldTransformInitializersUsingSet || shouldTransformInitializersUsingDefine; + const shouldTransformInitializers = shouldTransformInitializersUsingSet || + shouldTransformInitializersUsingDefine; // We need to transform private members and class static blocks when target < ES2022. const shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < ScriptTarget.ES2022; // We need to transform `accessor` fields when target < ESNext. // We may need to transform `accessor` fields when `useDefineForClassFields: false` - const shouldTransformAutoAccessors = languageVersion < ScriptTarget.ESNext ? Ternary.True : - !useDefineForClassFields ? Ternary.Maybe : - Ternary.False; + const shouldTransformAutoAccessors = languageVersion < ScriptTarget.ESNext + ? Ternary.True + : !useDefineForClassFields + ? Ternary.Maybe + : Ternary.False; // We need to transform `this` in a static initializer into a reference to the class // when target < ES2022 since the assignment will be moved outside of the class body. @@ -388,7 +400,8 @@ export function transformClassFields(context: TransformationContext): (x: Source // We don't need to transform `super` property access when target <= ES5 because // the es2015 transformation handles those. - const shouldTransformSuperInStaticInitializers = shouldTransformThisInStaticInitializers && languageVersion >= ScriptTarget.ES2015; + const shouldTransformSuperInStaticInitializers = shouldTransformThisInStaticInitializers && + languageVersion >= ScriptTarget.ES2015; const shouldTransformAnything = shouldTransformInitializers || shouldTransformPrivateElementsOrClassStaticBlocks || @@ -436,8 +449,14 @@ export function transformClassFields(context: TransformationContext): (x: Source } lexicalEnvironment = undefined; - shouldTransformPrivateStaticElementsInFile = !!(getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements); - if (!shouldTransformAnything && !shouldTransformPrivateStaticElementsInFile) { + shouldTransformPrivateStaticElementsInFile = !!( + getInternalEmitFlags(node) & + InternalEmitFlags.TransformPrivateStaticElements + ); + if ( + !shouldTransformAnything && + !shouldTransformPrivateStaticElementsInFile + ) { return node; } @@ -446,10 +465,14 @@ export function transformClassFields(context: TransformationContext): (x: Source return visited; } - function modifierVisitor(node: ModifierLike): VisitResult { + function modifierVisitor( + node: ModifierLike, + ): VisitResult { switch (node.kind) { case SyntaxKind.AccessorKeyword: - return shouldTransformAutoAccessorsInCurrentClass() ? undefined : node; + return shouldTransformAutoAccessorsInCurrentClass() + ? undefined + : node; default: return tryCast(node, isModifier); } @@ -467,45 +490,60 @@ export function transformClassFields(context: TransformationContext): (x: Source case SyntaxKind.AccessorKeyword: return Debug.fail("Use `modifierVisitor` instead."); case SyntaxKind.ClassDeclaration: - return visitClassDeclaration(node as ClassDeclaration); + return visitClassDeclaration(node); case SyntaxKind.ClassExpression: - return visitClassExpression(node as ClassExpression); + return visitClassExpression(node); case SyntaxKind.ClassStaticBlockDeclaration: case SyntaxKind.PropertyDeclaration: return Debug.fail("Use `classElementVisitor` instead."); case SyntaxKind.PropertyAssignment: - return visitPropertyAssignment(node as PropertyAssignment); + return visitPropertyAssignment(node); case SyntaxKind.VariableStatement: - return visitVariableStatement(node as VariableStatement); + return visitVariableStatement(node); case SyntaxKind.VariableDeclaration: - return visitVariableDeclaration(node as VariableDeclaration); + return visitVariableDeclaration(node); case SyntaxKind.Parameter: - return visitParameterDeclaration(node as ParameterDeclaration); + return visitParameterDeclaration(node); case SyntaxKind.BindingElement: - return visitBindingElement(node as BindingElement); + return visitBindingElement(node); case SyntaxKind.ExportAssignment: - return visitExportAssignment(node as ExportAssignment); + return visitExportAssignment(node); case SyntaxKind.PrivateIdentifier: - return visitPrivateIdentifier(node as PrivateIdentifier); + return visitPrivateIdentifier(node); case SyntaxKind.PropertyAccessExpression: - return visitPropertyAccessExpression(node as PropertyAccessExpression); + return visitPropertyAccessExpression( + node, + ); case SyntaxKind.ElementAccessExpression: - return visitElementAccessExpression(node as ElementAccessExpression); + return visitElementAccessExpression( + node, + ); case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.PostfixUnaryExpression: - return visitPreOrPostfixUnaryExpression(node as PrefixUnaryExpression | PostfixUnaryExpression, /*discarded*/ false); + return visitPreOrPostfixUnaryExpression( + node, + /*discarded*/ false, + ); case SyntaxKind.BinaryExpression: - return visitBinaryExpression(node as BinaryExpression, /*discarded*/ false); + return visitBinaryExpression( + node, + /*discarded*/ false, + ); case SyntaxKind.ParenthesizedExpression: - return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false); + return visitParenthesizedExpression( + node, + /*discarded*/ false, + ); case SyntaxKind.CallExpression: - return visitCallExpression(node as CallExpression); + return visitCallExpression(node); case SyntaxKind.ExpressionStatement: - return visitExpressionStatement(node as ExpressionStatement); + return visitExpressionStatement(node); case SyntaxKind.TaggedTemplateExpression: - return visitTaggedTemplateExpression(node as TaggedTemplateExpression); + return visitTaggedTemplateExpression( + node, + ); case SyntaxKind.ForStatement: - return visitForStatement(node as ForStatement); + return visitForStatement(node); case SyntaxKind.ThisKeyword: return visitThisExpression(node as ThisExpression); case SyntaxKind.FunctionDeclaration: @@ -522,7 +560,7 @@ export function transformClassFields(context: TransformationContext): (x: Source case SyntaxKind.SetAccessor: { // If we are descending into a class element, set the class element return setCurrentClassElementAnd( - node as ConstructorDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration, + node, fallbackVisitor, node, ); @@ -543,13 +581,25 @@ export function transformClassFields(context: TransformationContext): (x: Source switch (node.kind) { case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.PostfixUnaryExpression: - return visitPreOrPostfixUnaryExpression(node as PrefixUnaryExpression | PostfixUnaryExpression, /*discarded*/ true); + return visitPreOrPostfixUnaryExpression( + node, + /*discarded*/ true, + ); case SyntaxKind.BinaryExpression: - return visitBinaryExpression(node as BinaryExpression, /*discarded*/ true); + return visitBinaryExpression( + node, + /*discarded*/ true, + ); case SyntaxKind.CommaListExpression: - return visitCommaListExpression(node as CommaListExpression, /*discarded*/ true); + return visitCommaListExpression( + node, + /*discarded*/ true, + ); case SyntaxKind.ParenthesizedExpression: - return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ true); + return visitParenthesizedExpression( + node, + /*discarded*/ true, + ); default: return visitor(node); } @@ -563,7 +613,9 @@ export function transformClassFields(context: TransformationContext): (x: Source case SyntaxKind.HeritageClause: return visitEachChild(node, heritageClauseVisitor, context); case SyntaxKind.ExpressionWithTypeArguments: - return visitExpressionWithTypeArgumentsInHeritageClause(node as ExpressionWithTypeArguments); + return visitExpressionWithTypeArgumentsInHeritageClause( + node, + ); default: return visitor(node); } @@ -589,9 +641,9 @@ export function transformClassFields(context: TransformationContext): (x: Source switch (node.kind) { case SyntaxKind.Constructor: return setCurrentClassElementAnd( - node as ConstructorDeclaration, + node, visitConstructorDeclaration, - node as ConstructorDeclaration, + node, ); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: @@ -603,22 +655,24 @@ export function transformClassFields(context: TransformationContext): (x: Source ); case SyntaxKind.PropertyDeclaration: return setCurrentClassElementAnd( - node as PropertyDeclaration, + node, visitPropertyDeclaration, - node as PropertyDeclaration, + node, ); case SyntaxKind.ClassStaticBlockDeclaration: return setCurrentClassElementAnd( - node as ClassStaticBlockDeclaration, + node, visitClassStaticBlockDeclaration, - node as ClassStaticBlockDeclaration, + node, ); case SyntaxKind.ComputedPropertyName: - return visitComputedPropertyName(node as ComputedPropertyName); + return visitComputedPropertyName(node); case SyntaxKind.SemicolonClassElement: return node; default: - return isModifierLike(node) ? modifierVisitor(node) : visitor(node); + return isModifierLike(node) + ? modifierVisitor(node) + : visitor(node); } } @@ -628,7 +682,7 @@ export function transformClassFields(context: TransformationContext): (x: Source function propertyNameVisitor(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.ComputedPropertyName: - return visitComputedPropertyName(node as ComputedPropertyName); + return visitComputedPropertyName(node); default: return visitor(node); } @@ -640,12 +694,15 @@ export function transformClassFields(context: TransformationContext): (x: Source function accessorFieldResultVisitor(node: Node) { switch (node.kind) { case SyntaxKind.PropertyDeclaration: - return transformFieldInitializer(node as PropertyDeclaration); + return transformFieldInitializer(node); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: return classElementVisitor(node); default: - Debug.assertMissingNode(node, "Expected node to either be a PropertyDeclaration, GetAccessorDeclaration, or SetAccessorDeclaration"); + Debug.assertMissingNode( + node, + "Expected node to either be a PropertyDeclaration, GetAccessorDeclaration, or SetAccessorDeclaration", + ); break; } } @@ -669,12 +726,17 @@ export function transformClassFields(context: TransformationContext): (x: Source /** * Visits `#id in expr` */ - function transformPrivateIdentifierInInExpression(node: PrivateIdentifierInExpression) { + function transformPrivateIdentifierInInExpression( + node: PrivateIdentifierInExpression, + ) { const info = accessPrivateIdentifier(node.left); if (info) { const receiver = visitNode(node.right, visitor, isExpression); return setOriginalNode( - emitHelpers().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver), + emitHelpers().createClassPrivateFieldInHelper( + info.brandCheckIdentifier, + receiver, + ), node, ); } @@ -703,9 +765,9 @@ export function transformClassFields(context: TransformationContext): (x: Source pendingStatements = []; const visitedNode = visitEachChild(node, visitor, context); - const statement = some(pendingStatements) ? - [visitedNode, ...pendingStatements] : - visitedNode; + const statement = some(pendingStatements) + ? [visitedNode, ...pendingStatements] + : visitedNode; pendingStatements = savedPendingStatements; return statement; @@ -792,7 +854,12 @@ export function transformClassFields(context: TransformationContext): (x: Source // is `""`. if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - node = transformNamedEvaluation(context, node, /*ignoreEmptyStringLiteral*/ true, node.isExportEquals ? "" : "default"); + node = transformNamedEvaluation( + context, + node, + /*ignoreEmptyStringLiteral*/ true, + node.isExportEquals ? "" : "default", + ); } return visitEachChild(node, visitor, context); @@ -802,7 +869,10 @@ export function transformClassFields(context: TransformationContext): (x: Source if (some(pendingExpressions)) { if (isParenthesizedExpression(expression)) { pendingExpressions.push(expression.expression); - expression = factory.updateParenthesizedExpression(expression, factory.inlineExpressions(pendingExpressions)); + expression = factory.updateParenthesizedExpression( + expression, + factory.inlineExpressions(pendingExpressions), + ); } else { pendingExpressions.push(expression); @@ -815,7 +885,10 @@ export function transformClassFields(context: TransformationContext): (x: Source function visitComputedPropertyName(node: ComputedPropertyName) { const expression = visitNode(node.expression, visitor, isExpression); - return factory.updateComputedPropertyName(node, injectPendingExpressions(expression)); + return factory.updateComputedPropertyName( + node, + injectPendingExpressions(expression), + ); } function visitConstructorDeclaration(node: ConstructorDeclaration) { @@ -825,16 +898,30 @@ export function transformClassFields(context: TransformationContext): (x: Source return fallbackVisitor(node); } - function shouldTransformClassElementToWeakMap(node: PrivateIdentifierMethodDeclaration | PrivateIdentifierAccessorDeclaration | PrivateIdentifierPropertyDeclaration) { + function shouldTransformClassElementToWeakMap( + node: + | PrivateIdentifierMethodDeclaration + | PrivateIdentifierAccessorDeclaration + | PrivateIdentifierPropertyDeclaration, + ) { if (shouldTransformPrivateElementsOrClassStaticBlocks) return true; - if (hasStaticModifier(node) && getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements) return true; + if ( + hasStaticModifier(node) && + getInternalEmitFlags(node) & + InternalEmitFlags.TransformPrivateStaticElements + ) return true; return false; } - function visitMethodOrAccessorDeclaration(node: MethodDeclaration | AccessorDeclaration) { + function visitMethodOrAccessorDeclaration( + node: MethodDeclaration | AccessorDeclaration, + ) { Debug.assert(!hasDecorators(node)); - if (!isPrivateIdentifierClassElementDeclaration(node) || !shouldTransformClassElementToWeakMap(node)) { + if ( + !isPrivateIdentifierClassElementDeclaration(node) || + !shouldTransformClassElementToWeakMap(node) + ) { return visitEachChild(node, classElementVisitor, context); } @@ -851,7 +938,13 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.createAssignment( functionName, factory.createFunctionExpression( - filter(node.modifiers, (m): m is Modifier => isModifier(m) && !isStaticModifier(m) && !isAccessorModifier(m)), + filter( + node.modifiers, + (m): m is Modifier => + isModifier(m) && + !isStaticModifier(m) && + !isAccessorModifier(m), + ), node.asteriskToken, functionName, /*typeParameters*/ undefined, @@ -882,7 +975,9 @@ export function transformClassFields(context: TransformationContext): (x: Source return visitor(arg); } - function getHoistedFunctionName(node: MethodDeclaration | AccessorDeclaration) { + function getHoistedFunctionName( + node: MethodDeclaration | AccessorDeclaration, + ) { Debug.assert(isPrivateIdentifier(node.name)); const info = accessPrivateIdentifier(node.name); Debug.assert(info, "Undeclared private name for property declaration."); @@ -903,11 +998,15 @@ export function transformClassFields(context: TransformationContext): (x: Source function getClassThis() { const lex = getClassLexicalEnvironment(); - const classThis = lex.classThis ?? lex.classConstructor ?? currentClassContainer?.name; + const classThis = lex.classThis ?? + lex.classConstructor ?? + currentClassContainer?.name; return Debug.checkDefined(classThis); } - function transformAutoAccessor(node: AutoAccessorPropertyDeclaration): VisitResult { + function transformAutoAccessor( + node: AutoAccessorPropertyDeclaration, + ): VisitResult { // transforms: // accessor x = 1; // into: @@ -923,50 +1022,100 @@ export function transformClassFields(context: TransformationContext): (x: Source const name = node.name; let getterName = name; let setterName = name; - if (isComputedPropertyName(name) && !isSimpleInlineableExpression(name.expression)) { + if ( + isComputedPropertyName(name) && + !isSimpleInlineableExpression(name.expression) + ) { const cacheAssignment = findComputedPropertyNameCacheAssignment(name); if (cacheAssignment) { - getterName = factory.updateComputedPropertyName(name, visitNode(name.expression, visitor, isExpression)); - setterName = factory.updateComputedPropertyName(name, cacheAssignment.left); + getterName = factory.updateComputedPropertyName( + name, + visitNode(name.expression, visitor, isExpression), + ); + setterName = factory.updateComputedPropertyName( + name, + cacheAssignment.left, + ); } else { - const temp = factory.createTempVariable(hoistVariableDeclaration); + const temp = factory.createTempVariable( + hoistVariableDeclaration, + ); setSourceMapRange(temp, name.expression); - const expression = visitNode(name.expression, visitor, isExpression); + const expression = visitNode( + name.expression, + visitor, + isExpression, + ); const assignment = factory.createAssignment(temp, expression); setSourceMapRange(assignment, name.expression); - getterName = factory.updateComputedPropertyName(name, assignment); + getterName = factory.updateComputedPropertyName( + name, + assignment, + ); setterName = factory.updateComputedPropertyName(name, temp); } } - const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); - const backingField = createAccessorPropertyBackingField(factory, node, modifiers, node.initializer); + const modifiers = visitNodes( + node.modifiers, + modifierVisitor, + isModifier, + ); + const backingField = createAccessorPropertyBackingField( + factory, + node, + modifiers, + node.initializer, + ); setOriginalNode(backingField, node); setEmitFlags(backingField, EmitFlags.NoComments); setSourceMapRange(backingField, sourceMapRange); const receiver = isStatic(node) ? getClassThis() : factory.createThis(); - const getter = createAccessorPropertyGetRedirector(factory, node, modifiers, getterName, receiver); + const getter = createAccessorPropertyGetRedirector( + factory, + node, + modifiers, + getterName, + receiver, + ); setOriginalNode(getter, node); setCommentRange(getter, commentRange); setSourceMapRange(getter, sourceMapRange); // create a fresh copy of the modifiers so that we don't duplicate comments - const setterModifiers = factory.createModifiersFromModifierFlags(modifiersToFlags(modifiers)); - const setter = createAccessorPropertySetRedirector(factory, node, setterModifiers, setterName, receiver); + const setterModifiers = factory.createModifiersFromModifierFlags( + modifiersToFlags(modifiers), + ); + const setter = createAccessorPropertySetRedirector( + factory, + node, + setterModifiers, + setterName, + receiver, + ); setOriginalNode(setter, node); setEmitFlags(setter, EmitFlags.NoComments); setSourceMapRange(setter, sourceMapRange); - return visitArray([backingField, getter, setter], accessorFieldResultVisitor, isClassElement); + return visitArray( + [backingField, getter, setter], + accessorFieldResultVisitor, + isClassElement, + ); } - function transformPrivateFieldInitializer(node: PrivateIdentifierPropertyDeclaration) { + function transformPrivateFieldInitializer( + node: PrivateIdentifierPropertyDeclaration, + ) { if (shouldTransformClassElementToWeakMap(node)) { // If we are transforming private elements into WeakMap/WeakSet, we should elide the node. const info = accessPrivateIdentifier(node.name); - Debug.assert(info, "Undeclared private name for property declaration."); + Debug.assert( + info, + "Undeclared private name for property declaration.", + ); // Leave invalid code untransformed if (!info.isValid) { @@ -975,18 +1124,32 @@ export function transformClassFields(context: TransformationContext): (x: Source // If we encounter a valid private static field and we're not transforming // class static blocks, initialize it - if (info.isStatic && !shouldTransformPrivateElementsOrClassStaticBlocks) { + if ( + info.isStatic && + !shouldTransformPrivateElementsOrClassStaticBlocks + ) { // TODO: fix - const statement = transformPropertyOrClassStaticBlock(node, factory.createThis()); + const statement = transformPropertyOrClassStaticBlock( + node, + factory.createThis(), + ); if (statement) { - return factory.createClassStaticBlockDeclaration(factory.createBlock([statement], /*multiLine*/ true)); + return factory.createClassStaticBlockDeclaration( + factory.createBlock([statement], /*multiLine*/ true), + ); } } return undefined; } - if (shouldTransformInitializersUsingSet && !isStatic(node) && lexicalEnvironment?.data && lexicalEnvironment.data.facts & ClassFacts.WillHoistInitializersToConstructor) { + if ( + shouldTransformInitializersUsingSet && + !isStatic(node) && + lexicalEnvironment?.data && + lexicalEnvironment.data.facts & + ClassFacts.WillHoistInitializersToConstructor + ) { // If we are transforming initializers using Set semantics we will elide the initializer as it will // be moved to the constructor to preserve evaluation order next to public instance fields. We don't // need to do this transformation for private static fields since public static fields can be @@ -1016,7 +1179,10 @@ export function transformClassFields(context: TransformationContext): (x: Source } function transformPublicFieldInitializer(node: PropertyDeclaration) { - if (shouldTransformInitializers && !isAutoAccessorPropertyDeclaration(node)) { + if ( + shouldTransformInitializers && + !isAutoAccessorPropertyDeclaration(node) + ) { // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. @@ -1029,8 +1195,14 @@ export function transformClassFields(context: TransformationContext): (x: Source getPendingExpressions().push(...flattenCommaList(expr)); } - if (isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks) { - const initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); + if ( + isStatic(node) && + !shouldTransformPrivateElementsOrClassStaticBlocks + ) { + const initializerStatement = transformPropertyOrClassStaticBlock( + node, + factory.createThis(), + ); if (initializerStatement) { const staticBlock = factory.createClassStaticBlockDeclaration( factory.createBlock([initializerStatement]), @@ -1042,8 +1214,14 @@ export function transformClassFields(context: TransformationContext): (x: Source // Set the comment range for the statement to an empty synthetic range // and drop synthetic comments from the statement to avoid printing them twice. setCommentRange(initializerStatement, { pos: -1, end: -1 }); - setSyntheticLeadingComments(initializerStatement, undefined); - setSyntheticTrailingComments(initializerStatement, undefined); + setSyntheticLeadingComments( + initializerStatement, + undefined, + ); + setSyntheticTrailingComments( + initializerStatement, + undefined, + ); return staticBlock; } } @@ -1062,24 +1240,36 @@ export function transformClassFields(context: TransformationContext): (x: Source } function transformFieldInitializer(node: PropertyDeclaration) { - Debug.assert(!hasDecorators(node), "Decorators should already have been transformed and elided."); - return isPrivateIdentifierClassElementDeclaration(node) ? - transformPrivateFieldInitializer(node) : - transformPublicFieldInitializer(node); + Debug.assert( + !hasDecorators(node), + "Decorators should already have been transformed and elided.", + ); + return isPrivateIdentifierClassElementDeclaration(node) + ? transformPrivateFieldInitializer(node) + : transformPublicFieldInitializer(node); } function shouldTransformAutoAccessorsInCurrentClass() { - return shouldTransformAutoAccessors === Ternary.True || - shouldTransformAutoAccessors === Ternary.Maybe && - !!lexicalEnvironment?.data && !!(lexicalEnvironment.data.facts & ClassFacts.WillHoistInitializersToConstructor); + return ( + shouldTransformAutoAccessors === Ternary.True || + (shouldTransformAutoAccessors === Ternary.Maybe && + !!lexicalEnvironment?.data && + !!( + lexicalEnvironment.data.facts & + ClassFacts.WillHoistInitializersToConstructor + )) + ); } function visitPropertyDeclaration(node: PropertyDeclaration) { // If this is an auto-accessor, we defer to `transformAutoAccessor`. That function // will in turn call `transformFieldInitializer` as needed. if ( - isAutoAccessorPropertyDeclaration(node) && (shouldTransformAutoAccessorsInCurrentClass() || - hasStaticModifier(node) && getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements) + isAutoAccessorPropertyDeclaration(node) && + (shouldTransformAutoAccessorsInCurrentClass() || + (hasStaticModifier(node) && + getInternalEmitFlags(node) & + InternalEmitFlags.TransformPrivateStaticElements)) ) { return transformAutoAccessor(node); } @@ -1088,10 +1278,14 @@ export function transformClassFields(context: TransformationContext): (x: Source } function shouldForceDynamicThis() { - return !!currentClassElement && + return ( + !!currentClassElement && hasStaticModifier(currentClassElement) && isAccessor(currentClassElement) && - isAutoAccessorPropertyDeclaration(getOriginalNode(currentClassElement)); + isAutoAccessorPropertyDeclaration( + getOriginalNode(currentClassElement), + ) + ); } /** @@ -1108,13 +1302,19 @@ export function transformClassFields(context: TransformationContext): (x: Source } } - function createPrivateIdentifierAccess(info: PrivateIdentifierInfo, receiver: Expression): Expression { + function createPrivateIdentifierAccess( + info: PrivateIdentifierInfo, + receiver: Expression, + ): Expression { receiver = visitNode(receiver, visitor, isExpression); ensureDynamicThisIfNeeded(receiver); return createPrivateIdentifierAccessHelper(info, receiver); } - function createPrivateIdentifierAccessHelper(info: PrivateIdentifierInfo, receiver: Expression): Expression { + function createPrivateIdentifierAccessHelper( + info: PrivateIdentifierInfo, + receiver: Expression, + ): Expression { setCommentRange(receiver, moveRangePos(receiver, -1)); switch (info.kind) { @@ -1140,7 +1340,9 @@ export function transformClassFields(context: TransformationContext): (x: Source info.isStatic ? info.variableName : undefined, ); case "untransformed": - return Debug.fail("Access helpers should not be created for untransformed private elements"); + return Debug.fail( + "Access helpers should not be created for untransformed private elements", + ); default: Debug.assertNever(info, "Unknown private element type"); @@ -1153,7 +1355,10 @@ export function transformClassFields(context: TransformationContext): (x: Source if (privateIdentifierInfo) { return setTextRange( setOriginalNode( - createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), + createPrivateIdentifierAccess( + privateIdentifierInfo, + node.expression, + ), node, ), node, @@ -1165,7 +1370,9 @@ export function transformClassFields(context: TransformationContext): (x: Source currentClassElement && isSuperProperty(node) && isIdentifier(node.name) && - isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && + isStaticPropertyDeclarationOrClassStaticBlock( + currentClassElement, + ) && lexicalEnvironment?.data ) { const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; @@ -1192,7 +1399,9 @@ export function transformClassFields(context: TransformationContext): (x: Source shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && - isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && + isStaticPropertyDeclarationOrClassStaticBlock( + currentClassElement, + ) && lexicalEnvironment?.data ) { const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; @@ -1215,7 +1424,10 @@ export function transformClassFields(context: TransformationContext): (x: Source return visitEachChild(node, visitor, context); } - function visitPreOrPostfixUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression, discarded: boolean) { + function visitPreOrPostfixUnaryExpression( + node: PrefixUnaryExpression | PostfixUnaryExpression, + discarded: boolean, + ) { if ( node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken @@ -1224,14 +1436,31 @@ export function transformClassFields(context: TransformationContext): (x: Source if (isPrivateIdentifierPropertyAccessExpression(operand)) { let info: PrivateIdentifierInfo | undefined; - if (info = accessPrivateIdentifier(operand.name)) { - const receiver = visitNode(operand.expression, visitor, isExpression); + if ((info = accessPrivateIdentifier(operand.name))) { + const receiver = visitNode( + operand.expression, + visitor, + isExpression, + ); ensureDynamicThisIfNeeded(receiver); const { readExpression, initializeExpression } = createCopiableReceiverExpr(receiver); - let expression: Expression = createPrivateIdentifierAccess(info, readExpression); - const temp = isPrefixUnaryExpression(node) || discarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); - expression = expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp); + let expression: Expression = createPrivateIdentifierAccess( + info, + readExpression, + ); + const temp = isPrefixUnaryExpression(node) || discarded + ? undefined + : factory.createTempVariable( + hoistVariableDeclaration, + ); + expression = expandPreOrPostfixIncrementOrDecrementExpression( + factory, + node, + expression, + hoistVariableDeclaration, + temp, + ); expression = createPrivateIdentifierAssignment( info, initializeExpression || readExpression, @@ -1251,7 +1480,9 @@ export function transformClassFields(context: TransformationContext): (x: Source shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(operand) && - isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && + isStaticPropertyDeclarationOrClassStaticBlock( + currentClassElement, + ) && lexicalEnvironment?.data ) { // converts `++super.a` into `(Reflect.set(_baseTemp, "a", (_a = Reflect.get(_baseTemp, "a", _classTemp), _b = ++_a), _classTemp), _b)` @@ -1265,34 +1496,75 @@ export function transformClassFields(context: TransformationContext): (x: Source const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; if (facts & ClassFacts.ClassWasDecorated) { const expression = visitInvalidSuperProperty(operand); - return isPrefixUnaryExpression(node) ? - factory.updatePrefixUnaryExpression(node, expression) : - factory.updatePostfixUnaryExpression(node, expression); + return isPrefixUnaryExpression(node) + ? factory.updatePrefixUnaryExpression(node, expression) + : factory.updatePostfixUnaryExpression( + node, + expression, + ); } if (classConstructor && superClassReference) { let setterName: Expression | undefined; let getterName: Expression | undefined; if (isPropertyAccessExpression(operand)) { if (isIdentifier(operand.name)) { - getterName = setterName = factory.createStringLiteralFromNode(operand.name); + getterName = + setterName = + factory.createStringLiteralFromNode( + operand.name, + ); } } else { - if (isSimpleInlineableExpression(operand.argumentExpression)) { - getterName = setterName = operand.argumentExpression; + if ( + isSimpleInlineableExpression( + operand.argumentExpression, + ) + ) { + getterName = + setterName = + operand.argumentExpression; } else { - getterName = factory.createTempVariable(hoistVariableDeclaration); - setterName = factory.createAssignment(getterName, visitNode(operand.argumentExpression, visitor, isExpression)); + getterName = factory.createTempVariable( + hoistVariableDeclaration, + ); + setterName = factory.createAssignment( + getterName, + visitNode( + operand.argumentExpression, + visitor, + isExpression, + ), + ); } } if (setterName && getterName) { - let expression: Expression = factory.createReflectGetCall(superClassReference, getterName, classConstructor); + let expression: Expression = factory.createReflectGetCall( + superClassReference, + getterName, + classConstructor, + ); setTextRange(expression, operand); - const temp = discarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); - expression = expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp); - expression = factory.createReflectSetCall(superClassReference, setterName, expression, classConstructor); + const temp = discarded + ? undefined + : factory.createTempVariable( + hoistVariableDeclaration, + ); + expression = expandPreOrPostfixIncrementOrDecrementExpression( + factory, + node, + expression, + hoistVariableDeclaration, + temp, + ); + expression = factory.createReflectSetCall( + superClassReference, + setterName, + expression, + classConstructor, + ); setOriginalNode(expression, node); setTextRange(expression, node); if (temp) { @@ -1310,7 +1582,11 @@ export function transformClassFields(context: TransformationContext): (x: Source function visitForStatement(node: ForStatement) { return factory.updateForStatement( node, - visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode( + node.initializer, + discardedValueVisitor, + isForInitializer, + ), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), visitIterationBody(node.statement, visitor, context), @@ -1324,16 +1600,29 @@ export function transformClassFields(context: TransformationContext): (x: Source ); } - function createCopiableReceiverExpr(receiver: Expression): { readExpression: Expression; initializeExpression: Expression | undefined; } { - const clone = nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver); - if (receiver.kind === SyntaxKind.ThisKeyword && noSubstitution.has(receiver)) { + function createCopiableReceiverExpr(receiver: Expression): { + readExpression: Expression; + initializeExpression: Expression | undefined; + } { + const clone = nodeIsSynthesized(receiver) + ? receiver + : factory.cloneNode(receiver); + if ( + receiver.kind === SyntaxKind.ThisKeyword && + noSubstitution.has(receiver) + ) { noSubstitution.add(clone); } if (isSimpleInlineableExpression(receiver)) { return { readExpression: clone, initializeExpression: undefined }; } - const readExpression = factory.createTempVariable(hoistVariableDeclaration); - const initializeExpression = factory.createAssignment(readExpression, clone); + const readExpression = factory.createTempVariable( + hoistVariableDeclaration, + ); + const initializeExpression = factory.createAssignment( + readExpression, + clone, + ); return { readExpression, initializeExpression }; } @@ -1345,21 +1634,38 @@ export function transformClassFields(context: TransformationContext): (x: Source // obj.#x() // Transform call expressions of private names to properly bind the `this` parameter. - const { thisArg, target } = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion); + const { thisArg, target } = factory.createCallBinding( + node.expression, + hoistVariableDeclaration, + languageVersion, + ); if (isCallChain(node)) { return factory.updateCallChain( node, - factory.createPropertyAccessChain(visitNode(target, visitor, isExpression), node.questionDotToken, "call"), + factory.createPropertyAccessChain( + visitNode(target, visitor, isExpression), + node.questionDotToken, + "call", + ), /*questionDotToken*/ undefined, /*typeArguments*/ undefined, - [visitNode(thisArg, visitor, isExpression), ...visitNodes(node.arguments, visitor, isExpression)], + [ + visitNode(thisArg, visitor, isExpression), + ...visitNodes(node.arguments, visitor, isExpression), + ], ); } return factory.updateCallExpression( node, - factory.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "call"), + factory.createPropertyAccessExpression( + visitNode(target, visitor, isExpression), + "call", + ), /*typeArguments*/ undefined, - [visitNode(thisArg, visitor, isExpression), ...visitNodes(node.arguments, visitor, isExpression)], + [ + visitNode(thisArg, visitor, isExpression), + ...visitNodes(node.arguments, visitor, isExpression), + ], ); } @@ -1367,7 +1673,9 @@ export function transformClassFields(context: TransformationContext): (x: Source shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.expression) && - isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && + isStaticPropertyDeclarationOrClassStaticBlock( + currentClassElement, + ) && lexicalEnvironment?.data?.classConstructor ) { // super.x() @@ -1393,11 +1701,18 @@ export function transformClassFields(context: TransformationContext): (x: Source accessPrivateIdentifier(node.tag.name) ) { // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access. - const { thisArg, target } = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion); + const { thisArg, target } = factory.createCallBinding( + node.tag, + hoistVariableDeclaration, + languageVersion, + ); return factory.updateTaggedTemplateExpression( node, factory.createCallExpression( - factory.createPropertyAccessExpression(visitNode(target, visitor, isExpression), "bind"), + factory.createPropertyAccessExpression( + visitNode(target, visitor, isExpression), + "bind", + ), /*typeArguments*/ undefined, [visitNode(thisArg, visitor, isExpression)], ), @@ -1409,7 +1724,9 @@ export function transformClassFields(context: TransformationContext): (x: Source shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.tag) && - isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && + isStaticPropertyDeclarationOrClassStaticBlock( + currentClassElement, + ) && lexicalEnvironment?.data?.classConstructor ) { // converts `` super.f`x` `` into `` Reflect.get(_baseTemp, "f", _classTemp).bind(_classTemp)`x` `` @@ -1430,18 +1747,30 @@ export function transformClassFields(context: TransformationContext): (x: Source return visitEachChild(node, visitor, context); } - function transformClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration) { + function transformClassStaticBlockDeclaration( + node: ClassStaticBlockDeclaration, + ) { if (lexicalEnvironment) { - lexicalEnvironmentMap.set(getOriginalNode(node), lexicalEnvironment); + lexicalEnvironmentMap.set( + getOriginalNode(node), + lexicalEnvironment, + ); } if (shouldTransformPrivateElementsOrClassStaticBlocks) { if (isClassThisAssignmentBlock(node)) { - const result = visitNode(node.body.statements[0].expression, visitor, isExpression); + const result = visitNode( + node.body.statements[0].expression, + visitor, + isExpression, + ); // If the generated `_classThis` assignment is a noop (i.e., `_classThis = _classThis`), we can // eliminate the expression if ( - isAssignmentExpression(result, /*excludeCompoundAssignment*/ true) && + isAssignmentExpression( + result, + /*excludeCompoundAssignment*/ true, + ) && result.left === result.right ) { return undefined; @@ -1450,7 +1779,11 @@ export function transformClassFields(context: TransformationContext): (x: Source } if (isClassNamedEvaluationHelperBlock(node)) { - return visitNode(node.body.statements[0].expression, visitor, isExpression); + return visitNode( + node.body.statements[0].expression, + visitor, + isExpression, + ); } startLexicalEnvironment(); @@ -1459,30 +1792,50 @@ export function transformClassFields(context: TransformationContext): (x: Source statements => visitNodes(statements, visitor, isStatement), node.body.statements, ); - statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + statements = factory.mergeLexicalEnvironment( + statements, + endLexicalEnvironment(), + ); const iife = factory.createImmediatelyInvokedArrowFunction(statements); setOriginalNode(skipParentheses(iife.expression), node); - addEmitFlags(skipParentheses(iife.expression), EmitFlags.AdviseOnEmitNode); + addEmitFlags( + skipParentheses(iife.expression), + EmitFlags.AdviseOnEmitNode, + ); setOriginalNode(iife, node); setTextRange(iife, node); return iife; } } - function isAnonymousClassNeedingAssignedName(node: AnonymousFunctionDefinition) { + function isAnonymousClassNeedingAssignedName( + node: AnonymousFunctionDefinition, + ) { if (isClassExpression(node) && !node.name) { const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); - if (some(staticPropertiesOrClassStaticBlocks, isClassNamedEvaluationHelperBlock)) { + if ( + some( + staticPropertiesOrClassStaticBlocks, + isClassNamedEvaluationHelperBlock, + ) + ) { return false; } const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || - !!(getInternalEmitFlags(node) && InternalEmitFlags.TransformPrivateStaticElements)) && - some(staticPropertiesOrClassStaticBlocks, node => - isClassStaticBlockDeclaration(node) || - isPrivateIdentifierClassElementDeclaration(node) || - shouldTransformInitializers && isInitializedProperty(node)); + !!( + getInternalEmitFlags(node) && + InternalEmitFlags.TransformPrivateStaticElements + )) && + some( + staticPropertiesOrClassStaticBlocks, + node => + isClassStaticBlockDeclaration(node) || + isPrivateIdentifierClassElementDeclaration(node) || + (shouldTransformInitializers && + isInitializedProperty(node)), + ); return hasTransformableStatics; } return false; @@ -1501,9 +1854,11 @@ export function transformClassFields(context: TransformationContext): (x: Source node.operatorToken, visitNode(node.right, visitor, isExpression), ); - const expr = some(pendingExpressions) ? - factory.inlineExpressions(compact([...pendingExpressions, node])) : - node; + const expr = some(pendingExpressions) + ? factory.inlineExpressions( + compact([...pendingExpressions, node]), + ) + : node; pendingExpressions = savedPendingExpressions; return expr; } @@ -1539,14 +1894,23 @@ export function transformClassFields(context: TransformationContext): (x: Source Debug.assertNode(node, isAssignmentExpression); } - const left = skipOuterExpressions(node.left, OuterExpressionKinds.PartiallyEmittedExpressions | OuterExpressionKinds.Parentheses); + const left = skipOuterExpressions( + node.left, + OuterExpressionKinds.PartiallyEmittedExpressions | + OuterExpressionKinds.Parentheses, + ); if (isPrivateIdentifierPropertyAccessExpression(left)) { // obj.#x = ... const info = accessPrivateIdentifier(left.name); if (info) { return setTextRange( setOriginalNode( - createPrivateIdentifierAssignment(info, left.expression, node.right, node.operatorToken.kind), + createPrivateIdentifierAssignment( + info, + left.expression, + node.right, + node.operatorToken.kind, + ), node, ), node, @@ -1557,7 +1921,9 @@ export function transformClassFields(context: TransformationContext): (x: Source shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node.left) && - isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && + isStaticPropertyDeclarationOrClassStaticBlock( + currentClassElement, + ) && lexicalEnvironment?.data ) { // super.x = ... @@ -1574,21 +1940,36 @@ export function transformClassFields(context: TransformationContext): (x: Source ); } if (classConstructor && superClassReference) { - let setterName = isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : - isIdentifier(node.left.name) ? factory.createStringLiteralFromNode(node.left.name) : - undefined; + let setterName = isElementAccessExpression(node.left) + ? visitNode( + node.left.argumentExpression, + visitor, + isExpression, + ) + : isIdentifier(node.left.name) + ? factory.createStringLiteralFromNode(node.left.name) + : undefined; if (setterName) { // converts `super.x = 1` into `(Reflect.set(_baseTemp, "x", _a = 1, _classTemp), _a)` // converts `super[f()] = 1` into `(Reflect.set(_baseTemp, f(), _a = 1, _classTemp), _a)` // converts `super.x += 1` into `(Reflect.set(_baseTemp, "x", _a = Reflect.get(_baseTemp, "x", _classtemp) + 1, _classTemp), _a)` // converts `super[f()] += 1` into `(Reflect.set(_baseTemp, _a = f(), _b = Reflect.get(_baseTemp, _a, _classtemp) + 1, _classTemp), _b)` - let expression = visitNode(node.right, visitor, isExpression); + let expression = visitNode( + node.right, + visitor, + isExpression, + ); if (isCompoundAssignment(node.operatorToken.kind)) { let getterName = setterName; if (!isSimpleInlineableExpression(setterName)) { - getterName = factory.createTempVariable(hoistVariableDeclaration); - setterName = factory.createAssignment(getterName, setterName); + getterName = factory.createTempVariable( + hoistVariableDeclaration, + ); + setterName = factory.createAssignment( + getterName, + setterName, + ); } const superPropertyGet = factory.createReflectGetCall( superClassReference, @@ -1599,15 +1980,24 @@ export function transformClassFields(context: TransformationContext): (x: Source setTextRange(superPropertyGet, node.left); expression = factory.createBinaryExpression( superPropertyGet, - getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind), + getNonAssignmentOperatorForCompoundAssignment( + node.operatorToken.kind, + ), expression, ); setTextRange(expression, node); } - const temp = discarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); + const temp = discarded + ? undefined + : factory.createTempVariable( + hoistVariableDeclaration, + ); if (temp) { - expression = factory.createAssignment(temp, expression); + expression = factory.createAssignment( + temp, + expression, + ); setTextRange(temp, node); } @@ -1637,26 +2027,46 @@ export function transformClassFields(context: TransformationContext): (x: Source return visitEachChild(node, visitor, context); } - function visitCommaListExpression(node: CommaListExpression, discarded: boolean) { - const elements = discarded ? - visitCommaListElements(node.elements, discardedValueVisitor) : - visitCommaListElements(node.elements, visitor, discardedValueVisitor); + function visitCommaListExpression( + node: CommaListExpression, + discarded: boolean, + ) { + const elements = discarded + ? visitCommaListElements(node.elements, discardedValueVisitor) + : visitCommaListElements( + node.elements, + visitor, + discardedValueVisitor, + ); return factory.updateCommaListExpression(node, elements); } - function visitParenthesizedExpression(node: ParenthesizedExpression, discarded: boolean) { + function visitParenthesizedExpression( + node: ParenthesizedExpression, + discarded: boolean, + ) { // 8.4.5 RS: NamedEvaluation // ParenthesizedExpression : `(` Expression `)` // ... // 2. Return ? NamedEvaluation of |Expression| with argument _name_. - const visitorFunc: Visitor = discarded ? discardedValueVisitor : - visitor; - const expression = visitNode(node.expression, visitorFunc, isExpression); + const visitorFunc: Visitor = discarded + ? discardedValueVisitor + : visitor; + const expression = visitNode( + node.expression, + visitorFunc, + isExpression, + ); return factory.updateParenthesizedExpression(node, expression); } - function createPrivateIdentifierAssignment(info: PrivateIdentifierInfo, receiver: Expression, right: Expression, operator: AssignmentOperator): Expression { + function createPrivateIdentifierAssignment( + info: PrivateIdentifierInfo, + receiver: Expression, + right: Expression, + operator: AssignmentOperator, + ): Expression { receiver = visitNode(receiver, visitor, isExpression); right = visitNode(right, visitor, isExpression); ensureDynamicThisIfNeeded(receiver); @@ -1699,7 +2109,9 @@ export function transformClassFields(context: TransformationContext): (x: Source info.isStatic ? info.variableName : undefined, ); case "untransformed": - return Debug.fail("Access helpers should not be created for untransformed private elements"); + return Debug.fail( + "Access helpers should not be created for untransformed private elements", + ); default: Debug.assertNever(info, "Unknown private element type"); @@ -1713,10 +2125,17 @@ export function transformClassFields(context: TransformationContext): (x: Source function getClassFacts(node: ClassLikeDeclaration) { let facts = ClassFacts.None; const original = getOriginalNode(node); - if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { + if ( + isClassDeclaration(original) && + classOrConstructorParameterIsDecorated(legacyDecorators, original) + ) { facts |= ClassFacts.ClassWasDecorated; } - if (shouldTransformPrivateElementsOrClassStaticBlocks && (classHasClassThisAssignment(node) || classHasExplicitlyAssignedName(node))) { + if ( + shouldTransformPrivateElementsOrClassStaticBlocks && + (classHasClassThisAssignment(node) || + classHasExplicitlyAssignedName(node)) + ) { facts |= ClassFacts.NeedsClassConstructorReference; } let containsPublicInstanceFields = false; @@ -1726,24 +2145,43 @@ export function transformClassFields(context: TransformationContext): (x: Source for (const member of node.members) { if (isStatic(member)) { if ( - member.name && (isPrivateIdentifier(member.name) || isAutoAccessorPropertyDeclaration(member)) && + member.name && + (isPrivateIdentifier(member.name) || + isAutoAccessorPropertyDeclaration(member)) && shouldTransformPrivateElementsOrClassStaticBlocks ) { facts |= ClassFacts.NeedsClassConstructorReference; } - else if (isAutoAccessorPropertyDeclaration(member) && shouldTransformAutoAccessors === Ternary.True && !node.name && !node.emitNode?.classThis) { + else if ( + isAutoAccessorPropertyDeclaration(member) && + shouldTransformAutoAccessors === Ternary.True && + !node.name && + !node.emitNode?.classThis + ) { facts |= ClassFacts.NeedsClassConstructorReference; } - if (isPropertyDeclaration(member) || isClassStaticBlockDeclaration(member)) { - if (shouldTransformThisInStaticInitializers && member.transformFlags & TransformFlags.ContainsLexicalThis) { + if ( + isPropertyDeclaration(member) || + isClassStaticBlockDeclaration(member) + ) { + if ( + shouldTransformThisInStaticInitializers && + member.transformFlags & + TransformFlags.ContainsLexicalThis + ) { facts |= ClassFacts.NeedsSubstitutionForThisInClassStaticField; if (!(facts & ClassFacts.ClassWasDecorated)) { facts |= ClassFacts.NeedsClassConstructorReference; } } - if (shouldTransformSuperInStaticInitializers && member.transformFlags & TransformFlags.ContainsLexicalSuper) { + if ( + shouldTransformSuperInStaticInitializers && + member.transformFlags & + TransformFlags.ContainsLexicalSuper + ) { if (!(facts & ClassFacts.ClassWasDecorated)) { - facts |= ClassFacts.NeedsClassConstructorReference | ClassFacts.NeedsClassSuperReference; + facts |= ClassFacts.NeedsClassConstructorReference | + ClassFacts.NeedsClassSuperReference; } } } @@ -1755,7 +2193,10 @@ export function transformClassFields(context: TransformationContext): (x: Source } else if (isPrivateIdentifierClassElementDeclaration(member)) { containsInstancePrivateElements = true; - if (resolver.getNodeCheckFlags(member) & NodeCheckFlags.ContainsConstructorReference) { + if ( + resolver.getNodeCheckFlags(member) & + NodeCheckFlags.ContainsConstructorReference + ) { facts |= ClassFacts.NeedsClassConstructorReference; } } @@ -1766,10 +2207,15 @@ export function transformClassFields(context: TransformationContext): (x: Source } } - const willHoistInitializersToConstructor = shouldTransformInitializersUsingDefine && containsPublicInstanceFields || - shouldTransformInitializersUsingSet && containsInitializedPublicInstanceFields || - shouldTransformPrivateElementsOrClassStaticBlocks && containsInstancePrivateElements || - shouldTransformPrivateElementsOrClassStaticBlocks && containsInstanceAutoAccessors && shouldTransformAutoAccessors === Ternary.True; + const willHoistInitializersToConstructor = (shouldTransformInitializersUsingDefine && + containsPublicInstanceFields) || + (shouldTransformInitializersUsingSet && + containsInitializedPublicInstanceFields) || + (shouldTransformPrivateElementsOrClassStaticBlocks && + containsInstancePrivateElements) || + (shouldTransformPrivateElementsOrClassStaticBlocks && + containsInstanceAutoAccessors && + shouldTransformAutoAccessors === Ternary.True); if (willHoistInitializersToConstructor) { facts |= ClassFacts.WillHoistInitializersToConstructor; @@ -1778,10 +2224,15 @@ export function transformClassFields(context: TransformationContext): (x: Source return facts; } - function visitExpressionWithTypeArgumentsInHeritageClause(node: ExpressionWithTypeArguments) { + function visitExpressionWithTypeArgumentsInHeritageClause( + node: ExpressionWithTypeArguments, + ) { const facts = lexicalEnvironment?.data?.facts || ClassFacts.None; if (facts & ClassFacts.NeedsClassSuperReference) { - const temp = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true); + const temp = factory.createTempVariable( + hoistVariableDeclaration, + /*reservedInNestedScopes*/ true, + ); getClassLexicalEnvironment().superClassReference = temp; return factory.updateExpressionWithTypeArguments( node, @@ -1795,7 +2246,10 @@ export function transformClassFields(context: TransformationContext): (x: Source return visitEachChild(node, visitor, context); } - function visitInNewClassLexicalEnvironment(node: T, visitor: (node: T, facts: ClassFacts) => U) { + function visitInNewClassLexicalEnvironment< + T extends ClassLikeDeclaration, + U, + >(node: T, visitor: (node: T, facts: ClassFacts) => U) { const savedCurrentClassContainer = currentClassContainer; const savedPendingExpressions = pendingExpressions; const savedLexicalEnvironment = lexicalEnvironment; @@ -1803,8 +2257,12 @@ export function transformClassFields(context: TransformationContext): (x: Source pendingExpressions = undefined; startClassLexicalEnvironment(); - const shouldAlwaysTransformPrivateStaticElements = getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements; - if (shouldTransformPrivateElementsOrClassStaticBlocks || shouldAlwaysTransformPrivateStaticElements) { + const shouldAlwaysTransformPrivateStaticElements = getInternalEmitFlags(node) & + InternalEmitFlags.TransformPrivateStaticElements; + if ( + shouldTransformPrivateElementsOrClassStaticBlocks || + shouldAlwaysTransformPrivateStaticElements + ) { const name = getNameOfDeclaration(node); if (name && isIdentifier(name)) { getPrivateIdentifierEnvironment().data.className = name; @@ -1821,8 +2279,15 @@ export function transformClassFields(context: TransformationContext): (x: Source } // If the class name was assigned from a string literal that is a valid identifier, create an // identifier from it. - else if (isIdentifierText(node.emitNode.assignedName.text, languageVersion)) { - const prefixName = factory.createIdentifier(node.emitNode.assignedName.text); + else if ( + isIdentifierText( + node.emitNode.assignedName.text, + languageVersion, + ) + ) { + const prefixName = factory.createIdentifier( + node.emitNode.assignedName.text, + ); getPrivateIdentifierEnvironment().data.className = prefixName; } } @@ -1857,10 +2322,16 @@ export function transformClassFields(context: TransformationContext): (x: Source } function visitClassDeclaration(node: ClassDeclaration) { - return visitInNewClassLexicalEnvironment(node, visitClassDeclarationInNewClassLexicalEnvironment); + return visitInNewClassLexicalEnvironment( + node, + visitClassDeclarationInNewClassLexicalEnvironment, + ); } - function visitClassDeclarationInNewClassLexicalEnvironment(node: ClassDeclaration, facts: ClassFacts) { + function visitClassDeclarationInNewClassLexicalEnvironment( + node: ClassDeclaration, + facts: ClassFacts, + ) { // If a class has private static fields, or a static field has a `this` or `super` reference, // then we need to allocate a temp variable to hold on to that reference. let pendingClassReferenceAssignment: BinaryExpression | undefined; @@ -1874,14 +2345,26 @@ export function transformClassFields(context: TransformationContext): (x: Source // will be evaluated *before* the transformed static blocks are evaluated and thus won't overwrite // the replacement constructor. - if (shouldTransformPrivateElementsOrClassStaticBlocks && node.emitNode?.classThis) { + if ( + shouldTransformPrivateElementsOrClassStaticBlocks && + node.emitNode?.classThis + ) { getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; - pendingClassReferenceAssignment = factory.createAssignment(node.emitNode.classThis, factory.getInternalName(node)); + pendingClassReferenceAssignment = factory.createAssignment( + node.emitNode.classThis, + factory.getInternalName(node), + ); } else { - const temp = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true); + const temp = factory.createTempVariable( + hoistVariableDeclaration, + /*reservedInNestedScopes*/ true, + ); getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp); - pendingClassReferenceAssignment = factory.createAssignment(temp, factory.getInternalName(node)); + pendingClassReferenceAssignment = factory.createAssignment( + temp, + factory.getInternalName(node), + ); } } @@ -1889,11 +2372,16 @@ export function transformClassFields(context: TransformationContext): (x: Source getClassLexicalEnvironment().classThis = node.emitNode.classThis; } - const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & NodeCheckFlags.ContainsConstructorReference; + const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & + NodeCheckFlags.ContainsConstructorReference; const isExport = hasSyntacticModifier(node, ModifierFlags.Export); const isDefault = hasSyntacticModifier(node, ModifierFlags.Default); let modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); - const heritageClauses = visitNodes(node.heritageClauses, heritageClauseVisitor, isHeritageClause); + const heritageClauses = visitNodes( + node.heritageClauses, + heritageClauseVisitor, + isHeritageClause, + ); const { members, prologue } = transformClassMembers(node); const statements: Statement[] = []; @@ -1903,10 +2391,19 @@ export function transformClassFields(context: TransformationContext): (x: Source // Write any pending expressions from elided or moved computed property names if (some(pendingExpressions)) { - statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))); + statements.push( + factory.createExpressionStatement( + factory.inlineExpressions(pendingExpressions), + ), + ); } - if (shouldTransformInitializersUsingSet || shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements) { + if ( + shouldTransformInitializersUsingSet || + shouldTransformPrivateElementsOrClassStaticBlocks || + getInternalEmitFlags(node) & + InternalEmitFlags.TransformPrivateStaticElements + ) { // Emit static property assignment. Because classDeclaration is lexically evaluated, // it is safe to emit static property assignment after classDeclaration // From ES6 specification: @@ -1915,17 +2412,31 @@ export function transformClassFields(context: TransformationContext): (x: Source const staticProperties = getStaticPropertiesAndClassStaticBlock(node); if (some(staticProperties)) { - addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory.getInternalName(node)); + addPropertyOrClassStaticBlockStatements( + statements, + staticProperties, + factory.getInternalName(node), + ); } } if (statements.length > 0 && isExport && isDefault) { - modifiers = visitNodes(modifiers, node => isExportOrDefaultModifier(node) ? undefined : node, isModifier); - statements.push(factory.createExportAssignment( - /*modifiers*/ undefined, - /*isExportEquals*/ false, - factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true), - )); + modifiers = visitNodes( + modifiers, + node => (isExportOrDefaultModifier(node) ? undefined : node), + isModifier, + ); + statements.push( + factory.createExportAssignment( + /*modifiers*/ undefined, + /*isExportEquals*/ false, + factory.getLocalName( + node, + /*allowComments*/ false, + /*allowSourceMaps*/ true, + ), + ), + ); } const alias = getClassLexicalEnvironment().classConstructor; @@ -1952,10 +2463,16 @@ export function transformClassFields(context: TransformationContext): (x: Source } function visitClassExpression(node: ClassExpression): Expression { - return visitInNewClassLexicalEnvironment(node, visitClassExpressionInNewClassLexicalEnvironment); + return visitInNewClassLexicalEnvironment( + node, + visitClassExpressionInNewClassLexicalEnvironment, + ); } - function visitClassExpressionInNewClassLexicalEnvironment(node: ClassExpression, facts: ClassFacts): Expression { + function visitClassExpressionInNewClassLexicalEnvironment( + node: ClassExpression, + facts: ClassFacts, + ): Expression { // If this class expression is a transformation of a decorated class declaration, // then we want to output the pendingExpressions as statements, not as inlined // expressions with the class statement. @@ -1963,7 +2480,9 @@ export function transformClassFields(context: TransformationContext): (x: Source // In this case, we use pendingStatements to produce the same output as the // class declaration transformation. The VariableStatement visitor will insert // these statements after the class expression variable statement. - const isDecoratedClassDeclaration = !!(facts & ClassFacts.ClassWasDecorated); + const isDecoratedClassDeclaration = !!( + facts & ClassFacts.ClassWasDecorated + ); const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); const classCheckFlags = resolver.getNodeCheckFlags(node); const isClassWithConstructorReference = classCheckFlags & NodeCheckFlags.ContainsConstructorReference; @@ -1979,12 +2498,20 @@ export function transformClassFields(context: TransformationContext): (x: Source // will be evaluated *before* the transformed static blocks are evaluated and thus won't overwrite // the replacement constructor. - if (shouldTransformPrivateElementsOrClassStaticBlocks && node.emitNode?.classThis) { - return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; + if ( + shouldTransformPrivateElementsOrClassStaticBlocks && + node.emitNode?.classThis + ) { + return (getClassLexicalEnvironment().classConstructor = node.emitNode.classThis); } const requiresBlockScopedVar = classCheckFlags & NodeCheckFlags.BlockScopedBindingInLoop; - const temp = factory.createTempVariable(requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, /*reservedInNestedScopes*/ true); + const temp = factory.createTempVariable( + requiresBlockScopedVar + ? addBlockScopedVariable + : hoistVariableDeclaration, + /*reservedInNestedScopes*/ true, + ); getClassLexicalEnvironment().classConstructor = factory.cloneNode(temp); return temp; } @@ -1997,8 +2524,16 @@ export function transformClassFields(context: TransformationContext): (x: Source temp ??= createClassTempVar(); } - const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); - const heritageClauses = visitNodes(node.heritageClauses, heritageClauseVisitor, isHeritageClause); + const modifiers = visitNodes( + node.modifiers, + modifierVisitor, + isModifier, + ); + const heritageClauses = visitNodes( + node.heritageClauses, + heritageClauseVisitor, + isHeritageClause, + ); const { members, prologue } = transformClassMembers(node); const classExpression = factory.updateClassExpression( node, @@ -2016,30 +2551,59 @@ export function transformClassFields(context: TransformationContext): (x: Source // Static initializers are transformed to `static {}` blocks when `useDefineForClassFields: false` // and not also transforming static blocks. - const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements) && - some(staticPropertiesOrClassStaticBlocks, node => - isClassStaticBlockDeclaration(node) || - isPrivateIdentifierClassElementDeclaration(node) || - shouldTransformInitializers && isInitializedProperty(node)); + const hasTransformableStatics = (shouldTransformPrivateElementsOrClassStaticBlocks || + getInternalEmitFlags(node) & + InternalEmitFlags.TransformPrivateStaticElements) && + some( + staticPropertiesOrClassStaticBlocks, + node => + isClassStaticBlockDeclaration(node) || + isPrivateIdentifierClassElementDeclaration(node) || + (shouldTransformInitializers && isInitializedProperty(node)), + ); if (hasTransformableStatics || some(pendingExpressions)) { if (isDecoratedClassDeclaration) { - Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); + Debug.assertIsDefined( + pendingStatements, + "Decorated classes transformed by TypeScript are expected to be within a variable declaration.", + ); // Write any pending expressions from elided or moved computed property names if (some(pendingExpressions)) { - addRange(pendingStatements, map(pendingExpressions, factory.createExpressionStatement)); + addRange( + pendingStatements, + map( + pendingExpressions, + factory.createExpressionStatement, + ), + ); } if (some(staticPropertiesOrClassStaticBlocks)) { - addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, node.emitNode?.classThis ?? factory.getInternalName(node)); + addPropertyOrClassStaticBlockStatements( + pendingStatements, + staticPropertiesOrClassStaticBlocks, + node.emitNode?.classThis ?? + factory.getInternalName(node), + ); } if (temp) { - expressions.push(factory.createAssignment(temp, classExpression)); + expressions.push( + factory.createAssignment(temp, classExpression), + ); } - else if (shouldTransformPrivateElementsOrClassStaticBlocks && node.emitNode?.classThis) { - expressions.push(factory.createAssignment(node.emitNode.classThis, classExpression)); + else if ( + shouldTransformPrivateElementsOrClassStaticBlocks && + node.emitNode?.classThis + ) { + expressions.push( + factory.createAssignment( + node.emitNode.classThis, + classExpression, + ), + ); } else { expressions.push(classExpression); @@ -2050,16 +2614,26 @@ export function transformClassFields(context: TransformationContext): (x: Source if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); - const alias = factory.cloneNode(temp) as GeneratedIdentifier; + const alias = factory.cloneNode( + temp, + ) as GeneratedIdentifier; alias.emitNode.autoGenerate.flags &= ~GeneratedIdentifierFlags.ReservedInNestedScopes; classAliases[getOriginalNodeId(node)] = alias; } - expressions.push(factory.createAssignment(temp, classExpression)); + expressions.push( + factory.createAssignment(temp, classExpression), + ); // Add any pending expressions leftover from elided or relocated computed property names addRange(expressions, pendingExpressions); - addRange(expressions, generateInitializedPropertyExpressionsOrClassStaticBlock(staticPropertiesOrClassStaticBlocks, temp)); + addRange( + expressions, + generateInitializedPropertyExpressionsOrClassStaticBlock( + staticPropertiesOrClassStaticBlocks, + temp, + ), + ); expressions.push(factory.cloneNode(temp)); } } @@ -2077,7 +2651,9 @@ export function transformClassFields(context: TransformationContext): (x: Source return factory.inlineExpressions(expressions); } - function visitClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration) { + function visitClassStaticBlockDeclaration( + node: ClassStaticBlockDeclaration, + ) { if (!shouldTransformPrivateElementsOrClassStaticBlocks) { return visitEachChild(node, visitor, context); } @@ -2087,7 +2663,8 @@ export function transformClassFields(context: TransformationContext): (x: Source function visitThisExpression(node: ThisExpression) { if ( - shouldTransformThisInStaticInitializers && currentClassElement && + shouldTransformThisInStaticInitializers && + currentClassElement && isClassStaticBlockDeclaration(currentClassElement) && lexicalEnvironment?.data ) { @@ -2099,18 +2676,30 @@ export function transformClassFields(context: TransformationContext): (x: Source } function transformClassMembers(node: ClassDeclaration | ClassExpression) { - const shouldTransformPrivateStaticElementsInClass = !!(getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements); + const shouldTransformPrivateStaticElementsInClass = !!( + getInternalEmitFlags(node) & + InternalEmitFlags.TransformPrivateStaticElements + ); // Declare private names - if (shouldTransformPrivateElementsOrClassStaticBlocks || shouldTransformPrivateStaticElementsInFile) { + if ( + shouldTransformPrivateElementsOrClassStaticBlocks || + shouldTransformPrivateStaticElementsInFile + ) { for (const member of node.members) { if (isPrivateIdentifierClassElementDeclaration(member)) { if (shouldTransformClassElementToWeakMap(member)) { - addPrivateIdentifierToEnvironment(member, member.name, addPrivateIdentifierClassElementToEnvironment); + addPrivateIdentifierToEnvironment( + member, + member.name, + addPrivateIdentifierClassElementToEnvironment, + ); } else { const privateEnv = getPrivateIdentifierEnvironment(); - setPrivateIdentifier(privateEnv, member.name, { kind: "untransformed" }); + setPrivateIdentifier(privateEnv, member.name, { + kind: "untransformed", + }); } } } @@ -2124,28 +2713,46 @@ export function transformClassFields(context: TransformationContext): (x: Source if (shouldTransformAutoAccessorsInCurrentClass()) { for (const member of node.members) { if (isAutoAccessorPropertyDeclaration(member)) { - const storageName = factory.getGeneratedPrivateNameForNode(member.name, /*prefix*/ undefined, "_accessor_storage"); + const storageName = factory.getGeneratedPrivateNameForNode( + member.name, + /*prefix*/ undefined, + "_accessor_storage", + ); if ( shouldTransformPrivateElementsOrClassStaticBlocks || - shouldTransformPrivateStaticElementsInClass && hasStaticModifier(member) + (shouldTransformPrivateStaticElementsInClass && + hasStaticModifier(member)) ) { - addPrivateIdentifierToEnvironment(member, storageName, addPrivateIdentifierPropertyDeclarationToEnvironment); + addPrivateIdentifierToEnvironment( + member, + storageName, + addPrivateIdentifierPropertyDeclarationToEnvironment, + ); } else { const privateEnv = getPrivateIdentifierEnvironment(); - setPrivateIdentifier(privateEnv, storageName, { kind: "untransformed" }); + setPrivateIdentifier(privateEnv, storageName, { + kind: "untransformed", + }); } } } } } - let members = visitNodes(node.members, classElementVisitor, isClassElement); + let members = visitNodes( + node.members, + classElementVisitor, + isClassElement, + ); // Create a synthetic constructor if necessary let syntheticConstructor: ConstructorDeclaration | undefined; if (!some(members, isConstructorDeclaration)) { - syntheticConstructor = transformConstructor(/*constructor*/ undefined, node); + syntheticConstructor = transformConstructor( + /*constructor*/ undefined, + node, + ); } let prologue: Expression | undefined; @@ -2155,13 +2762,23 @@ export function transformClassFields(context: TransformationContext): (x: Source // to ensure that expressions from computed property names are evaluated before any other static // initializers. let syntheticStaticBlock: ClassStaticBlockDeclaration | undefined; - if (!shouldTransformPrivateElementsOrClassStaticBlocks && some(pendingExpressions)) { - let statement = factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)); - if (statement.transformFlags & TransformFlags.ContainsLexicalThisOrSuper) { + if ( + !shouldTransformPrivateElementsOrClassStaticBlocks && + some(pendingExpressions) + ) { + let statement = factory.createExpressionStatement( + factory.inlineExpressions(pendingExpressions), + ); + if ( + statement.transformFlags & + TransformFlags.ContainsLexicalThisOrSuper + ) { // If there are `this` or `super` references from computed property names, shift the expression // into an arrow function to be evaluated in the outer scope so that `this` and `super` are // properly captured. - const temp = factory.createTempVariable(hoistVariableDeclaration); + const temp = factory.createTempVariable( + hoistVariableDeclaration, + ); const arrow = factory.createArrowFunction( /*modifiers*/ undefined, /*typeParameters*/ undefined, @@ -2171,7 +2788,13 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.createBlock([statement]), ); prologue = factory.createAssignment(temp, arrow); - statement = factory.createExpressionStatement(factory.createCallExpression(temp, /*typeArguments*/ undefined, [])); + statement = factory.createExpressionStatement( + factory.createCallExpression( + temp, + /*typeArguments*/ undefined, + [], + ), + ); } const block = factory.createBlock([statement]); @@ -2183,17 +2806,34 @@ export function transformClassFields(context: TransformationContext): (x: Source // and return a new array. if (syntheticConstructor || syntheticStaticBlock) { let membersArray: ClassElement[] | undefined; - const classThisAssignmentBlock = find(members, isClassThisAssignmentBlock); - const classNamedEvaluationHelperBlock = find(members, isClassNamedEvaluationHelperBlock); + const classThisAssignmentBlock = find( + members, + isClassThisAssignmentBlock, + ); + const classNamedEvaluationHelperBlock = find( + members, + isClassNamedEvaluationHelperBlock, + ); membersArray = append(membersArray, classThisAssignmentBlock); - membersArray = append(membersArray, classNamedEvaluationHelperBlock); + membersArray = append( + membersArray, + classNamedEvaluationHelperBlock, + ); membersArray = append(membersArray, syntheticConstructor); membersArray = append(membersArray, syntheticStaticBlock); - const remainingMembers = classThisAssignmentBlock || classNamedEvaluationHelperBlock ? - filter(members, member => member !== classThisAssignmentBlock && member !== classNamedEvaluationHelperBlock) : - members; + const remainingMembers = classThisAssignmentBlock || classNamedEvaluationHelperBlock + ? filter( + members, + member => + member !== classThisAssignmentBlock && + member !== classNamedEvaluationHelperBlock, + ) + : members; membersArray = addRange(membersArray, remainingMembers); - members = setTextRange(factory.createNodeArray(membersArray), /*location*/ node.members); + members = setTextRange( + factory.createNodeArray(membersArray), + /*location*/ node.members, + ); } return { members, prologue }; @@ -2201,7 +2841,10 @@ export function transformClassFields(context: TransformationContext): (x: Source function createBrandCheckWeakSetForPrivateMethods() { const { weakSetName } = getPrivateIdentifierEnvironment().data; - Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + Debug.assert( + weakSetName, + "weakSetName should be set in private identifier environment", + ); getPendingExpressions().push( factory.createAssignment( @@ -2215,23 +2858,49 @@ export function transformClassFields(context: TransformationContext): (x: Source ); } - function transformConstructor(constructor: ConstructorDeclaration | undefined, container: ClassDeclaration | ClassExpression) { + function transformConstructor( + constructor: ConstructorDeclaration | undefined, + container: ClassDeclaration | ClassExpression, + ) { constructor = visitNode(constructor, visitor, isConstructorDeclaration); - if (!lexicalEnvironment?.data || !(lexicalEnvironment.data.facts & ClassFacts.WillHoistInitializersToConstructor)) { + if ( + !lexicalEnvironment?.data || + !( + lexicalEnvironment.data.facts & + ClassFacts.WillHoistInitializersToConstructor + ) + ) { return constructor; } const extendsClauseElement = getEffectiveBaseTypeNode(container); - const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword); - const parameters = visitParameterList(constructor ? constructor.parameters : undefined, visitor, context); - const body = transformConstructorBody(container, constructor, isDerivedClass); + const isDerivedClass = !!( + extendsClauseElement && + skipOuterExpressions(extendsClauseElement.expression).kind !== + SyntaxKind.NullKeyword + ); + const parameters = visitParameterList( + constructor ? constructor.parameters : undefined, + visitor, + context, + ); + const body = transformConstructorBody( + container, + constructor, + isDerivedClass, + ); if (!body) { return constructor; } if (constructor) { Debug.assert(parameters); - return factory.updateConstructorDeclaration(constructor, /*modifiers*/ undefined, parameters, body); + return factory.updateConstructorDeclaration( + constructor, + /*modifiers*/ undefined, + parameters, + body, + ); } return startOnNewLine( @@ -2249,10 +2918,27 @@ export function transformClassFields(context: TransformationContext): (x: Source ); } - function transformConstructorBodyWorker(statementsOut: Statement[], statementsIn: NodeArray, statementOffset: number, superPath: readonly number[], superPathDepth: number, initializerStatements: readonly Statement[], constructor: ConstructorDeclaration) { + function transformConstructorBodyWorker( + statementsOut: Statement[], + statementsIn: NodeArray, + statementOffset: number, + superPath: readonly number[], + superPathDepth: number, + initializerStatements: readonly Statement[], + constructor: ConstructorDeclaration, + ) { const superStatementIndex = superPath[superPathDepth]; const superStatement = statementsIn[superStatementIndex]; - addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); + addRange( + statementsOut, + visitNodes( + statementsIn, + visitor, + isStatement, + statementOffset, + superStatementIndex - statementOffset, + ), + ); statementOffset = superStatementIndex + 1; if (isTryStatement(superStatement)) { const tryBlockStatements: Statement[] = []; @@ -2268,17 +2954,38 @@ export function transformClassFields(context: TransformationContext): (x: Source ); const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); - setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); + setTextRange( + tryBlockStatementsArray, + superStatement.tryBlock.statements, + ); - statementsOut.push(factory.updateTryStatement( - superStatement, - factory.updateBlock(superStatement.tryBlock, tryBlockStatements), - visitNode(superStatement.catchClause, visitor, isCatchClause), - visitNode(superStatement.finallyBlock, visitor, isBlock), - )); + statementsOut.push( + factory.updateTryStatement( + superStatement, + factory.updateBlock( + superStatement.tryBlock, + tryBlockStatements, + ), + visitNode( + superStatement.catchClause, + visitor, + isCatchClause, + ), + visitNode(superStatement.finallyBlock, visitor, isBlock), + ), + ); } else { - addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex, 1)); + addRange( + statementsOut, + visitNodes( + statementsIn, + visitor, + isStatement, + superStatementIndex, + 1, + ), + ); // Add the property initializers. Transforms this: // @@ -2297,7 +3004,12 @@ export function transformClassFields(context: TransformationContext): (x: Source // so only count the statements that immediately follow. while (statementOffset < statementsIn.length) { const statement = statementsIn[statementOffset]; - if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) { + if ( + isParameterPropertyDeclaration( + getOriginalNode(statement), + constructor, + ) + ) { statementOffset++; } else { @@ -2308,14 +3020,31 @@ export function transformClassFields(context: TransformationContext): (x: Source addRange(statementsOut, initializerStatements); } - addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset)); + addRange( + statementsOut, + visitNodes(statementsIn, visitor, isStatement, statementOffset), + ); } - function transformConstructorBody(node: ClassDeclaration | ClassExpression, constructor: ConstructorDeclaration | undefined, isDerivedClass: boolean) { - const instanceProperties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); + function transformConstructorBody( + node: ClassDeclaration | ClassExpression, + constructor: ConstructorDeclaration | undefined, + isDerivedClass: boolean, + ) { + const instanceProperties = getProperties( + node, + /*requireInitializer*/ false, + /*isStatic*/ false, + ); let properties = instanceProperties; if (!useDefineForClassFields) { - properties = filter(properties, property => !!property.initializer || isPrivateIdentifier(property.name) || hasAccessorModifier(property)); + properties = filter( + properties, + property => + !!property.initializer || + isPrivateIdentifier(property.name) || + hasAccessorModifier(property), + ); } const privateMethodsAndAccessors = getPrivateInstanceMethodsAndAccessors(node); @@ -2346,20 +3075,55 @@ export function transformClassFields(context: TransformationContext): (x: Source const receiver = factory.createThis(); // private methods can be called in property initializers, they should execute first. - addInstanceMethodStatements(initializerStatements, privateMethodsAndAccessors, receiver); + addInstanceMethodStatements( + initializerStatements, + privateMethodsAndAccessors, + receiver, + ); if (constructor) { - const parameterProperties = filter(instanceProperties, prop => isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); - const nonParameterProperties = filter(properties, prop => !isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); - addPropertyOrClassStaticBlockStatements(initializerStatements, parameterProperties, receiver); - addPropertyOrClassStaticBlockStatements(initializerStatements, nonParameterProperties, receiver); + const parameterProperties = filter(instanceProperties, prop => + isParameterPropertyDeclaration( + getOriginalNode(prop), + constructor, + )); + const nonParameterProperties = filter( + properties, + prop => + !isParameterPropertyDeclaration( + getOriginalNode(prop), + constructor, + ), + ); + addPropertyOrClassStaticBlockStatements( + initializerStatements, + parameterProperties, + receiver, + ); + addPropertyOrClassStaticBlockStatements( + initializerStatements, + nonParameterProperties, + receiver, + ); } else { - addPropertyOrClassStaticBlockStatements(initializerStatements, properties, receiver); + addPropertyOrClassStaticBlockStatements( + initializerStatements, + properties, + receiver, + ); } if (constructor?.body) { - statementOffset = factory.copyPrologue(constructor.body.statements, statements, /*ensureUseStrict*/ false, visitor); - const superStatementIndices = findSuperStatementIndexPath(constructor.body.statements, statementOffset); + statementOffset = factory.copyPrologue( + constructor.body.statements, + statements, + /*ensureUseStrict*/ false, + visitor, + ); + const superStatementIndices = findSuperStatementIndexPath( + constructor.body.statements, + statementOffset, + ); if (superStatementIndices.length) { transformConstructorBodyWorker( statements, @@ -2376,7 +3140,12 @@ export function transformClassFields(context: TransformationContext): (x: Source // so only count the statements that immediately follow. while (statementOffset < constructor.body.statements.length) { const statement = constructor.body.statements[statementOffset]; - if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) { + if ( + isParameterPropertyDeclaration( + getOriginalNode(statement), + constructor, + ) + ) { statementOffset++; } else { @@ -2384,7 +3153,15 @@ export function transformClassFields(context: TransformationContext): (x: Source } } addRange(statements, initializerStatements); - addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, statementOffset)); + addRange( + statements, + visitNodes( + constructor.body.statements, + visitor, + isStatement, + statementOffset, + ), + ); } } else { @@ -2398,7 +3175,11 @@ export function transformClassFields(context: TransformationContext): (x: Source factory.createCallExpression( factory.createSuper(), /*typeArguments*/ undefined, - [factory.createSpreadElement(factory.createIdentifier("arguments"))], + [ + factory.createSpreadElement( + factory.createIdentifier("arguments"), + ), + ], ), ), ); @@ -2406,21 +3187,27 @@ export function transformClassFields(context: TransformationContext): (x: Source addRange(statements, initializerStatements); } - statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + statements = factory.mergeLexicalEnvironment( + statements, + endLexicalEnvironment(), + ); if (statements.length === 0 && !constructor) { return undefined; } - const multiLine = constructor?.body && constructor.body.statements.length >= statements.length ? - constructor.body.multiLine ?? statements.length > 0 : - statements.length > 0; + const multiLine = constructor?.body && + constructor.body.statements.length >= statements.length + ? constructor.body.multiLine ?? statements.length > 0 + : statements.length > 0; return setTextRange( factory.createBlock( setTextRange( factory.createNodeArray(statements), - /*location*/ constructor ? constructor.body!.statements : node.members, + /*location*/ constructor + ? constructor.body!.statements + : node.members, ), multiLine, ), @@ -2434,13 +3221,26 @@ export function transformClassFields(context: TransformationContext): (x: Source * @param properties An array of property declarations to transform. * @param receiver The receiver on which each property should be assigned. */ - function addPropertyOrClassStaticBlockStatements(statements: Statement[], properties: readonly (PropertyDeclaration | ClassStaticBlockDeclaration)[], receiver: LeftHandSideExpression) { + function addPropertyOrClassStaticBlockStatements( + statements: Statement[], + properties: readonly ( + | PropertyDeclaration + | ClassStaticBlockDeclaration + )[], + receiver: LeftHandSideExpression, + ) { for (const property of properties) { - if (isStatic(property) && !shouldTransformPrivateElementsOrClassStaticBlocks) { + if ( + isStatic(property) && + !shouldTransformPrivateElementsOrClassStaticBlocks + ) { continue; } - const statement = transformPropertyOrClassStaticBlock(property, receiver); + const statement = transformPropertyOrClassStaticBlock( + property, + receiver, + ); if (!statement) { continue; } @@ -2449,10 +3249,17 @@ export function transformClassFields(context: TransformationContext): (x: Source } } - function transformPropertyOrClassStaticBlock(property: PropertyDeclaration | ClassStaticBlockDeclaration, receiver: LeftHandSideExpression) { - const expression = isClassStaticBlockDeclaration(property) ? - setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : - transformProperty(property, receiver); + function transformPropertyOrClassStaticBlock( + property: PropertyDeclaration | ClassStaticBlockDeclaration, + receiver: LeftHandSideExpression, + ) { + const expression = isClassStaticBlockDeclaration(property) + ? setCurrentClassElementAnd( + property, + transformClassStaticBlockDeclaration, + property, + ) + : transformProperty(property, receiver); if (!expression) { return undefined; } @@ -2493,18 +3300,35 @@ export function transformClassFields(context: TransformationContext): (x: Source * @param propertiesOrClassStaticBlocks An array of property declarations to transform. * @param receiver The receiver on which each property should be assigned. */ - function generateInitializedPropertyExpressionsOrClassStaticBlock(propertiesOrClassStaticBlocks: readonly (PropertyDeclaration | ClassStaticBlockDeclaration)[], receiver: LeftHandSideExpression) { + function generateInitializedPropertyExpressionsOrClassStaticBlock( + propertiesOrClassStaticBlocks: readonly ( + | PropertyDeclaration + | ClassStaticBlockDeclaration + )[], + receiver: LeftHandSideExpression, + ) { const expressions: Expression[] = []; for (const property of propertiesOrClassStaticBlocks) { - const expression = isClassStaticBlockDeclaration(property) ? - setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : - setCurrentClassElementAnd(property, () => transformProperty(property, receiver), /*arg*/ undefined); + const expression = isClassStaticBlockDeclaration(property) + ? setCurrentClassElementAnd( + property, + transformClassStaticBlockDeclaration, + property, + ) + : setCurrentClassElementAnd( + property, + () => transformProperty(property, receiver), + /*arg*/ undefined, + ); if (!expression) { continue; } startOnNewLine(expression); setOriginalNode(expression, property); - addEmitFlags(expression, getEmitFlags(property) & EmitFlags.NoComments); + addEmitFlags( + expression, + getEmitFlags(property) & EmitFlags.NoComments, + ); setSourceMapRange(expression, moveRangePastModifiers(property)); setCommentRange(expression, property); expressions.push(expression); @@ -2519,21 +3343,34 @@ export function transformClassFields(context: TransformationContext): (x: Source * @param property The property declaration. * @param receiver The object receiving the property assignment. */ - function transformProperty(property: PropertyDeclaration, receiver: LeftHandSideExpression) { + function transformProperty( + property: PropertyDeclaration, + receiver: LeftHandSideExpression, + ) { const savedCurrentClassElement = currentClassElement; const transformed = transformPropertyWorker(property, receiver); - if (transformed && hasStaticModifier(property) && lexicalEnvironment?.data?.facts) { + if ( + transformed && + hasStaticModifier(property) && + lexicalEnvironment?.data?.facts + ) { // capture the lexical environment for the member setOriginalNode(transformed, property); addEmitFlags(transformed, EmitFlags.AdviseOnEmitNode); setSourceMapRange(transformed, getSourceMapRange(property.name)); - lexicalEnvironmentMap.set(getOriginalNode(property), lexicalEnvironment); + lexicalEnvironmentMap.set( + getOriginalNode(property), + lexicalEnvironment, + ); } currentClassElement = savedCurrentClassElement; return transformed; } - function transformPropertyWorker(property: PropertyDeclaration, receiver: LeftHandSideExpression) { + function transformPropertyWorker( + property: PropertyDeclaration, + receiver: LeftHandSideExpression, + ) { // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) const emitAssignment = !useDefineForClassFields; @@ -2541,25 +3378,40 @@ export function transformClassFields(context: TransformationContext): (x: Source property = transformNamedEvaluation(context, property); } - const propertyName = hasAccessorModifier(property) ? - factory.getGeneratedPrivateNameForNode(property.name) : - isComputedPropertyName(property.name) && !isSimpleInlineableExpression(property.name.expression) ? - factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name)) : - property.name; + const propertyName = hasAccessorModifier(property) + ? factory.getGeneratedPrivateNameForNode(property.name) + : isComputedPropertyName(property.name) && + !isSimpleInlineableExpression(property.name.expression) + ? factory.updateComputedPropertyName( + property.name, + factory.getGeneratedNameForNode(property.name), + ) + : property.name; if (hasStaticModifier(property)) { currentClassElement = property; } - if (isPrivateIdentifier(propertyName) && shouldTransformClassElementToWeakMap(property as PrivateIdentifierPropertyDeclaration)) { + if ( + isPrivateIdentifier(propertyName) && + shouldTransformClassElementToWeakMap( + property as PrivateIdentifierPropertyDeclaration, + ) + ) { const privateIdentifierInfo = accessPrivateIdentifier(propertyName); if (privateIdentifierInfo) { - if (privateIdentifierInfo.kind === PrivateIdentifierKind.Field) { + if ( + privateIdentifierInfo.kind === PrivateIdentifierKind.Field + ) { if (!privateIdentifierInfo.isStatic) { return createPrivateInstanceFieldInitializer( factory, receiver, - visitNode(property.initializer, visitor, isExpression), + visitNode( + property.initializer, + visitor, + isExpression, + ), privateIdentifierInfo.brandCheckIdentifier, ); } @@ -2567,7 +3419,11 @@ export function transformClassFields(context: TransformationContext): (x: Source return createPrivateStaticFieldInitializer( factory, privateIdentifierInfo.variableName, - visitNode(property.initializer, visitor, isExpression), + visitNode( + property.initializer, + visitor, + isExpression, + ), ); } } @@ -2579,17 +3435,33 @@ export function transformClassFields(context: TransformationContext): (x: Source Debug.fail("Undeclared private name for property declaration."); } } - if ((isPrivateIdentifier(propertyName) || hasStaticModifier(property)) && !property.initializer) { + if ( + (isPrivateIdentifier(propertyName) || + hasStaticModifier(property)) && + !property.initializer + ) { return undefined; } const propertyOriginalNode = getOriginalNode(property); - if (hasSyntacticModifier(propertyOriginalNode, ModifierFlags.Abstract)) { + if ( + hasSyntacticModifier(propertyOriginalNode, ModifierFlags.Abstract) + ) { return undefined; } - let initializer = visitNode(property.initializer, visitor, isExpression); - if (isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && isIdentifier(propertyName)) { + let initializer = visitNode( + property.initializer, + visitor, + isExpression, + ); + if ( + isParameterPropertyDeclaration( + propertyOriginalNode, + propertyOriginalNode.parent, + ) && + isIdentifier(propertyName) + ) { // A parameter-property declaration always overrides the initializer. The only time a parameter-property // declaration *should* have an initializer is when decorators have added initializers that need to run before // any other initializer @@ -2599,18 +3471,27 @@ export function transformClassFields(context: TransformationContext): (x: Source if ( isParenthesizedExpression(initializer) && isCommaExpression(initializer.expression) && - isCallToHelper(initializer.expression.left, "___runInitializers" as __String) && + isCallToHelper( + initializer.expression.left, + "___runInitializers" as __String, + ) && isVoidExpression(initializer.expression.right) && isNumericLiteral(initializer.expression.right.expression) ) { initializer = initializer.expression.left; } - initializer = factory.inlineExpressions([initializer, localName]); + initializer = factory.inlineExpressions([ + initializer, + localName, + ]); } else { initializer = localName; } - setEmitFlags(propertyName, EmitFlags.NoComments | EmitFlags.NoSourceMap); + setEmitFlags( + propertyName, + EmitFlags.NoComments | EmitFlags.NoSourceMap, + ); setSourceMapRange(localName, propertyOriginalNode.name); setEmitFlags(localName, EmitFlags.NoComments); } @@ -2619,22 +3500,47 @@ export function transformClassFields(context: TransformationContext): (x: Source } if (emitAssignment || isPrivateIdentifier(propertyName)) { - const memberAccess = createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ propertyName); + const memberAccess = createMemberAccessForPropertyName( + factory, + receiver, + propertyName, + /*location*/ propertyName, + ); addEmitFlags(memberAccess, EmitFlags.NoLeadingComments); - const expression = factory.createAssignment(memberAccess, initializer); + const expression = factory.createAssignment( + memberAccess, + initializer, + ); return expression; } else { - const name = isComputedPropertyName(propertyName) ? propertyName.expression - : isIdentifier(propertyName) ? factory.createStringLiteral(unescapeLeadingUnderscores(propertyName.escapedText)) + const name = isComputedPropertyName(propertyName) + ? propertyName.expression + : isIdentifier(propertyName) + ? factory.createStringLiteral( + unescapeLeadingUnderscores(propertyName.escapedText), + ) : propertyName; - const descriptor = factory.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true }); - return factory.createObjectDefinePropertyCall(receiver, name, descriptor); + const descriptor = factory.createPropertyDescriptor({ + value: initializer, + configurable: true, + writable: true, + enumerable: true, + }); + return factory.createObjectDefinePropertyCall( + receiver, + name, + descriptor, + ); } } function enableSubstitutionForClassAliases() { - if ((enabledSubstitutions & ClassPropertySubstitutionFlags.ClassAliases) === 0) { + if ( + (enabledSubstitutions & + ClassPropertySubstitutionFlags.ClassAliases) === + 0 + ) { enabledSubstitutions |= ClassPropertySubstitutionFlags.ClassAliases; // We need to enable substitutions for identifiers. This allows us to @@ -2647,7 +3553,11 @@ export function transformClassFields(context: TransformationContext): (x: Source } function enableSubstitutionForClassStaticThisOrSuperReference() { - if ((enabledSubstitutions & ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference) === 0) { + if ( + (enabledSubstitutions & + ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference) === + 0 + ) { enabledSubstitutions |= ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference; // substitute `this` in a static field initializer @@ -2670,28 +3580,46 @@ export function transformClassFields(context: TransformationContext): (x: Source * @param methods An array of method declarations. * @param receiver The receiver on which each method should be assigned. */ - function addInstanceMethodStatements(statements: Statement[], methods: readonly (MethodDeclaration | AccessorDeclaration | AutoAccessorPropertyDeclaration)[], receiver: LeftHandSideExpression) { - if (!shouldTransformPrivateElementsOrClassStaticBlocks || !some(methods)) { + function addInstanceMethodStatements( + statements: Statement[], + methods: readonly ( + | MethodDeclaration + | AccessorDeclaration + | AutoAccessorPropertyDeclaration + )[], + receiver: LeftHandSideExpression, + ) { + if ( + !shouldTransformPrivateElementsOrClassStaticBlocks || + !some(methods) + ) { return; } const { weakSetName } = getPrivateIdentifierEnvironment().data; - Debug.assert(weakSetName, "weakSetName should be set in private identifier environment"); + Debug.assert( + weakSetName, + "weakSetName should be set in private identifier environment", + ); statements.push( factory.createExpressionStatement( - createPrivateInstanceMethodInitializer(factory, receiver, weakSetName), + createPrivateInstanceMethodInitializer( + factory, + receiver, + weakSetName, + ), ), ); } function visitInvalidSuperProperty(node: SuperProperty) { - return isPropertyAccessExpression(node) ? - factory.updatePropertyAccessExpression( + return isPropertyAccessExpression(node) + ? factory.updatePropertyAccessExpression( node, factory.createVoidZero(), node.name, - ) : - factory.updateElementAccessExpression( + ) + : factory.updateElementAccessExpression( node, factory.createVoidZero(), visitNode(node.argumentExpression, visitor, isExpression), @@ -2703,16 +3631,28 @@ export function transformClassFields(context: TransformationContext): (x: Source * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) */ - function getPropertyNameExpressionIfNeeded(name: PropertyName, shouldHoist: boolean): Expression | undefined { + function getPropertyNameExpressionIfNeeded( + name: PropertyName, + shouldHoist: boolean, + ): Expression | undefined { if (isComputedPropertyName(name)) { const cacheAssignment = findComputedPropertyNameCacheAssignment(name); - const expression = visitNode(name.expression, visitor, isExpression); + const expression = visitNode( + name.expression, + visitor, + isExpression, + ); const innerExpression = skipPartiallyEmittedExpressions(expression); const inlinable = isSimpleInlineableExpression(innerExpression); - const alreadyTransformed = !!cacheAssignment || isAssignmentExpression(innerExpression) && isGeneratedIdentifier(innerExpression.left); + const alreadyTransformed = !!cacheAssignment || + (isAssignmentExpression(innerExpression) && + isGeneratedIdentifier(innerExpression.left)); if (!alreadyTransformed && !inlinable && shouldHoist) { const generatedName = factory.getGeneratedNameForNode(name); - if (resolver.getNodeCheckFlags(name) & NodeCheckFlags.BlockScopedBindingInLoop) { + if ( + resolver.getNodeCheckFlags(name) & + NodeCheckFlags.BlockScopedBindingInLoop + ) { addBlockScopedVariable(generatedName); } else { @@ -2720,7 +3660,9 @@ export function transformClassFields(context: TransformationContext): (x: Source } return factory.createAssignment(generatedName, expression); } - return (inlinable || isIdentifier(innerExpression)) ? undefined : expression; + return inlinable || isIdentifier(innerExpression) + ? undefined + : expression; } } @@ -2734,29 +3676,33 @@ export function transformClassFields(context: TransformationContext): (x: Source function getClassLexicalEnvironment(): ClassLexicalEnvironment { Debug.assert(lexicalEnvironment); - return lexicalEnvironment.data ??= { + return (lexicalEnvironment.data ??= { facts: ClassFacts.None, classConstructor: undefined, classThis: undefined, superClassReference: undefined, // privateIdentifierEnvironment: undefined, - }; + }); } function getPrivateIdentifierEnvironment(): PrivateEnv { Debug.assert(lexicalEnvironment); - return lexicalEnvironment.privateEnv ??= newPrivateEnvironment({ + return (lexicalEnvironment.privateEnv ??= newPrivateEnvironment({ className: undefined, weakSetName: undefined, - }); + })); } function getPendingExpressions() { - return pendingExpressions ??= []; + return (pendingExpressions ??= []); } function addPrivateIdentifierClassElementToEnvironment( - node: PropertyDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration, + node: + | PropertyDeclaration + | MethodDeclaration + | GetAccessorDeclaration + | SetAccessorDeclaration, name: PrivateIdentifier, lex: ClassLexicalEnvironment, privateEnv: PrivateEnv, @@ -2765,19 +3711,59 @@ export function transformClassFields(context: TransformationContext): (x: Source previousInfo: PrivateIdentifierInfo | undefined, ) { if (isAutoAccessorPropertyDeclaration(node)) { - addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo); + addPrivateIdentifierAutoAccessorPropertyDeclarationToEnvironment( + node, + name, + lex, + privateEnv, + isStatic, + isValid, + previousInfo, + ); } else if (isPropertyDeclaration(node)) { - addPrivateIdentifierPropertyDeclarationToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo); + addPrivateIdentifierPropertyDeclarationToEnvironment( + node, + name, + lex, + privateEnv, + isStatic, + isValid, + previousInfo, + ); } else if (isMethodDeclaration(node)) { - addPrivateIdentifierMethodDeclarationToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo); + addPrivateIdentifierMethodDeclarationToEnvironment( + node, + name, + lex, + privateEnv, + isStatic, + isValid, + previousInfo, + ); } else if (isGetAccessorDeclaration(node)) { - addPrivateIdentifierGetAccessorDeclarationToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo); + addPrivateIdentifierGetAccessorDeclarationToEnvironment( + node, + name, + lex, + privateEnv, + isStatic, + isValid, + previousInfo, + ); } else if (isSetAccessorDeclaration(node)) { - addPrivateIdentifierSetAccessorDeclarationToEnvironment(node, name, lex, privateEnv, isStatic, isValid, previousInfo); + addPrivateIdentifierSetAccessorDeclarationToEnvironment( + node, + name, + lex, + privateEnv, + isStatic, + isValid, + previousInfo, + ); } } @@ -2791,7 +3777,10 @@ export function transformClassFields(context: TransformationContext): (x: Source _previousInfo: PrivateIdentifierInfo | undefined, ) { if (isStatic) { - const brandCheckIdentifier = Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment"); + const brandCheckIdentifier = Debug.checkDefined( + lex.classThis ?? lex.classConstructor, + "classConstructor should be set in private identifier environment", + ); const variableName = createHoistedVariableForPrivateName(name); setPrivateIdentifier(privateEnv, name, { @@ -2812,14 +3801,16 @@ export function transformClassFields(context: TransformationContext): (x: Source isValid, }); - getPendingExpressions().push(factory.createAssignment( - weakMapName, - factory.createNewExpression( - factory.createIdentifier("WeakMap"), - /*typeArguments*/ undefined, - [], + getPendingExpressions().push( + factory.createAssignment( + weakMapName, + factory.createNewExpression( + factory.createIdentifier("WeakMap"), + /*typeArguments*/ undefined, + [], + ), ), - )); + ); } } @@ -2833,9 +3824,15 @@ export function transformClassFields(context: TransformationContext): (x: Source _previousInfo: PrivateIdentifierInfo | undefined, ) { const methodName = createHoistedVariableForPrivateName(name); - const brandCheckIdentifier = isStatic ? - Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : - Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic + ? Debug.checkDefined( + lex.classThis ?? lex.classConstructor, + "classConstructor should be set in private identifier environment", + ) + : Debug.checkDefined( + privateEnv.data.weakSetName, + "weakSetName should be set in private identifier environment", + ); setPrivateIdentifier(privateEnv, name, { kind: PrivateIdentifierKind.Method, @@ -2856,11 +3853,21 @@ export function transformClassFields(context: TransformationContext): (x: Source previousInfo: PrivateIdentifierInfo | undefined, ) { const getterName = createHoistedVariableForPrivateName(name, "_get"); - const brandCheckIdentifier = isStatic ? - Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : - Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic + ? Debug.checkDefined( + lex.classThis ?? lex.classConstructor, + "classConstructor should be set in private identifier environment", + ) + : Debug.checkDefined( + privateEnv.data.weakSetName, + "weakSetName should be set in private identifier environment", + ); - if (previousInfo?.kind === PrivateIdentifierKind.Accessor && previousInfo.isStatic === isStatic && !previousInfo.getterName) { + if ( + previousInfo?.kind === PrivateIdentifierKind.Accessor && + previousInfo.isStatic === isStatic && + !previousInfo.getterName + ) { previousInfo.getterName = getterName; } else { @@ -2885,13 +3892,20 @@ export function transformClassFields(context: TransformationContext): (x: Source previousInfo: PrivateIdentifierInfo | undefined, ) { const setterName = createHoistedVariableForPrivateName(name, "_set"); - const brandCheckIdentifier = isStatic ? - Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : - Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic + ? Debug.checkDefined( + lex.classThis ?? lex.classConstructor, + "classConstructor should be set in private identifier environment", + ) + : Debug.checkDefined( + privateEnv.data.weakSetName, + "weakSetName should be set in private identifier environment", + ); if ( previousInfo?.kind === PrivateIdentifierKind.Accessor && - previousInfo.isStatic === isStatic && !previousInfo.setterName + previousInfo.isStatic === isStatic && + !previousInfo.setterName ) { previousInfo.setterName = setterName; } @@ -2918,9 +3932,15 @@ export function transformClassFields(context: TransformationContext): (x: Source ) { const getterName = createHoistedVariableForPrivateName(name, "_get"); const setterName = createHoistedVariableForPrivateName(name, "_set"); - const brandCheckIdentifier = isStatic ? - Debug.checkDefined(lex.classThis ?? lex.classConstructor, "classConstructor should be set in private identifier environment") : - Debug.checkDefined(privateEnv.data.weakSetName, "weakSetName should be set in private identifier environment"); + const brandCheckIdentifier = isStatic + ? Debug.checkDefined( + lex.classThis ?? lex.classConstructor, + "classConstructor should be set in private identifier environment", + ) + : Debug.checkDefined( + privateEnv.data.weakSetName, + "weakSetName should be set in private identifier environment", + ); setPrivateIdentifier(privateEnv, name, { kind: PrivateIdentifierKind.Accessor, @@ -2932,7 +3952,13 @@ export function transformClassFields(context: TransformationContext): (x: Source }); } - function addPrivateIdentifierToEnvironment( + function addPrivateIdentifierToEnvironment< + T extends + | PropertyDeclaration + | MethodDeclaration + | GetAccessorDeclaration + | SetAccessorDeclaration, + >( node: T, name: PrivateIdentifier, addDeclaration: ( @@ -2950,17 +3976,52 @@ export function transformClassFields(context: TransformationContext): (x: Source const previousInfo = getPrivateIdentifier(privateEnv, name); const isStatic = hasStaticModifier(node); const isValid = !isReservedPrivateName(name) && previousInfo === undefined; - addDeclaration(node, name, lex, privateEnv, isStatic, isValid, previousInfo); + addDeclaration( + node, + name, + lex, + privateEnv, + isStatic, + isValid, + previousInfo, + ); } - function createHoistedVariableForClass(name: string | PrivateIdentifier | undefined, node: PrivateIdentifier | ClassStaticBlockDeclaration, suffix?: string): Identifier { + function createHoistedVariableForClass( + name: string | PrivateIdentifier | undefined, + node: PrivateIdentifier | ClassStaticBlockDeclaration, + suffix?: string, + ): Identifier { const { className } = getPrivateIdentifierEnvironment().data; - const prefix: GeneratedNamePart | string = className ? { prefix: "_", node: className, suffix: "_" } : "_"; - const identifier = typeof name === "object" ? factory.getGeneratedNameForNode(name, GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.ReservedInNestedScopes, prefix, suffix) : - typeof name === "string" ? factory.createUniqueName(name, GeneratedIdentifierFlags.Optimistic, prefix, suffix) : - factory.createTempVariable(/*recordTempVariable*/ undefined, /*reservedInNestedScopes*/ true, prefix, suffix); + const prefix: GeneratedNamePart | string = className + ? { prefix: "_", node: className, suffix: "_" } + : "_"; + const identifier = typeof name === "object" + ? factory.getGeneratedNameForNode( + name, + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.ReservedInNestedScopes, + prefix, + suffix, + ) + : typeof name === "string" + ? factory.createUniqueName( + name, + GeneratedIdentifierFlags.Optimistic, + prefix, + suffix, + ) + : factory.createTempVariable( + /*recordTempVariable*/ undefined, + /*reservedInNestedScopes*/ true, + prefix, + suffix, + ); - if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.BlockScopedBindingInLoop) { + if ( + resolver.getNodeCheckFlags(node) & + NodeCheckFlags.BlockScopedBindingInLoop + ) { addBlockScopedVariable(identifier); } else { @@ -2970,9 +4031,16 @@ export function transformClassFields(context: TransformationContext): (x: Source return identifier; } - function createHoistedVariableForPrivateName(name: PrivateIdentifier, suffix?: string): Identifier { + function createHoistedVariableForPrivateName( + name: PrivateIdentifier, + suffix?: string, + ): Identifier { const text = tryGetTextOfPropertyName(name) as string | undefined; - return createHoistedVariableForClass(text?.substring(1) ?? name, name, suffix); + return createHoistedVariableForClass( + text?.substring(1) ?? name, + name, + suffix, + ); } /** @@ -2985,7 +4053,9 @@ export function transformClassFields(context: TransformationContext): (x: Source return info?.kind === "untransformed" ? undefined : info; } - function wrapPrivateIdentifierForDestructuringTarget(node: PrivateIdentifierPropertyAccessExpression) { + function wrapPrivateIdentifierForDestructuringTarget( + node: PrivateIdentifierPropertyAccessExpression, + ) { const parameter = factory.getGeneratedNameForNode(node); const info = accessPrivateIdentifier(node.name); if (!info) { @@ -2994,9 +4064,22 @@ export function transformClassFields(context: TransformationContext): (x: Source let receiver = node.expression; // We cannot copy `this` or `super` into the function because they will be bound // differently inside the function. - if (isThisProperty(node) || isSuperProperty(node) || !isSimpleCopiableExpression(node.expression)) { - receiver = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true); - getPendingExpressions().push(factory.createBinaryExpression(receiver, SyntaxKind.EqualsToken, visitNode(node.expression, visitor, isExpression))); + if ( + isThisProperty(node) || + isSuperProperty(node) || + !isSimpleCopiableExpression(node.expression) + ) { + receiver = factory.createTempVariable( + hoistVariableDeclaration, + /*reservedInNestedScopes*/ true, + ); + getPendingExpressions().push( + factory.createBinaryExpression( + receiver, + SyntaxKind.EqualsToken, + visitNode(node.expression, visitor, isExpression), + ), + ); } return factory.createAssignmentTargetWrapper( parameter, @@ -3009,7 +4092,9 @@ export function transformClassFields(context: TransformationContext): (x: Source ); } - function visitDestructuringAssignmentTarget(node: LeftHandSideExpression): LeftHandSideExpression { + function visitDestructuringAssignmentTarget( + node: LeftHandSideExpression, + ): LeftHandSideExpression { if (isObjectLiteralExpression(node) || isArrayLiteralExpression(node)) { return visitAssignmentPattern(node); } @@ -3021,7 +4106,9 @@ export function transformClassFields(context: TransformationContext): (x: Source shouldTransformSuperInStaticInitializers && currentClassElement && isSuperProperty(node) && - isStaticPropertyDeclarationOrClassStaticBlock(currentClassElement) && + isStaticPropertyDeclarationOrClassStaticBlock( + currentClassElement, + ) && lexicalEnvironment?.data ) { const { classConstructor, superClassReference, facts } = lexicalEnvironment.data; @@ -3029,11 +4116,15 @@ export function transformClassFields(context: TransformationContext): (x: Source return visitInvalidSuperProperty(node); } else if (classConstructor && superClassReference) { - const name = isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : - isIdentifier(node.name) ? factory.createStringLiteralFromNode(node.name) : - undefined; + const name = isElementAccessExpression(node) + ? visitNode(node.argumentExpression, visitor, isExpression) + : isIdentifier(node.name) + ? factory.createStringLiteralFromNode(node.name) + : undefined; if (name) { - const temp = factory.createTempVariable(/*recordTempVariable*/ undefined); + const temp = factory.createTempVariable( + /*recordTempVariable*/ undefined, + ); return factory.createAssignmentTargetWrapper( temp, factory.createReflectSetCall( @@ -3049,7 +4140,9 @@ export function transformClassFields(context: TransformationContext): (x: Source return visitEachChild(node, visitor, context); } - function visitAssignmentElement(node: Exclude): ArrayAssignmentElement { + function visitAssignmentElement( + node: Exclude, + ): ArrayAssignmentElement { // 13.15.5.5 RS: IteratorDestructuringAssignmentEvaluation // AssignmentElement : DestructuringAssignmentTarget Initializer? // ... @@ -3064,14 +4157,23 @@ export function transformClassFields(context: TransformationContext): (x: Source if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { const left = visitDestructuringAssignmentTarget(node.left); const right = visitNode(node.right, visitor, isExpression); - return factory.updateBinaryExpression(node, left, node.operatorToken, right) as AssignmentExpression; + return factory.updateBinaryExpression( + node, + left, + node.operatorToken, + right, + ) as AssignmentExpression; } - return visitDestructuringAssignmentTarget(node) as ArrayAssignmentElement; + return visitDestructuringAssignmentTarget( + node, + ) as ArrayAssignmentElement; } function visitAssignmentRestElement(node: SpreadElement) { if (isLeftHandSideExpression(node.expression)) { - const expression = visitDestructuringAssignmentTarget(node.expression); + const expression = visitDestructuringAssignmentTarget( + node.expression, + ); return factory.updateSpreadElement(node, expression); } @@ -3099,20 +4201,37 @@ export function transformClassFields(context: TransformationContext): (x: Source // ... const name = visitNode(node.name, visitor, isPropertyName); - if (isAssignmentExpression(node.initializer, /*excludeCompoundAssignment*/ true)) { + if ( + isAssignmentExpression( + node.initializer, + /*excludeCompoundAssignment*/ true, + ) + ) { const assignmentElement = visitAssignmentElement(node.initializer); - return factory.updatePropertyAssignment(node, name, assignmentElement); + return factory.updatePropertyAssignment( + node, + name, + assignmentElement, + ); } if (isLeftHandSideExpression(node.initializer)) { - const assignmentElement = visitDestructuringAssignmentTarget(node.initializer); - return factory.updatePropertyAssignment(node, name, assignmentElement); + const assignmentElement = visitDestructuringAssignmentTarget( + node.initializer, + ); + return factory.updatePropertyAssignment( + node, + name, + assignmentElement, + ); } return visitEachChild(node, visitor, context); } - function visitShorthandAssignmentProperty(node: ShorthandPropertyAssignment) { + function visitShorthandAssignmentProperty( + node: ShorthandPropertyAssignment, + ) { // AssignmentProperty : IdentifierReference Initializer? // 13.15.5.3 RS: PropertyDestructuringAssignmentEvaluation @@ -3132,7 +4251,9 @@ export function transformClassFields(context: TransformationContext): (x: Source function visitAssignmentRestProperty(node: SpreadAssignment) { if (isLeftHandSideExpression(node.expression)) { - const expression = visitDestructuringAssignmentTarget(node.expression); + const expression = visitDestructuringAssignmentTarget( + node.expression, + ); return factory.updateSpreadAssignment(node, expression); } @@ -3159,7 +4280,11 @@ export function transformClassFields(context: TransformationContext): (x: Source // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ]; return factory.updateArrayLiteralExpression( node, - visitNodes(node.elements, visitArrayAssignmentElement, isExpression), + visitNodes( + node.elements, + visitArrayAssignmentElement, + isExpression, + ), ); } else { @@ -3173,12 +4298,20 @@ export function transformClassFields(context: TransformationContext): (x: Source // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" }; return factory.updateObjectLiteralExpression( node, - visitNodes(node.properties, visitObjectAssignmentElement, isObjectLiteralElementLike), + visitNodes( + node.properties, + visitObjectAssignmentElement, + isObjectLiteralElementLike, + ), ); } } - function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) { + function onEmitNode( + hint: EmitHint, + node: Node, + emitCallback: (hint: EmitHint, node: Node) => void, + ) { const original = getOriginalNode(node); const lex = lexicalEnvironmentMap.get(original); if (lex) { @@ -3187,7 +4320,11 @@ export function transformClassFields(context: TransformationContext): (x: Source const savedPreviousShouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; lexicalEnvironment = lex; previousShouldSubstituteThisWithClassThis = shouldSubstituteThisWithClassThis; - shouldSubstituteThisWithClassThis = !isClassStaticBlockDeclaration(original) || !(getInternalEmitFlags(original) & InternalEmitFlags.TransformPrivateStaticElements); + shouldSubstituteThisWithClassThis = !isClassStaticBlockDeclaration(original) || + !( + getInternalEmitFlags(original) & + InternalEmitFlags.TransformPrivateStaticElements + ); previousOnEmitNode(hint, node, emitCallback); shouldSubstituteThisWithClassThis = previousShouldSubstituteThisWithClassThis; previousShouldSubstituteThisWithClassThis = savedPreviousShouldSubstituteThisWithClassThis; @@ -3197,12 +4334,15 @@ export function transformClassFields(context: TransformationContext): (x: Source switch (node.kind) { case SyntaxKind.FunctionExpression: - if (isArrowFunction(original) || getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { + if ( + isArrowFunction(original) || + getEmitFlags(node) & EmitFlags.AsyncFunctionBody + ) { // Arrow functions and functions that serve as the transformed body of an async function should // preserve the outer lexical environment. break; } - // falls through + // falls through case SyntaxKind.FunctionDeclaration: case SyntaxKind.Constructor: @@ -3258,32 +4398,34 @@ export function transformClassFields(context: TransformationContext): (x: Source function substituteExpression(node: Expression) { switch (node.kind) { case SyntaxKind.Identifier: - return substituteExpressionIdentifier(node as Identifier); + return substituteExpressionIdentifier(node); case SyntaxKind.ThisKeyword: - return substituteThisExpression(node as ThisExpression); + return substituteThisExpression(node); } return node; } function substituteThisExpression(node: ThisExpression) { if ( - enabledSubstitutions & ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference && + enabledSubstitutions & + ClassPropertySubstitutionFlags.ClassStaticThisOrSuperReference && lexicalEnvironment?.data && !noSubstitution.has(node) ) { const { facts, classConstructor, classThis } = lexicalEnvironment.data; - const substituteThis = shouldSubstituteThisWithClassThis ? classThis ?? classConstructor : classConstructor; + const substituteThis = shouldSubstituteThisWithClassThis + ? classThis ?? classConstructor + : classConstructor; if (substituteThis) { return setTextRange( - setOriginalNode( - factory.cloneNode(substituteThis), - node, - ), + setOriginalNode(factory.cloneNode(substituteThis), node), node, ); } if (facts & ClassFacts.ClassWasDecorated && legacyDecorators) { - return factory.createParenthesizedExpression(factory.createVoidZero()); + return factory.createParenthesizedExpression( + factory.createVoidZero(), + ); } } return node; @@ -3294,8 +4436,13 @@ export function transformClassFields(context: TransformationContext): (x: Source } function trySubstituteClassAlias(node: Identifier): Expression | undefined { - if (enabledSubstitutions & ClassPropertySubstitutionFlags.ClassAliases) { - if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.ConstructorReference) { + if ( + enabledSubstitutions & ClassPropertySubstitutionFlags.ClassAliases + ) { + if ( + resolver.getNodeCheckFlags(node) & + NodeCheckFlags.ConstructorReference + ) { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. @@ -3318,16 +4465,28 @@ export function transformClassFields(context: TransformationContext): (x: Source } } -function createPrivateStaticFieldInitializer(factory: NodeFactory, variableName: Identifier, initializer: Expression | undefined) { +function createPrivateStaticFieldInitializer( + factory: NodeFactory, + variableName: Identifier, + initializer: Expression | undefined, +) { return factory.createAssignment( variableName, factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("value", initializer || factory.createVoidZero()), + factory.createPropertyAssignment( + "value", + initializer || factory.createVoidZero(), + ), ]), ); } -function createPrivateInstanceFieldInitializer(factory: NodeFactory, receiver: LeftHandSideExpression, initializer: Expression | undefined, weakMapName: Identifier) { +function createPrivateInstanceFieldInitializer( + factory: NodeFactory, + receiver: LeftHandSideExpression, + initializer: Expression | undefined, + weakMapName: Identifier, +) { return factory.createCallExpression( factory.createPropertyAccessExpression(weakMapName, "set"), /*typeArguments*/ undefined, @@ -3335,7 +4494,11 @@ function createPrivateInstanceFieldInitializer(factory: NodeFactory, receiver: L ); } -function createPrivateInstanceMethodInitializer(factory: NodeFactory, receiver: LeftHandSideExpression, weakSetName: Identifier) { +function createPrivateInstanceMethodInitializer( + factory: NodeFactory, + receiver: LeftHandSideExpression, + weakSetName: Identifier, +) { return factory.createCallExpression( factory.createPropertyAccessExpression(weakSetName, "add"), /*typeArguments*/ undefined, @@ -3344,20 +4507,34 @@ function createPrivateInstanceMethodInitializer(factory: NodeFactory, receiver: } function isReservedPrivateName(node: PrivateIdentifier) { - return !isGeneratedPrivateIdentifier(node) && node.escapedText === "#constructor"; + return ( + !isGeneratedPrivateIdentifier(node) && + node.escapedText === "#constructor" + ); } -type PrivateIdentifierInExpression = BinaryExpression & { readonly left: PrivateIdentifier; readonly token: InKeyword; }; - -function isPrivateIdentifierInExpression(node: BinaryExpression): node is PrivateIdentifierInExpression { - return isPrivateIdentifier(node.left) - && node.operatorToken.kind === SyntaxKind.InKeyword; +type PrivateIdentifierInExpression = BinaryExpression & { + readonly left: PrivateIdentifier; + readonly token: InKeyword; +}; + +function isPrivateIdentifierInExpression( + node: BinaryExpression, +): node is PrivateIdentifierInExpression { + return ( + isPrivateIdentifier(node.left) && + node.operatorToken.kind === SyntaxKind.InKeyword + ); } function isStaticPropertyDeclaration(node: Node): node is PropertyDeclaration { return isPropertyDeclaration(node) && hasStaticModifier(node); } -function isStaticPropertyDeclarationOrClassStaticBlock(node: Node): node is ClassStaticBlockDeclaration | PropertyDeclaration { - return isClassStaticBlockDeclaration(node) || isStaticPropertyDeclaration(node); +function isStaticPropertyDeclarationOrClassStaticBlock( + node: Node, +): node is ClassStaticBlockDeclaration | PropertyDeclaration { + return ( + isClassStaticBlockDeclaration(node) || isStaticPropertyDeclaration(node) + ); } diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index e649e1b2b4330..7e5ef2ada0b7b 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -171,6 +171,7 @@ import { needsScopeMarker, Node, NodeArray, + NodeBase, NodeBuilderFlags, NodeFactory, NodeFlags, @@ -194,7 +195,6 @@ import { setOriginalNode, setParent, setTextRange, - SignatureDeclaration, skipTrivia, some, SourceFile, @@ -246,8 +246,8 @@ function hasInternalAnnotation(range: CommentRange, currentSourceFile: SourceFil export function isInternalDeclaration(node: Node, currentSourceFile: SourceFile) { const parseTreeNode = getParseTreeNode(node); if (parseTreeNode && parseTreeNode.kind === SyntaxKind.Parameter) { - const paramIdx = (parseTreeNode.parent as SignatureDeclaration).parameters.indexOf(parseTreeNode as ParameterDeclaration); - const previousSibling = paramIdx > 0 ? (parseTreeNode.parent as SignatureDeclaration).parameters[paramIdx - 1] : undefined; + const paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode); + const previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined; const text = currentSourceFile.text; const commentRanges = previousSibling ? concatenate( @@ -837,8 +837,9 @@ export function transformDeclarations(context: TransformationContext) { return !resolver.isDeclarationVisible(node); // The following should be doing their own visibility checks based on filtering their members case SyntaxKind.VariableDeclaration: - return !getBindingNameVisible(node as VariableDeclaration); + return !getBindingNameVisible(node); case SyntaxKind.ImportEqualsDeclaration: + // @ts-expect-error -- ?! Not in NamedDeclaration? case SyntaxKind.ImportDeclaration: case SyntaxKind.ExportDeclaration: case SyntaxKind.ExportAssignment: @@ -940,7 +941,7 @@ export function transformDeclarations(context: TransformationContext) { return setCommentRange(updated, getCommentRange(original)); } - function rewriteModuleSpecifier(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration | ImportTypeNode, input: T | undefined): T | StringLiteral { + function rewriteModuleSpecifier(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration | ImportTypeNode, input: T | undefined): T | StringLiteral { if (!input) return undefined!; // TODO: GH#18217 resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== SyntaxKind.ModuleDeclaration && parent.kind !== SyntaxKind.ImportType); if (isStringLiteralLike(input)) { @@ -1116,7 +1117,7 @@ export function transformDeclarations(context: TransformationContext) { function visitDeclarationSubtree(input: Node): VisitResult { if (shouldStripInternal(input)) return; if (isDeclaration(input)) { - if (isDeclarationAndNotVisible(input)) return; + if (isDeclarationAndNotVisible(input as NamedDeclaration)) return; if (hasDynamicName(input) && !resolver.isLateBound(getParseTreeNode(input) as Declaration)) { return; } diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index 09c388378bd5c..147996dcd937f 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -49,7 +49,7 @@ import { MethodDeclaration, MethodSignature, ModifierFlags, - NamedDeclaration, + NamedDeclarationBase, Node, ParameterDeclaration, PropertyAccessExpression, @@ -144,7 +144,7 @@ export function createGetSymbolAccessibilityDiagnosticForNodeName(node: Declarat return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, - typeName: (node as NamedDeclaration).name, + typeName: (node as NamedDeclarationBase).name, } : undefined; } @@ -175,7 +175,7 @@ export function createGetSymbolAccessibilityDiagnosticForNodeName(node: Declarat return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, - typeName: (node as NamedDeclaration).name, + typeName: (node as NamedDeclarationBase).name, } : undefined; } @@ -278,7 +278,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, - typeName: (node as NamedDeclaration).name, + typeName: (node as NamedDeclarationBase).name, } : undefined; } @@ -316,8 +316,8 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD } return { diagnosticMessage, - errorNode: (node as NamedDeclaration).name!, - typeName: (node as NamedDeclaration).name, + errorNode: (node as NamedDeclarationBase).name!, + typeName: (node as NamedDeclarationBase).name, }; } @@ -383,7 +383,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return { diagnosticMessage, - errorNode: (node as NamedDeclaration).name || node, + errorNode: (node as NamedDeclarationBase).name || node, }; } @@ -392,7 +392,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, - typeName: (node as NamedDeclaration).name, + typeName: (node as NamedDeclarationBase).name, } : undefined; } @@ -525,7 +525,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return { diagnosticMessage, errorNode: node, - typeName: (node as NamedDeclaration).name, + typeName: (node as NamedDeclarationBase).name, }; } @@ -555,7 +555,7 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD return { diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1, errorNode: node, - typeName: (node as NamedDeclaration).name, + typeName: (node as NamedDeclarationBase).name, }; } diff --git a/src/compiler/transformers/destructuring.ts b/src/compiler/transformers/destructuring.ts index 1a3b93e8b77fa..c1425c1f9dd0e 100644 --- a/src/compiler/transformers/destructuring.ts +++ b/src/compiler/transformers/destructuring.ts @@ -69,10 +69,21 @@ interface FlattenContext { hoistTempVariables: boolean; hasTransformedPriorElement?: boolean; // indicates whether we've transformed a prior declaration emitExpression: (value: Expression) => void; - emitBindingOrAssignment: (target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node | undefined) => void; - createArrayBindingOrAssignmentPattern: (elements: BindingOrAssignmentElement[]) => ArrayBindingOrAssignmentPattern; - createObjectBindingOrAssignmentPattern: (elements: BindingOrAssignmentElement[]) => ObjectBindingOrAssignmentPattern; - createArrayBindingOrAssignmentElement: (node: Identifier) => BindingOrAssignmentElement; + emitBindingOrAssignment: ( + target: BindingOrAssignmentElementTarget, + value: Expression, + location: TextRange, + original: Node | undefined, + ) => void; + createArrayBindingOrAssignmentPattern: ( + elements: BindingOrAssignmentElement[], + ) => ArrayBindingOrAssignmentPattern; + createObjectBindingOrAssignmentPattern: ( + elements: BindingOrAssignmentElement[], + ) => ObjectBindingOrAssignmentPattern; + createArrayBindingOrAssignmentElement: ( + node: Identifier, + ) => BindingOrAssignmentElement; visitor: (node: Node) => VisitResult; } @@ -101,19 +112,28 @@ export function flattenDestructuringAssignment( context: TransformationContext, level: FlattenLevel, needsValue?: boolean, - createAssignmentCallback?: (name: Identifier, value: Expression, location?: TextRange) => Expression, + createAssignmentCallback?: ( + name: Identifier, + value: Expression, + location?: TextRange, + ) => Expression, ): Expression { let location: TextRange = node; let value: Expression | undefined; if (isDestructuringAssignment(node)) { value = node.right; - while (isEmptyArrayLiteral(node.left) || isEmptyObjectLiteral(node.left)) { + while ( + isEmptyArrayLiteral(node.left) || + isEmptyObjectLiteral(node.left) + ) { if (isDestructuringAssignment(value)) { location = node = value; value = node.right; } else { - return Debug.checkDefined(visitNode(value, visitor, isExpression)); + return Debug.checkDefined( + visitNode(value, visitor, isExpression), + ); } } } @@ -137,12 +157,21 @@ export function flattenDestructuringAssignment( Debug.assert(value); if ( - isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) || + (isIdentifier(value) && + bindingOrAssignmentElementAssignsToName( + node, + value.escapedText, + )) || bindingOrAssignmentElementContainsNonLiteralComputedName(node) ) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. - value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + value = ensureIdentifier( + flattenContext, + value, + /*reuseIdentifierExpressions*/ false, + location, + ); } else if (needsValue) { // If the right-hand value of the destructuring assignment needs to be preserved (as @@ -151,7 +180,12 @@ export function flattenDestructuringAssignment( // // The source map location for the assignment should point to the entire binary // expression. - value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + value = ensureIdentifier( + flattenContext, + value, + /*reuseIdentifierExpressions*/ true, + location, + ); } else if (nodeIsSynthesized(node)) { // Generally, the source map location for a destructuring assignment is the root @@ -164,7 +198,13 @@ export function flattenDestructuringAssignment( } } - flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ isDestructuringAssignment(node)); + flattenBindingOrAssignmentElement( + flattenContext, + node, + value, + location, + /*skipInitializer*/ isDestructuringAssignment(node), + ); if (value && needsValue) { if (!some(expressions)) { @@ -174,18 +214,34 @@ export function flattenDestructuringAssignment( expressions.push(value); } - return context.factory.inlineExpressions(expressions!) || context.factory.createOmittedExpression(); + return ( + context.factory.inlineExpressions(expressions!) || + context.factory.createOmittedExpression() + ); function emitExpression(expression: Expression) { expressions = append(expressions, expression); } - function emitBindingOrAssignment(target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange, original: Node | undefined) { - Debug.assertNode(target, createAssignmentCallback ? isIdentifier : isExpression); + function emitBindingOrAssignment( + target: BindingOrAssignmentElementTarget, + value: Expression, + location: TextRange, + original: Node | undefined, + ) { + Debug.assertNode( + target, + createAssignmentCallback ? isIdentifier : isExpression, + ); const expression = createAssignmentCallback ? createAssignmentCallback(target as Identifier, value, location) : setTextRange( - context.factory.createAssignment(Debug.checkDefined(visitNode(target as Expression, visitor, isExpression)), value), + context.factory.createAssignment( + Debug.checkDefined( + visitNode(target as Expression, visitor, isExpression), + ), + value, + ), location, ); expression.original = original; @@ -193,7 +249,10 @@ export function flattenDestructuringAssignment( } } -function bindingOrAssignmentElementAssignsToName(element: BindingOrAssignmentElement, escapedName: __String): boolean { +function bindingOrAssignmentElementAssignsToName( + element: BindingOrAssignmentElement, + escapedName: __String, +): boolean { const target = getTargetOfBindingOrAssignmentElement(element)!; // TODO: GH#18217 if (isBindingOrAssignmentPattern(target)) { return bindingOrAssignmentPatternAssignsToName(target, escapedName); @@ -204,7 +263,10 @@ function bindingOrAssignmentElementAssignsToName(element: BindingOrAssignmentEle return false; } -function bindingOrAssignmentPatternAssignsToName(pattern: BindingOrAssignmentPattern, escapedName: __String): boolean { +function bindingOrAssignmentPatternAssignsToName( + pattern: BindingOrAssignmentPattern, + escapedName: __String, +): boolean { const elements = getElementsOfBindingOrAssignmentPattern(pattern); for (const element of elements) { if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { @@ -214,17 +276,32 @@ function bindingOrAssignmentPatternAssignsToName(pattern: BindingOrAssignmentPat return false; } -function bindingOrAssignmentElementContainsNonLiteralComputedName(element: BindingOrAssignmentElement): boolean { +function bindingOrAssignmentElementContainsNonLiteralComputedName( + element: BindingOrAssignmentElement, +): boolean { const propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(element); - if (propertyName && isComputedPropertyName(propertyName) && !isLiteralExpression(propertyName.expression)) { + if ( + propertyName && + isComputedPropertyName(propertyName) && + !isLiteralExpression(propertyName.expression) + ) { return true; } const target = getTargetOfBindingOrAssignmentElement(element); - return !!target && isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target); + return ( + !!target && + isBindingOrAssignmentPattern(target) && + bindingOrAssignmentPatternContainsNonLiteralComputedName(target) + ); } -function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern: BindingOrAssignmentPattern): boolean { - return !!forEach(getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName); +function bindingOrAssignmentPatternContainsNonLiteralComputedName( + pattern: BindingOrAssignmentPattern, +): boolean { + return !!forEach( + getElementsOfBindingOrAssignmentPattern(pattern), + bindingOrAssignmentElementContainsNonLiteralComputedName, + ); } /** @@ -250,7 +327,13 @@ export function flattenDestructuringBinding( skipInitializer?: boolean, ): VariableDeclaration[] { let pendingExpressions: Expression[] | undefined; - const pendingDeclarations: { pendingExpressions?: Expression[]; name: BindingName; value: Expression; location?: TextRange; original?: Node; }[] = []; + const pendingDeclarations: { + pendingExpressions?: Expression[]; + name: BindingName; + value: Expression; + location?: TextRange; + original?: Node; + }[] = []; const declarations: VariableDeclaration[] = []; const flattenContext: FlattenContext = { context, @@ -268,23 +351,54 @@ export function flattenDestructuringBinding( if (isVariableDeclaration(node)) { let initializer = getInitializerOfBindingOrAssignmentElement(node); if ( - initializer && (isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) || + initializer && + ((isIdentifier(initializer) && + bindingOrAssignmentElementAssignsToName( + node, + initializer.escapedText, + )) || bindingOrAssignmentElementContainsNonLiteralComputedName(node)) ) { // If the right-hand value of the assignment is also an assignment target then // we need to cache the right-hand value. - initializer = ensureIdentifier(flattenContext, Debug.checkDefined(visitNode(initializer, flattenContext.visitor, isExpression)), /*reuseIdentifierExpressions*/ false, initializer); - node = context.factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, initializer); + initializer = ensureIdentifier( + flattenContext, + Debug.checkDefined( + visitNode(initializer, flattenContext.visitor, isExpression), + ), + /*reuseIdentifierExpressions*/ false, + initializer, + ); + node = context.factory.updateVariableDeclaration( + node, + node.name, + /*exclamationToken*/ undefined, + /*type*/ undefined, + initializer, + ); } } - flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); + flattenBindingOrAssignmentElement( + flattenContext, + node, + rval, + node, + skipInitializer, + ); if (pendingExpressions) { - const temp = context.factory.createTempVariable(/*recordTempVariable*/ undefined); + const temp = context.factory.createTempVariable( + /*recordTempVariable*/ undefined, + ); if (hoistTempVariables) { const value = context.factory.inlineExpressions(pendingExpressions); pendingExpressions = undefined; - emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined); + emitBindingOrAssignment( + temp, + value, + /*location*/ undefined, + /*original*/ undefined, + ); } else { context.hoistVariableDeclaration(temp); @@ -297,12 +411,24 @@ export function flattenDestructuringBinding( pendingDeclaration.value = temp; } } - for (const { pendingExpressions, name, value, location, original } of pendingDeclarations) { + for ( + const { + pendingExpressions, + name, + value, + location, + original, + } of pendingDeclarations + ) { const variable = context.factory.createVariableDeclaration( name, /*exclamationToken*/ undefined, /*type*/ undefined, - pendingExpressions ? context.factory.inlineExpressions(append(pendingExpressions, value)) : value, + pendingExpressions + ? context.factory.inlineExpressions( + append(pendingExpressions, value), + ) + : value, ); variable.original = original; setTextRange(variable, location); @@ -314,13 +440,26 @@ export function flattenDestructuringBinding( pendingExpressions = append(pendingExpressions, value); } - function emitBindingOrAssignment(target: BindingOrAssignmentElementTarget, value: Expression, location: TextRange | undefined, original: Node | undefined) { + function emitBindingOrAssignment( + target: BindingOrAssignmentElementTarget, + value: Expression, + location: TextRange | undefined, + original: Node | undefined, + ) { Debug.assertNode(target, isBindingName); if (pendingExpressions) { - value = context.factory.inlineExpressions(append(pendingExpressions, value)); + value = context.factory.inlineExpressions( + append(pendingExpressions, value), + ); pendingExpressions = undefined; } - pendingDeclarations.push({ pendingExpressions, name: target, value, location, original }); + pendingDeclarations.push({ + pendingExpressions, + name: target, + value, + location, + original, + }); } } @@ -343,14 +482,31 @@ function flattenBindingOrAssignmentElement( ) { const bindingTarget = getTargetOfBindingOrAssignmentElement(element)!; // TODO: GH#18217 if (!skipInitializer) { - const initializer = visitNode(getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, isExpression); + const initializer = visitNode( + getInitializerOfBindingOrAssignmentElement(element), + flattenContext.visitor, + isExpression, + ); if (initializer) { // Combine value and initializer if (value) { - value = createDefaultValueCheck(flattenContext, value, initializer, location); + value = createDefaultValueCheck( + flattenContext, + value, + initializer, + location, + ); // If 'value' is not a simple expression, it could contain side-effecting code that should evaluate before an object or array binding pattern. - if (!isSimpleInlineableExpression(initializer) && isBindingOrAssignmentPattern(bindingTarget)) { - value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); + if ( + !isSimpleInlineableExpression(initializer) && + isBindingOrAssignmentPattern(bindingTarget) + ) { + value = ensureIdentifier( + flattenContext, + value, + /*reuseIdentifierExpressions*/ true, + location, + ); } } else { @@ -363,13 +519,30 @@ function flattenBindingOrAssignmentElement( } } if (isObjectBindingOrAssignmentPattern(bindingTarget)) { - flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value!, location); + flattenObjectBindingOrAssignmentPattern( + flattenContext, + element, + bindingTarget, + value!, + location, + ); } else if (isArrayBindingOrAssignmentPattern(bindingTarget)) { - flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value!, location); + flattenArrayBindingOrAssignmentPattern( + flattenContext, + element, + bindingTarget, + value!, + location, + ); } else { - flattenContext.emitBindingOrAssignment(bindingTarget, value!, location, /*original*/ element); // TODO: GH#18217 + flattenContext.emitBindingOrAssignment( + bindingTarget, + value!, + location, + /*original*/ element, + ); // TODO: GH#18217 } } @@ -382,7 +555,13 @@ function flattenBindingOrAssignmentElement( * @param value The current RHS value to assign to the element. * @param location The location to use for source maps and comments. */ -function flattenObjectBindingOrAssignmentPattern(flattenContext: FlattenContext, parent: BindingOrAssignmentElement, pattern: ObjectBindingOrAssignmentPattern, value: Expression, location: TextRange) { +function flattenObjectBindingOrAssignmentPattern( + flattenContext: FlattenContext, + parent: BindingOrAssignmentElement, + pattern: ObjectBindingOrAssignmentPattern, + value: Expression, + location: TextRange, +) { const elements = getElementsOfBindingOrAssignmentPattern(pattern); const numElements = elements.length; if (numElements !== 1) { @@ -391,7 +570,12 @@ function flattenObjectBindingOrAssignmentPattern(flattenContext: FlattenContext, // we need to emit *something* to ensure that in case a 'var' keyword was already emitted, // so in that case, we'll intentionally create that temporary. const reuseIdentifierExpressions = !isDeclarationBindingElement(parent) || numElements !== 0; - value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + value = ensureIdentifier( + flattenContext, + value, + reuseIdentifierExpressions, + location, + ); } let bindingElements: BindingOrAssignmentElement[] | undefined; let computedTempVariables: Expression[] | undefined; @@ -400,36 +584,97 @@ function flattenObjectBindingOrAssignmentPattern(flattenContext: FlattenContext, if (!getRestIndicatorOfBindingOrAssignmentElement(element)) { const propertyName = getPropertyNameOfBindingOrAssignmentElement(element)!; if ( - flattenContext.level >= FlattenLevel.ObjectRest - && !(element.transformFlags & (TransformFlags.ContainsRestOrSpread | TransformFlags.ContainsObjectRestOrSpread)) - && !(getTargetOfBindingOrAssignmentElement(element)!.transformFlags & (TransformFlags.ContainsRestOrSpread | TransformFlags.ContainsObjectRestOrSpread)) - && !isComputedPropertyName(propertyName) + flattenContext.level >= FlattenLevel.ObjectRest && + !( + element.transformFlags & + (TransformFlags.ContainsRestOrSpread | + TransformFlags.ContainsObjectRestOrSpread) + ) && + !( + getTargetOfBindingOrAssignmentElement(element)! + .transformFlags & + (TransformFlags.ContainsRestOrSpread | + TransformFlags.ContainsObjectRestOrSpread) + ) && + !isComputedPropertyName(propertyName) ) { - bindingElements = append(bindingElements, visitNode(element, flattenContext.visitor, isBindingOrAssignmentElement)); + bindingElements = append( + bindingElements, + visitNode( + element, + flattenContext.visitor, + isBindingOrAssignmentElement, + ), + ); } else { if (bindingElements) { - flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + flattenContext.emitBindingOrAssignment( + flattenContext.createObjectBindingOrAssignmentPattern( + bindingElements, + ), + value, + location, + pattern, + ); bindingElements = undefined; } - const rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName); + const rhsValue = createDestructuringPropertyAccess( + flattenContext, + value, + propertyName, + ); if (isComputedPropertyName(propertyName)) { - computedTempVariables = append(computedTempVariables, (rhsValue as ElementAccessExpression).argumentExpression); + computedTempVariables = append( + computedTempVariables, + (rhsValue as ElementAccessExpression).argumentExpression, + ); } - flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + flattenBindingOrAssignmentElement( + flattenContext, + element, + rhsValue, + /*location*/ element, + ); } } else if (i === numElements - 1) { if (bindingElements) { - flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + flattenContext.emitBindingOrAssignment( + flattenContext.createObjectBindingOrAssignmentPattern( + bindingElements, + ), + value, + location, + pattern, + ); bindingElements = undefined; } - const rhsValue = flattenContext.context.getEmitHelperFactory().createRestHelper(value, elements, computedTempVariables, pattern); - flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element); + const rhsValue = flattenContext.context + .getEmitHelperFactory() + .createRestHelper( + value, + elements, + computedTempVariables, + pattern, + ); + flattenBindingOrAssignmentElement( + flattenContext, + element, + rhsValue, + element, + ); } } if (bindingElements) { - flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern); + flattenContext.emitBindingOrAssignment( + flattenContext.createObjectBindingOrAssignmentPattern( + bindingElements, + ), + value, + location, + pattern, + ); } } @@ -442,20 +687,34 @@ function flattenObjectBindingOrAssignmentPattern(flattenContext: FlattenContext, * @param value The current RHS value to assign to the element. * @param location The location to use for source maps and comments. */ -function flattenArrayBindingOrAssignmentPattern(flattenContext: FlattenContext, parent: BindingOrAssignmentElement, pattern: ArrayBindingOrAssignmentPattern, value: Expression, location: TextRange) { +function flattenArrayBindingOrAssignmentPattern( + flattenContext: FlattenContext, + parent: BindingOrAssignmentElement, + pattern: ArrayBindingOrAssignmentPattern, + value: Expression, + location: TextRange, +) { const elements = getElementsOfBindingOrAssignmentPattern(pattern); const numElements = elements.length; - if (flattenContext.level < FlattenLevel.ObjectRest && flattenContext.downlevelIteration) { + if ( + flattenContext.level < FlattenLevel.ObjectRest && + flattenContext.downlevelIteration + ) { // Read the elements of the iterable into an array value = ensureIdentifier( flattenContext, setTextRange( - flattenContext.context.getEmitHelperFactory().createReadHelper( - value, - numElements > 0 && getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1]) - ? undefined - : numElements, - ), + flattenContext.context + .getEmitHelperFactory() + .createReadHelper( + value, + numElements > 0 && + getRestIndicatorOfBindingOrAssignmentElement( + elements[numElements - 1], + ) + ? undefined + : numElements, + ), location, ), /*reuseIdentifierExpressions*/ false, @@ -463,8 +722,10 @@ function flattenArrayBindingOrAssignmentPattern(flattenContext: FlattenContext, ); } else if ( - numElements !== 1 && (flattenContext.level < FlattenLevel.ObjectRest || numElements === 0) - || every(elements, isOmittedExpression) + (numElements !== 1 && + (flattenContext.level < FlattenLevel.ObjectRest || + numElements === 0)) || + every(elements, isOmittedExpression) ) { // For anything other than a single-element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. Additionally, if we have zero elements @@ -473,24 +734,44 @@ function flattenArrayBindingOrAssignmentPattern(flattenContext: FlattenContext, // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]", // then we will create temporary variable. const reuseIdentifierExpressions = !isDeclarationBindingElement(parent) || numElements !== 0; - value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location); + value = ensureIdentifier( + flattenContext, + value, + reuseIdentifierExpressions, + location, + ); } let bindingElements: BindingOrAssignmentElement[] | undefined; - let restContainingElements: [Identifier, BindingOrAssignmentElement][] | undefined; + let restContainingElements: + | [Identifier, BindingOrAssignmentElement][] + | undefined; for (let i = 0; i < numElements; i++) { const element = elements[i]; if (flattenContext.level >= FlattenLevel.ObjectRest) { // If an array pattern contains an ObjectRest, we must cache the result so that we // can perform the ObjectRest destructuring in a different declaration - if (element.transformFlags & TransformFlags.ContainsObjectRestOrSpread || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) { + if ( + element.transformFlags & + TransformFlags.ContainsObjectRestOrSpread || + (flattenContext.hasTransformedPriorElement && + !isSimpleBindingOrAssignmentElement(element)) + ) { flattenContext.hasTransformedPriorElement = true; - const temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); + const temp = flattenContext.context.factory.createTempVariable( + /*recordTempVariable*/ undefined, + ); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); } - restContainingElements = append(restContainingElements, [temp, element] as [Identifier, BindingOrAssignmentElement]); - bindingElements = append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp)); + restContainingElements = append(restContainingElements, [ + temp, + element, + ] as [Identifier, BindingOrAssignmentElement]); + bindingElements = append( + bindingElements, + flattenContext.createArrayBindingOrAssignmentElement(temp), + ); } else { bindingElements = append(bindingElements, element); @@ -500,32 +781,64 @@ function flattenArrayBindingOrAssignmentPattern(flattenContext: FlattenContext, continue; } else if (!getRestIndicatorOfBindingOrAssignmentElement(element)) { - const rhsValue = flattenContext.context.factory.createElementAccessExpression(value, i); - flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + const rhsValue = flattenContext.context.factory.createElementAccessExpression( + value, + i, + ); + flattenBindingOrAssignmentElement( + flattenContext, + element, + rhsValue, + /*location*/ element, + ); } else if (i === numElements - 1) { const rhsValue = flattenContext.context.factory.createArraySliceCall(value, i); - flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element); + flattenBindingOrAssignmentElement( + flattenContext, + element, + rhsValue, + /*location*/ element, + ); } } if (bindingElements) { - flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern); + flattenContext.emitBindingOrAssignment( + flattenContext.createArrayBindingOrAssignmentPattern( + bindingElements, + ), + value, + location, + pattern, + ); } if (restContainingElements) { for (const [id, element] of restContainingElements) { - flattenBindingOrAssignmentElement(flattenContext, element, id, element); + flattenBindingOrAssignmentElement( + flattenContext, + element, + id, + element, + ); } } } -function isSimpleBindingOrAssignmentElement(element: BindingOrAssignmentElement): boolean { +function isSimpleBindingOrAssignmentElement( + element: BindingOrAssignmentElement, +): boolean { const target = getTargetOfBindingOrAssignmentElement(element); if (!target || isOmittedExpression(target)) return true; const propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(element); if (propertyName && !isPropertyNameLiteral(propertyName)) return false; const initializer = getInitializerOfBindingOrAssignmentElement(element); if (initializer && !isSimpleInlineableExpression(initializer)) return false; - if (isBindingOrAssignmentPattern(target)) return every(getElementsOfBindingOrAssignmentPattern(target), isSimpleBindingOrAssignmentElement); + if (isBindingOrAssignmentPattern(target)) { + return every( + getElementsOfBindingOrAssignmentPattern(target), + isSimpleBindingOrAssignmentElement, + ); + } return isIdentifier(target); } @@ -537,9 +850,25 @@ function isSimpleBindingOrAssignmentElement(element: BindingOrAssignmentElement) * @param defaultValue The default value to use if `value` is `undefined` at runtime. * @param location The location to use for source maps and comments. */ -function createDefaultValueCheck(flattenContext: FlattenContext, value: Expression, defaultValue: Expression, location: TextRange): Expression { - value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location); - return flattenContext.context.factory.createConditionalExpression(flattenContext.context.factory.createTypeCheck(value, "undefined"), /*questionToken*/ undefined, defaultValue, /*colonToken*/ undefined, value); +function createDefaultValueCheck( + flattenContext: FlattenContext, + value: Expression, + defaultValue: Expression, + location: TextRange, +): Expression { + value = ensureIdentifier( + flattenContext, + value, + /*reuseIdentifierExpressions*/ true, + location, + ); + return flattenContext.context.factory.createConditionalExpression( + flattenContext.context.factory.createTypeCheck(value, "undefined"), + /*questionToken*/ undefined, + defaultValue, + /*colonToken*/ undefined, + value, + ); } /** @@ -552,19 +881,45 @@ function createDefaultValueCheck(flattenContext: FlattenContext, value: Expressi * @param value The RHS value that is the source of the property. * @param propertyName The destructuring property name. */ -function createDestructuringPropertyAccess(flattenContext: FlattenContext, value: Expression, propertyName: PropertyName): LeftHandSideExpression { +function createDestructuringPropertyAccess( + flattenContext: FlattenContext, + value: Expression, + propertyName: PropertyName, +): LeftHandSideExpression { const { factory } = flattenContext.context; if (isComputedPropertyName(propertyName)) { - const argumentExpression = ensureIdentifier(flattenContext, Debug.checkDefined(visitNode(propertyName.expression, flattenContext.visitor, isExpression)), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName); - return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression); + const argumentExpression = ensureIdentifier( + flattenContext, + Debug.checkDefined( + visitNode( + propertyName.expression, + flattenContext.visitor, + isExpression, + ), + ), + /*reuseIdentifierExpressions*/ false, + /*location*/ propertyName, + ); + return flattenContext.context.factory.createElementAccessExpression( + value, + argumentExpression, + ); } else if (isStringOrNumericLiteralLike(propertyName)) { const argumentExpression = factory.cloneNode(propertyName); - return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression); + return flattenContext.context.factory.createElementAccessExpression( + value, + argumentExpression, + ); } else { - const name = flattenContext.context.factory.createIdentifier(idText(propertyName)); - return flattenContext.context.factory.createPropertyAccessExpression(value, name); + const name = flattenContext.context.factory.createIdentifier( + idText(propertyName), + ); + return flattenContext.context.factory.createPropertyAccessExpression( + value, + name, + ); } } @@ -579,45 +934,85 @@ function createDestructuringPropertyAccess(flattenContext: FlattenContext, value * false if it is necessary to always emit an identifier. * @param location The location to use for source maps and comments. */ -function ensureIdentifier(flattenContext: FlattenContext, value: Expression, reuseIdentifierExpressions: boolean, location: TextRange) { +function ensureIdentifier( + flattenContext: FlattenContext, + value: Expression, + reuseIdentifierExpressions: boolean, + location: TextRange, +) { if (isIdentifier(value) && reuseIdentifierExpressions) { return value; } else { - const temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined); + const temp = flattenContext.context.factory.createTempVariable( + /*recordTempVariable*/ undefined, + ); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); - flattenContext.emitExpression(setTextRange(flattenContext.context.factory.createAssignment(temp, value), location)); + flattenContext.emitExpression( + setTextRange( + flattenContext.context.factory.createAssignment( + temp, + value, + ), + location, + ), + ); } else { - flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined); + flattenContext.emitBindingOrAssignment( + temp, + value, + location, + /*original*/ undefined, + ); } return temp; } } -function makeArrayBindingPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) { +function makeArrayBindingPattern( + factory: NodeFactory, + elements: BindingOrAssignmentElement[], +) { Debug.assertEachNode(elements, isArrayBindingElement); return factory.createArrayBindingPattern(elements); } -function makeArrayAssignmentPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) { +function makeArrayAssignmentPattern( + factory: NodeFactory, + elements: BindingOrAssignmentElement[], +) { Debug.assertEachNode(elements, isArrayBindingOrAssignmentElement); - return factory.createArrayLiteralExpression(map(elements, factory.converters.convertToArrayAssignmentElement)); + return factory.createArrayLiteralExpression( + map(elements, factory.converters.convertToArrayAssignmentElement), + ); } -function makeObjectBindingPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) { +function makeObjectBindingPattern( + factory: NodeFactory, + elements: BindingOrAssignmentElement[], +) { Debug.assertEachNode(elements, isBindingElement); return factory.createObjectBindingPattern(elements); } -function makeObjectAssignmentPattern(factory: NodeFactory, elements: BindingOrAssignmentElement[]) { +function makeObjectAssignmentPattern( + factory: NodeFactory, + elements: BindingOrAssignmentElement[], +) { Debug.assertEachNode(elements, isObjectBindingOrAssignmentElement); - return factory.createObjectLiteralExpression(map(elements, factory.converters.convertToObjectAssignmentElement)); + return factory.createObjectLiteralExpression( + map(elements, factory.converters.convertToObjectAssignmentElement), + ); } function makeBindingElement(factory: NodeFactory, name: Identifier) { - return factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name); + return factory.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + name, + ); } function makeAssignmentElement(name: Identifier) { diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index e715a2dd815e4..54a93336932ee 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -80,7 +80,6 @@ import { hasSyntacticModifier, Identifier, idText, - IfStatement, insertStatementAfterCustomPrologue, insertStatementsAfterCustomPrologue, insertStatementsAfterStandardPrologue, @@ -141,7 +140,6 @@ import { last, lastOrUndefined, LeftHandSideExpression, - LiteralExpression, map, MetaProperty, MethodDeclaration, @@ -197,6 +195,8 @@ import { SyntaxKind, TaggedTemplateExpression, TemplateExpression, + TemplateLiteral, + TemplateLiteralLikeNode, TextRange, ThisExpression, TokenFlags, @@ -571,7 +571,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile function isReturnVoidStatementInConstructorWithCapturedSuper(node: Node): boolean { return (hierarchyFacts & HierarchyFacts.ConstructorWithSuperCall) !== 0 && node.kind === SyntaxKind.ReturnStatement - && !(node as ReturnStatement).expression; + && !node.expression; } function isOrMayContainReturnCompletion(node: Node) { @@ -636,117 +636,117 @@ export function transformES2015(context: TransformationContext): (x: SourceFile return undefined; // elide static keyword case SyntaxKind.ClassDeclaration: - return visitClassDeclaration(node as ClassDeclaration); + return visitClassDeclaration(node); case SyntaxKind.ClassExpression: - return visitClassExpression(node as ClassExpression); + return visitClassExpression(node); case SyntaxKind.Parameter: - return visitParameter(node as ParameterDeclaration); + return visitParameter(node); case SyntaxKind.FunctionDeclaration: - return visitFunctionDeclaration(node as FunctionDeclaration); + return visitFunctionDeclaration(node); case SyntaxKind.ArrowFunction: - return visitArrowFunction(node as ArrowFunction); + return visitArrowFunction(node); case SyntaxKind.FunctionExpression: - return visitFunctionExpression(node as FunctionExpression); + return visitFunctionExpression(node); case SyntaxKind.VariableDeclaration: - return visitVariableDeclaration(node as VariableDeclaration); + return visitVariableDeclaration(node); case SyntaxKind.Identifier: - return visitIdentifier(node as Identifier); + return visitIdentifier(node); case SyntaxKind.VariableDeclarationList: - return visitVariableDeclarationList(node as VariableDeclarationList); + return visitVariableDeclarationList(node); case SyntaxKind.SwitchStatement: - return visitSwitchStatement(node as SwitchStatement); + return visitSwitchStatement(node); case SyntaxKind.CaseBlock: - return visitCaseBlock(node as CaseBlock); + return visitCaseBlock(node); case SyntaxKind.Block: - return visitBlock(node as Block, /*isFunctionBody*/ false); + return visitBlock(node, /*isFunctionBody*/ false); case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: return visitBreakOrContinueStatement(node as BreakOrContinueStatement); case SyntaxKind.LabeledStatement: - return visitLabeledStatement(node as LabeledStatement); + return visitLabeledStatement(node); case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: - return visitDoOrWhileStatement(node as DoStatement | WhileStatement, /*outermostLabeledStatement*/ undefined); + return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined); case SyntaxKind.ForStatement: - return visitForStatement(node as ForStatement, /*outermostLabeledStatement*/ undefined); + return visitForStatement(node, /*outermostLabeledStatement*/ undefined); case SyntaxKind.ForInStatement: - return visitForInStatement(node as ForInStatement, /*outermostLabeledStatement*/ undefined); + return visitForInStatement(node, /*outermostLabeledStatement*/ undefined); case SyntaxKind.ForOfStatement: - return visitForOfStatement(node as ForOfStatement, /*outermostLabeledStatement*/ undefined); + return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined); case SyntaxKind.ExpressionStatement: - return visitExpressionStatement(node as ExpressionStatement); + return visitExpressionStatement(node); case SyntaxKind.ObjectLiteralExpression: - return visitObjectLiteralExpression(node as ObjectLiteralExpression); + return visitObjectLiteralExpression(node); case SyntaxKind.CatchClause: - return visitCatchClause(node as CatchClause); + return visitCatchClause(node); case SyntaxKind.ShorthandPropertyAssignment: - return visitShorthandPropertyAssignment(node as ShorthandPropertyAssignment); + return visitShorthandPropertyAssignment(node); case SyntaxKind.ComputedPropertyName: - return visitComputedPropertyName(node as ComputedPropertyName); + return visitComputedPropertyName(node); case SyntaxKind.ArrayLiteralExpression: - return visitArrayLiteralExpression(node as ArrayLiteralExpression); + return visitArrayLiteralExpression(node); case SyntaxKind.CallExpression: - return visitCallExpression(node as CallExpression); + return visitCallExpression(node); case SyntaxKind.NewExpression: - return visitNewExpression(node as NewExpression); + return visitNewExpression(node); case SyntaxKind.ParenthesizedExpression: - return visitParenthesizedExpression(node as ParenthesizedExpression, expressionResultIsUnused); + return visitParenthesizedExpression(node, expressionResultIsUnused); case SyntaxKind.BinaryExpression: - return visitBinaryExpression(node as BinaryExpression, expressionResultIsUnused); + return visitBinaryExpression(node, expressionResultIsUnused); case SyntaxKind.CommaListExpression: - return visitCommaListExpression(node as CommaListExpression, expressionResultIsUnused); + return visitCommaListExpression(node, expressionResultIsUnused); case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TemplateHead: case SyntaxKind.TemplateMiddle: case SyntaxKind.TemplateTail: - return visitTemplateLiteral(node as LiteralExpression); + return visitTemplateLiteral(node); case SyntaxKind.StringLiteral: - return visitStringLiteral(node as StringLiteral); + return visitStringLiteral(node); case SyntaxKind.NumericLiteral: - return visitNumericLiteral(node as NumericLiteral); + return visitNumericLiteral(node); case SyntaxKind.TaggedTemplateExpression: - return visitTaggedTemplateExpression(node as TaggedTemplateExpression); + return visitTaggedTemplateExpression(node); case SyntaxKind.TemplateExpression: - return visitTemplateExpression(node as TemplateExpression); + return visitTemplateExpression(node); case SyntaxKind.YieldExpression: - return visitYieldExpression(node as YieldExpression); + return visitYieldExpression(node); case SyntaxKind.SpreadElement: - return visitSpreadElement(node as SpreadElement); + return visitSpreadElement(node); case SyntaxKind.SuperKeyword: return visitSuperKeyword(node as SuperExpression, /*isExpressionOfCall*/ false); @@ -755,23 +755,23 @@ export function transformES2015(context: TransformationContext): (x: SourceFile return visitThisKeyword(node); case SyntaxKind.MetaProperty: - return visitMetaProperty(node as MetaProperty); + return visitMetaProperty(node); case SyntaxKind.MethodDeclaration: - return visitMethodDeclaration(node as MethodDeclaration); + return visitMethodDeclaration(node); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: return visitAccessorDeclaration(node as AccessorDeclaration); case SyntaxKind.VariableStatement: - return visitVariableStatement(node as VariableStatement); + return visitVariableStatement(node); case SyntaxKind.ReturnStatement: - return visitReturnStatement(node as ReturnStatement); + return visitReturnStatement(node); case SyntaxKind.VoidExpression: - return visitVoidExpression(node as VoidExpression); + return visitVoidExpression(node); default: return visitEachChild(node, visitor, context); @@ -1800,7 +1800,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile } // An if-statement with two covered branches is covered. else if (statement.kind === SyntaxKind.IfStatement) { - const ifStatement = statement as IfStatement; + const ifStatement = statement; if (ifStatement.elseStatement) { return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); @@ -1808,7 +1808,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile } // A block is covered if it has a last statement which is covered. else if (statement.kind === SyntaxKind.Block) { - const lastStatement = lastOrUndefined((statement as Block).statements); + const lastStatement = lastOrUndefined(statement.statements); if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { return true; } @@ -2255,11 +2255,11 @@ export function transformES2015(context: TransformationContext): (x: SourceFile for (const member of node.members) { switch (member.kind) { case SyntaxKind.SemicolonClassElement: - statements.push(transformSemicolonClassElementToStatement(member as SemicolonClassElement)); + statements.push(transformSemicolonClassElementToStatement(member)); break; case SyntaxKind.MethodDeclaration: - statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member as MethodDeclaration, node)); + statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node)); break; case SyntaxKind.GetAccessor: @@ -2955,13 +2955,13 @@ export function transformES2015(context: TransformationContext): (x: SourceFile switch (node.kind) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: - return visitDoOrWhileStatement(node as DoStatement | WhileStatement, outermostLabeledStatement); + return visitDoOrWhileStatement(node, outermostLabeledStatement); case SyntaxKind.ForStatement: - return visitForStatement(node as ForStatement, outermostLabeledStatement); + return visitForStatement(node, outermostLabeledStatement); case SyntaxKind.ForInStatement: - return visitForInStatement(node as ForInStatement, outermostLabeledStatement); + return visitForInStatement(node, outermostLabeledStatement); case SyntaxKind.ForOfStatement: - return visitForOfStatement(node as ForOfStatement, outermostLabeledStatement); + return visitForOfStatement(node, outermostLabeledStatement); } } @@ -3488,15 +3488,15 @@ export function transformES2015(context: TransformationContext): (x: SourceFile function convertIterationStatementCore(node: IterationStatement, initializerFunction: IterationStatementPartFunction | undefined, convertedLoopBody: Statement) { switch (node.kind) { case SyntaxKind.ForStatement: - return convertForStatement(node as ForStatement, initializerFunction, convertedLoopBody); + return convertForStatement(node, initializerFunction, convertedLoopBody); case SyntaxKind.ForInStatement: - return convertForInStatement(node as ForInStatement, convertedLoopBody); + return convertForInStatement(node, convertedLoopBody); case SyntaxKind.ForOfStatement: - return convertForOfStatement(node as ForOfStatement, convertedLoopBody); + return convertForOfStatement(node, convertedLoopBody); case SyntaxKind.DoStatement: - return convertDoStatement(node as DoStatement, convertedLoopBody); + return convertDoStatement(node, convertedLoopBody); case SyntaxKind.WhileStatement: - return convertWhileStatement(node as WhileStatement, convertedLoopBody); + return convertWhileStatement(node, convertedLoopBody); default: return Debug.failBadSyntaxKind(node, "IterationStatement expected"); } @@ -3555,9 +3555,9 @@ export function transformES2015(context: TransformationContext): (x: SourceFile case SyntaxKind.ForStatement: case SyntaxKind.ForInStatement: case SyntaxKind.ForOfStatement: - const initializer = (node as ForStatement | ForInStatement | ForOfStatement).initializer; + const initializer = node.initializer; if (initializer && initializer.kind === SyntaxKind.VariableDeclarationList) { - loopInitializer = initializer as VariableDeclarationList; + loopInitializer = initializer; } break; } @@ -4753,7 +4753,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile * * @param node A template literal. */ - function visitTemplateLiteral(node: LiteralExpression): LeftHandSideExpression { + function visitTemplateLiteral(node: TemplateLiteralLikeNode): LeftHandSideExpression { return setTextRange(factory.createStringLiteral(node.text), node); } @@ -4904,7 +4904,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile * @param hint The context for the emitter. * @param node The node to substitute. */ - function onSubstituteNode(hint: EmitHint, node: Node) { + function onSubstituteNode(hint: EmitHint, node: Node): Node { node = previousOnSubstituteNode(hint, node); if (hint === EmitHint.Expression) { @@ -4961,7 +4961,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile function substituteExpression(node: Node) { switch (node.kind) { case SyntaxKind.Identifier: - return substituteExpressionIdentifier(node as Identifier); + return substituteExpressionIdentifier(node); case SyntaxKind.ThisKeyword: return substituteThisKeyword(node as PrimaryExpression); @@ -5045,22 +5045,22 @@ export function transformES2015(context: TransformationContext): (x: SourceFile return false; } - const statementExpression = (statement as ExpressionStatement).expression; + const statementExpression = statement.expression; if (!nodeIsSynthesized(statementExpression) || statementExpression.kind !== SyntaxKind.CallExpression) { return false; } - const callTarget = (statementExpression as CallExpression).expression; + const callTarget = statementExpression.expression; if (!nodeIsSynthesized(callTarget) || callTarget.kind !== SyntaxKind.SuperKeyword) { return false; } - const callArgument = singleOrUndefined((statementExpression as CallExpression).arguments); + const callArgument = singleOrUndefined(statementExpression.arguments); if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== SyntaxKind.SpreadElement) { return false; } - const expression = (callArgument as SpreadElement).expression; + const expression = callArgument.expression; return isIdentifier(expression) && expression.escapedText === "arguments"; } } diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index d30b25e2a4580..3c7402864b03f 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -98,7 +98,12 @@ import { VisitResult, } from "../_namespaces/ts"; -type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration; +type SuperContainer = + | ClassDeclaration + | MethodDeclaration + | GetAccessorDeclaration + | SetAccessorDeclaration + | ConstructorDeclaration; const enum ES2017SubstitutionFlags { /** Enables substitutions for async methods with `super` calls. */ @@ -112,7 +117,9 @@ const enum ContextFlags { } /** @internal */ -export function transformES2017(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle { +export function transformES2017( + context: TransformationContext, +): (x: SourceFile | Bundle) => SourceFile | Bundle { const { factory, getEmitHelperFactory: emitHelpers, @@ -166,7 +173,10 @@ export function transformES2017(context: TransformationContext): (x: SourceFile } setContextFlag(ContextFlags.NonTopLevel, false); - setContextFlag(ContextFlags.HasLexicalThis, !isEffectiveStrictModeSourceFile(node, compilerOptions)); + setContextFlag( + ContextFlags.HasLexicalThis, + !isEffectiveStrictModeSourceFile(node, compilerOptions), + ); const visited = visitEachChild(node, visitor, context); addEmitHelpers(visited, context.readEmitHelpers()); return visited; @@ -188,7 +198,11 @@ export function transformES2017(context: TransformationContext): (x: SourceFile return inContext(ContextFlags.HasLexicalThis); } - function doWithContext(flags: ContextFlags, cb: (value: T) => U, value: T) { + function doWithContext( + flags: ContextFlags, + cb: (value: T) => U, + value: T, + ) { const contextFlagsToSet = flags & ~contextFlags; if (contextFlagsToSet) { setContextFlag(contextFlagsToSet, /*val*/ true); @@ -216,38 +230,78 @@ export function transformES2017(context: TransformationContext): (x: SourceFile return visitAwaitExpression(node as AwaitExpression); case SyntaxKind.MethodDeclaration: - return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitMethodDeclaration, node as MethodDeclaration); + return doWithContext( + ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, + visitMethodDeclaration, + node as MethodDeclaration, + ); case SyntaxKind.FunctionDeclaration: - return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionDeclaration, node as FunctionDeclaration); + return doWithContext( + ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, + visitFunctionDeclaration, + node as FunctionDeclaration, + ); case SyntaxKind.FunctionExpression: - return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitFunctionExpression, node as FunctionExpression); + return doWithContext( + ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, + visitFunctionExpression, + node as FunctionExpression, + ); case SyntaxKind.ArrowFunction: - return doWithContext(ContextFlags.NonTopLevel, visitArrowFunction, node as ArrowFunction); + return doWithContext( + ContextFlags.NonTopLevel, + visitArrowFunction, + node as ArrowFunction, + ); case SyntaxKind.PropertyAccessExpression: - if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) { + if ( + capturedSuperProperties && + isPropertyAccessExpression(node) && + node.expression.kind === SyntaxKind.SuperKeyword + ) { capturedSuperProperties.add(node.name.escapedText); } return visitEachChild(node, visitor, context); case SyntaxKind.ElementAccessExpression: - if (capturedSuperProperties && (node as ElementAccessExpression).expression.kind === SyntaxKind.SuperKeyword) { + if ( + capturedSuperProperties && + (node as ElementAccessExpression).expression.kind === + SyntaxKind.SuperKeyword + ) { hasSuperElementAccess = true; } return visitEachChild(node, visitor, context); case SyntaxKind.GetAccessor: - return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitGetAccessorDeclaration, node as GetAccessorDeclaration); + return doWithContext( + ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, + visitGetAccessorDeclaration, + node as GetAccessorDeclaration, + ); case SyntaxKind.SetAccessor: - return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitSetAccessorDeclaration, node as SetAccessorDeclaration); + return doWithContext( + ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, + visitSetAccessorDeclaration, + node as SetAccessorDeclaration, + ); case SyntaxKind.Constructor: - return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitConstructorDeclaration, node as ConstructorDeclaration); + return doWithContext( + ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, + visitConstructorDeclaration, + node as ConstructorDeclaration, + ); case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: - return doWithContext(ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, visitDefault, node); + return doWithContext( + ContextFlags.NonTopLevel | ContextFlags.HasLexicalThis, + visitDefault, + node, + ); default: return visitEachChild(node, visitor, context); @@ -295,7 +349,9 @@ export function transformES2017(context: TransformationContext): (x: SourceFile catchClauseNames.forEach((_, escapedName) => { if (enclosingFunctionParameterNames.has(escapedName)) { if (!catchClauseUnshadowedNames) { - catchClauseUnshadowedNames = new Set(enclosingFunctionParameterNames); + catchClauseUnshadowedNames = new Set( + enclosingFunctionParameterNames, + ); } catchClauseUnshadowedNames.delete(escapedName); } @@ -315,8 +371,13 @@ export function transformES2017(context: TransformationContext): (x: SourceFile function visitVariableStatementInAsyncBody(node: VariableStatement) { if (isVariableDeclarationListWithCollidingName(node.declarationList)) { - const expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); - return expression ? factory.createExpressionStatement(expression) : undefined; + const expression = visitVariableDeclarationListWithCollidingNames( + node.declarationList, + /*hasReceiver*/ false, + ); + return expression + ? factory.createExpressionStatement(expression) + : undefined; } return visitEachChild(node, visitor, context); } @@ -325,9 +386,16 @@ export function transformES2017(context: TransformationContext): (x: SourceFile return factory.updateForInStatement( node, isVariableDeclarationListWithCollidingName(node.initializer) - ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)! - : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + ? visitVariableDeclarationListWithCollidingNames( + node.initializer, + /*hasReceiver*/ true, + )! + : Debug.checkDefined( + visitNode(node.initializer, visitor, isForInitializer), + ), + Debug.checkDefined( + visitNode(node.expression, visitor, isExpression), + ), visitIterationBody(node.statement, asyncBodyVisitor, context), ); } @@ -337,9 +405,16 @@ export function transformES2017(context: TransformationContext): (x: SourceFile node, visitNode(node.awaitModifier, visitor, isAwaitKeyword), isVariableDeclarationListWithCollidingName(node.initializer) - ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)! - : Debug.checkDefined(visitNode(node.initializer, visitor, isForInitializer)), - Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), + ? visitVariableDeclarationListWithCollidingNames( + node.initializer, + /*hasReceiver*/ true, + )! + : Debug.checkDefined( + visitNode(node.initializer, visitor, isForInitializer), + ), + Debug.checkDefined( + visitNode(node.expression, visitor, isExpression), + ), visitIterationBody(node.statement, asyncBodyVisitor, context), ); } @@ -349,7 +424,10 @@ export function transformES2017(context: TransformationContext): (x: SourceFile return factory.updateForStatement( node, isVariableDeclarationListWithCollidingName(initializer) - ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false) + ? visitVariableDeclarationListWithCollidingNames( + initializer, + /*hasReceiver*/ false, + ) : visitNode(node.initializer, visitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitor, isExpression), @@ -443,7 +521,9 @@ export function transformES2017(context: TransformationContext): (x: SourceFile * * @param node The node to visit. */ - function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult { + function visitFunctionDeclaration( + node: FunctionDeclaration, + ): VisitResult { return factory.updateFunctionDeclaration( node, visitNodes(node.modifiers, visitor, isModifierLike), @@ -503,7 +583,10 @@ export function transformES2017(context: TransformationContext): (x: SourceFile ); } - function recordDeclarationName({ name }: ParameterDeclaration | VariableDeclaration | BindingElement, names: Set<__String>) { + function recordDeclarationName( + { name }: ParameterDeclaration | VariableDeclaration | BindingElement, + names: Set<__String>, + ) { if (isIdentifier(name)) { names.add(name.escapedText); } @@ -516,25 +599,40 @@ export function transformES2017(context: TransformationContext): (x: SourceFile } } - function isVariableDeclarationListWithCollidingName(node: ForInitializer): node is VariableDeclarationList { - return !!node - && isVariableDeclarationList(node) - && !(node.flags & NodeFlags.BlockScoped) - && node.declarations.some(collidesWithParameterName); + function isVariableDeclarationListWithCollidingName( + node: ForInitializer, + ): node is VariableDeclarationList { + return ( + !!node && + isVariableDeclarationList(node) && + !(node.flags & NodeFlags.BlockScoped) && + node.declarations.some(collidesWithParameterName) + ); } - function visitVariableDeclarationListWithCollidingNames(node: VariableDeclarationList, hasReceiver: boolean) { + function visitVariableDeclarationListWithCollidingNames( + node: VariableDeclarationList, + hasReceiver: boolean, + ) { hoistVariableDeclarationList(node); const variables = getInitializedVariables(node); if (variables.length === 0) { if (hasReceiver) { - return visitNode(factory.converters.convertToAssignmentElementTarget(node.declarations[0].name), visitor, isExpression); + return visitNode( + factory.converters.convertToAssignmentElementTarget( + node.declarations[0].name, + ), + visitor, + isExpression, + ); } return undefined; } - return factory.inlineExpressions(map(variables, transformInitializedVariable)); + return factory.inlineExpressions( + map(variables, transformInitializedVariable), + ); } function hoistVariableDeclarationList(node: VariableDeclarationList) { @@ -565,13 +663,18 @@ export function transformES2017(context: TransformationContext): (x: SourceFile return Debug.checkDefined(visitNode(converted, visitor, isExpression)); } - function collidesWithParameterName({ name }: VariableDeclaration | BindingElement): boolean { + function collidesWithParameterName({ + name, + }: VariableDeclaration | BindingElement): boolean { if (isIdentifier(name)) { return enclosingFunctionParameterNames.has(name.escapedText); } else { for (const element of name.elements) { - if (!isOmittedExpression(element) && collidesWithParameterName(element)) { + if ( + !isOmittedExpression(element) && + collidesWithParameterName(element) + ) { return true; } } @@ -579,7 +682,9 @@ export function transformES2017(context: TransformationContext): (x: SourceFile return false; } - function transformMethodBody(node: MethodDeclaration | AccessorDeclaration | ConstructorDeclaration): FunctionBody | undefined { + function transformMethodBody( + node: MethodDeclaration | AccessorDeclaration | ConstructorDeclaration, + ): FunctionBody | undefined { Debug.assertIsDefined(node.body); const savedCapturedSuperProperties = capturedSuperProperties; @@ -593,26 +698,43 @@ export function transformES2017(context: TransformationContext): (x: SourceFile // This step isn't needed if we eventually transform this to ES5. const originalMethod = getOriginalNode(node, isFunctionLikeDeclaration); const emitSuperHelpers = languageVersion >= ScriptTarget.ES2015 && - resolver.getNodeCheckFlags(node) & (NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync | NodeCheckFlags.MethodWithSuperPropertyAccessInAsync) && - (getFunctionFlags(originalMethod) & FunctionFlags.AsyncGenerator) !== FunctionFlags.AsyncGenerator; + resolver.getNodeCheckFlags(node) & + (NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync | + NodeCheckFlags.MethodWithSuperPropertyAccessInAsync) && + (getFunctionFlags(originalMethod) & + FunctionFlags.AsyncGenerator) !== + FunctionFlags.AsyncGenerator; if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { - const variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); + const variableStatement = createSuperAccessVariableStatement( + factory, + resolver, + node, + capturedSuperProperties, + ); substitutedSuperAccessors[getNodeId(variableStatement)] = true; const statements = updated.statements.slice(); - insertStatementsAfterStandardPrologue(statements, [variableStatement]); + insertStatementsAfterStandardPrologue(statements, [ + variableStatement, + ]); updated = factory.updateBlock(updated, statements); } if (hasSuperElementAccess) { // Emit helpers for super element access expressions (`super[x]`). - if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) { + if ( + resolver.getNodeCheckFlags(node) & + NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync + ) { addEmitHelper(updated, advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAccessInAsync) { + else if ( + resolver.getNodeCheckFlags(node) & + NodeCheckFlags.MethodWithSuperPropertyAccessInAsync + ) { addEmitHelper(updated, asyncSuperHelper); } } @@ -623,16 +745,28 @@ export function transformES2017(context: TransformationContext): (x: SourceFile return updated; } - function transformAsyncFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody; + function transformAsyncFunctionBody( + node: + | MethodDeclaration + | AccessorDeclaration + | FunctionDeclaration + | FunctionExpression, + ): FunctionBody; function transformAsyncFunctionBody(node: ArrowFunction): ConciseBody; - function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody { + function transformAsyncFunctionBody( + node: FunctionLikeDeclaration, + ): ConciseBody { resumeLexicalEnvironment(); const original = getOriginalNode(node, isFunctionLike); const nodeType = original.type; - const promiseConstructor = languageVersion < ScriptTarget.ES2015 ? getPromiseConstructor(nodeType) : undefined; + const promiseConstructor = languageVersion < ScriptTarget.ES2015 + ? getPromiseConstructor(nodeType) + : undefined; const isArrowFunction = node.kind === SyntaxKind.ArrowFunction; - const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0; + const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & + NodeCheckFlags.CaptureArguments) !== + 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -656,30 +790,51 @@ export function transformES2017(context: TransformationContext): (x: SourceFile let result: ConciseBody; if (!isArrowFunction) { const statements: Statement[] = []; - const statementOffset = factory.copyPrologue((node.body as Block).statements, statements, /*ensureUseStrict*/ false, visitor); + const statementOffset = factory.copyPrologue( + (node.body as Block).statements, + statements, + /*ensureUseStrict*/ false, + visitor, + ); statements.push( factory.createReturnStatement( emitHelpers().createAwaiterHelper( inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, - transformAsyncFunctionBodyWorker(node.body as Block, statementOffset), + transformAsyncFunctionBodyWorker( + node.body as Block, + statementOffset, + ), ), ), ); - insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); + insertStatementsAfterStandardPrologue( + statements, + endLexicalEnvironment(), + ); // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - const emitSuperHelpers = languageVersion >= ScriptTarget.ES2015 && resolver.getNodeCheckFlags(node) & (NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync | NodeCheckFlags.MethodWithSuperPropertyAccessInAsync); + const emitSuperHelpers = languageVersion >= ScriptTarget.ES2015 && + resolver.getNodeCheckFlags(node) & + (NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync | + NodeCheckFlags.MethodWithSuperPropertyAccessInAsync); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { - const variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); + const variableStatement = createSuperAccessVariableStatement( + factory, + resolver, + node, + capturedSuperProperties, + ); substitutedSuperAccessors[getNodeId(variableStatement)] = true; - insertStatementsAfterStandardPrologue(statements, [variableStatement]); + insertStatementsAfterStandardPrologue(statements, [ + variableStatement, + ]); } } @@ -688,10 +843,16 @@ export function transformES2017(context: TransformationContext): (x: SourceFile if (emitSuperHelpers && hasSuperElementAccess) { // Emit helpers for super element access expressions (`super[x]`). - if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) { + if ( + resolver.getNodeCheckFlags(node) & + NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync + ) { addEmitHelper(block, advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAccessInAsync) { + else if ( + resolver.getNodeCheckFlags(node) & + NodeCheckFlags.MethodWithSuperPropertyAccessInAsync + ) { addEmitHelper(block, asyncSuperHelper); } } @@ -709,7 +870,15 @@ export function transformES2017(context: TransformationContext): (x: SourceFile const declarations = endLexicalEnvironment(); if (some(declarations)) { const block = factory.converters.convertToFunctionBlock(expression); - result = factory.updateBlock(block, setTextRange(factory.createNodeArray(concatenate(declarations, block.statements)), block.statements)); + result = factory.updateBlock( + block, + setTextRange( + factory.createNodeArray( + concatenate(declarations, block.statements), + ), + block.statements, + ), + ); } else { result = expression; @@ -724,12 +893,27 @@ export function transformES2017(context: TransformationContext): (x: SourceFile return result; } - function transformAsyncFunctionBodyWorker(body: ConciseBody, start?: number) { + function transformAsyncFunctionBodyWorker( + body: ConciseBody, + start?: number, + ) { if (isBlock(body)) { - return factory.updateBlock(body, visitNodes(body.statements, asyncBodyVisitor, isStatement, start)); + return factory.updateBlock( + body, + visitNodes( + body.statements, + asyncBodyVisitor, + isStatement, + start, + ), + ); } else { - return factory.converters.convertToFunctionBlock(Debug.checkDefined(visitNode(body, asyncBodyVisitor, isConciseBody))); + return factory.converters.convertToFunctionBlock( + Debug.checkDefined( + visitNode(body, asyncBodyVisitor, isConciseBody), + ), + ); } } @@ -738,8 +922,9 @@ export function transformES2017(context: TransformationContext): (x: SourceFile if (typeName && isEntityName(typeName)) { const serializationKind = resolver.getTypeReferenceSerializationKind(typeName); if ( - serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue - || serializationKind === TypeReferenceSerializationKind.Unknown + serializationKind === + TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue || + serializationKind === TypeReferenceSerializationKind.Unknown ) { return typeName; } @@ -749,7 +934,11 @@ export function transformES2017(context: TransformationContext): (x: SourceFile } function enableSubstitutionForAsyncMethodsWithSuper() { - if ((enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper) === 0) { + if ( + (enabledSubstitutions & + ES2017SubstitutionFlags.AsyncMethodsWithSuper) === + 0 + ) { enabledSubstitutions |= ES2017SubstitutionFlags.AsyncMethodsWithSuper; // We need to enable substitutions for call, property access, and element access @@ -776,11 +965,21 @@ export function transformES2017(context: TransformationContext): (x: SourceFile * @param node The node to emit. * @param emit A callback used to emit the node in the printer. */ - function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void { + function onEmitNode( + hint: EmitHint, + node: Node, + emitCallback: (hint: EmitHint, node: Node) => void, + ): void { // If we need to support substitutions for `super` in an async method, // we should track it here. - if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) { - const superContainerFlags = resolver.getNodeCheckFlags(node) & (NodeCheckFlags.MethodWithSuperPropertyAccessInAsync | NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync); + if ( + enabledSubstitutions & + ES2017SubstitutionFlags.AsyncMethodsWithSuper && + isSuperContainer(node) + ) { + const superContainerFlags = resolver.getNodeCheckFlags(node) & + (NodeCheckFlags.MethodWithSuperPropertyAccessInAsync | + NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync); if (superContainerFlags !== enclosingSuperContainerFlags) { const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -790,7 +989,10 @@ export function transformES2017(context: TransformationContext): (x: SourceFile } } // Disable substitution in the generated super accessor itself. - else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) { + else if ( + enabledSubstitutions && + substitutedSuperAccessors[getNodeId(node)] + ) { const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = 0; previousOnEmitNode(hint, node, emitCallback); @@ -818,20 +1020,30 @@ export function transformES2017(context: TransformationContext): (x: SourceFile function substituteExpression(node: Expression) { switch (node.kind) { case SyntaxKind.PropertyAccessExpression: - return substitutePropertyAccessExpression(node as PropertyAccessExpression); + return substitutePropertyAccessExpression( + node as PropertyAccessExpression, + ); case SyntaxKind.ElementAccessExpression: - return substituteElementAccessExpression(node as ElementAccessExpression); + return substituteElementAccessExpression( + node as ElementAccessExpression, + ); case SyntaxKind.CallExpression: return substituteCallExpression(node as CallExpression); } return node; } - function substitutePropertyAccessExpression(node: PropertyAccessExpression) { + function substitutePropertyAccessExpression( + node: PropertyAccessExpression, + ) { if (node.expression.kind === SyntaxKind.SuperKeyword) { return setTextRange( factory.createPropertyAccessExpression( - factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), + factory.createUniqueName( + "_super", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ), node.name, ), node, @@ -857,12 +1069,12 @@ export function transformES2017(context: TransformationContext): (x: SourceFile ? substitutePropertyAccessExpression(expression) : substituteElementAccessExpression(expression); return factory.createCallExpression( - factory.createPropertyAccessExpression(argumentExpression, "call"), + factory.createPropertyAccessExpression( + argumentExpression, + "call", + ), /*typeArguments*/ undefined, - [ - factory.createThis(), - ...node.arguments, - ], + [factory.createThis(), ...node.arguments], ); } return node; @@ -870,19 +1082,31 @@ export function transformES2017(context: TransformationContext): (x: SourceFile function isSuperContainer(node: Node): node is SuperContainer { const kind = node.kind; - return kind === SyntaxKind.ClassDeclaration - || kind === SyntaxKind.Constructor - || kind === SyntaxKind.MethodDeclaration - || kind === SyntaxKind.GetAccessor - || kind === SyntaxKind.SetAccessor; + return ( + kind === SyntaxKind.ClassDeclaration || + kind === SyntaxKind.Constructor || + kind === SyntaxKind.MethodDeclaration || + kind === SyntaxKind.GetAccessor || + kind === SyntaxKind.SetAccessor + ); } - function createSuperElementAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression { - if (enclosingSuperContainerFlags & NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) { + function createSuperElementAccessInAsyncMethod( + argumentExpression: Expression, + location: TextRange, + ): LeftHandSideExpression { + if ( + enclosingSuperContainerFlags & + NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync + ) { return setTextRange( factory.createPropertyAccessExpression( factory.createCallExpression( - factory.createUniqueName("_superIndex", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), + factory.createUniqueName( + "_superIndex", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ), /*typeArguments*/ undefined, [argumentExpression], ), @@ -894,7 +1118,11 @@ export function transformES2017(context: TransformationContext): (x: SourceFile else { return setTextRange( factory.createCallExpression( - factory.createUniqueName("_superIndex", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), + factory.createUniqueName( + "_superIndex", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ), /*typeArguments*/ undefined, [argumentExpression], ), @@ -909,34 +1137,43 @@ export function transformES2017(context: TransformationContext): (x: SourceFile * * @internal */ -export function createSuperAccessVariableStatement(factory: NodeFactory, resolver: EmitResolver, node: FunctionLikeDeclaration, names: Set<__String>) { +export function createSuperAccessVariableStatement( + factory: NodeFactory, + resolver: EmitResolver, + node: FunctionLikeDeclaration, + names: Set<__String>, +) { // Create a variable declaration with a getter/setter (if binding) definition for each name: // const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... }); - const hasBinding = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) !== 0; + const hasBinding = (resolver.getNodeCheckFlags(node) & + NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) !== + 0; const accessors: PropertyAssignment[] = []; names.forEach((_, key) => { const name = unescapeLeadingUnderscores(key); const getterAndSetter: PropertyAssignment[] = []; - getterAndSetter.push(factory.createPropertyAssignment( - "get", - factory.createArrowFunction( - /*modifiers*/ undefined, - /*typeParameters*/ undefined, - /* parameters */ [], - /*type*/ undefined, - /*equalsGreaterThanToken*/ undefined, - setEmitFlags( - factory.createPropertyAccessExpression( - setEmitFlags( - factory.createSuper(), - EmitFlags.NoSubstitution, + getterAndSetter.push( + factory.createPropertyAssignment( + "get", + factory.createArrowFunction( + /*modifiers*/ undefined, + /*typeParameters*/ undefined, + /* parameters */ [], + /*type*/ undefined, + /*equalsGreaterThanToken*/ undefined, + setEmitFlags( + factory.createPropertyAccessExpression( + setEmitFlags( + factory.createSuper(), + EmitFlags.NoSubstitution, + ), + name, ), - name, + EmitFlags.NoSubstitution, ), - EmitFlags.NoSubstitution, ), ), - )); + ); if (hasBinding) { getterAndSetter.push( factory.createPropertyAssignment( @@ -985,7 +1222,11 @@ export function createSuperAccessVariableStatement(factory: NodeFactory, resolve factory.createVariableDeclarationList( [ factory.createVariableDeclaration( - factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), + factory.createUniqueName( + "_super", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ), /*exclamationToken*/ undefined, /*type*/ undefined, factory.createCallExpression( @@ -996,7 +1237,10 @@ export function createSuperAccessVariableStatement(factory: NodeFactory, resolve /*typeArguments*/ undefined, [ factory.createNull(), - factory.createObjectLiteralExpression(accessors, /*multiLine*/ true), + factory.createObjectLiteralExpression( + accessors, + /*multiLine*/ true, + ), ], ), ), diff --git a/src/compiler/transformers/es2018.ts b/src/compiler/transformers/es2018.ts index e04d1c679e848..0c45d5b075cff 100644 --- a/src/compiler/transformers/es2018.ts +++ b/src/compiler/transformers/es2018.ts @@ -67,7 +67,7 @@ import { isSuperProperty, isVariableDeclarationList, LabeledStatement, - LeftHandSideExpression, + LeftHandSideExpressionBase, MethodDeclaration, ModifierFlags, Node, @@ -150,7 +150,9 @@ const enum HierarchyFacts { } /** @internal */ -export function transformES2018(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle { +export function transformES2018( + context: TransformationContext, +): (x: SourceFile | Bundle) => SourceFile | Bundle { const { factory, getEmitHelperFactory: emitHelpers, @@ -172,7 +174,9 @@ export function transformES2018(context: TransformationContext): (x: SourceFile let exportedVariableStatement = false; let enabledSubstitutions: ESNextSubstitutionFlags; let enclosingFunctionFlags: FunctionFlags; - let parametersWithPrecedingObjectRestOrSpread: Set | undefined; + let parametersWithPrecedingObjectRestOrSpread: + | Set + | undefined; let enclosingSuperContainerFlags: NodeCheckFlags = 0; let hierarchyFacts: HierarchyFacts = 0; @@ -188,8 +192,13 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return chainBundle(context, transformSourceFile); - function affectsSubtree(excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts) { - return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts); + function affectsSubtree( + excludeFacts: HierarchyFacts, + includeFacts: HierarchyFacts, + ) { + return ( + hierarchyFacts !== ((hierarchyFacts & ~excludeFacts) | includeFacts) + ); } /** @@ -197,9 +206,13 @@ export function transformES2018(context: TransformationContext): (x: SourceFile * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree. * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree. */ - function enterSubtree(excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts) { + function enterSubtree( + excludeFacts: HierarchyFacts, + includeFacts: HierarchyFacts, + ) { const ancestorFacts = hierarchyFacts; - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & HierarchyFacts.AncestorFactsMask; + hierarchyFacts = ((hierarchyFacts & ~excludeFacts) | includeFacts) & + HierarchyFacts.AncestorFactsMask; return ancestorFacts; } @@ -248,7 +261,12 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return node; } - function doWithHierarchyFacts(cb: (value: T) => U, value: T, excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts) { + function doWithHierarchyFacts( + cb: (value: T) => U, + value: T, + excludeFacts: HierarchyFacts, + includeFacts: HierarchyFacts, + ) { if (affectsSubtree(excludeFacts, includeFacts)) { const ancestorFacts = enterSubtree(excludeFacts, includeFacts); const result = cb(value); @@ -266,7 +284,10 @@ export function transformES2018(context: TransformationContext): (x: SourceFile * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the * expression of an `ExpressionStatement`). */ - function visitorWorker(node: Node, expressionResultIsUnused: boolean): VisitResult { + function visitorWorker( + node: Node, + expressionResultIsUnused: boolean, + ): VisitResult { if ((node.transformFlags & TransformFlags.ContainsES2018) === 0) { return node; } @@ -280,11 +301,19 @@ export function transformES2018(context: TransformationContext): (x: SourceFile case SyntaxKind.LabeledStatement: return visitLabeledStatement(node as LabeledStatement); case SyntaxKind.ObjectLiteralExpression: - return visitObjectLiteralExpression(node as ObjectLiteralExpression); + return visitObjectLiteralExpression( + node as ObjectLiteralExpression, + ); case SyntaxKind.BinaryExpression: - return visitBinaryExpression(node as BinaryExpression, expressionResultIsUnused); + return visitBinaryExpression( + node as BinaryExpression, + expressionResultIsUnused, + ); case SyntaxKind.CommaListExpression: - return visitCommaListExpression(node as CommaListExpression, expressionResultIsUnused); + return visitCommaListExpression( + node as CommaListExpression, + expressionResultIsUnused, + ); case SyntaxKind.CatchClause: return visitCatchClause(node as CatchClause); case SyntaxKind.VariableStatement: @@ -301,7 +330,10 @@ export function transformES2018(context: TransformationContext): (x: SourceFile HierarchyFacts.IterationStatementIncludes, ); case SyntaxKind.ForOfStatement: - return visitForOfStatement(node as ForOfStatement, /*outermostLabeledStatement*/ undefined); + return visitForOfStatement( + node as ForOfStatement, + /*outermostLabeledStatement*/ undefined, + ); case SyntaxKind.ForStatement: return doWithHierarchyFacts( visitForStatement, @@ -365,16 +397,29 @@ export function transformES2018(context: TransformationContext): (x: SourceFile case SyntaxKind.ExpressionStatement: return visitExpressionStatement(node as ExpressionStatement); case SyntaxKind.ParenthesizedExpression: - return visitParenthesizedExpression(node as ParenthesizedExpression, expressionResultIsUnused); + return visitParenthesizedExpression( + node as ParenthesizedExpression, + expressionResultIsUnused, + ); case SyntaxKind.TaggedTemplateExpression: - return visitTaggedTemplateExpression(node as TaggedTemplateExpression); + return visitTaggedTemplateExpression( + node as TaggedTemplateExpression, + ); case SyntaxKind.PropertyAccessExpression: - if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) { + if ( + capturedSuperProperties && + isPropertyAccessExpression(node) && + node.expression.kind === SyntaxKind.SuperKeyword + ) { capturedSuperProperties.add(node.name.escapedText); } return visitEachChild(node, visitor, context); case SyntaxKind.ElementAccessExpression: - if (capturedSuperProperties && (node as ElementAccessExpression).expression.kind === SyntaxKind.SuperKeyword) { + if ( + capturedSuperProperties && + (node as ElementAccessExpression).expression.kind === + SyntaxKind.SuperKeyword + ) { hasSuperElementAccess = true; } return visitEachChild(node, visitor, context); @@ -392,10 +437,18 @@ export function transformES2018(context: TransformationContext): (x: SourceFile } function visitAwaitExpression(node: AwaitExpression): Expression { - if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { + if ( + enclosingFunctionFlags & FunctionFlags.Async && + enclosingFunctionFlags & FunctionFlags.Generator + ) { return setOriginalNode( setTextRange( - factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(visitNode(node.expression, visitor, isExpression))), + factory.createYieldExpression( + /*asteriskToken*/ undefined, + emitHelpers().createAwaitHelper( + visitNode(node.expression, visitor, isExpression), + ), + ), /*location*/ node, ), node, @@ -405,9 +458,16 @@ export function transformES2018(context: TransformationContext): (x: SourceFile } function visitYieldExpression(node: YieldExpression) { - if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { + if ( + enclosingFunctionFlags & FunctionFlags.Async && + enclosingFunctionFlags & FunctionFlags.Generator + ) { if (node.asteriskToken) { - const expression = visitNode(Debug.checkDefined(node.expression), visitor, isExpression); + const expression = visitNode( + Debug.checkDefined(node.expression), + visitor, + isExpression, + ); return setOriginalNode( setTextRange( @@ -420,7 +480,9 @@ export function transformES2018(context: TransformationContext): (x: SourceFile setTextRange( emitHelpers().createAsyncDelegatorHelper( setTextRange( - emitHelpers().createAsyncValuesHelper(expression), + emitHelpers().createAsyncValuesHelper( + expression, + ), expression, ), ), @@ -441,7 +503,11 @@ export function transformES2018(context: TransformationContext): (x: SourceFile /*asteriskToken*/ undefined, createDownlevelAwait( node.expression - ? visitNode(node.expression, visitor, isExpression) + ? visitNode( + node.expression, + visitor, + isExpression, + ) : factory.createVoidZero(), ), ), @@ -455,11 +521,16 @@ export function transformES2018(context: TransformationContext): (x: SourceFile } function visitReturnStatement(node: ReturnStatement) { - if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { + if ( + enclosingFunctionFlags & FunctionFlags.Async && + enclosingFunctionFlags & FunctionFlags.Generator + ) { return factory.updateReturnStatement( node, createDownlevelAwait( - node.expression ? visitNode(node.expression, visitor, isExpression) : factory.createVoidZero(), + node.expression + ? visitNode(node.expression, visitor, isExpression) + : factory.createVoidZero(), ), ); } @@ -470,21 +541,31 @@ export function transformES2018(context: TransformationContext): (x: SourceFile function visitLabeledStatement(node: LabeledStatement) { if (enclosingFunctionFlags & FunctionFlags.Async) { const statement = unwrapInnermostStatementOfLabel(node); - if (statement.kind === SyntaxKind.ForOfStatement && (statement as ForOfStatement).awaitModifier) { + if ( + statement.kind === SyntaxKind.ForOfStatement && + (statement as ForOfStatement).awaitModifier + ) { return visitForOfStatement(statement as ForOfStatement, node); } - return factory.restoreEnclosingLabel(visitNode(statement, visitor, isStatement, factory.liftToBlock), node); + return factory.restoreEnclosingLabel( + visitNode(statement, visitor, isStatement, factory.liftToBlock), + node, + ); } return visitEachChild(node, visitor, context); } - function chunkObjectLiteralElements(elements: readonly ObjectLiteralElementLike[]): Expression[] { + function chunkObjectLiteralElements( + elements: readonly ObjectLiteralElementLike[], + ): Expression[] { let chunkObject: ObjectLiteralElementLike[] | undefined; const objects: Expression[] = []; for (const e of elements) { if (e.kind === SyntaxKind.SpreadAssignment) { if (chunkObject) { - objects.push(factory.createObjectLiteralExpression(chunkObject)); + objects.push( + factory.createObjectLiteralExpression(chunkObject), + ); chunkObject = undefined; } const target = e.expression; @@ -494,7 +575,10 @@ export function transformES2018(context: TransformationContext): (x: SourceFile chunkObject = append( chunkObject, e.kind === SyntaxKind.PropertyAssignment - ? factory.createPropertyAssignment(e.name, visitNode(e.initializer, visitor, isExpression)) + ? factory.createPropertyAssignment( + e.name, + visitNode(e.initializer, visitor, isExpression), + ) : visitNode(e, visitor, isObjectLiteralElementLike), ); } @@ -506,7 +590,9 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return objects; } - function visitObjectLiteralExpression(node: ObjectLiteralExpression): Expression { + function visitObjectLiteralExpression( + node: ObjectLiteralExpression, + ): Expression { if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: @@ -530,13 +616,19 @@ export function transformES2018(context: TransformationContext): (x: SourceFile // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we // end up with `{ a: 1, b: 2, c: 3 }` const objects = chunkObjectLiteralElements(node.properties); - if (objects.length && objects[0].kind !== SyntaxKind.ObjectLiteralExpression) { + if ( + objects.length && + objects[0].kind !== SyntaxKind.ObjectLiteralExpression + ) { objects.unshift(factory.createObjectLiteralExpression()); } let expression: Expression = objects[0]; if (objects.length > 1) { for (let i = 1; i < objects.length; i++) { - expression = emitHelpers().createAssignHelper([expression, objects[i]]); + expression = emitHelpers().createAssignHelper([ + expression, + objects[i], + ]); } return expression; } @@ -547,7 +639,9 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return visitEachChild(node, visitor, context); } - function visitExpressionStatement(node: ExpressionStatement): ExpressionStatement { + function visitExpressionStatement( + node: ExpressionStatement, + ): ExpressionStatement { return visitEachChild(node, visitorWithUnusedExpressionResult, context); } @@ -555,26 +649,43 @@ export function transformES2018(context: TransformationContext): (x: SourceFile * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the * expression of an `ExpressionStatement`). */ - function visitParenthesizedExpression(node: ParenthesizedExpression, expressionResultIsUnused: boolean): ParenthesizedExpression { - return visitEachChild(node, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, context); + function visitParenthesizedExpression( + node: ParenthesizedExpression, + expressionResultIsUnused: boolean, + ): ParenthesizedExpression { + return visitEachChild( + node, + expressionResultIsUnused + ? visitorWithUnusedExpressionResult + : visitor, + context, + ); } function visitSourceFile(node: SourceFile): SourceFile { const ancestorFacts = enterSubtree( HierarchyFacts.SourceFileExcludes, - isEffectiveStrictModeSourceFile(node, compilerOptions) ? - HierarchyFacts.StrictModeSourceFileIncludes : - HierarchyFacts.SourceFileIncludes, + isEffectiveStrictModeSourceFile(node, compilerOptions) + ? HierarchyFacts.StrictModeSourceFileIncludes + : HierarchyFacts.SourceFileIncludes, ); exportedVariableStatement = false; const visited = visitEachChild(node, visitor, context); const statement = concatenate( visited.statements, taggedTemplateStringDeclarations && [ - factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations)), + factory.createVariableStatement( + /*modifiers*/ undefined, + factory.createVariableDeclarationList( + taggedTemplateStringDeclarations, + ), + ), ], ); - const result = factory.updateSourceFile(visited, setTextRange(factory.createNodeArray(statement), node.statements)); + const result = factory.updateSourceFile( + visited, + setTextRange(factory.createNodeArray(statement), node.statements), + ); exitSubtree(ancestorFacts); return result; } @@ -597,8 +708,14 @@ export function transformES2018(context: TransformationContext): (x: SourceFile * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the * expression of an `ExpressionStatement`). */ - function visitBinaryExpression(node: BinaryExpression, expressionResultIsUnused: boolean): Expression { - if (isDestructuringAssignment(node) && containsObjectRestOrSpread(node.left)) { + function visitBinaryExpression( + node: BinaryExpression, + expressionResultIsUnused: boolean, + ): Expression { + if ( + isDestructuringAssignment(node) && + containsObjectRestOrSpread(node.left) + ) { return flattenDestructuringAssignment( node, visitor, @@ -610,9 +727,19 @@ export function transformES2018(context: TransformationContext): (x: SourceFile if (node.operatorToken.kind === SyntaxKind.CommaToken) { return factory.updateBinaryExpression( node, - visitNode(node.left, visitorWithUnusedExpressionResult, isExpression), + visitNode( + node.left, + visitorWithUnusedExpressionResult, + isExpression, + ), node.operatorToken, - visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, isExpression), + visitNode( + node.right, + expressionResultIsUnused + ? visitorWithUnusedExpressionResult + : visitor, + isExpression, + ), ); } return visitEachChild(node, visitor, context); @@ -622,20 +749,35 @@ export function transformES2018(context: TransformationContext): (x: SourceFile * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the * expression of an `ExpressionStatement`). */ - function visitCommaListExpression(node: CommaListExpression, expressionResultIsUnused: boolean): Expression { + function visitCommaListExpression( + node: CommaListExpression, + expressionResultIsUnused: boolean, + ): Expression { if (expressionResultIsUnused) { - return visitEachChild(node, visitorWithUnusedExpressionResult, context); + return visitEachChild( + node, + visitorWithUnusedExpressionResult, + context, + ); } let result: Expression[] | undefined; for (let i = 0; i < node.elements.length; i++) { const element = node.elements[i]; - const visited = visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, isExpression); + const visited = visitNode( + element, + i < node.elements.length - 1 + ? visitorWithUnusedExpressionResult + : visitor, + isExpression, + ); if (result || visited !== element) { result ||= node.elements.slice(0, i); result.push(visited); } } - const elements = result ? setTextRange(factory.createNodeArray(result), node.elements) : node.elements; + const elements = result + ? setTextRange(factory.createNodeArray(result), node.elements) + : node.elements; return factory.updateCommaListExpression(node, elements); } @@ -643,28 +785,53 @@ export function transformES2018(context: TransformationContext): (x: SourceFile if ( node.variableDeclaration && isBindingPattern(node.variableDeclaration.name) && - node.variableDeclaration.name.transformFlags & TransformFlags.ContainsObjectRestOrSpread + node.variableDeclaration.name.transformFlags & + TransformFlags.ContainsObjectRestOrSpread ) { - const name = factory.getGeneratedNameForNode(node.variableDeclaration.name); - const updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name); - const visitedBindings = flattenDestructuringBinding(updatedDecl, visitor, context, FlattenLevel.ObjectRest); + const name = factory.getGeneratedNameForNode( + node.variableDeclaration.name, + ); + const updatedDecl = factory.updateVariableDeclaration( + node.variableDeclaration, + node.variableDeclaration.name, + /*exclamationToken*/ undefined, + /*type*/ undefined, + name, + ); + const visitedBindings = flattenDestructuringBinding( + updatedDecl, + visitor, + context, + FlattenLevel.ObjectRest, + ); let block = visitNode(node.block, visitor, isBlock); if (some(visitedBindings)) { block = factory.updateBlock(block, [ - factory.createVariableStatement(/*modifiers*/ undefined, visitedBindings), + factory.createVariableStatement( + /*modifiers*/ undefined, + visitedBindings, + ), ...block.statements, ]); } return factory.updateCatchClause( node, - factory.updateVariableDeclaration(node.variableDeclaration, name, /*exclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined), + factory.updateVariableDeclaration( + node.variableDeclaration, + name, + /*exclamationToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined, + ), block, ); } return visitEachChild(node, visitor, context); } - function visitVariableStatement(node: VariableStatement): VisitResult { + function visitVariableStatement( + node: VariableStatement, + ): VisitResult { if (hasSyntacticModifier(node, ModifierFlags.Export)) { const savedExportedVariableStatement = exportedVariableStatement; exportedVariableStatement = true; @@ -680,20 +847,34 @@ export function transformES2018(context: TransformationContext): (x: SourceFile * * @param node A VariableDeclaration node. */ - function visitVariableDeclaration(node: VariableDeclaration): VisitResult { + function visitVariableDeclaration( + node: VariableDeclaration, + ): VisitResult { if (exportedVariableStatement) { const savedExportedVariableStatement = exportedVariableStatement; exportedVariableStatement = false; - const visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true); + const visited = visitVariableDeclarationWorker( + node, + /*exportedVariableStatement*/ true, + ); exportedVariableStatement = savedExportedVariableStatement; return visited; } - return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false); + return visitVariableDeclarationWorker( + node, + /*exportedVariableStatement*/ false, + ); } - function visitVariableDeclarationWorker(node: VariableDeclaration, exportedVariableStatement: boolean): VisitResult { + function visitVariableDeclarationWorker( + node: VariableDeclaration, + exportedVariableStatement: boolean, + ): VisitResult { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (isBindingPattern(node.name) && node.name.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { + if ( + isBindingPattern(node.name) && + node.name.transformFlags & TransformFlags.ContainsObjectRestOrSpread + ) { return flattenDestructuringBinding( node, visitor, @@ -709,9 +890,17 @@ export function transformES2018(context: TransformationContext): (x: SourceFile function visitForStatement(node: ForStatement): VisitResult { return factory.updateForStatement( node, - visitNode(node.initializer, visitorWithUnusedExpressionResult, isForInitializer), + visitNode( + node.initializer, + visitorWithUnusedExpressionResult, + isForInitializer, + ), visitNode(node.condition, visitor, isExpression), - visitNode(node.incrementor, visitorWithUnusedExpressionResult, isExpression), + visitNode( + node.incrementor, + visitorWithUnusedExpressionResult, + isExpression, + ), visitIterationBody(node.statement, visitor, context), ); } @@ -725,28 +914,56 @@ export function transformES2018(context: TransformationContext): (x: SourceFile * * @param node A ForOfStatement. */ - function visitForOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined): VisitResult { - const ancestorFacts = enterSubtree(HierarchyFacts.IterationStatementExcludes, HierarchyFacts.IterationStatementIncludes); + function visitForOfStatement( + node: ForOfStatement, + outermostLabeledStatement: LabeledStatement | undefined, + ): VisitResult { + const ancestorFacts = enterSubtree( + HierarchyFacts.IterationStatementExcludes, + HierarchyFacts.IterationStatementIncludes, + ); if ( - node.initializer.transformFlags & TransformFlags.ContainsObjectRestOrSpread || - isAssignmentPattern(node.initializer) && containsObjectRestOrSpread(node.initializer) + node.initializer.transformFlags & + TransformFlags.ContainsObjectRestOrSpread || + (isAssignmentPattern(node.initializer) && + containsObjectRestOrSpread(node.initializer)) ) { node = transformForOfStatementWithObjectRest(node); } - const result = node.awaitModifier ? - transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) : - factory.restoreEnclosingLabel(visitEachChild(node, visitor, context), outermostLabeledStatement); + const result = node.awaitModifier + ? transformForAwaitOfStatement( + node, + outermostLabeledStatement, + ancestorFacts, + ) + : factory.restoreEnclosingLabel( + visitEachChild(node, visitor, context), + outermostLabeledStatement, + ); exitSubtree(ancestorFacts); return result; } function transformForOfStatementWithObjectRest(node: ForOfStatement) { - const initializerWithoutParens = skipParentheses(node.initializer) as ForInitializer; - if (isVariableDeclarationList(initializerWithoutParens) || isAssignmentPattern(initializerWithoutParens)) { + const initializerWithoutParens = skipParentheses( + node.initializer, + ) as ForInitializer; + if ( + isVariableDeclarationList(initializerWithoutParens) || + isAssignmentPattern(initializerWithoutParens) + ) { let bodyLocation: TextRange | undefined; let statementsLocation: TextRange | undefined; - const temp = factory.createTempVariable(/*recordTempVariable*/ undefined); - const statements: Statement[] = [createForOfBindingStatement(factory, initializerWithoutParens, temp)]; + const temp = factory.createTempVariable( + /*recordTempVariable*/ undefined, + ); + const statements: Statement[] = [ + createForOfBindingStatement( + factory, + initializerWithoutParens, + temp, + ), + ]; if (isBlock(node.statement)) { addRange(statements, node.statement.statements); bodyLocation = node.statement; @@ -763,7 +980,10 @@ export function transformES2018(context: TransformationContext): (x: SourceFile setTextRange( factory.createVariableDeclarationList( [ - setTextRange(factory.createVariableDeclaration(temp), node.initializer), + setTextRange( + factory.createVariableDeclaration(temp), + node.initializer, + ), ], NodeFlags.Let, ), @@ -772,7 +992,10 @@ export function transformES2018(context: TransformationContext): (x: SourceFile node.expression, setTextRange( factory.createBlock( - setTextRange(factory.createNodeArray(statements), statementsLocation), + setTextRange( + factory.createNodeArray(statements), + statementsLocation, + ), /*multiLine*/ true, ), bodyLocation, @@ -782,18 +1005,39 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return node; } - function convertForOfStatementHead(node: ForOfStatement, boundValue: Expression, nonUserCode: Identifier) { + function convertForOfStatementHead( + node: ForOfStatement, + boundValue: Expression, + nonUserCode: Identifier, + ) { const value = factory.createTempVariable(hoistVariableDeclaration); - const iteratorValueExpression = factory.createAssignment(value, boundValue); - const iteratorValueStatement = factory.createExpressionStatement(iteratorValueExpression); + const iteratorValueExpression = factory.createAssignment( + value, + boundValue, + ); + const iteratorValueStatement = factory.createExpressionStatement( + iteratorValueExpression, + ); setSourceMapRange(iteratorValueStatement, node.expression); - const exitNonUserCodeExpression = factory.createAssignment(nonUserCode, factory.createFalse()); - const exitNonUserCodeStatement = factory.createExpressionStatement(exitNonUserCodeExpression); + const exitNonUserCodeExpression = factory.createAssignment( + nonUserCode, + factory.createFalse(), + ); + const exitNonUserCodeStatement = factory.createExpressionStatement( + exitNonUserCodeExpression, + ); setSourceMapRange(exitNonUserCodeStatement, node.expression); - const statements: Statement[] = [iteratorValueStatement, exitNonUserCodeStatement]; - const binding = createForOfBindingStatement(factory, node.initializer, value); + const statements: Statement[] = [ + iteratorValueStatement, + exitNonUserCodeStatement, + ]; + const binding = createForOfBindingStatement( + factory, + node.initializer, + value, + ); statements.push(visitNode(binding, visitor, isStatement)); let bodyLocation: TextRange | undefined; @@ -810,7 +1054,10 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return setTextRange( factory.createBlock( - setTextRange(factory.createNodeArray(statements), statementsLocation), + setTextRange( + factory.createNodeArray(statements), + statementsLocation, + ), /*multiLine*/ true, ), bodyLocation, @@ -819,32 +1066,67 @@ export function transformES2018(context: TransformationContext): (x: SourceFile function createDownlevelAwait(expression: Expression) { return enclosingFunctionFlags & FunctionFlags.Generator - ? factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(expression)) + ? factory.createYieldExpression( + /*asteriskToken*/ undefined, + emitHelpers().createAwaitHelper(expression), + ) : factory.createAwaitExpression(expression); } - function transformForAwaitOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement | undefined, ancestorFacts: HierarchyFacts) { + function transformForAwaitOfStatement( + node: ForOfStatement, + outermostLabeledStatement: LabeledStatement | undefined, + ancestorFacts: HierarchyFacts, + ) { const expression = visitNode(node.expression, visitor, isExpression); - const iterator = isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined); - const result = isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined); - const nonUserCode = factory.createTempVariable(/*recordTempVariable*/ undefined); + const iterator = isIdentifier(expression) + ? factory.getGeneratedNameForNode(expression) + : factory.createTempVariable(/*recordTempVariable*/ undefined); + const result = isIdentifier(expression) + ? factory.getGeneratedNameForNode(iterator) + : factory.createTempVariable(/*recordTempVariable*/ undefined); + const nonUserCode = factory.createTempVariable( + /*recordTempVariable*/ undefined, + ); const done = factory.createTempVariable(hoistVariableDeclaration); const errorRecord = factory.createUniqueName("e"); const catchVariable = factory.getGeneratedNameForNode(errorRecord); - const returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined); - const callValues = setTextRange(emitHelpers().createAsyncValuesHelper(expression), node.expression); - const callNext = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []); + const returnMethod = factory.createTempVariable( + /*recordTempVariable*/ undefined, + ); + const callValues = setTextRange( + emitHelpers().createAsyncValuesHelper(expression), + node.expression, + ); + const callNext = factory.createCallExpression( + factory.createPropertyAccessExpression(iterator, "next"), + /*typeArguments*/ undefined, + [], + ); const getDone = factory.createPropertyAccessExpression(result, "done"); - const getValue = factory.createPropertyAccessExpression(result, "value"); - const callReturn = factory.createFunctionCallCall(returnMethod, iterator, []); + const getValue = factory.createPropertyAccessExpression( + result, + "value", + ); + const callReturn = factory.createFunctionCallCall( + returnMethod, + iterator, + [], + ); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration - const initializer = ancestorFacts & HierarchyFacts.IterationContainer ? - factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), callValues]) : - callValues; + const initializer = ancestorFacts & HierarchyFacts.IterationContainer + ? factory.inlineExpressions([ + factory.createAssignment( + errorRecord, + factory.createVoidZero(), + ), + callValues, + ]) + : callValues; const forStatement = setEmitFlags( setTextRange( @@ -852,8 +1134,21 @@ export function transformES2018(context: TransformationContext): (x: SourceFile /*initializer*/ setEmitFlags( setTextRange( factory.createVariableDeclarationList([ - factory.createVariableDeclaration(nonUserCode, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createTrue()), - setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression), + factory.createVariableDeclaration( + nonUserCode, + /*exclamationToken*/ undefined, + /*type*/ undefined, + factory.createTrue(), + ), + setTextRange( + factory.createVariableDeclaration( + iterator, + /*exclamationToken*/ undefined, + /*type*/ undefined, + initializer, + ), + node.expression, + ), factory.createVariableDeclaration(result), ]), node.expression, @@ -861,12 +1156,22 @@ export function transformES2018(context: TransformationContext): (x: SourceFile EmitFlags.NoHoisting, ), /*condition*/ factory.inlineExpressions([ - factory.createAssignment(result, createDownlevelAwait(callNext)), + factory.createAssignment( + result, + createDownlevelAwait(callNext), + ), factory.createAssignment(done, getDone), factory.createLogicalNot(done), ]), - /*incrementor*/ factory.createAssignment(nonUserCode, factory.createTrue()), - /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode), + /*incrementor*/ factory.createAssignment( + nonUserCode, + factory.createTrue(), + ), + /*statement*/ convertForOfStatementHead( + node, + getValue, + nonUserCode, + ), ), /*location*/ node, ), @@ -889,7 +1194,10 @@ export function transformES2018(context: TransformationContext): (x: SourceFile factory.createAssignment( errorRecord, factory.createObjectLiteralExpression([ - factory.createPropertyAssignment("error", catchVariable), + factory.createPropertyAssignment( + "error", + catchVariable, + ), ]), ), ), @@ -909,10 +1217,15 @@ export function transformES2018(context: TransformationContext): (x: SourceFile ), factory.createAssignment( returnMethod, - factory.createPropertyAccessExpression(iterator, "return"), + factory.createPropertyAccessExpression( + iterator, + "return", + ), ), ), - factory.createExpressionStatement(createDownlevelAwait(callReturn)), + factory.createExpressionStatement( + createDownlevelAwait(callReturn), + ), ), EmitFlags.SingleLine, ), @@ -924,7 +1237,10 @@ export function transformES2018(context: TransformationContext): (x: SourceFile factory.createIfStatement( errorRecord, factory.createThrowStatement( - factory.createPropertyAccessExpression(errorRecord, "error"), + factory.createPropertyAccessExpression( + errorRecord, + "error", + ), ), ), EmitFlags.SingleLine, @@ -948,7 +1264,9 @@ export function transformES2018(context: TransformationContext): (x: SourceFile node, /*modifiers*/ undefined, node.dotDotDotToken, - isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, + isBindingPattern(node.name) + ? factory.getGeneratedNameForNode(node) + : node.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined, @@ -970,13 +1288,18 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return visitEachChild(node, visitor, context); } - function collectParametersWithPrecedingObjectRestOrSpread(node: SignatureDeclaration) { + function collectParametersWithPrecedingObjectRestOrSpread( + node: SignatureDeclaration, + ) { let parameters: Set | undefined; for (const parameter of node.parameters) { if (parameters) { parameters.add(parameter); } - else if (parameter.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { + else if ( + parameter.transformFlags & + TransformFlags.ContainsObjectRestOrSpread + ) { parameters = new Set(); } } @@ -1042,7 +1365,11 @@ export function transformES2018(context: TransformationContext): (x: SourceFile const updated = factory.updateMethodDeclaration( node, enclosingFunctionFlags & FunctionFlags.Generator - ? visitNodes(node.modifiers, visitorNoAsyncModifier, isModifierLike) + ? visitNodes( + node.modifiers, + visitorNoAsyncModifier, + isModifierLike, + ) : node.modifiers, enclosingFunctionFlags & FunctionFlags.Async ? undefined @@ -1052,7 +1379,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, - enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator + enclosingFunctionFlags & FunctionFlags.Async && + enclosingFunctionFlags & FunctionFlags.Generator ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node), ); @@ -1078,7 +1406,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, - enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator + enclosingFunctionFlags & FunctionFlags.Async && + enclosingFunctionFlags & FunctionFlags.Generator ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node), ); @@ -1123,7 +1452,8 @@ export function transformES2018(context: TransformationContext): (x: SourceFile /*typeParameters*/ undefined, visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, - enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator + enclosingFunctionFlags & FunctionFlags.Async && + enclosingFunctionFlags & FunctionFlags.Generator ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node), ); @@ -1132,10 +1462,21 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return updated; } - function transformAsyncGeneratorFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody { + function transformAsyncGeneratorFunctionBody( + node: + | MethodDeclaration + | AccessorDeclaration + | FunctionDeclaration + | FunctionExpression, + ): FunctionBody { resumeLexicalEnvironment(); const statements: Statement[] = []; - const statementOffset = factory.copyPrologue(node.body!.statements, statements, /*ensureUseStrict*/ false, visitor); + const statementOffset = factory.copyPrologue( + node.body!.statements, + statements, + /*ensureUseStrict*/ false, + visitor, + ); appendObjectRestAssignmentsIfNeeded(statements, node); const savedCapturedSuperProperties = capturedSuperProperties; @@ -1154,7 +1495,12 @@ export function transformES2018(context: TransformationContext): (x: SourceFile /*type*/ undefined, factory.updateBlock( node.body!, - visitLexicalEnvironment(node.body!.statements, visitor, context, statementOffset), + visitLexicalEnvironment( + node.body!.statements, + visitor, + context, + statementOffset, + ), ), ), !!(hierarchyFacts & HierarchyFacts.HasLexicalThis), @@ -1163,25 +1509,44 @@ export function transformES2018(context: TransformationContext): (x: SourceFile // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - const emitSuperHelpers = languageVersion >= ScriptTarget.ES2015 && resolver.getNodeCheckFlags(node) & (NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync | NodeCheckFlags.MethodWithSuperPropertyAccessInAsync); + const emitSuperHelpers = languageVersion >= ScriptTarget.ES2015 && + resolver.getNodeCheckFlags(node) & + (NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync | + NodeCheckFlags.MethodWithSuperPropertyAccessInAsync); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); - const variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties); + const variableStatement = createSuperAccessVariableStatement( + factory, + resolver, + node, + capturedSuperProperties, + ); substitutedSuperAccessors[getNodeId(variableStatement)] = true; - insertStatementsAfterStandardPrologue(statements, [variableStatement]); + insertStatementsAfterStandardPrologue(statements, [ + variableStatement, + ]); } statements.push(returnStatement); - insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); + insertStatementsAfterStandardPrologue( + statements, + endLexicalEnvironment(), + ); const block = factory.updateBlock(node.body!, statements); if (emitSuperHelpers && hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) { + if ( + resolver.getNodeCheckFlags(node) & + NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync + ) { addEmitHelper(block, advancedAsyncSuperHelper); } - else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.MethodWithSuperPropertyAccessInAsync) { + else if ( + resolver.getNodeCheckFlags(node) & + NodeCheckFlags.MethodWithSuperPropertyAccessInAsync + ) { addEmitHelper(block, asyncSuperHelper); } } @@ -1192,29 +1557,64 @@ export function transformES2018(context: TransformationContext): (x: SourceFile return block; } - function transformFunctionBody(node: FunctionDeclaration | FunctionExpression | ConstructorDeclaration | MethodDeclaration | AccessorDeclaration): FunctionBody; + function transformFunctionBody( + node: + | FunctionDeclaration + | FunctionExpression + | ConstructorDeclaration + | MethodDeclaration + | AccessorDeclaration, + ): FunctionBody; function transformFunctionBody(node: ArrowFunction): ConciseBody; function transformFunctionBody(node: FunctionLikeDeclaration): ConciseBody { resumeLexicalEnvironment(); let statementOffset = 0; const statements: Statement[] = []; - const body = visitNode(node.body, visitor, isConciseBody) ?? factory.createBlock([]); + const body = visitNode(node.body, visitor, isConciseBody) ?? + factory.createBlock([]); if (isBlock(body)) { - statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor); + statementOffset = factory.copyPrologue( + body.statements, + statements, + /*ensureUseStrict*/ false, + visitor, + ); } - addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node)); + addRange( + statements, + appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node), + ); const leadingStatements = endLexicalEnvironment(); - if (statementOffset > 0 || some(statements) || some(leadingStatements)) { - const block = factory.converters.convertToFunctionBlock(body, /*multiLine*/ true); - insertStatementsAfterStandardPrologue(statements, leadingStatements); + if ( + statementOffset > 0 || + some(statements) || + some(leadingStatements) + ) { + const block = factory.converters.convertToFunctionBlock( + body, + /*multiLine*/ true, + ); + insertStatementsAfterStandardPrologue( + statements, + leadingStatements, + ); addRange(statements, block.statements.slice(statementOffset)); - return factory.updateBlock(block, setTextRange(factory.createNodeArray(statements), block.statements)); + return factory.updateBlock( + block, + setTextRange( + factory.createNodeArray(statements), + block.statements, + ), + ); } return body; } - function appendObjectRestAssignmentsIfNeeded(statements: Statement[] | undefined, node: FunctionLikeDeclaration): Statement[] | undefined { + function appendObjectRestAssignmentsIfNeeded( + statements: Statement[] | undefined, + node: FunctionLikeDeclaration, + ): Statement[] | undefined { let containsPrecedingObjectRestOrSpread = false; for (const parameter of node.parameters) { if (containsPrecedingObjectRestOrSpread) { @@ -1233,16 +1633,28 @@ export function transformES2018(context: TransformationContext): (x: SourceFile factory.getGeneratedNameForNode(parameter), ); if (some(declarations)) { - const declarationList = factory.createVariableDeclarationList(declarations); - const statement = factory.createVariableStatement(/*modifiers*/ undefined, declarationList); + const declarationList = factory.createVariableDeclarationList( + declarations, + ); + const statement = factory.createVariableStatement( + /*modifiers*/ undefined, + declarationList, + ); setEmitFlags(statement, EmitFlags.CustomPrologue); statements = append(statements, statement); } } else if (parameter.initializer) { const name = factory.getGeneratedNameForNode(parameter); - const initializer = visitNode(parameter.initializer, visitor, isExpression); - const assignment = factory.createAssignment(name, initializer); + const initializer = visitNode( + parameter.initializer, + visitor, + isExpression, + ); + const assignment = factory.createAssignment( + name, + initializer, + ); const statement = factory.createExpressionStatement(assignment); setEmitFlags(statement, EmitFlags.CustomPrologue); statements = append(statements, statement); @@ -1263,26 +1675,59 @@ export function transformES2018(context: TransformationContext): (x: SourceFile setTextRange(name, parameter.name); setEmitFlags(name, EmitFlags.NoSourceMap); - const initializer = visitNode(parameter.initializer, visitor, isExpression); - addEmitFlags(initializer, EmitFlags.NoSourceMap | EmitFlags.NoComments); - - const assignment = factory.createAssignment(name, initializer); + const initializer = visitNode( + parameter.initializer, + visitor, + isExpression, + ); + addEmitFlags( + initializer, + EmitFlags.NoSourceMap | EmitFlags.NoComments, + ); + + const assignment = factory.createAssignment( + name, + initializer, + ); setTextRange(assignment, parameter); setEmitFlags(assignment, EmitFlags.NoComments); - const block = factory.createBlock([factory.createExpressionStatement(assignment)]); + const block = factory.createBlock([ + factory.createExpressionStatement(assignment), + ]); setTextRange(block, parameter); - setEmitFlags(block, EmitFlags.SingleLine | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTokenSourceMaps | EmitFlags.NoComments); - - const typeCheck = factory.createTypeCheck(factory.cloneNode(parameter.name), "undefined"); - const statement = factory.createIfStatement(typeCheck, block); + setEmitFlags( + block, + EmitFlags.SingleLine | + EmitFlags.NoTrailingSourceMap | + EmitFlags.NoTokenSourceMaps | + EmitFlags.NoComments, + ); + + const typeCheck = factory.createTypeCheck( + factory.cloneNode(parameter.name), + "undefined", + ); + const statement = factory.createIfStatement( + typeCheck, + block, + ); startOnNewLine(statement); setTextRange(statement, parameter); - setEmitFlags(statement, EmitFlags.NoTokenSourceMaps | EmitFlags.NoTrailingSourceMap | EmitFlags.CustomPrologue | EmitFlags.NoComments); + setEmitFlags( + statement, + EmitFlags.NoTokenSourceMaps | + EmitFlags.NoTrailingSourceMap | + EmitFlags.CustomPrologue | + EmitFlags.NoComments, + ); statements = append(statements, statement); } } - else if (parameter.transformFlags & TransformFlags.ContainsObjectRestOrSpread) { + else if ( + parameter.transformFlags & + TransformFlags.ContainsObjectRestOrSpread + ) { containsPrecedingObjectRestOrSpread = true; const declarations = flattenDestructuringBinding( parameter, @@ -1295,7 +1740,10 @@ export function transformES2018(context: TransformationContext): (x: SourceFile ); if (some(declarations)) { const declarationList = factory.createVariableDeclarationList(declarations); - const statement = factory.createVariableStatement(/*modifiers*/ undefined, declarationList); + const statement = factory.createVariableStatement( + /*modifiers*/ undefined, + declarationList, + ); setEmitFlags(statement, EmitFlags.CustomPrologue); statements = append(statements, statement); } @@ -1305,7 +1753,11 @@ export function transformES2018(context: TransformationContext): (x: SourceFile } function enableSubstitutionForAsyncMethodsWithSuper() { - if ((enabledSubstitutions & ESNextSubstitutionFlags.AsyncMethodsWithSuper) === 0) { + if ( + (enabledSubstitutions & + ESNextSubstitutionFlags.AsyncMethodsWithSuper) === + 0 + ) { enabledSubstitutions |= ESNextSubstitutionFlags.AsyncMethodsWithSuper; // We need to enable substitutions for call, property access, and element access @@ -1332,11 +1784,21 @@ export function transformES2018(context: TransformationContext): (x: SourceFile * @param node The node to be printed. * @param emitCallback The callback used to emit the node. */ - function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) { + function onEmitNode( + hint: EmitHint, + node: Node, + emitCallback: (hint: EmitHint, node: Node) => void, + ) { // If we need to support substitutions for `super` in an async method, // we should track it here. - if (enabledSubstitutions & ESNextSubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) { - const superContainerFlags = resolver.getNodeCheckFlags(node) & (NodeCheckFlags.MethodWithSuperPropertyAccessInAsync | NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync); + if ( + enabledSubstitutions & + ESNextSubstitutionFlags.AsyncMethodsWithSuper && + isSuperContainer(node) + ) { + const superContainerFlags = resolver.getNodeCheckFlags(node) & + (NodeCheckFlags.MethodWithSuperPropertyAccessInAsync | + NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync); if (superContainerFlags !== enclosingSuperContainerFlags) { const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -1346,7 +1808,10 @@ export function transformES2018(context: TransformationContext): (x: SourceFile } } // Disable substitution in the generated super accessor itself. - else if (enabledSubstitutions && substitutedSuperAccessors[getNodeId(node)]) { + else if ( + enabledSubstitutions && + substitutedSuperAccessors[getNodeId(node)] + ) { const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = 0 as NodeCheckFlags; previousOnEmitNode(hint, node, emitCallback); @@ -1374,20 +1839,30 @@ export function transformES2018(context: TransformationContext): (x: SourceFile function substituteExpression(node: Expression) { switch (node.kind) { case SyntaxKind.PropertyAccessExpression: - return substitutePropertyAccessExpression(node as PropertyAccessExpression); + return substitutePropertyAccessExpression( + node as PropertyAccessExpression, + ); case SyntaxKind.ElementAccessExpression: - return substituteElementAccessExpression(node as ElementAccessExpression); + return substituteElementAccessExpression( + node as ElementAccessExpression, + ); case SyntaxKind.CallExpression: return substituteCallExpression(node as CallExpression); } return node; } - function substitutePropertyAccessExpression(node: PropertyAccessExpression) { + function substitutePropertyAccessExpression( + node: PropertyAccessExpression, + ) { if (node.expression.kind === SyntaxKind.SuperKeyword) { return setTextRange( factory.createPropertyAccessExpression( - factory.createUniqueName("_super", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel), + factory.createUniqueName( + "_super", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ), node.name, ), node, @@ -1413,12 +1888,12 @@ export function transformES2018(context: TransformationContext): (x: SourceFile ? substitutePropertyAccessExpression(expression) : substituteElementAccessExpression(expression); return factory.createCallExpression( - factory.createPropertyAccessExpression(argumentExpression, "call"), + factory.createPropertyAccessExpression( + argumentExpression, + "call", + ), /*typeArguments*/ undefined, - [ - factory.createThis(), - ...node.arguments, - ], + [factory.createThis(), ...node.arguments], ); } return node; @@ -1426,15 +1901,23 @@ export function transformES2018(context: TransformationContext): (x: SourceFile function isSuperContainer(node: Node) { const kind = node.kind; - return kind === SyntaxKind.ClassDeclaration - || kind === SyntaxKind.Constructor - || kind === SyntaxKind.MethodDeclaration - || kind === SyntaxKind.GetAccessor - || kind === SyntaxKind.SetAccessor; + return ( + kind === SyntaxKind.ClassDeclaration || + kind === SyntaxKind.Constructor || + kind === SyntaxKind.MethodDeclaration || + kind === SyntaxKind.GetAccessor || + kind === SyntaxKind.SetAccessor + ); } - function createSuperElementAccessInAsyncMethod(argumentExpression: Expression, location: TextRange): LeftHandSideExpression { - if (enclosingSuperContainerFlags & NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync) { + function createSuperElementAccessInAsyncMethod( + argumentExpression: Expression, + location: TextRange, + ): LeftHandSideExpressionBase { + if ( + enclosingSuperContainerFlags & + NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync + ) { return setTextRange( factory.createPropertyAccessExpression( factory.createCallExpression( diff --git a/src/compiler/transformers/esDecorators.ts b/src/compiler/transformers/esDecorators.ts index a356421c191ae..949629492be01 100644 --- a/src/compiler/transformers/esDecorators.ts +++ b/src/compiler/transformers/esDecorators.ts @@ -281,7 +281,9 @@ type LexicalEnvironmentStackEntry = | PropertyNameLexicalEnvironmentStackEntry; /** @internal */ -export function transformESDecorators(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle { +export function transformESDecorators( + context: TransformationContext, +): (x: SourceFile | Bundle) => SourceFile | Bundle { const { factory, getEmitHelperFactory: emitHelpers, @@ -306,7 +308,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc const visited = visitEachChild(node, visitor, context); addEmitHelpers(visited, context.readEmitHelpers()); if (shouldTransformPrivateStaticElementsInFile) { - addInternalEmitFlags(visited, InternalEmitFlags.TransformPrivateStaticElements); + addInternalEmitFlags( + visited, + InternalEmitFlags.TransformPrivateStaticElements, + ); shouldTransformPrivateStaticElementsInFile = false; } return visited; @@ -337,22 +342,38 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } function enterClass(classInfo: ClassInfo | undefined) { - top = { kind: "class", next: top, classInfo, savedPendingExpressions: pendingExpressions }; + top = { + kind: "class", + next: top, + classInfo, + savedPendingExpressions: pendingExpressions, + }; pendingExpressions = undefined; updateState(); } function exitClass() { - Debug.assert(top?.kind === "class", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class' but got '${top?.kind}' instead.`); + Debug.assert( + top?.kind === "class", + "Incorrect value for top.kind.", + () => `Expected top.kind to be 'class' but got '${top?.kind}' instead.`, + ); pendingExpressions = top.savedPendingExpressions; top = top.next; updateState(); } function enterClassElement(node: ClassElement) { - Debug.assert(top?.kind === "class", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class' but got '${top?.kind}' instead.`); + Debug.assert( + top?.kind === "class", + "Incorrect value for top.kind.", + () => `Expected top.kind to be 'class' but got '${top?.kind}' instead.`, + ); top = { kind: "class-element", next: top }; - if (isClassStaticBlockDeclaration(node) || isPropertyDeclaration(node) && hasStaticModifier(node)) { + if ( + isClassStaticBlockDeclaration(node) || + (isPropertyDeclaration(node) && hasStaticModifier(node)) + ) { top.classThis = top.next.classInfo?.classThis; top.classSuper = top.next.classInfo?.classSuper; } @@ -360,20 +381,36 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } function exitClassElement() { - Debug.assert(top?.kind === "class-element", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class-element' but got '${top?.kind}' instead.`); - Debug.assert(top.next?.kind === "class", "Incorrect value for top.next.kind.", () => `Expected top.next.kind to be 'class' but got '${top!.next?.kind}' instead.`); + Debug.assert( + top?.kind === "class-element", + "Incorrect value for top.kind.", + () => `Expected top.kind to be 'class-element' but got '${top?.kind}' instead.`, + ); + Debug.assert( + top.next?.kind === "class", + "Incorrect value for top.next.kind.", + () => `Expected top.next.kind to be 'class' but got '${top!.next?.kind}' instead.`, + ); top = top.next; updateState(); } function enterName() { - Debug.assert(top?.kind === "class-element", "Incorrect value for top.kind.", () => `Expected top.kind to be 'class-element' but got '${top?.kind}' instead.`); + Debug.assert( + top?.kind === "class-element", + "Incorrect value for top.kind.", + () => `Expected top.kind to be 'class-element' but got '${top?.kind}' instead.`, + ); top = { kind: "name", next: top }; updateState(); } function exitName() { - Debug.assert(top?.kind === "name", "Incorrect value for top.kind.", () => `Expected top.kind to be 'name' but got '${top?.kind}' instead.`); + Debug.assert( + top?.kind === "name", + "Incorrect value for top.kind.", + () => `Expected top.kind to be 'name' but got '${top?.kind}' instead.`, + ); top = top.next; updateState(); } @@ -384,14 +421,23 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc top.depth++; } else { - top = { kind: "other", next: top, depth: 0, savedPendingExpressions: pendingExpressions }; + top = { + kind: "other", + next: top, + depth: 0, + savedPendingExpressions: pendingExpressions, + }; pendingExpressions = undefined; updateState(); } } function exitOther() { - Debug.assert(top?.kind === "other", "Incorrect value for top.kind.", () => `Expected top.kind to be 'other' but got '${top?.kind}' instead.`); + Debug.assert( + top?.kind === "other", + "Incorrect value for top.kind.", + () => `Expected top.kind to be 'other' but got '${top?.kind}' instead.`, + ); if (top.depth > 0) { Debug.assert(!pendingExpressions); top.depth--; @@ -404,9 +450,14 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } function shouldVisitNode(node: Node) { - return !!(node.transformFlags & TransformFlags.ContainsDecorators) - || !!classThis && !!(node.transformFlags & TransformFlags.ContainsLexicalThis) - || !!classThis && !!classSuper && !!(node.transformFlags & TransformFlags.ContainsLexicalSuper); + return ( + !!(node.transformFlags & TransformFlags.ContainsDecorators) || + (!!classThis && + !!(node.transformFlags & TransformFlags.ContainsLexicalThis)) || + (!!classThis && + !!classSuper && + !!(node.transformFlags & TransformFlags.ContainsLexicalSuper)) + ); } function visitor(node: Node): VisitResult { @@ -424,13 +475,18 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc case SyntaxKind.Constructor: case SyntaxKind.PropertyDeclaration: case SyntaxKind.ClassStaticBlockDeclaration: - return Debug.fail("Not supported outside of a class. Use 'classElementVisitor' instead."); + return Debug.fail( + "Not supported outside of a class. Use 'classElementVisitor' instead.", + ); case SyntaxKind.Parameter: return visitParameterDeclaration(node as ParameterDeclaration); // Support NamedEvaluation to ensure the correct class name for class expressions. case SyntaxKind.BinaryExpression: - return visitBinaryExpression(node as BinaryExpression, /*discarded*/ false); + return visitBinaryExpression( + node as BinaryExpression, + /*discarded*/ false, + ); case SyntaxKind.PropertyAssignment: return visitPropertyAssignment(node as PropertyAssignment); case SyntaxKind.VariableDeclaration: @@ -446,22 +502,40 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc case SyntaxKind.ExpressionStatement: return visitExpressionStatement(node as ExpressionStatement); case SyntaxKind.CommaListExpression: - return visitCommaListExpression(node as CommaListExpression, /*discarded*/ false); + return visitCommaListExpression( + node as CommaListExpression, + /*discarded*/ false, + ); case SyntaxKind.ParenthesizedExpression: - return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false); + return visitParenthesizedExpression( + node as ParenthesizedExpression, + /*discarded*/ false, + ); case SyntaxKind.PartiallyEmittedExpression: - return visitPartiallyEmittedExpression(node as PartiallyEmittedExpression, /*discarded*/ false); + return visitPartiallyEmittedExpression( + node as PartiallyEmittedExpression, + /*discarded*/ false, + ); case SyntaxKind.CallExpression: return visitCallExpression(node as CallExpression); case SyntaxKind.TaggedTemplateExpression: - return visitTaggedTemplateExpression(node as TaggedTemplateExpression); + return visitTaggedTemplateExpression( + node as TaggedTemplateExpression, + ); case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.PostfixUnaryExpression: - return visitPreOrPostfixUnaryExpression(node as PrefixUnaryExpression | PostfixUnaryExpression, /*discarded*/ false); + return visitPreOrPostfixUnaryExpression( + node as PrefixUnaryExpression | PostfixUnaryExpression, + /*discarded*/ false, + ); case SyntaxKind.PropertyAccessExpression: - return visitPropertyAccessExpression(node as PropertyAccessExpression); + return visitPropertyAccessExpression( + node as PropertyAccessExpression, + ); case SyntaxKind.ElementAccessExpression: - return visitElementAccessExpression(node as ElementAccessExpression); + return visitElementAccessExpression( + node as ElementAccessExpression, + ); case SyntaxKind.ComputedPropertyName: return visitComputedPropertyName(node as ComputedPropertyName); @@ -490,7 +564,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } } - function modifierVisitor(node: ModifierLike): VisitResult { + function modifierVisitor( + node: ModifierLike, + ): VisitResult { switch (node.kind) { case SyntaxKind.Decorator: // elided, will be emitted as part of `visitClassDeclaration` return undefined; @@ -502,17 +578,25 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc function classElementVisitor(node: Node) { switch (node.kind) { case SyntaxKind.Constructor: - return visitConstructorDeclaration(node as ConstructorDeclaration); + return visitConstructorDeclaration( + node as ConstructorDeclaration, + ); case SyntaxKind.MethodDeclaration: return visitMethodDeclaration(node as MethodDeclaration); case SyntaxKind.GetAccessor: - return visitGetAccessorDeclaration(node as GetAccessorDeclaration); + return visitGetAccessorDeclaration( + node as GetAccessorDeclaration, + ); case SyntaxKind.SetAccessor: - return visitSetAccessorDeclaration(node as SetAccessorDeclaration); + return visitSetAccessorDeclaration( + node as SetAccessorDeclaration, + ); case SyntaxKind.PropertyDeclaration: return visitPropertyDeclaration(node as PropertyDeclaration); case SyntaxKind.ClassStaticBlockDeclaration: - return visitClassStaticBlockDeclaration(node as ClassStaticBlockDeclaration); + return visitClassStaticBlockDeclaration( + node as ClassStaticBlockDeclaration, + ); default: return visitor(node); } @@ -522,23 +606,46 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc switch (node.kind) { case SyntaxKind.PrefixUnaryExpression: case SyntaxKind.PostfixUnaryExpression: - return visitPreOrPostfixUnaryExpression(node as PrefixUnaryExpression | PostfixUnaryExpression, /*discarded*/ true); + return visitPreOrPostfixUnaryExpression( + node as PrefixUnaryExpression | PostfixUnaryExpression, + /*discarded*/ true, + ); case SyntaxKind.BinaryExpression: - return visitBinaryExpression(node as BinaryExpression, /*discarded*/ true); + return visitBinaryExpression( + node as BinaryExpression, + /*discarded*/ true, + ); case SyntaxKind.CommaListExpression: - return visitCommaListExpression(node as CommaListExpression, /*discarded*/ true); + return visitCommaListExpression( + node as CommaListExpression, + /*discarded*/ true, + ); case SyntaxKind.ParenthesizedExpression: - return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ true); + return visitParenthesizedExpression( + node as ParenthesizedExpression, + /*discarded*/ true, + ); default: return visitor(node); } } function getHelperVariableName(node: ClassLikeDeclaration | ClassElement) { - let declarationName = node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name) : - node.name && isPrivateIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name).slice(1) : - node.name && isStringLiteral(node.name) && isIdentifierText(node.name.text, ScriptTarget.ESNext) ? node.name.text : - isClassLike(node) ? "class" : "member"; + let declarationName = node.name && + isIdentifier(node.name) && + !isGeneratedIdentifier(node.name) + ? idText(node.name) + : node.name && + isPrivateIdentifier(node.name) && + !isGeneratedIdentifier(node.name) + ? idText(node.name).slice(1) + : node.name && + isStringLiteral(node.name) && + isIdentifierText(node.name.text, ScriptTarget.ESNext) + ? node.name.text + : isClassLike(node) + ? "class" + : "member"; if (isGetAccessor(node)) declarationName = `get_${declarationName}`; if (isSetAccessor(node)) declarationName = `set_${declarationName}`; if (node.name && isPrivateIdentifier(node.name)) declarationName = `private_${declarationName}`; @@ -546,26 +653,40 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc return "_" + declarationName; } - function createHelperVariable(node: ClassLikeDeclaration | ClassElement, suffix: string) { - return factory.createUniqueName(`${getHelperVariableName(node)}_${suffix}`, GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.ReservedInNestedScopes); + function createHelperVariable( + node: ClassLikeDeclaration | ClassElement, + suffix: string, + ) { + return factory.createUniqueName( + `${getHelperVariableName(node)}_${suffix}`, + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.ReservedInNestedScopes, + ); } function createLet(name: Identifier, initializer?: Expression) { return factory.createVariableStatement( /*modifiers*/ undefined, - factory.createVariableDeclarationList([ - factory.createVariableDeclaration( - name, - /*exclamationToken*/ undefined, - /*type*/ undefined, - initializer, - ), - ], NodeFlags.Let), + factory.createVariableDeclarationList( + [ + factory.createVariableDeclaration( + name, + /*exclamationToken*/ undefined, + /*type*/ undefined, + initializer, + ), + ], + NodeFlags.Let, + ), ); } function createClassInfo(node: ClassLikeDeclaration): ClassInfo { - const metadataReference = factory.createUniqueName("_metadata", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + const metadataReference = factory.createUniqueName( + "_metadata", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ); let instanceExtraInitializersName: Identifier | undefined; let staticExtraInitializersName: Identifier | undefined; let hasStaticInitializers = false; @@ -576,12 +697,27 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // as we descend. for (const member of node.members) { - if (isNamedClassElement(member) && nodeOrChildIsDecorated(/*useLegacyDecorators*/ false, member, node)) { + if ( + isNamedClassElement(member) && + nodeOrChildIsDecorated( + /*useLegacyDecorators*/ false, + member, + node, + ) + ) { if (hasStaticModifier(member)) { - staticExtraInitializersName ??= factory.createUniqueName("_staticExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + staticExtraInitializersName ??= factory.createUniqueName( + "_staticExtraInitializers", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ); } else { - instanceExtraInitializersName ??= factory.createUniqueName("_instanceExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + instanceExtraInitializersName ??= factory.createUniqueName( + "_instanceExtraInitializers", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ); } } if (isClassStaticBlockDeclaration(member)) { @@ -598,7 +734,11 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } } - if ((isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)) { + if ( + (isPrivateIdentifierClassElementDeclaration(member) || + isAutoAccessorPropertyDeclaration(member)) && + hasStaticModifier(member) + ) { hasStaticPrivateClassElements = true; } @@ -630,11 +770,26 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // When a class has class decorators we end up transforming it into a statement that would otherwise give it an // assigned name. If the class doesn't have an assigned name, we'll give it an assigned name of `""`) - if (!classHasDeclaredOrExplicitlyAssignedName(node) && classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, node)) { - node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, factory.createStringLiteral("")); + if ( + !classHasDeclaredOrExplicitlyAssignedName(node) && + classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ false, + node, + ) + ) { + node = injectClassNamedEvaluationHelperBlockIfMissing( + context, + node, + factory.createStringLiteral(""), + ); } - const classReference = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false, /*ignoreAssignedName*/ true); + const classReference = factory.getLocalName( + node, + /*allowComments*/ false, + /*allowSourceMaps*/ false, + /*ignoreAssignedName*/ true, + ); const classInfo = createClassInfo(node); const classDefinitionStatements: Statement[] = []; let leadingBlockStatements: Statement[] | undefined; @@ -644,7 +799,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc let shouldTransformPrivateStaticElementsInClass = false; // 1. Class decorators are evaluated outside of the private name scope of the class. - const classDecorators = transformAllDecoratorsOfDeclaration(getAllDecoratorsOfClass(node)); + const classDecorators = transformAllDecoratorsOfDeclaration( + getAllDecoratorsOfClass(node), + ); if (classDecorators) { // - Since class decorators don't have privileged access to private names defined inside the class, // they must be evaluated outside of the class body. @@ -652,22 +809,48 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // of the mutated class. // - Since a class decorator can add extra initializers, we must define a variable to keep track of // extra initializers. - classInfo.classDecoratorsName = factory.createUniqueName("_classDecorators", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); - classInfo.classDescriptorName = factory.createUniqueName("_classDescriptor", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); - classInfo.classExtraInitializersName = factory.createUniqueName("_classExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + classInfo.classDecoratorsName = factory.createUniqueName( + "_classDecorators", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ); + classInfo.classDescriptorName = factory.createUniqueName( + "_classDescriptor", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ); + classInfo.classExtraInitializersName = factory.createUniqueName( + "_classExtraInitializers", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ); // We do not mark _classThis as FileLevel if it may be reused by class private fields, which requires the // ability access the captured `_classThis` of outer scopes. - const needsUniqueClassThis = some(node.members, member => (isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)); + const needsUniqueClassThis = some( + node.members, + member => + (isPrivateIdentifierClassElementDeclaration(member) || + isAutoAccessorPropertyDeclaration(member)) && + hasStaticModifier(member), + ); classInfo.classThis = factory.createUniqueName( "_classThis", - needsUniqueClassThis ? - GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.ReservedInNestedScopes : - GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel, + needsUniqueClassThis + ? GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.ReservedInNestedScopes + : GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, ); classDefinitionStatements.push( - createLet(classInfo.classDecoratorsName, factory.createArrayLiteralExpression(classDecorators)), + createLet( + classInfo.classDecoratorsName, + factory.createArrayLiteralExpression(classDecorators), + ), createLet(classInfo.classDescriptorName), - createLet(classInfo.classExtraInitializersName, factory.createArrayLiteralExpression()), + createLet( + classInfo.classExtraInitializersName, + factory.createArrayLiteralExpression(), + ), createLet(classInfo.classThis), ); @@ -678,23 +861,43 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } // Rewrite `super` in static initializers so that we can use the correct `this`. - const extendsClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); + const extendsClause = getHeritageClause( + node.heritageClauses, + SyntaxKind.ExtendsKeyword, + ); const extendsElement = extendsClause && firstOrUndefined(extendsClause.types); - const extendsExpression = extendsElement && visitNode(extendsElement.expression, visitor, isExpression); + const extendsExpression = extendsElement && + visitNode(extendsElement.expression, visitor, isExpression); if (extendsExpression) { - classInfo.classSuper = factory.createUniqueName("_classSuper", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + classInfo.classSuper = factory.createUniqueName( + "_classSuper", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + ); // Ensure we do not give the class or function an assigned name due to the variable by prefixing it // with `0, `. const unwrapped = skipOuterExpressions(extendsExpression); - const safeExtendsExpression = isClassExpression(unwrapped) && !unwrapped.name || - isFunctionExpression(unwrapped) && !unwrapped.name || - isArrowFunction(unwrapped) ? - factory.createComma(factory.createNumericLiteral(0), extendsExpression) : - extendsExpression; - classDefinitionStatements.push(createLet(classInfo.classSuper, safeExtendsExpression)); - const updatedExtendsElement = factory.updateExpressionWithTypeArguments(extendsElement, classInfo.classSuper, /*typeArguments*/ undefined); - const updatedExtendsClause = factory.updateHeritageClause(extendsClause, [updatedExtendsElement]); + const safeExtendsExpression = (isClassExpression(unwrapped) && !unwrapped.name) || + (isFunctionExpression(unwrapped) && !unwrapped.name) || + isArrowFunction(unwrapped) + ? factory.createComma( + factory.createNumericLiteral(0), + extendsExpression, + ) + : extendsExpression; + classDefinitionStatements.push( + createLet(classInfo.classSuper, safeExtendsExpression), + ); + const updatedExtendsElement = factory.updateExpressionWithTypeArguments( + extendsElement, + classInfo.classSuper, + /*typeArguments*/ undefined, + ); + const updatedExtendsClause = factory.updateHeritageClause( + extendsClause, + [updatedExtendsElement], + ); heritageClauses = factory.createNodeArray([updatedExtendsClause]); } @@ -716,9 +919,16 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // NOTE: If there are no constructors, but there are instance initializers, a synthetic constructor is added. enterClass(classInfo); - leadingBlockStatements = append(leadingBlockStatements, createMetadata(classInfo.metadataReference, classInfo.classSuper)); + leadingBlockStatements = append( + leadingBlockStatements, + createMetadata(classInfo.metadataReference, classInfo.classSuper), + ); - let members = visitNodes(node.members, classElementVisitor, isClassElement); + let members = visitNodes( + node.members, + classElementVisitor, + isClassElement, + ); if (pendingExpressions) { let outerThis: Identifier | undefined; for (let expression of pendingExpressions) { @@ -726,61 +936,113 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // container and transform it in the expression. This ensures we use the correct `this` in the resulting // class `static` block. We don't use substitution here because the size of the tree we are visiting // is likely to be small and doesn't justify the complexity of introducing substitution. - expression = visitNode(expression, function thisVisitor(node: Node): Node { - if (!(node.transformFlags & TransformFlags.ContainsLexicalThis)) { - return node; - } - - switch (node.kind) { - case SyntaxKind.ThisKeyword: - if (!outerThis) { - outerThis = factory.createUniqueName("_outerThis", GeneratedIdentifierFlags.Optimistic); - classDefinitionStatements.unshift(createLet(outerThis, factory.createThis())); - } - return outerThis; + expression = visitNode( + expression, + function thisVisitor(node: Node): Node { + if ( + !( + node.transformFlags & + TransformFlags.ContainsLexicalThis + ) + ) { + return node; + } - default: - return visitEachChild(node, thisVisitor, context); - } - }, isExpression); + switch (node.kind) { + case SyntaxKind.ThisKeyword: + if (!outerThis) { + outerThis = factory.createUniqueName( + "_outerThis", + GeneratedIdentifierFlags.Optimistic, + ); + classDefinitionStatements.unshift( + createLet( + outerThis, + factory.createThis(), + ), + ); + } + return outerThis; + + default: + return visitEachChild( + node, + thisVisitor, + context, + ); + } + }, + isExpression, + ); const statement = factory.createExpressionStatement(expression); - leadingBlockStatements = append(leadingBlockStatements, statement); + leadingBlockStatements = append( + leadingBlockStatements, + statement, + ); } pendingExpressions = undefined; } exitClass(); - if (classInfo.instanceExtraInitializersName && !getFirstConstructorWithBody(node)) { + if ( + classInfo.instanceExtraInitializersName && + !getFirstConstructorWithBody(node) + ) { const initializerStatements = prepareConstructor(node, classInfo); if (initializerStatements) { const extendsClauseElement = getEffectiveBaseTypeNode(node); - const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword); + const isDerivedClass = !!( + extendsClauseElement && + skipOuterExpressions(extendsClauseElement.expression) + .kind !== SyntaxKind.NullKeyword + ); const constructorStatements: Statement[] = []; if (isDerivedClass) { - const spreadArguments = factory.createSpreadElement(factory.createIdentifier("arguments")); - const superCall = factory.createCallExpression(factory.createSuper(), /*typeArguments*/ undefined, [spreadArguments]); - constructorStatements.push(factory.createExpressionStatement(superCall)); + const spreadArguments = factory.createSpreadElement( + factory.createIdentifier("arguments"), + ); + const superCall = factory.createCallExpression( + factory.createSuper(), + /*typeArguments*/ undefined, + [spreadArguments], + ); + constructorStatements.push( + factory.createExpressionStatement(superCall), + ); } addRange(constructorStatements, initializerStatements); - const constructorBody = factory.createBlock(constructorStatements, /*multiLine*/ true); - syntheticConstructor = factory.createConstructorDeclaration(/*modifiers*/ undefined, [], constructorBody); + const constructorBody = factory.createBlock( + constructorStatements, + /*multiLine*/ true, + ); + syntheticConstructor = factory.createConstructorDeclaration( + /*modifiers*/ undefined, + [], + constructorBody, + ); } } // Used in steps 5, 7, and 11 if (classInfo.staticExtraInitializersName) { classDefinitionStatements.push( - createLet(classInfo.staticExtraInitializersName, factory.createArrayLiteralExpression()), + createLet( + classInfo.staticExtraInitializersName, + factory.createArrayLiteralExpression(), + ), ); } // Used in steps 6, 8, and during construction if (classInfo.instanceExtraInitializersName) { classDefinitionStatements.push( - createLet(classInfo.instanceExtraInitializersName, factory.createArrayLiteralExpression()), + createLet( + classInfo.instanceExtraInitializersName, + factory.createArrayLiteralExpression(), + ), ); } @@ -788,12 +1050,21 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc if (classInfo.memberInfos) { forEachEntry(classInfo.memberInfos, (memberInfo, member) => { if (isStatic(member)) { - classDefinitionStatements.push(createLet(memberInfo.memberDecoratorsName)); + classDefinitionStatements.push( + createLet(memberInfo.memberDecoratorsName), + ); if (memberInfo.memberInitializersName) { - classDefinitionStatements.push(createLet(memberInfo.memberInitializersName, factory.createArrayLiteralExpression())); + classDefinitionStatements.push( + createLet( + memberInfo.memberInitializersName, + factory.createArrayLiteralExpression(), + ), + ); } if (memberInfo.memberDescriptorName) { - classDefinitionStatements.push(createLet(memberInfo.memberDescriptorName)); + classDefinitionStatements.push( + createLet(memberInfo.memberDescriptorName), + ); } } }); @@ -803,83 +1074,162 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc if (classInfo.memberInfos) { forEachEntry(classInfo.memberInfos, (memberInfo, member) => { if (!isStatic(member)) { - classDefinitionStatements.push(createLet(memberInfo.memberDecoratorsName)); + classDefinitionStatements.push( + createLet(memberInfo.memberDecoratorsName), + ); if (memberInfo.memberInitializersName) { - classDefinitionStatements.push(createLet(memberInfo.memberInitializersName, factory.createArrayLiteralExpression())); + classDefinitionStatements.push( + createLet( + memberInfo.memberInitializersName, + factory.createArrayLiteralExpression(), + ), + ); } if (memberInfo.memberDescriptorName) { - classDefinitionStatements.push(createLet(memberInfo.memberDescriptorName)); + classDefinitionStatements.push( + createLet(memberInfo.memberDescriptorName), + ); } } }); } // 5. Static non-field element decorators are applied - leadingBlockStatements = addRange(leadingBlockStatements, classInfo.staticNonFieldDecorationStatements); + leadingBlockStatements = addRange( + leadingBlockStatements, + classInfo.staticNonFieldDecorationStatements, + ); // 6. Non-static non-field element decorators are applied - leadingBlockStatements = addRange(leadingBlockStatements, classInfo.nonStaticNonFieldDecorationStatements); + leadingBlockStatements = addRange( + leadingBlockStatements, + classInfo.nonStaticNonFieldDecorationStatements, + ); // 7. Static field element decorators are applied - leadingBlockStatements = addRange(leadingBlockStatements, classInfo.staticFieldDecorationStatements); + leadingBlockStatements = addRange( + leadingBlockStatements, + classInfo.staticFieldDecorationStatements, + ); // 8. Non-static field element decorators are applied - leadingBlockStatements = addRange(leadingBlockStatements, classInfo.nonStaticFieldDecorationStatements); + leadingBlockStatements = addRange( + leadingBlockStatements, + classInfo.nonStaticFieldDecorationStatements, + ); // 9. Class decorators are applied // 10. Class binding is initialized - if (classInfo.classDescriptorName && classInfo.classDecoratorsName && classInfo.classExtraInitializersName && classInfo.classThis) { + if ( + classInfo.classDescriptorName && + classInfo.classDecoratorsName && + classInfo.classExtraInitializersName && + classInfo.classThis + ) { leadingBlockStatements ??= []; // produces: // __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name, metadata }, _classExtraInitializers); - const valueProperty = factory.createPropertyAssignment("value", renamedClassThis); - const classDescriptor = factory.createObjectLiteralExpression([valueProperty]); - const classDescriptorAssignment = factory.createAssignment(classInfo.classDescriptorName, classDescriptor); - const classNameReference = factory.createPropertyAccessExpression(renamedClassThis, "name"); + const valueProperty = factory.createPropertyAssignment( + "value", + renamedClassThis, + ); + const classDescriptor = factory.createObjectLiteralExpression([ + valueProperty, + ]); + const classDescriptorAssignment = factory.createAssignment( + classInfo.classDescriptorName, + classDescriptor, + ); + const classNameReference = factory.createPropertyAccessExpression( + renamedClassThis, + "name", + ); const esDecorateHelper = emitHelpers().createESDecorateHelper( factory.createNull(), classDescriptorAssignment, classInfo.classDecoratorsName, - { kind: "class", name: classNameReference, metadata: classInfo.metadataReference }, + { + kind: "class", + name: classNameReference, + metadata: classInfo.metadataReference, + }, factory.createNull(), classInfo.classExtraInitializersName, ); const esDecorateStatement = factory.createExpressionStatement(esDecorateHelper); - setSourceMapRange(esDecorateStatement, moveRangePastDecorators(node)); + setSourceMapRange( + esDecorateStatement, + moveRangePastDecorators(node), + ); leadingBlockStatements.push(esDecorateStatement); // produces: // C = _classThis = _classDescriptor.value; - const classDescriptorValueReference = factory.createPropertyAccessExpression(classInfo.classDescriptorName, "value"); - const classThisAssignment = factory.createAssignment(classInfo.classThis, classDescriptorValueReference); - const classReferenceAssignment = factory.createAssignment(classReference, classThisAssignment); - leadingBlockStatements.push(factory.createExpressionStatement(classReferenceAssignment)); + const classDescriptorValueReference = factory.createPropertyAccessExpression( + classInfo.classDescriptorName, + "value", + ); + const classThisAssignment = factory.createAssignment( + classInfo.classThis, + classDescriptorValueReference, + ); + const classReferenceAssignment = factory.createAssignment( + classReference, + classThisAssignment, + ); + leadingBlockStatements.push( + factory.createExpressionStatement(classReferenceAssignment), + ); } // if (metadata) Object.defineProperty(C, Symbol.metadata, { configurable: true, writable: true, value: metadata }); - leadingBlockStatements.push(createSymbolMetadata(renamedClassThis, classInfo.metadataReference)); + leadingBlockStatements.push( + createSymbolMetadata(renamedClassThis, classInfo.metadataReference), + ); // 11. Static extra initializers are evaluated if (classInfo.staticExtraInitializersName) { - const runStaticInitializersHelper = emitHelpers().createRunInitializersHelper(renamedClassThis, classInfo.staticExtraInitializersName); + const runStaticInitializersHelper = emitHelpers().createRunInitializersHelper( + renamedClassThis, + classInfo.staticExtraInitializersName, + ); const runStaticInitializersStatement = factory.createExpressionStatement(runStaticInitializersHelper); - setSourceMapRange(runStaticInitializersStatement, node.name ?? moveRangePastDecorators(node)); - leadingBlockStatements = append(leadingBlockStatements, runStaticInitializersStatement); + setSourceMapRange( + runStaticInitializersStatement, + node.name ?? moveRangePastDecorators(node), + ); + leadingBlockStatements = append( + leadingBlockStatements, + runStaticInitializersStatement, + ); } // 12. Static fields are initialized and static blocks are evaluated // 13. Class extra initializers are evaluated if (classInfo.classExtraInitializersName) { - const runClassInitializersHelper = emitHelpers().createRunInitializersHelper(renamedClassThis, classInfo.classExtraInitializersName); + const runClassInitializersHelper = emitHelpers().createRunInitializersHelper( + renamedClassThis, + classInfo.classExtraInitializersName, + ); const runClassInitializersStatement = factory.createExpressionStatement(runClassInitializersHelper); - setSourceMapRange(runClassInitializersStatement, node.name ?? moveRangePastDecorators(node)); - trailingBlockStatements = append(trailingBlockStatements, runClassInitializersStatement); + setSourceMapRange( + runClassInitializersStatement, + node.name ?? moveRangePastDecorators(node), + ); + trailingBlockStatements = append( + trailingBlockStatements, + runClassInitializersStatement, + ); } // If there are no other static initializers to run, combine the leading and trailing block statements - if (leadingBlockStatements && trailingBlockStatements && !classInfo.hasStaticInitializers) { + if ( + leadingBlockStatements && + trailingBlockStatements && + !classInfo.hasStaticInitializers + ) { addRange(leadingBlockStatements, trailingBlockStatements); trailingBlockStatements = undefined; } @@ -892,13 +1242,18 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // ... // } const leadingStaticBlock = leadingBlockStatements && - factory.createClassStaticBlockDeclaration(factory.createBlock(leadingBlockStatements, /*multiLine*/ true)); + factory.createClassStaticBlockDeclaration( + factory.createBlock(leadingBlockStatements, /*multiLine*/ true), + ); if (leadingStaticBlock && shouldTransformPrivateStaticElementsInClass) { // We use `InternalEmitFlags.TransformPrivateStaticElements` as a marker on a class static block // to inform the classFields transform that it shouldn't rename `this` to `_classThis` in the // transformed class static block. - setInternalEmitFlags(leadingStaticBlock, InternalEmitFlags.TransformPrivateStaticElements); + setInternalEmitFlags( + leadingStaticBlock, + InternalEmitFlags.TransformPrivateStaticElements, + ); } // prepare a trailing `static {}` block, if necessary @@ -909,20 +1264,33 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // static { ... } // } const trailingStaticBlock = trailingBlockStatements && - factory.createClassStaticBlockDeclaration(factory.createBlock(trailingBlockStatements, /*multiLine*/ true)); + factory.createClassStaticBlockDeclaration( + factory.createBlock(trailingBlockStatements, /*multiLine*/ true), + ); if (leadingStaticBlock || syntheticConstructor || trailingStaticBlock) { const newMembers: ClassElement[] = []; // add the NamedEvaluation helper block, if needed - const existingNamedEvaluationHelperBlockIndex = members.findIndex(isClassNamedEvaluationHelperBlock); + const existingNamedEvaluationHelperBlockIndex = members.findIndex( + isClassNamedEvaluationHelperBlock, + ); // add the leading `static {}` block if (leadingStaticBlock) { // add the `static {}` block after any existing NamedEvaluation helper block, if one exists. - addRange(newMembers, members, 0, existingNamedEvaluationHelperBlockIndex + 1); + addRange( + newMembers, + members, + 0, + existingNamedEvaluationHelperBlockIndex + 1, + ); newMembers.push(leadingStaticBlock); - addRange(newMembers, members, existingNamedEvaluationHelperBlockIndex + 1); + addRange( + newMembers, + members, + existingNamedEvaluationHelperBlockIndex + 1, + ); } else { addRange(newMembers, members); @@ -938,7 +1306,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc newMembers.push(trailingStaticBlock); } - members = setTextRange(factory.createNodeArray(newMembers), members); + members = setTextRange( + factory.createNodeArray(newMembers), + members, + ); } const lexicalEnvironment = endLexicalEnvironment(); @@ -967,70 +1338,143 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // return C; // })(); - classExpression = factory.createClassExpression(/*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, heritageClauses, members); + classExpression = factory.createClassExpression( + /*modifiers*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + heritageClauses, + members, + ); if (classInfo.classThis) { - classExpression = injectClassThisAssignmentIfMissing(factory, classExpression, classInfo.classThis); + classExpression = injectClassThisAssignmentIfMissing( + factory, + classExpression, + classInfo.classThis, + ); } - const classReferenceDeclaration = factory.createVariableDeclaration(classReference, /*exclamationToken*/ undefined, /*type*/ undefined, classExpression); - const classReferenceVarDeclList = factory.createVariableDeclarationList([classReferenceDeclaration]); - const returnExpr = classInfo.classThis ? factory.createAssignment(classReference, classInfo.classThis) : classReference; + const classReferenceDeclaration = factory.createVariableDeclaration( + classReference, + /*exclamationToken*/ undefined, + /*type*/ undefined, + classExpression, + ); + const classReferenceVarDeclList = factory.createVariableDeclarationList([ + classReferenceDeclaration, + ]); + const returnExpr = classInfo.classThis + ? factory.createAssignment(classReference, classInfo.classThis) + : classReference; classDefinitionStatements.push( - factory.createVariableStatement(/*modifiers*/ undefined, classReferenceVarDeclList), + factory.createVariableStatement( + /*modifiers*/ undefined, + classReferenceVarDeclList, + ), factory.createReturnStatement(returnExpr), ); } else { // produces: // return ; - classExpression = factory.createClassExpression(/*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, heritageClauses, members); - classDefinitionStatements.push(factory.createReturnStatement(classExpression)); + classExpression = factory.createClassExpression( + /*modifiers*/ undefined, + node.name, + /*typeParameters*/ undefined, + heritageClauses, + members, + ); + classDefinitionStatements.push( + factory.createReturnStatement(classExpression), + ); } if (shouldTransformPrivateStaticElementsInClass) { - addInternalEmitFlags(classExpression, InternalEmitFlags.TransformPrivateStaticElements); + addInternalEmitFlags( + classExpression, + InternalEmitFlags.TransformPrivateStaticElements, + ); for (const member of classExpression.members) { - if ((isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)) { - addInternalEmitFlags(member, InternalEmitFlags.TransformPrivateStaticElements); + if ( + (isPrivateIdentifierClassElementDeclaration(member) || + isAutoAccessorPropertyDeclaration(member)) && + hasStaticModifier(member) + ) { + addInternalEmitFlags( + member, + InternalEmitFlags.TransformPrivateStaticElements, + ); } } } setOriginalNode(classExpression, node); - return factory.createImmediatelyInvokedArrowFunction(factory.mergeLexicalEnvironment(classDefinitionStatements, lexicalEnvironment)); + return factory.createImmediatelyInvokedArrowFunction( + factory.mergeLexicalEnvironment( + classDefinitionStatements, + lexicalEnvironment, + ), + ); } function isDecoratedClassLike(node: ClassLikeDeclaration) { - return classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, node) || - childIsDecorated(/*useLegacyDecorators*/ false, node); + return ( + classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ false, + node, + ) || childIsDecorated(/*useLegacyDecorators*/ false, node) + ); } - function visitClassDeclaration(node: ClassDeclaration): VisitResult { + function visitClassDeclaration( + node: ClassDeclaration, + ): VisitResult { if (isDecoratedClassLike(node)) { const statements: Statement[] = []; const originalClass = getOriginalNode(node, isClassLike) ?? node; - const className = originalClass.name ? factory.createStringLiteralFromNode(originalClass.name) : factory.createStringLiteral("default"); + const className = originalClass.name + ? factory.createStringLiteralFromNode(originalClass.name) + : factory.createStringLiteral("default"); const isExport = hasSyntacticModifier(node, ModifierFlags.Export); const isDefault = hasSyntacticModifier(node, ModifierFlags.Default); if (!node.name) { - node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, className); + node = injectClassNamedEvaluationHelperBlockIfMissing( + context, + node, + className, + ); } if (isExport && isDefault) { const iife = transformClassLike(node); if (node.name) { // let C = (() => { ... })(); // export default C; - const varDecl = factory.createVariableDeclaration(factory.getLocalName(node), /*exclamationToken*/ undefined, /*type*/ undefined, iife); + const varDecl = factory.createVariableDeclaration( + factory.getLocalName(node), + /*exclamationToken*/ undefined, + /*type*/ undefined, + iife, + ); setOriginalNode(varDecl, node); - const varDecls = factory.createVariableDeclarationList([varDecl], NodeFlags.Let); - const varStatement = factory.createVariableStatement(/*modifiers*/ undefined, varDecls); + const varDecls = factory.createVariableDeclarationList( + [varDecl], + NodeFlags.Let, + ); + const varStatement = factory.createVariableStatement( + /*modifiers*/ undefined, + varDecls, + ); statements.push(varStatement); - const exportStatement = factory.createExportDefault(factory.getDeclarationName(node)); + const exportStatement = factory.createExportDefault( + factory.getDeclarationName(node), + ); setOriginalNode(exportStatement, node); setCommentRange(exportStatement, getCommentRange(node)); - setSourceMapRange(exportStatement, moveRangePastDecorators(node)); + setSourceMapRange( + exportStatement, + moveRangePastDecorators(node), + ); statements.push(exportStatement); } else { @@ -1038,22 +1482,52 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc const exportStatement = factory.createExportDefault(iife); setOriginalNode(exportStatement, node); setCommentRange(exportStatement, getCommentRange(node)); - setSourceMapRange(exportStatement, moveRangePastDecorators(node)); + setSourceMapRange( + exportStatement, + moveRangePastDecorators(node), + ); statements.push(exportStatement); } } else { // let C = (() => { ... })(); - Debug.assertIsDefined(node.name, "A class declaration that is not a default export must have a name."); + Debug.assertIsDefined( + node.name, + "A class declaration that is not a default export must have a name.", + ); const iife = transformClassLike(node); - const modifierVisitorNoExport = isExport ? ((node: ModifierLike) => isExportModifier(node) ? undefined : modifierVisitor(node)) : modifierVisitor; - const modifiers = visitNodes(node.modifiers, modifierVisitorNoExport, isModifier); - const declName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); - const varDecl = factory.createVariableDeclaration(declName, /*exclamationToken*/ undefined, /*type*/ undefined, iife); + const modifierVisitorNoExport = isExport + ? (node: ModifierLike) => + isExportModifier(node) + ? undefined + : modifierVisitor(node) + : modifierVisitor; + const modifiers = visitNodes( + node.modifiers, + modifierVisitorNoExport, + isModifier, + ); + const declName = factory.getLocalName( + node, + /*allowComments*/ false, + /*allowSourceMaps*/ true, + ); + const varDecl = factory.createVariableDeclaration( + declName, + /*exclamationToken*/ undefined, + /*type*/ undefined, + iife, + ); setOriginalNode(varDecl, node); - const varDecls = factory.createVariableDeclarationList([varDecl], NodeFlags.Let); - const varStatement = factory.createVariableStatement(modifiers, varDecls); + const varDecls = factory.createVariableDeclarationList( + [varDecl], + NodeFlags.Let, + ); + const varStatement = factory.createVariableStatement( + modifiers, + varDecls, + ); setOriginalNode(varStatement, node); setCommentRange(varStatement, getCommentRange(node)); statements.push(varStatement); @@ -1067,12 +1541,31 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc return singleOrMany(statements); } else { - const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); - const heritageClauses = visitNodes(node.heritageClauses, visitor, isHeritageClause); + const modifiers = visitNodes( + node.modifiers, + modifierVisitor, + isModifier, + ); + const heritageClauses = visitNodes( + node.heritageClauses, + visitor, + isHeritageClause, + ); enterClass(/*classInfo*/ undefined); - const members = visitNodes(node.members, classElementVisitor, isClassElement); + const members = visitNodes( + node.members, + classElementVisitor, + isClassElement, + ); exitClass(); - return factory.updateClassDeclaration(node, modifiers, node.name, /*typeParameters*/ undefined, heritageClauses, members); + return factory.updateClassDeclaration( + node, + modifiers, + node.name, + /*typeParameters*/ undefined, + heritageClauses, + members, + ); } } @@ -1083,21 +1576,46 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc return iife; } else { - const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); - const heritageClauses = visitNodes(node.heritageClauses, visitor, isHeritageClause); + const modifiers = visitNodes( + node.modifiers, + modifierVisitor, + isModifier, + ); + const heritageClauses = visitNodes( + node.heritageClauses, + visitor, + isHeritageClause, + ); enterClass(/*classInfo*/ undefined); - const members = visitNodes(node.members, classElementVisitor, isClassElement); + const members = visitNodes( + node.members, + classElementVisitor, + isClassElement, + ); exitClass(); - return factory.updateClassExpression(node, modifiers, node.name, /*typeParameters*/ undefined, heritageClauses, members); + return factory.updateClassExpression( + node, + modifiers, + node.name, + /*typeParameters*/ undefined, + heritageClauses, + members, + ); } } - function prepareConstructor(_parent: ClassLikeDeclaration, classInfo: ClassInfo) { + function prepareConstructor( + _parent: ClassLikeDeclaration, + classInfo: ClassInfo, + ) { // Decorated instance members can add "extra" initializers to the instance. If a class contains any instance // fields, we'll inject the `__runInitializers()` call for these extra initializers into the initializer of // the first class member that will be initialized. However, if the class does not contain any fields that // we can piggyback on, we need to synthesize a `__runInitializers()` call in the constructor instead. - if (classInfo.instanceExtraInitializersName && !classInfo.hasNonAmbientInstanceFields) { + if ( + classInfo.instanceExtraInitializersName && + !classInfo.hasNonAmbientInstanceFields + ) { // If there are instance extra initializers we need to add them to the body along with any // field initializers const statements: Statement[] = []; @@ -1115,10 +1633,26 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } } - function transformConstructorBodyWorker(statementsOut: Statement[], statementsIn: NodeArray, statementOffset: number, superPath: readonly number[], superPathDepth: number, initializerStatements: readonly Statement[]) { + function transformConstructorBodyWorker( + statementsOut: Statement[], + statementsIn: NodeArray, + statementOffset: number, + superPath: readonly number[], + superPathDepth: number, + initializerStatements: readonly Statement[], + ) { const superStatementIndex = superPath[superPathDepth]; const superStatement = statementsIn[superStatementIndex]; - addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); + addRange( + statementsOut, + visitNodes( + statementsIn, + visitor, + isStatement, + statementOffset, + superStatementIndex - statementOffset, + ), + ); if (isTryStatement(superStatement)) { const tryBlockStatements: Statement[] = []; @@ -1132,41 +1666,95 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc ); const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); - setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); + setTextRange( + tryBlockStatementsArray, + superStatement.tryBlock.statements, + ); - statementsOut.push(factory.updateTryStatement( - superStatement, - factory.updateBlock(superStatement.tryBlock, tryBlockStatements), - visitNode(superStatement.catchClause, visitor, isCatchClause), - visitNode(superStatement.finallyBlock, visitor, isBlock), - )); + statementsOut.push( + factory.updateTryStatement( + superStatement, + factory.updateBlock( + superStatement.tryBlock, + tryBlockStatements, + ), + visitNode( + superStatement.catchClause, + visitor, + isCatchClause, + ), + visitNode(superStatement.finallyBlock, visitor, isBlock), + ), + ); } else { - addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex, 1)); + addRange( + statementsOut, + visitNodes( + statementsIn, + visitor, + isStatement, + superStatementIndex, + 1, + ), + ); addRange(statementsOut, initializerStatements); } - addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex + 1)); + addRange( + statementsOut, + visitNodes( + statementsIn, + visitor, + isStatement, + superStatementIndex + 1, + ), + ); } function visitConstructorDeclaration(node: ConstructorDeclaration) { enterClassElement(node); - const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); + const modifiers = visitNodes( + node.modifiers, + modifierVisitor, + isModifier, + ); const parameters = visitNodes(node.parameters, visitor, isParameter); let body: Block | undefined; if (node.body && classInfo) { // If there are instance extra initializers we need to add them to the body along with any // field initializers - const initializerStatements = prepareConstructor(classInfo.class, classInfo); + const initializerStatements = prepareConstructor( + classInfo.class, + classInfo, + ); if (initializerStatements) { const statements: Statement[] = []; - const nonPrologueStart = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor); - const superStatementIndices = findSuperStatementIndexPath(node.body.statements, nonPrologueStart); + const nonPrologueStart = factory.copyPrologue( + node.body.statements, + statements, + /*ensureUseStrict*/ false, + visitor, + ); + const superStatementIndices = findSuperStatementIndexPath( + node.body.statements, + nonPrologueStart, + ); if (superStatementIndices.length > 0) { - transformConstructorBodyWorker(statements, node.body.statements, nonPrologueStart, superStatementIndices, 0, initializerStatements); + transformConstructorBodyWorker( + statements, + node.body.statements, + nonPrologueStart, + superStatementIndices, + 0, + initializerStatements, + ); } else { addRange(statements, initializerStatements); - addRange(statements, visitNodes(node.body.statements, visitor, isStatement)); + addRange( + statements, + visitNodes(node.body.statements, visitor, isStatement), + ); } body = factory.createBlock(statements, /*multiLine*/ true); setOriginalNode(body, node.body); @@ -1176,7 +1764,12 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc body ??= visitNode(node.body, visitor, isBlock); exitClassElement(); - return factory.updateConstructorDeclaration(node, modifiers, parameters, body); + return factory.updateConstructorDeclaration( + node, + modifiers, + parameters, + body, + ); } function finishClassElement(updated: ClassElement, original: ClassElement) { @@ -1190,11 +1783,18 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } function partialTransformClassElement< - TNode extends MethodDeclaration | PropertyDeclaration | GetAccessorDeclaration | SetAccessorDeclaration, + TNode extends + | MethodDeclaration + | PropertyDeclaration + | GetAccessorDeclaration + | SetAccessorDeclaration, >( member: TNode, classInfo: ClassInfo | undefined, - createDescriptor?: (node: TNode & { readonly name: PrivateIdentifier; }, modifiers: ModifiersArray | undefined) => Expression, + createDescriptor?: ( + node: TNode & { readonly name: PrivateIdentifier; }, + modifiers: ModifiersArray | undefined, + ) => Expression, ) { let referencedName: Expression | undefined; let name: PropertyName | undefined; @@ -1202,23 +1802,50 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc let thisArg: Identifier | undefined; let descriptorName: Identifier | undefined; if (!classInfo) { - const modifiers = visitNodes(member.modifiers, modifierVisitor, isModifier); + const modifiers = visitNodes( + member.modifiers, + modifierVisitor, + isModifier, + ); enterName(); name = visitPropertyName(member.name); exitName(); - return { modifiers, referencedName, name, initializersName, descriptorName, thisArg }; + return { + modifiers, + referencedName, + name, + initializersName, + descriptorName, + thisArg, + }; } // Member decorators require privileged access to private names. However, computed property // evaluation occurs interspersed with decorator evaluation. This means that if we encounter // a computed property name we must inline decorator evaluation. - const memberDecorators = transformAllDecoratorsOfDeclaration(getAllDecoratorsOfClassElement(member, classInfo.class, /*useLegacyDecorators*/ false)); - const modifiers = visitNodes(member.modifiers, modifierVisitor, isModifier); + const memberDecorators = transformAllDecoratorsOfDeclaration( + getAllDecoratorsOfClassElement( + member, + classInfo.class, + /*useLegacyDecorators*/ false, + ), + ); + const modifiers = visitNodes( + member.modifiers, + modifierVisitor, + isModifier, + ); if (memberDecorators) { - const memberDecoratorsName = createHelperVariable(member, "decorators"); + const memberDecoratorsName = createHelperVariable( + member, + "decorators", + ); const memberDecoratorsArray = factory.createArrayLiteralExpression(memberDecorators); - const memberDecoratorsAssignment = factory.createAssignment(memberDecoratorsName, memberDecoratorsArray); + const memberDecoratorsAssignment = factory.createAssignment( + memberDecoratorsName, + memberDecoratorsArray, + ); const memberInfo: MemberInfo = { memberDecoratorsName }; classInfo.memberInfos ??= new Map(); classInfo.memberInfos.set(member, memberInfo); @@ -1229,38 +1856,56 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // 6. Non-static non-field (method/getter/setter/auto-accessor) element decorators are applied // 7. Static field (excl. auto-accessor) element decorators are applied // 8. Non-static field (excl. auto-accessor) element decorators are applied - const statements = isMethodOrAccessor(member) || isAutoAccessorPropertyDeclaration(member) ? - isStatic(member) ? - classInfo.staticNonFieldDecorationStatements ??= [] : - classInfo.nonStaticNonFieldDecorationStatements ??= [] : - isPropertyDeclaration(member) && !isAutoAccessorPropertyDeclaration(member) ? - isStatic(member) ? - classInfo.staticFieldDecorationStatements ??= [] : - classInfo.nonStaticFieldDecorationStatements ??= [] : - Debug.fail(); - - const kind = isGetAccessorDeclaration(member) ? "getter" : - isSetAccessorDeclaration(member) ? "setter" : - isMethodDeclaration(member) ? "method" : - isAutoAccessorPropertyDeclaration(member) ? "accessor" : - isPropertyDeclaration(member) ? "field" : - Debug.fail(); + const statements = isMethodOrAccessor(member) || + isAutoAccessorPropertyDeclaration(member) + ? isStatic(member) + ? (classInfo.staticNonFieldDecorationStatements ??= []) + : (classInfo.nonStaticNonFieldDecorationStatements ??= []) + : isPropertyDeclaration(member) && + !isAutoAccessorPropertyDeclaration(member) + ? isStatic(member) + ? (classInfo.staticFieldDecorationStatements ??= []) + : (classInfo.nonStaticFieldDecorationStatements ??= []) + : Debug.fail(); + + const kind = isGetAccessorDeclaration(member) + ? "getter" + : isSetAccessorDeclaration(member) + ? "setter" + : isMethodDeclaration(member) + ? "method" + : isAutoAccessorPropertyDeclaration(member) + ? "accessor" + : isPropertyDeclaration(member) + ? "field" + : Debug.fail(); let propertyName: ESDecorateName; if (isIdentifier(member.name) || isPrivateIdentifier(member.name)) { propertyName = { computed: false, name: member.name }; } else if (isPropertyNameLiteral(member.name)) { - propertyName = { computed: true, name: factory.createStringLiteralFromNode(member.name) }; + propertyName = { + computed: true, + name: factory.createStringLiteralFromNode(member.name), + }; } else { const expression = member.name.expression; - if (isPropertyNameLiteral(expression) && !isIdentifier(expression)) { - propertyName = { computed: true, name: factory.createStringLiteralFromNode(expression) }; + if ( + isPropertyNameLiteral(expression) && + !isIdentifier(expression) + ) { + propertyName = { + computed: true, + name: factory.createStringLiteralFromNode(expression), + }; } else { enterName(); - ({ referencedName, name } = visitReferencedPropertyName(member.name)); + ({ referencedName, name } = visitReferencedPropertyName( + member.name, + )); propertyName = { computed: true, name: referencedName }; exitName(); } @@ -1274,16 +1919,27 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc access: { // 15.7.3 CreateDecoratorAccessObject (kind, name) // 2. If _kind_ is ~field~, ~method~, ~accessor~, or ~getter~, then ... - get: isPropertyDeclaration(member) || isGetAccessorDeclaration(member) || isMethodDeclaration(member), + get: isPropertyDeclaration(member) || + isGetAccessorDeclaration(member) || + isMethodDeclaration(member), // 3. If _kind_ is ~field~, ~accessor~, or ~setter~, then ... - set: isPropertyDeclaration(member) || isSetAccessorDeclaration(member), + set: isPropertyDeclaration(member) || + isSetAccessorDeclaration(member), }, metadata: classInfo.metadataReference, }; - const extraInitializers = isStatic(member) ? - classInfo.staticExtraInitializersName ??= factory.createUniqueName("_staticExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel) : - classInfo.instanceExtraInitializersName ??= factory.createUniqueName("_instanceExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + const extraInitializers = isStatic(member) + ? (classInfo.staticExtraInitializersName ??= factory.createUniqueName( + "_staticExtraInitializers", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + )) + : (classInfo.instanceExtraInitializersName ??= factory.createUniqueName( + "_instanceExtraInitializers", + GeneratedIdentifierFlags.Optimistic | + GeneratedIdentifierFlags.FileLevel, + )); if (isMethodOrAccessor(member)) { // __esDecorate(this, null, _static_member_decorators, { kind: "method", name: "...", static: true, private: false, access: { ... } }, _staticExtraInitializers); @@ -1301,15 +1957,40 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // __esDecorate(this, _member_descriptor = { set() { ... } }, _member_decorators, { kind: "setter", name: "...", static: false, private: true, access: { ... } }, _instanceExtraInitializers); let descriptor: Expression | undefined; - if (isPrivateIdentifierClassElementDeclaration(member) && createDescriptor) { - descriptor = createDescriptor(member, visitNodes(modifiers, node => tryCast(node, isAsyncModifier), isModifier)); - memberInfo.memberDescriptorName = descriptorName = createHelperVariable(member, "descriptor"); - descriptor = factory.createAssignment(descriptorName, descriptor); + if ( + isPrivateIdentifierClassElementDeclaration(member) && + createDescriptor + ) { + descriptor = createDescriptor( + member, + visitNodes( + modifiers, + node => tryCast(node, isAsyncModifier), + isModifier, + ), + ); + memberInfo.memberDescriptorName = + descriptorName = + createHelperVariable(member, "descriptor"); + descriptor = factory.createAssignment( + descriptorName, + descriptor, + ); } - const esDecorateExpression = emitHelpers().createESDecorateHelper(factory.createThis(), descriptor ?? factory.createNull(), memberDecoratorsName, context, factory.createNull(), extraInitializers); + const esDecorateExpression = emitHelpers().createESDecorateHelper( + factory.createThis(), + descriptor ?? factory.createNull(), + memberDecoratorsName, + context, + factory.createNull(), + extraInitializers, + ); const esDecorateStatement = factory.createExpressionStatement(esDecorateExpression); - setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member)); + setSourceMapRange( + esDecorateStatement, + moveRangePastDecorators(member), + ); statements.push(esDecorateStatement); } else if (isPropertyDeclaration(member)) { @@ -1320,18 +2001,30 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } let descriptor: Expression | undefined; - if (isPrivateIdentifierClassElementDeclaration(member) && hasAccessorModifier(member) && createDescriptor) { - descriptor = createDescriptor(member, /*modifiers*/ undefined); - memberInfo.memberDescriptorName = descriptorName = createHelperVariable(member, "descriptor"); - descriptor = factory.createAssignment(descriptorName, descriptor); + if ( + isPrivateIdentifierClassElementDeclaration(member) && + hasAccessorModifier(member) && + createDescriptor + ) { + descriptor = createDescriptor( + member, + /*modifiers*/ undefined, + ); + memberInfo.memberDescriptorName = + descriptorName = + createHelperVariable(member, "descriptor"); + descriptor = factory.createAssignment( + descriptorName, + descriptor, + ); } // _static_field_initializers = __esDecorate(null, null, _static_member_decorators, { kind: "field", name: "...", static: true, private: ..., access: { ... } }, _staticExtraInitializers); // _field_initializers = __esDecorate(null, null, _member_decorators, { kind: "field", name: "...", static: false, private: ..., access: { ... } }, _instanceExtraInitializers); const esDecorateExpression = emitHelpers().createESDecorateHelper( - isAutoAccessorPropertyDeclaration(member) ? - factory.createThis() : - factory.createNull(), + isAutoAccessorPropertyDeclaration(member) + ? factory.createThis() + : factory.createNull(), descriptor ?? factory.createNull(), memberDecoratorsName, context, @@ -1339,7 +2032,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc extraInitializers, ); const esDecorateStatement = factory.createExpressionStatement(esDecorateExpression); - setSourceMapRange(esDecorateStatement, moveRangePastDecorators(member)); + setSourceMapRange( + esDecorateStatement, + moveRangePastDecorators(member), + ); statements.push(esDecorateStatement); } } @@ -1350,61 +2046,150 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc exitName(); } - if (!some(modifiers) && (isMethodDeclaration(member) || isPropertyDeclaration(member))) { + if ( + !some(modifiers) && + (isMethodDeclaration(member) || isPropertyDeclaration(member)) + ) { // Don't emit leading comments on the name for methods and properties without modifiers, otherwise we // will end up printing duplicate comments. setEmitFlags(name, EmitFlags.NoLeadingComments); } - return { modifiers, referencedName, name, initializersName, descriptorName, thisArg }; + return { + modifiers, + referencedName, + name, + initializersName, + descriptorName, + thisArg, + }; } function visitMethodDeclaration(node: MethodDeclaration) { enterClassElement(node); - const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createMethodDescriptorObject); + const { modifiers, name, descriptorName } = partialTransformClassElement( + node, + classInfo, + createMethodDescriptorObject, + ); if (descriptorName) { exitClassElement(); - return finishClassElement(createMethodDescriptorForwarder(modifiers, name, descriptorName), node); + return finishClassElement( + createMethodDescriptorForwarder( + modifiers, + name, + descriptorName, + ), + node, + ); } else { - const parameters = visitNodes(node.parameters, visitor, isParameter); + const parameters = visitNodes( + node.parameters, + visitor, + isParameter, + ); const body = visitNode(node.body, visitor, isBlock); exitClassElement(); - return finishClassElement(factory.updateMethodDeclaration(node, modifiers, node.asteriskToken, name, /*questionToken*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body), node); + return finishClassElement( + factory.updateMethodDeclaration( + node, + modifiers, + node.asteriskToken, + name, + /*questionToken*/ undefined, + /*typeParameters*/ undefined, + parameters, + /*type*/ undefined, + body, + ), + node, + ); } } function visitGetAccessorDeclaration(node: GetAccessorDeclaration) { enterClassElement(node); - const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createGetAccessorDescriptorObject); + const { modifiers, name, descriptorName } = partialTransformClassElement( + node, + classInfo, + createGetAccessorDescriptorObject, + ); if (descriptorName) { exitClassElement(); - return finishClassElement(createGetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); + return finishClassElement( + createGetAccessorDescriptorForwarder( + modifiers, + name, + descriptorName, + ), + node, + ); } else { - const parameters = visitNodes(node.parameters, visitor, isParameter); + const parameters = visitNodes( + node.parameters, + visitor, + isParameter, + ); const body = visitNode(node.body, visitor, isBlock); exitClassElement(); - return finishClassElement(factory.updateGetAccessorDeclaration(node, modifiers, name, parameters, /*type*/ undefined, body), node); + return finishClassElement( + factory.updateGetAccessorDeclaration( + node, + modifiers, + name, + parameters, + /*type*/ undefined, + body, + ), + node, + ); } } function visitSetAccessorDeclaration(node: SetAccessorDeclaration) { enterClassElement(node); - const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createSetAccessorDescriptorObject); + const { modifiers, name, descriptorName } = partialTransformClassElement( + node, + classInfo, + createSetAccessorDescriptorObject, + ); if (descriptorName) { exitClassElement(); - return finishClassElement(createSetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); + return finishClassElement( + createSetAccessorDescriptorForwarder( + modifiers, + name, + descriptorName, + ), + node, + ); } else { - const parameters = visitNodes(node.parameters, visitor, isParameter); + const parameters = visitNodes( + node.parameters, + visitor, + isParameter, + ); const body = visitNode(node.body, visitor, isBlock); exitClassElement(); - return finishClassElement(factory.updateSetAccessorDeclaration(node, modifiers, name, parameters, body), node); + return finishClassElement( + factory.updateSetAccessorDeclaration( + node, + modifiers, + name, + parameters, + body, + ), + node, + ); } } - function visitClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration) { + function visitClassStaticBlockDeclaration( + node: ClassStaticBlockDeclaration, + ) { enterClassElement(node); let result: ClassStaticBlockDeclaration; @@ -1428,7 +2213,11 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc function visitPropertyDeclaration(node: PropertyDeclaration) { if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + node = transformNamedEvaluation( + context, + node, + canIgnoreEmptyStringLiteralInAssignedName(node.initializer), + ); } enterClassElement(node); @@ -1436,7 +2225,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // TODO(rbuckton): We support decorating `declare x` fields with legacyDecorators, but we currently don't // support them with esDecorators. We need to consider whether we will support them in the // future, and how. For now, these should be elided by the `ts` transform. - Debug.assert(!isAmbientPropertyDeclaration(node), "Not yet implemented."); + Debug.assert( + !isAmbientPropertyDeclaration(node), + "Not yet implemented.", + ); // 10.2.1.3 RS: EvaluateBody // Initializer : `=` AssignmentExpression @@ -1445,7 +2237,13 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // a. Let _value_ be ? NamedEvaluation of |Initializer| with argument _functionObject_.[[ClassFieldInitializerName]]. // ... - const { modifiers, name, initializersName, descriptorName, thisArg } = partialTransformClassElement(node, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : undefined); + const { modifiers, name, initializersName, descriptorName, thisArg } = partialTransformClassElement( + node, + classInfo, + hasAccessorModifier(node) + ? createAccessorPropertyDescriptorObject + : undefined, + ); startLexicalEnvironment(); @@ -1458,17 +2256,23 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc ); } - if (!isStatic(node) && classInfo?.instanceExtraInitializersName && !classInfo?.hasInjectedInstanceInitializers) { + if ( + !isStatic(node) && + classInfo?.instanceExtraInitializersName && + !classInfo?.hasInjectedInstanceInitializers + ) { // for the first non-static field initializer, inject a call to `__runInitializers`. classInfo.hasInjectedInstanceInitializers = true; initializer ??= factory.createVoidZero(); - initializer = factory.createParenthesizedExpression(factory.createComma( - emitHelpers().createRunInitializersHelper( - factory.createThis(), - classInfo.instanceExtraInitializersName, + initializer = factory.createParenthesizedExpression( + factory.createComma( + emitHelpers().createRunInitializersHelper( + factory.createThis(), + classInfo.instanceExtraInitializersName, + ), + initializer, ), - initializer, - )); + ); } if (isStatic(node) && classInfo && initializer) { @@ -1506,37 +2310,75 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc const name = node.name; let getterName = name; let setterName = name; - if (isComputedPropertyName(name) && !isSimpleInlineableExpression(name.expression)) { + if ( + isComputedPropertyName(name) && + !isSimpleInlineableExpression(name.expression) + ) { const cacheAssignment = findComputedPropertyNameCacheAssignment(name); if (cacheAssignment) { - getterName = factory.updateComputedPropertyName(name, visitNode(name.expression, visitor, isExpression)); - setterName = factory.updateComputedPropertyName(name, cacheAssignment.left); + getterName = factory.updateComputedPropertyName( + name, + visitNode(name.expression, visitor, isExpression), + ); + setterName = factory.updateComputedPropertyName( + name, + cacheAssignment.left, + ); } else { - const temp = factory.createTempVariable(hoistVariableDeclaration); + const temp = factory.createTempVariable( + hoistVariableDeclaration, + ); setSourceMapRange(temp, name.expression); - const expression = visitNode(name.expression, visitor, isExpression); - const assignment = factory.createAssignment(temp, expression); + const expression = visitNode( + name.expression, + visitor, + isExpression, + ); + const assignment = factory.createAssignment( + temp, + expression, + ); setSourceMapRange(assignment, name.expression); - getterName = factory.updateComputedPropertyName(name, assignment); + getterName = factory.updateComputedPropertyName( + name, + assignment, + ); setterName = factory.updateComputedPropertyName(name, temp); } } - const modifiersWithoutAccessor = visitNodes(modifiers, node => node.kind !== SyntaxKind.AccessorKeyword ? node : undefined, isModifier); + const modifiersWithoutAccessor = visitNodes( + modifiers, + node => node.kind !== SyntaxKind.AccessorKeyword ? node : undefined, + isModifier, + ); - const backingField = createAccessorPropertyBackingField(factory, node, modifiersWithoutAccessor, initializer); + const backingField = createAccessorPropertyBackingField( + factory, + node, + modifiersWithoutAccessor, + initializer, + ); setOriginalNode(backingField, node); setEmitFlags(backingField, EmitFlags.NoComments); setSourceMapRange(backingField, sourceMapRange); setSourceMapRange(backingField.name, node.name); - const getter = createGetAccessorDescriptorForwarder(modifiersWithoutAccessor, getterName, descriptorName); + const getter = createGetAccessorDescriptorForwarder( + modifiersWithoutAccessor, + getterName, + descriptorName, + ); setOriginalNode(getter, node); setCommentRange(getter, commentRange); setSourceMapRange(getter, sourceMapRange); - const setter = createSetAccessorDescriptorForwarder(modifiersWithoutAccessor, setterName, descriptorName); + const setter = createSetAccessorDescriptorForwarder( + modifiersWithoutAccessor, + setterName, + descriptorName, + ); setOriginalNode(setter, node); setEmitFlags(setter, EmitFlags.NoComments); setSourceMapRange(setter, sourceMapRange); @@ -1544,7 +2386,17 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc return [backingField, getter, setter]; } - return finishClassElement(factory.updatePropertyDeclaration(node, modifiers, name, /*questionOrExclamationToken*/ undefined, /*type*/ undefined, initializer), node); + return finishClassElement( + factory.updatePropertyDeclaration( + node, + modifiers, + name, + /*questionOrExclamationToken*/ undefined, + /*type*/ undefined, + initializer, + ), + node, + ); } function visitThisExpression(node: ThisExpression) { @@ -1553,9 +2405,21 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc function visitCallExpression(node: CallExpression) { if (isSuperProperty(node.expression) && classThis) { - const expression = visitNode(node.expression, visitor, isExpression); - const argumentsList = visitNodes(node.arguments, visitor, isExpression); - const invocation = factory.createFunctionCallCall(expression, classThis, argumentsList); + const expression = visitNode( + node.expression, + visitor, + isExpression, + ); + const argumentsList = visitNodes( + node.arguments, + visitor, + isExpression, + ); + const invocation = factory.createFunctionCallCall( + expression, + classThis, + argumentsList, + ); setOriginalNode(invocation, node); setTextRange(invocation, node); return invocation; @@ -1570,17 +2434,35 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc const boundTag = factory.createFunctionBindCall(tag, classThis, []); setOriginalNode(boundTag, node); setTextRange(boundTag, node); - const template = visitNode(node.template, visitor, isTemplateLiteral); - return factory.updateTaggedTemplateExpression(node, boundTag, /*typeArguments*/ undefined, template); + const template = visitNode( + node.template, + visitor, + isTemplateLiteral, + ); + return factory.updateTaggedTemplateExpression( + node, + boundTag, + /*typeArguments*/ undefined, + template, + ); } return visitEachChild(node, visitor, context); } function visitPropertyAccessExpression(node: PropertyAccessExpression) { - if (isSuperProperty(node) && isIdentifier(node.name) && classThis && classSuper) { + if ( + isSuperProperty(node) && + isIdentifier(node.name) && + classThis && + classSuper + ) { const propertyName = factory.createStringLiteralFromNode(node.name); - const superProperty = factory.createReflectGetCall(classSuper, propertyName, classThis); + const superProperty = factory.createReflectGetCall( + classSuper, + propertyName, + classThis, + ); setOriginalNode(superProperty, node.expression); setTextRange(superProperty, node.expression); return superProperty; @@ -1591,8 +2473,16 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc function visitElementAccessExpression(node: ElementAccessExpression) { if (isSuperProperty(node) && classThis && classSuper) { - const propertyName = visitNode(node.argumentExpression, visitor, isExpression); - const superProperty = factory.createReflectGetCall(classSuper, propertyName, classThis); + const propertyName = visitNode( + node.argumentExpression, + visitor, + isExpression, + ); + const superProperty = factory.createReflectGetCall( + classSuper, + propertyName, + classThis, + ); setOriginalNode(superProperty, node.expression); setTextRange(superProperty, node.expression); return superProperty; @@ -1619,7 +2509,11 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // ... if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + node = transformNamedEvaluation( + context, + node, + canIgnoreEmptyStringLiteralInAssignedName(node.initializer), + ); } const updated = factory.updateParameterDeclaration( @@ -1643,24 +2537,41 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc return updated; } - function isAnonymousClassNeedingAssignedName(node: AnonymousFunctionDefinition) { - return isClassExpression(node) && !node.name && isDecoratedClassLike(node); + function isAnonymousClassNeedingAssignedName( + node: AnonymousFunctionDefinition, + ) { + return ( + isClassExpression(node) && !node.name && isDecoratedClassLike(node) + ); } - function canIgnoreEmptyStringLiteralInAssignedName(node: WrappedExpression) { + function canIgnoreEmptyStringLiteralInAssignedName( + node: WrappedExpression, + ) { // The IIFE produced for `(@dec class {})` will result in an assigned name of the form // `var class_1 = class { };`, and thus the empty string cannot be ignored. However, The IIFE // produced for `(class { @dec x; })` will not result in an assigned name since it // transforms to `return class { };`, and thus the empty string *can* be ignored. const innerExpression = skipOuterExpressions(node); - return isClassExpression(innerExpression) && !innerExpression.name && !classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, innerExpression); + return ( + isClassExpression(innerExpression) && + !innerExpression.name && + !classOrConstructorParameterIsDecorated( + /*useLegacyDecorators*/ false, + innerExpression, + ) + ); } function visitForStatement(node: ForStatement) { return factory.updateForStatement( node, - visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode( + node.initializer, + discardedValueVisitor, + isForInitializer, + ), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), visitIterationBody(node.statement, visitor, context), @@ -1675,7 +2586,12 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc if (isDestructuringAssignment(node)) { const left = visitAssignmentPattern(node.left); const right = visitNode(node.right, visitor, isExpression); - return factory.updateBinaryExpression(node, left, node.operatorToken, right); + return factory.updateBinaryExpression( + node, + left, + node.operatorToken, + right, + ); } if (isAssignmentExpression(node)) { @@ -1706,25 +2622,44 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // ... if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right)); + node = transformNamedEvaluation( + context, + node, + canIgnoreEmptyStringLiteralInAssignedName(node.right), + ); return visitEachChild(node, visitor, context); } if (isSuperProperty(node.left) && classThis && classSuper) { - let setterName = isElementAccessExpression(node.left) ? visitNode(node.left.argumentExpression, visitor, isExpression) : - isIdentifier(node.left.name) ? factory.createStringLiteralFromNode(node.left.name) : - undefined; + let setterName = isElementAccessExpression(node.left) + ? visitNode( + node.left.argumentExpression, + visitor, + isExpression, + ) + : isIdentifier(node.left.name) + ? factory.createStringLiteralFromNode(node.left.name) + : undefined; if (setterName) { // super.x = ... // super.x += ... // super[x] = ... // super[x] += ... - let expression = visitNode(node.right, visitor, isExpression); + let expression = visitNode( + node.right, + visitor, + isExpression, + ); if (isCompoundAssignment(node.operatorToken.kind)) { let getterName = setterName; if (!isSimpleInlineableExpression(setterName)) { - getterName = factory.createTempVariable(hoistVariableDeclaration); - setterName = factory.createAssignment(getterName, setterName); + getterName = factory.createTempVariable( + hoistVariableDeclaration, + ); + setterName = factory.createAssignment( + getterName, + setterName, + ); } const superPropertyGet = factory.createReflectGetCall( @@ -1737,13 +2672,17 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc expression = factory.createBinaryExpression( superPropertyGet, - getNonAssignmentOperatorForCompoundAssignment(node.operatorToken.kind), + getNonAssignmentOperatorForCompoundAssignment( + node.operatorToken.kind, + ), expression, ); setTextRange(expression, node); } - const temp = discarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); + const temp = discarded + ? undefined + : factory.createTempVariable(hoistVariableDeclaration); if (temp) { expression = factory.createAssignment(temp, expression); setTextRange(temp, node); @@ -1769,32 +2708,63 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc } if (node.operatorToken.kind === SyntaxKind.CommaToken) { - const left = visitNode(node.left, discardedValueVisitor, isExpression); - const right = visitNode(node.right, discarded ? discardedValueVisitor : visitor, isExpression); - return factory.updateBinaryExpression(node, left, node.operatorToken, right); + const left = visitNode( + node.left, + discardedValueVisitor, + isExpression, + ); + const right = visitNode( + node.right, + discarded ? discardedValueVisitor : visitor, + isExpression, + ); + return factory.updateBinaryExpression( + node, + left, + node.operatorToken, + right, + ); } return visitEachChild(node, visitor, context); } - function visitPreOrPostfixUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression, discarded: boolean) { + function visitPreOrPostfixUnaryExpression( + node: PrefixUnaryExpression | PostfixUnaryExpression, + discarded: boolean, + ) { if ( node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken ) { const operand = skipParentheses(node.operand); if (isSuperProperty(operand) && classThis && classSuper) { - let setterName = isElementAccessExpression(operand) ? visitNode(operand.argumentExpression, visitor, isExpression) : - isIdentifier(operand.name) ? factory.createStringLiteralFromNode(operand.name) : - undefined; + let setterName = isElementAccessExpression(operand) + ? visitNode( + operand.argumentExpression, + visitor, + isExpression, + ) + : isIdentifier(operand.name) + ? factory.createStringLiteralFromNode(operand.name) + : undefined; if (setterName) { let getterName = setterName; if (!isSimpleInlineableExpression(setterName)) { - getterName = factory.createTempVariable(hoistVariableDeclaration); - setterName = factory.createAssignment(getterName, setterName); + getterName = factory.createTempVariable( + hoistVariableDeclaration, + ); + setterName = factory.createAssignment( + getterName, + setterName, + ); } - let expression: Expression = factory.createReflectGetCall(classSuper, getterName, classThis); + let expression: Expression = factory.createReflectGetCall( + classSuper, + getterName, + classThis, + ); setOriginalNode(expression, node); setTextRange(expression, node); @@ -1819,9 +2789,22 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // When the result isn't discarded, we introduce a new temp variable (`_b`) to capture the // result of the operation so that we can provide it to `y` when the assignment is complete. - const temp = discarded ? undefined : factory.createTempVariable(hoistVariableDeclaration); - expression = expandPreOrPostfixIncrementOrDecrementExpression(factory, node, expression, hoistVariableDeclaration, temp); - expression = factory.createReflectSetCall(classSuper, setterName, expression, classThis); + const temp = discarded + ? undefined + : factory.createTempVariable(hoistVariableDeclaration); + expression = expandPreOrPostfixIncrementOrDecrementExpression( + factory, + node, + expression, + hoistVariableDeclaration, + temp, + ); + expression = factory.createReflectSetCall( + classSuper, + setterName, + expression, + classThis, + ); setOriginalNode(expression, node); setTextRange(expression, node); @@ -1838,10 +2821,17 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc return visitEachChild(node, visitor, context); } - function visitCommaListExpression(node: CommaListExpression, discarded: boolean) { - const elements = discarded ? - visitCommaListElements(node.elements, discardedValueVisitor) : - visitCommaListElements(node.elements, visitor, discardedValueVisitor); + function visitCommaListExpression( + node: CommaListExpression, + discarded: boolean, + ) { + const elements = discarded + ? visitCommaListElements(node.elements, discardedValueVisitor) + : visitCommaListElements( + node.elements, + visitor, + discardedValueVisitor, + ); return factory.updateCommaListExpression(node, elements); } @@ -1852,8 +2842,13 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc return { referencedName, name }; } - if (isPropertyNameLiteral(node.expression) && !isIdentifier(node.expression)) { - const referencedName = factory.createStringLiteralFromNode(node.expression); + if ( + isPropertyNameLiteral(node.expression) && + !isIdentifier(node.expression) + ) { + const referencedName = factory.createStringLiteralFromNode( + node.expression, + ); const name = visitNode(node, visitor, isPropertyName); return { referencedName, name }; } @@ -1861,9 +2856,14 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc const referencedName = factory.getGeneratedNameForNode(node); hoistVariableDeclaration(referencedName); - const key = emitHelpers().createPropKeyHelper(visitNode(node.expression, visitor, isExpression)); + const key = emitHelpers().createPropKeyHelper( + visitNode(node.expression, visitor, isExpression), + ); const assignment = factory.createAssignment(referencedName, key); - const name = factory.updateComputedPropertyName(node, injectPendingExpressions(assignment)); + const name = factory.updateComputedPropertyName( + node, + injectPendingExpressions(assignment), + ); return { referencedName, name }; } @@ -1891,7 +2891,11 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // ... if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + node = transformNamedEvaluation( + context, + node, + canIgnoreEmptyStringLiteralInAssignedName(node.initializer), + ); } return visitEachChild(node, visitor, context); @@ -1913,7 +2917,11 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // ... if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + node = transformNamedEvaluation( + context, + node, + canIgnoreEmptyStringLiteralInAssignedName(node.initializer), + ); } return visitEachChild(node, visitor, context); @@ -1937,23 +2945,33 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // ... if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + node = transformNamedEvaluation( + context, + node, + canIgnoreEmptyStringLiteralInAssignedName(node.initializer), + ); } return visitEachChild(node, visitor, context); } - function visitDestructuringAssignmentTarget(node: LeftHandSideExpression): Expression { + function visitDestructuringAssignmentTarget( + node: LeftHandSideExpression, + ): Expression { if (isObjectLiteralExpression(node) || isArrayLiteralExpression(node)) { return visitAssignmentPattern(node); } if (isSuperProperty(node) && classThis && classSuper) { - const propertyName = isElementAccessExpression(node) ? visitNode(node.argumentExpression, visitor, isExpression) : - isIdentifier(node.name) ? factory.createStringLiteralFromNode(node.name) : - undefined; + const propertyName = isElementAccessExpression(node) + ? visitNode(node.argumentExpression, visitor, isExpression) + : isIdentifier(node.name) + ? factory.createStringLiteralFromNode(node.name) + : undefined; if (propertyName) { - const paramName = factory.createTempVariable(/*recordTempVariable*/ undefined); + const paramName = factory.createTempVariable( + /*recordTempVariable*/ undefined, + ); const expression = factory.createAssignmentTargetWrapper( paramName, factory.createReflectSetCall( @@ -1972,7 +2990,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc return visitEachChild(node, visitor, context); } - function visitAssignmentElement(node: Exclude): ArrayAssignmentElement { + function visitAssignmentElement( + node: Exclude, + ): ArrayAssignmentElement { // 13.15.5.5 RS: IteratorDestructuringAssignmentEvaluation // AssignmentElement : DestructuringAssignmentTarget Initializer? // ... @@ -1983,21 +3003,36 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right)); + node = transformNamedEvaluation( + context, + node, + canIgnoreEmptyStringLiteralInAssignedName(node.right), + ); } - const assignmentTarget = visitDestructuringAssignmentTarget(node.left); + const assignmentTarget = visitDestructuringAssignmentTarget( + node.left, + ); const initializer = visitNode(node.right, visitor, isExpression); - return factory.updateBinaryExpression(node, assignmentTarget, node.operatorToken, initializer) as ArrayAssignmentElement; + return factory.updateBinaryExpression( + node, + assignmentTarget, + node.operatorToken, + initializer, + ) as ArrayAssignmentElement; } else { - return visitDestructuringAssignmentTarget(node) as ArrayAssignmentElement; + return visitDestructuringAssignmentTarget( + node, + ) as ArrayAssignmentElement; } } function visitAssignmentRestElement(node: SpreadElement) { if (isLeftHandSideExpression(node.expression)) { - const expression = visitDestructuringAssignmentTarget(node.expression); + const expression = visitDestructuringAssignmentTarget( + node.expression, + ); return factory.updateSpreadElement(node, expression); } @@ -2024,20 +3059,37 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // ... const name = visitNode(node.name, visitor, isPropertyName); - if (isAssignmentExpression(node.initializer, /*excludeCompoundAssignment*/ true)) { + if ( + isAssignmentExpression( + node.initializer, + /*excludeCompoundAssignment*/ true, + ) + ) { const assignmentElement = visitAssignmentElement(node.initializer); - return factory.updatePropertyAssignment(node, name, assignmentElement); + return factory.updatePropertyAssignment( + node, + name, + assignmentElement, + ); } if (isLeftHandSideExpression(node.initializer)) { - const assignmentElement = visitDestructuringAssignmentTarget(node.initializer); - return factory.updatePropertyAssignment(node, name, assignmentElement); + const assignmentElement = visitDestructuringAssignmentTarget( + node.initializer, + ); + return factory.updatePropertyAssignment( + node, + name, + assignmentElement, + ); } return visitEachChild(node, visitor, context); } - function visitShorthandAssignmentProperty(node: ShorthandPropertyAssignment) { + function visitShorthandAssignmentProperty( + node: ShorthandPropertyAssignment, + ) { // AssignmentProperty : IdentifierReference Initializer? // 13.15.5.3 RS: PropertyDestructuringAssignmentEvaluation @@ -2049,7 +3101,13 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // ... if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.objectAssignmentInitializer)); + node = transformNamedEvaluation( + context, + node, + canIgnoreEmptyStringLiteralInAssignedName( + node.objectAssignmentInitializer, + ), + ); } return visitEachChild(node, visitor, context); @@ -2057,7 +3115,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc function visitAssignmentRestProperty(node: SpreadAssignment) { if (isLeftHandSideExpression(node.expression)) { - const expression = visitDestructuringAssignmentTarget(node.expression); + const expression = visitDestructuringAssignmentTarget( + node.expression, + ); return factory.updateSpreadAssignment(node, expression); } @@ -2074,11 +3134,19 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc function visitAssignmentPattern(node: AssignmentPattern) { if (isArrayLiteralExpression(node)) { - const elements = visitNodes(node.elements, visitArrayAssignmentElement, isExpression); + const elements = visitNodes( + node.elements, + visitArrayAssignmentElement, + isExpression, + ); return factory.updateArrayLiteralExpression(node, elements); } else { - const properties = visitNodes(node.properties, visitObjectAssignmentElement, isObjectLiteralElementLike); + const properties = visitNodes( + node.properties, + visitObjectAssignmentElement, + isObjectLiteralElementLike, + ); return factory.updateObjectLiteralExpression(node, properties); } } @@ -2091,28 +3159,50 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc // ... if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { - node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.expression)); + node = transformNamedEvaluation( + context, + node, + canIgnoreEmptyStringLiteralInAssignedName(node.expression), + ); } return visitEachChild(node, visitor, context); } - function visitParenthesizedExpression(node: ParenthesizedExpression, discarded: boolean) { + function visitParenthesizedExpression( + node: ParenthesizedExpression, + discarded: boolean, + ) { // 8.4.5 RS: NamedEvaluation // ParenthesizedExpression : `(` Expression `)` // ... // 2. Return ? NamedEvaluation of |Expression| with argument _name_. - const visitorFunc: Visitor = discarded ? discardedValueVisitor : visitor; - const expression = visitNode(node.expression, visitorFunc, isExpression); + const visitorFunc: Visitor = discarded + ? discardedValueVisitor + : visitor; + const expression = visitNode( + node.expression, + visitorFunc, + isExpression, + ); return factory.updateParenthesizedExpression(node, expression); } - function visitPartiallyEmittedExpression(node: PartiallyEmittedExpression, discarded: boolean) { + function visitPartiallyEmittedExpression( + node: PartiallyEmittedExpression, + discarded: boolean, + ) { // Emulates 8.4.5 RS: NamedEvaluation - const visitorFunc: Visitor = discarded ? discardedValueVisitor : visitor; - const expression = visitNode(node.expression, visitorFunc, isExpression); + const visitorFunc: Visitor = discarded + ? discardedValueVisitor + : visitor; + const expression = visitNode( + node.expression, + visitorFunc, + isExpression, + ); return factory.updatePartiallyEmittedExpression(node, expression); } @@ -2120,7 +3210,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc if (some(pendingExpressions)) { if (isParenthesizedExpression(expression)) { pendingExpressions.push(expression.expression); - expression = factory.updateParenthesizedExpression(expression, factory.inlineExpressions(pendingExpressions)); + expression = factory.updateParenthesizedExpression( + expression, + factory.inlineExpressions(pendingExpressions), + ); } else { pendingExpressions.push(expression); @@ -2136,13 +3229,18 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc * * @param allDecorators An object containing all of the decorators for the declaration. */ - function transformAllDecoratorsOfDeclaration(allDecorators: AllDecorators | undefined) { + function transformAllDecoratorsOfDeclaration( + allDecorators: AllDecorators | undefined, + ) { if (!allDecorators) { return undefined; } const decoratorExpressions: Expression[] = []; - addRange(decoratorExpressions, map(allDecorators.decorators, transformDecorator)); + addRange( + decoratorExpressions, + map(allDecorators.decorators, transformDecorator), + ); return decoratorExpressions; } @@ -2152,14 +3250,26 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc * @param decorator The decorator node. */ function transformDecorator(decorator: Decorator) { - const expression = visitNode(decorator.expression, visitor, isExpression); + const expression = visitNode( + decorator.expression, + visitor, + isExpression, + ); setEmitFlags(expression, EmitFlags.NoComments); // preserve the 'this' binding for an access expression const innerExpression = skipOuterExpressions(expression); if (isAccessExpression(innerExpression)) { - const { target, thisArg } = factory.createCallBinding(expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true); - return factory.restoreOuterExpressions(expression, factory.createFunctionBindCall(target, thisArg, [])); + const { target, thisArg } = factory.createCallBinding( + expression, + hoistVariableDeclaration, + languageVersion, + /*cacheIdentifiers*/ true, + ); + return factory.restoreOuterExpressions( + expression, + factory.createFunctionBindCall(target, thisArg, []), + ); } return expression; } @@ -2167,7 +3277,15 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc /** * Creates a `value`, `get`, or `set` method for a pseudo-{@link PropertyDescriptor} object created for a private element. */ - function createDescriptorMethod(original: Node, name: PrivateIdentifier, modifiers: ModifiersArray | undefined, asteriskToken: AsteriskToken | undefined, kind: "value" | "get" | "set", parameters: readonly ParameterDeclaration[], body: Block | undefined) { + function createDescriptorMethod( + original: Node, + name: PrivateIdentifier, + modifiers: ModifiersArray | undefined, + asteriskToken: AsteriskToken | undefined, + kind: "value" | "get" | "set", + parameters: readonly ParameterDeclaration[], + body: Block | undefined, + ) { const func = factory.createFunctionExpression( modifiers, asteriskToken, @@ -2182,9 +3300,19 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc setEmitFlags(func, EmitFlags.NoComments); const prefix = kind === "get" || kind === "set" ? kind : undefined; - const functionName = factory.createStringLiteralFromNode(name, /*isSingleQuote*/ undefined); - const namedFunction = emitHelpers().createSetFunctionNameHelper(func, functionName, prefix); - const method = factory.createPropertyAssignment(factory.createIdentifier(kind), namedFunction); + const functionName = factory.createStringLiteralFromNode( + name, + /*isSingleQuote*/ undefined, + ); + const namedFunction = emitHelpers().createSetFunctionNameHelper( + func, + functionName, + prefix, + ); + const method = factory.createPropertyAssignment( + factory.createIdentifier(kind), + namedFunction, + ); setOriginalNode(method, original); setSourceMapRange(method, moveRangePastDecorators(original)); setEmitFlags(method, EmitFlags.NoComments); @@ -2194,7 +3322,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc /** * Creates a pseudo-{@link PropertyDescriptor} object used when decorating a private {@link MethodDeclaration}. */ - function createMethodDescriptorObject(node: PrivateIdentifierMethodDeclaration, modifiers: ModifiersArray | undefined) { + function createMethodDescriptorObject( + node: PrivateIdentifierMethodDeclaration, + modifiers: ModifiersArray | undefined, + ) { return factory.createObjectLiteralExpression([ createDescriptorMethod( node, @@ -2211,7 +3342,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc /** * Creates a pseudo-{@link PropertyDescriptor} object used when decorating a private {@link GetAccessorDeclaration}. */ - function createGetAccessorDescriptorObject(node: PrivateIdentifierGetAccessorDeclaration, modifiers: ModifiersArray | undefined) { + function createGetAccessorDescriptorObject( + node: PrivateIdentifierGetAccessorDeclaration, + modifiers: ModifiersArray | undefined, + ) { return factory.createObjectLiteralExpression([ createDescriptorMethod( node, @@ -2228,7 +3362,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc /** * Creates a pseudo-{@link PropertyDescriptor} object used when decorating a private {@link SetAccessorDeclaration}. */ - function createSetAccessorDescriptorObject(node: PrivateIdentifierSetAccessorDeclaration, modifiers: ModifiersArray | undefined) { + function createSetAccessorDescriptorObject( + node: PrivateIdentifierSetAccessorDeclaration, + modifiers: ModifiersArray | undefined, + ) { return factory.createObjectLiteralExpression([ createDescriptorMethod( node, @@ -2245,7 +3382,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc /** * Creates a pseudo-{@link PropertyDescriptor} object used when decorating an `accessor` {@link PropertyDeclaration} with a private name. */ - function createAccessorPropertyDescriptorObject(node: PrivateIdentifierPropertyDeclaration, modifiers: ModifiersArray | undefined) { + function createAccessorPropertyDescriptorObject( + node: PrivateIdentifierPropertyDeclaration, + modifiers: ModifiersArray | undefined, + ) { // { // get() { return this.${privateName}; }, // set(value) { this.${privateName} = value; }, @@ -2274,17 +3414,21 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc modifiers, /*asteriskToken*/ undefined, "set", - [factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - "value", - )], + [ + factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + "value", + ), + ], factory.createBlock([ factory.createExpressionStatement( factory.createAssignment( factory.createPropertyAccessExpression( factory.createThis(), - factory.getGeneratedPrivateNameForNode(node.name), + factory.getGeneratedPrivateNameForNode( + node.name, + ), ), factory.createIdentifier("value"), ), @@ -2300,9 +3444,17 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc * @param name The name for the resulting declaration. * @param descriptorName The name of the descriptor variable. */ - function createMethodDescriptorForwarder(modifiers: ModifiersArray | undefined, name: PropertyName, descriptorName: Identifier) { + function createMethodDescriptorForwarder( + modifiers: ModifiersArray | undefined, + name: PropertyName, + descriptorName: Identifier, + ) { // strip off all but the `static` modifier - modifiers = visitNodes(modifiers, node => isStaticModifier(node) ? node : undefined, isModifier); + modifiers = visitNodes( + modifiers, + node => (isStaticModifier(node) ? node : undefined), + isModifier, + ); return factory.createGetAccessorDeclaration( modifiers, name, @@ -2325,9 +3477,17 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc * @param name The name for the resulting declaration. * @param descriptorName The name of the descriptor variable. */ - function createGetAccessorDescriptorForwarder(modifiers: ModifiersArray | undefined, name: PropertyName, descriptorName: Identifier) { + function createGetAccessorDescriptorForwarder( + modifiers: ModifiersArray | undefined, + name: PropertyName, + descriptorName: Identifier, + ) { // strip off all but the `static` modifier - modifiers = visitNodes(modifiers, node => isStaticModifier(node) ? node : undefined, isModifier); + modifiers = visitNodes( + modifiers, + node => (isStaticModifier(node) ? node : undefined), + isModifier, + ); return factory.createGetAccessorDeclaration( modifiers, name, @@ -2354,17 +3514,27 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc * @param name The name for the resulting declaration. * @param descriptorName The name of the descriptor variable. */ - function createSetAccessorDescriptorForwarder(modifiers: ModifiersArray | undefined, name: PropertyName, descriptorName: Identifier) { + function createSetAccessorDescriptorForwarder( + modifiers: ModifiersArray | undefined, + name: PropertyName, + descriptorName: Identifier, + ) { // strip off all but the `static` modifier - modifiers = visitNodes(modifiers, node => isStaticModifier(node) ? node : undefined, isModifier); + modifiers = visitNodes( + modifiers, + node => (isStaticModifier(node) ? node : undefined), + isModifier, + ); return factory.createSetAccessorDeclaration( modifiers, name, - [factory.createParameterDeclaration( - /*modifiers*/ undefined, - /*dotDotDotToken*/ undefined, - "value", - )], + [ + factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + "value", + ), + ], factory.createBlock([ factory.createReturnStatement( factory.createFunctionCallCall( @@ -2379,37 +3549,68 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc ]), ); } - function createMetadata(name: Identifier, classSuper: Identifier | undefined) { + function createMetadata( + name: Identifier, + classSuper: Identifier | undefined, + ) { const varDecl = factory.createVariableDeclaration( name, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createConditionalExpression( factory.createLogicalAnd( - factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), - factory.createPropertyAccessExpression(factory.createIdentifier("Symbol"), "metadata"), + factory.createTypeCheck( + factory.createIdentifier("Symbol"), + "function", + ), + factory.createPropertyAccessExpression( + factory.createIdentifier("Symbol"), + "metadata", + ), ), factory.createToken(SyntaxKind.QuestionToken), factory.createCallExpression( - factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "create"), + factory.createPropertyAccessExpression( + factory.createIdentifier("Object"), + "create", + ), /*typeArguments*/ undefined, - [classSuper ? createSymbolMetadataReference(classSuper) : factory.createNull()], + [ + classSuper + ? createSymbolMetadataReference(classSuper) + : factory.createNull(), + ], ), factory.createToken(SyntaxKind.ColonToken), factory.createVoidZero(), ), ); - return factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([varDecl], NodeFlags.Const)); + return factory.createVariableStatement( + /*modifiers*/ undefined, + factory.createVariableDeclarationList([varDecl], NodeFlags.Const), + ); } - function createSymbolMetadata(target: Identifier | ThisExpression, value: Identifier) { + function createSymbolMetadata( + target: Identifier | ThisExpression, + value: Identifier, + ) { const defineProperty = factory.createObjectDefinePropertyCall( target, - factory.createPropertyAccessExpression(factory.createIdentifier("Symbol"), "metadata"), - factory.createPropertyDescriptor({ configurable: true, writable: true, enumerable: true, value }, /*singleLine*/ true), + factory.createPropertyAccessExpression( + factory.createIdentifier("Symbol"), + "metadata", + ), + factory.createPropertyDescriptor( + { configurable: true, writable: true, enumerable: true, value }, + /*singleLine*/ true, + ), ); return setEmitFlags( - factory.createIfStatement(value, factory.createExpressionStatement(defineProperty)), + factory.createIfStatement( + value, + factory.createExpressionStatement(defineProperty), + ), EmitFlags.SingleLine, ); } @@ -2418,7 +3619,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc return factory.createBinaryExpression( factory.createElementAccessExpression( classSuper, - factory.createPropertyAccessExpression(factory.createIdentifier("Symbol"), "metadata"), + factory.createPropertyAccessExpression( + factory.createIdentifier("Symbol"), + "metadata", + ), ), SyntaxKind.QuestionQuestionToken, factory.createNull(), diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index 775075a6e8f6f..061f3122e581c 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -56,6 +56,7 @@ import { lastOrUndefined, LeftHandSideExpression, LiteralExpression, + LiteralLikeNode, map, Mutable, NewExpression, @@ -64,7 +65,6 @@ import { NumericLiteral, ObjectLiteralElementLike, ObjectLiteralExpression, - PropertyAccessExpression, reduceLeft, ReturnStatement, setCommentRange, @@ -220,20 +220,25 @@ type Label = number; // dprint-ignore const enum OpCode { - Nop, // No operation, used to force a new case in the state machine - Statement, // A regular javascript statement - Assign, // An assignment - Break, // A break instruction used to jump to a label - BreakWhenTrue, // A break instruction used to jump to a label if a condition evaluates to true - BreakWhenFalse, // A break instruction used to jump to a label if a condition evaluates to false - Yield, // A completion instruction for the `yield` keyword - YieldStar, // A completion instruction for the `yield*` keyword (not implemented, but reserved for future use) - Return, // A completion instruction for the `return` keyword - Throw, // A completion instruction for the `throw` keyword - Endfinally, // Marks the end of a `finally` block + Nop, // No operation, used to force a new case in the state machine + Statement, // A regular javascript statement + Assign, // An assignment + Break, // A break instruction used to jump to a label + BreakWhenTrue, // A break instruction used to jump to a label if a condition evaluates to true + BreakWhenFalse, // A break instruction used to jump to a label if a condition evaluates to false + Yield, // A completion instruction for the `yield` keyword + YieldStar, // A completion instruction for the `yield*` keyword (not implemented, but reserved for future use) + Return, // A completion instruction for the `return` keyword + Throw, // A completion instruction for the `throw` keyword + Endfinally, // Marks the end of a `finally` block } -type OperationArguments = [Label] | [Label, Expression] | [Statement] | [Expression | undefined] | [Expression, Expression]; +type OperationArguments = + | [Label] + | [Label, Expression] + | [Statement] + | [Expression | undefined] + | [Expression, Expression]; // whether a generated code block is opening or closing at the current operation for a FunctionBuilder const enum BlockAction { @@ -259,7 +264,12 @@ const enum ExceptionBlockState { } // A generated code block -type CodeBlock = ExceptionBlock | LabeledBlock | SwitchBlock | LoopBlock | WithBlock; +type CodeBlock = + | ExceptionBlock + | LabeledBlock + | SwitchBlock + | LoopBlock + | WithBlock; // a generated exception block, used for 'try' statements interface ExceptionBlock { @@ -333,7 +343,9 @@ function getInstructionName(instruction: Instruction): string { } /** @internal */ -export function transformGenerators(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle { +export function transformGenerators( + context: TransformationContext, +): (x: SourceFile | Bundle) => SourceFile | Bundle { const { factory, getEmitHelperFactory: emitHelpers, @@ -370,7 +382,7 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // allocating objects to store the same information to avoid GC overhead. // let labelOffsets: number[] | undefined; // The operation offset at which the label is defined. - let labelExpressions: Mutable[][] | undefined; // The NumericLiteral nodes bound to each label. + let labelExpressions: Mutable[][] | undefined; // The NumericLiteral nodes bound to each label. let nextLabelId = 1; // The next label id to use. // Operations store information about generated code for the function body. This @@ -400,7 +412,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF return chainBundle(context, transformSourceFile); function transformSourceFile(node: SourceFile) { - if (node.isDeclarationFile || (node.transformFlags & TransformFlags.ContainsGenerator) === 0) { + if ( + node.isDeclarationFile || + (node.transformFlags & TransformFlags.ContainsGenerator) === 0 + ) { return node; } @@ -438,16 +453,18 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * * @param node The node to visit. */ - function visitJavaScriptInStatementContainingYield(node: Node): VisitResult { + function visitJavaScriptInStatementContainingYield( + node: Node, + ): VisitResult { switch (node.kind) { case SyntaxKind.DoStatement: - return visitDoStatement(node as DoStatement); + return visitDoStatement(node); case SyntaxKind.WhileStatement: - return visitWhileStatement(node as WhileStatement); + return visitWhileStatement(node); case SyntaxKind.SwitchStatement: - return visitSwitchStatement(node as SwitchStatement); + return visitSwitchStatement(node); case SyntaxKind.LabeledStatement: - return visitLabeledStatement(node as LabeledStatement); + return visitLabeledStatement(node); default: return visitJavaScriptInGeneratorFunctionBody(node); } @@ -458,32 +475,38 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * * @param node The node to visit. */ - function visitJavaScriptInGeneratorFunctionBody(node: Node): VisitResult { + function visitJavaScriptInGeneratorFunctionBody( + node: Node, + ): VisitResult { switch (node.kind) { case SyntaxKind.FunctionDeclaration: - return visitFunctionDeclaration(node as FunctionDeclaration); + return visitFunctionDeclaration(node); case SyntaxKind.FunctionExpression: - return visitFunctionExpression(node as FunctionExpression); + return visitFunctionExpression(node); case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: return visitAccessorDeclaration(node as AccessorDeclaration); case SyntaxKind.VariableStatement: - return visitVariableStatement(node as VariableStatement); + return visitVariableStatement(node); case SyntaxKind.ForStatement: - return visitForStatement(node as ForStatement); + return visitForStatement(node); case SyntaxKind.ForInStatement: - return visitForInStatement(node as ForInStatement); + return visitForInStatement(node); case SyntaxKind.BreakStatement: - return visitBreakStatement(node as BreakStatement); + return visitBreakStatement(node); case SyntaxKind.ContinueStatement: - return visitContinueStatement(node as ContinueStatement); + return visitContinueStatement(node); case SyntaxKind.ReturnStatement: - return visitReturnStatement(node as ReturnStatement); + return visitReturnStatement(node); default: if (node.transformFlags & TransformFlags.ContainsYield) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (TransformFlags.ContainsGenerator | TransformFlags.ContainsHoistedDeclarationOrCompletion)) { + else if ( + node.transformFlags & + (TransformFlags.ContainsGenerator | + TransformFlags.ContainsHoistedDeclarationOrCompletion) + ) { return visitEachChild(node, visitor, context); } else { @@ -500,23 +523,31 @@ export function transformGenerators(context: TransformationContext): (x: SourceF function visitJavaScriptContainingYield(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.BinaryExpression: - return visitBinaryExpression(node as BinaryExpression); + return visitBinaryExpression(node); case SyntaxKind.CommaListExpression: - return visitCommaListExpression(node as CommaListExpression); + return visitCommaListExpression(node); case SyntaxKind.ConditionalExpression: - return visitConditionalExpression(node as ConditionalExpression); + return visitConditionalExpression( + node, + ); case SyntaxKind.YieldExpression: - return visitYieldExpression(node as YieldExpression); + return visitYieldExpression(node); case SyntaxKind.ArrayLiteralExpression: - return visitArrayLiteralExpression(node as ArrayLiteralExpression); + return visitArrayLiteralExpression( + node, + ); case SyntaxKind.ObjectLiteralExpression: - return visitObjectLiteralExpression(node as ObjectLiteralExpression); + return visitObjectLiteralExpression( + node, + ); case SyntaxKind.ElementAccessExpression: - return visitElementAccessExpression(node as ElementAccessExpression); + return visitElementAccessExpression( + node, + ); case SyntaxKind.CallExpression: - return visitCallExpression(node as CallExpression); + return visitCallExpression(node); case SyntaxKind.NewExpression: - return visitNewExpression(node as NewExpression); + return visitNewExpression(node); default: return visitEachChild(node, visitor, context); } @@ -530,10 +561,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF function visitGenerator(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.FunctionDeclaration: - return visitFunctionDeclaration(node as FunctionDeclaration); + return visitFunctionDeclaration(node); case SyntaxKind.FunctionExpression: - return visitFunctionExpression(node as FunctionExpression); + return visitFunctionExpression(node); default: return Debug.failBadSyntaxKind(node); @@ -549,7 +580,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * * @param node The node to visit. */ - function visitFunctionDeclaration(node: FunctionDeclaration): Statement | undefined { + function visitFunctionDeclaration( + node: FunctionDeclaration, + ): Statement | undefined { // Currently, we only support generators that were originally async functions. if (node.asteriskToken) { node = setOriginalNode( @@ -689,12 +722,20 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // Build the generator resumeLexicalEnvironment(); - const statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor); + const statementOffset = factory.copyPrologue( + body.statements, + statements, + /*ensureUseStrict*/ false, + visitor, + ); transformAndEmitStatements(body.statements, statementOffset); const buildResult = build(); - insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); + insertStatementsAfterStandardPrologue( + statements, + endLexicalEnvironment(), + ); statements.push(factory.createReturnStatement(buildResult)); // Restore previous generator state @@ -712,7 +753,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF operationLocations = savedOperationLocations; state = savedState; - return setTextRange(factory.createBlock(statements, body.multiLine), body); + return setTextRange( + factory.createBlock(statements, body.multiLine), + body, + ); } /** @@ -723,7 +767,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * * @param node The node to visit. */ - function visitVariableStatement(node: VariableStatement): Statement | undefined { + function visitVariableStatement( + node: VariableStatement, + ): Statement | undefined { if (node.transformFlags & TransformFlags.ContainsYield) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; @@ -796,9 +842,18 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // _a.b = %sent%; target = factory.updatePropertyAccessExpression( - left as PropertyAccessExpression, - cacheExpression(Debug.checkDefined(visitNode((left as PropertyAccessExpression).expression, visitor, isLeftHandSideExpression))), - (left as PropertyAccessExpression).name, + left, + cacheExpression( + Debug.checkDefined( + visitNode( + left + .expression, + visitor, + isLeftHandSideExpression, + ), + ), + ), + left.name, ); break; @@ -814,11 +869,35 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // .mark resumeLabel // _a[_b] = %sent%; - target = factory.updateElementAccessExpression(left as ElementAccessExpression, cacheExpression(Debug.checkDefined(visitNode((left as ElementAccessExpression).expression, visitor, isLeftHandSideExpression))), cacheExpression(Debug.checkDefined(visitNode((left as ElementAccessExpression).argumentExpression, visitor, isExpression)))); + target = factory.updateElementAccessExpression( + left, + cacheExpression( + Debug.checkDefined( + visitNode( + left + .expression, + visitor, + isLeftHandSideExpression, + ), + ), + ), + cacheExpression( + Debug.checkDefined( + visitNode( + left + .argumentExpression, + visitor, + isExpression, + ), + ), + ), + ); break; default: - target = Debug.checkDefined(visitNode(left, visitor, isExpression)); + target = Debug.checkDefined( + visitNode(left, visitor, isExpression), + ); break; } @@ -830,8 +909,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF setTextRange( factory.createBinaryExpression( cacheExpression(target), - getNonAssignmentOperatorForCompoundAssignment(operator), - Debug.checkDefined(visitNode(right, visitor, isExpression)), + getNonAssignmentOperatorForCompoundAssignment( + operator, + ), + Debug.checkDefined( + visitNode(right, visitor, isExpression), + ), ), node, ), @@ -840,7 +923,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF ); } else { - return factory.updateBinaryExpression(node, target, node.operatorToken, Debug.checkDefined(visitNode(right, visitor, isExpression))); + return factory.updateBinaryExpression( + node, + target, + node.operatorToken, + Debug.checkDefined(visitNode(right, visitor, isExpression)), + ); } } @@ -865,7 +953,16 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // .yield resumeLabel // _a + %sent% + c() - return factory.updateBinaryExpression(node, cacheExpression(Debug.checkDefined(visitNode(node.left, visitor, isExpression))), node.operatorToken, Debug.checkDefined(visitNode(node.right, visitor, isExpression))); + return factory.updateBinaryExpression( + node, + cacheExpression( + Debug.checkDefined( + visitNode(node.left, visitor, isExpression), + ), + ), + node.operatorToken, + Debug.checkDefined(visitNode(node.right, visitor, isExpression)), + ); } return visitEachChild(node, visitor, context); @@ -892,17 +989,26 @@ export function transformGenerators(context: TransformationContext): (x: SourceF return factory.inlineExpressions(pendingExpressions); function visit(node: Expression) { - if (isBinaryExpression(node) && node.operatorToken.kind === SyntaxKind.CommaToken) { + if ( + isBinaryExpression(node) && + node.operatorToken.kind === SyntaxKind.CommaToken + ) { visit(node.left); visit(node.right); } else { if (containsYield(node) && pendingExpressions.length > 0) { - emitWorker(OpCode.Statement, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]); + emitWorker(OpCode.Statement, [ + factory.createExpressionStatement( + factory.inlineExpressions(pendingExpressions), + ), + ]); pendingExpressions = []; } - pendingExpressions.push(Debug.checkDefined(visitNode(node, visitor, isExpression))); + pendingExpressions.push( + Debug.checkDefined(visitNode(node, visitor, isExpression)), + ); } } } @@ -916,15 +1022,24 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // flattened version of `visitCommaExpression` let pendingExpressions: Expression[] = []; for (const elem of node.elements) { - if (isBinaryExpression(elem) && elem.operatorToken.kind === SyntaxKind.CommaToken) { + if ( + isBinaryExpression(elem) && + elem.operatorToken.kind === SyntaxKind.CommaToken + ) { pendingExpressions.push(visitCommaExpression(elem)); } else { if (containsYield(elem) && pendingExpressions.length > 0) { - emitWorker(OpCode.Statement, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]); + emitWorker(OpCode.Statement, [ + factory.createExpressionStatement( + factory.inlineExpressions(pendingExpressions), + ), + ]); pendingExpressions = []; } - pendingExpressions.push(Debug.checkDefined(visitNode(elem, visitor, isExpression))); + pendingExpressions.push( + Debug.checkDefined(visitNode(elem, visitor, isExpression)), + ); } } return factory.inlineExpressions(pendingExpressions); @@ -968,17 +1083,29 @@ export function transformGenerators(context: TransformationContext): (x: SourceF const resultLabel = defineLabel(); const resultLocal = declareLocal(); - emitAssignment(resultLocal, Debug.checkDefined(visitNode(node.left, visitor, isExpression)), /*location*/ node.left); + emitAssignment( + resultLocal, + Debug.checkDefined(visitNode(node.left, visitor, isExpression)), + /*location*/ node.left, + ); if (node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) { // Logical `&&` shortcuts when the left-hand operand is falsey. - emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left); + emitBreakWhenFalse( + resultLabel, + resultLocal, + /*location*/ node.left, + ); } else { // Logical `||` shortcuts when the left-hand operand is truthy. emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left); } - emitAssignment(resultLocal, Debug.checkDefined(visitNode(node.right, visitor, isExpression)), /*location*/ node.right); + emitAssignment( + resultLocal, + Debug.checkDefined(visitNode(node.right, visitor, isExpression)), + /*location*/ node.right, + ); markLabel(resultLabel); return resultLocal; } @@ -988,7 +1115,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * * @param node The node to visit. */ - function visitConditionalExpression(node: ConditionalExpression): Expression { + function visitConditionalExpression( + node: ConditionalExpression, + ): Expression { // [source] // x = a() ? yield : b(); // @@ -1011,11 +1140,29 @@ export function transformGenerators(context: TransformationContext): (x: SourceF const whenFalseLabel = defineLabel(); const resultLabel = defineLabel(); const resultLocal = declareLocal(); - emitBreakWhenFalse(whenFalseLabel, Debug.checkDefined(visitNode(node.condition, visitor, isExpression)), /*location*/ node.condition); - emitAssignment(resultLocal, Debug.checkDefined(visitNode(node.whenTrue, visitor, isExpression)), /*location*/ node.whenTrue); + emitBreakWhenFalse( + whenFalseLabel, + Debug.checkDefined( + visitNode(node.condition, visitor, isExpression), + ), + /*location*/ node.condition, + ); + emitAssignment( + resultLocal, + Debug.checkDefined( + visitNode(node.whenTrue, visitor, isExpression), + ), + /*location*/ node.whenTrue, + ); emitBreak(resultLabel); markLabel(whenFalseLabel); - emitAssignment(resultLocal, Debug.checkDefined(visitNode(node.whenFalse, visitor, isExpression)), /*location*/ node.whenFalse); + emitAssignment( + resultLocal, + Debug.checkDefined( + visitNode(node.whenFalse, visitor, isExpression), + ), + /*location*/ node.whenFalse, + ); markLabel(resultLabel); return resultLocal; } @@ -1028,7 +1175,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * * @param node The node to visit. */ - function visitYieldExpression(node: YieldExpression): LeftHandSideExpression { + function visitYieldExpression( + node: YieldExpression, + ): LeftHandSideExpression { // [source] // x = yield a(); // @@ -1042,7 +1191,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF if (node.asteriskToken) { // NOTE: `expression` must be defined for `yield*`. const iterator = (getEmitFlags(node.expression!) & EmitFlags.Iterator) === 0 - ? setTextRange(emitHelpers().createValuesHelper(expression!), node) + ? setTextRange( + emitHelpers().createValuesHelper(expression!), + node, + ) : expression; emitYieldStar(iterator, /*location*/ node); } @@ -1060,7 +1212,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param node The node to visit. */ function visitArrayLiteralExpression(node: ArrayLiteralExpression) { - return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine); + return visitElements( + node.elements, + /*leadingElement*/ undefined, + /*location*/ undefined, + node.multiLine, + ); } /** @@ -1070,7 +1227,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param elements The elements to visit. * @param multiLine Whether array literals created should be emitted on multiple lines. */ - function visitElements(elements: NodeArray, leadingElement?: Expression, location?: TextRange, multiLine?: boolean) { + function visitElements( + elements: NodeArray, + leadingElement?: Expression, + location?: TextRange, + multiLine?: boolean, + ) { // [source] // ar = [1, yield, 2]; // @@ -1086,7 +1248,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF let temp: Identifier | undefined; if (numInitialElements > 0) { temp = declareLocal(); - const initialElements = visitNodes(elements, visitor, isExpression, 0, numInitialElements); + const initialElements = visitNodes( + elements, + visitor, + isExpression, + 0, + numInitialElements, + ); emitAssignment( temp, factory.createArrayLiteralExpression( @@ -1098,11 +1266,23 @@ export function transformGenerators(context: TransformationContext): (x: SourceF leadingElement = undefined; } - const expressions = reduceLeft(elements, reduceElement, [] as Expression[], numInitialElements); + const expressions = reduceLeft( + elements, + reduceElement, + [] as Expression[], + numInitialElements, + ); return temp - ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)]) + ? factory.createArrayConcatCall(temp, [ + factory.createArrayLiteralExpression(expressions, multiLine), + ]) : setTextRange( - factory.createArrayLiteralExpression(leadingElement ? [leadingElement, ...expressions] : expressions, multiLine), + factory.createArrayLiteralExpression( + leadingElement + ? [leadingElement, ...expressions] + : expressions, + multiLine, + ), location, ); @@ -1116,12 +1296,16 @@ export function transformGenerators(context: TransformationContext): (x: SourceF emitAssignment( temp, hasAssignedTemp - ? factory.createArrayConcatCall( - temp, - [factory.createArrayLiteralExpression(expressions, multiLine)], - ) + ? factory.createArrayConcatCall(temp, [ + factory.createArrayLiteralExpression( + expressions, + multiLine, + ), + ]) : factory.createArrayLiteralExpression( - leadingElement ? [leadingElement, ...expressions] : expressions, + leadingElement + ? [leadingElement, ...expressions] + : expressions, multiLine, ), ); @@ -1129,7 +1313,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF expressions = []; } - expressions.push(Debug.checkDefined(visitNode(element, visitor, isExpression))); + expressions.push( + Debug.checkDefined(visitNode(element, visitor, isExpression)), + ); return expressions; } } @@ -1161,23 +1347,55 @@ export function transformGenerators(context: TransformationContext): (x: SourceF emitAssignment( temp, factory.createObjectLiteralExpression( - visitNodes(properties, visitor, isObjectLiteralElementLike, 0, numInitialProperties), + visitNodes( + properties, + visitor, + isObjectLiteralElementLike, + 0, + numInitialProperties, + ), multiLine, ), ); - const expressions = reduceLeft(properties, reduceProperty, [] as Expression[], numInitialProperties); + const expressions = reduceLeft( + properties, + reduceProperty, + [] as Expression[], + numInitialProperties, + ); // TODO(rbuckton): Does this need to be parented? - expressions.push(multiLine ? startOnNewLine(setParent(setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp); + expressions.push( + multiLine + ? startOnNewLine( + setParent( + setTextRange(factory.cloneNode(temp), temp), + temp.parent, + ), + ) + : temp, + ); return factory.inlineExpressions(expressions); - function reduceProperty(expressions: Expression[], property: ObjectLiteralElementLike) { + function reduceProperty( + expressions: Expression[], + property: ObjectLiteralElementLike, + ) { if (containsYield(property) && expressions.length > 0) { - emitStatement(factory.createExpressionStatement(factory.inlineExpressions(expressions))); + emitStatement( + factory.createExpressionStatement( + factory.inlineExpressions(expressions), + ), + ); expressions = []; } - const expression = createExpressionForObjectLiteralElementLike(factory, node, property, temp); + const expression = createExpressionForObjectLiteralElementLike( + factory, + node, + property, + temp, + ); const visited = visitNode(expression, visitor, isExpression); if (visited) { if (multiLine) { @@ -1206,7 +1424,21 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // .mark resumeLabel // a = _a[%sent%] - return factory.updateElementAccessExpression(node, cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isLeftHandSideExpression))), Debug.checkDefined(visitNode(node.argumentExpression, visitor, isExpression))); + return factory.updateElementAccessExpression( + node, + cacheExpression( + Debug.checkDefined( + visitNode( + node.expression, + visitor, + isLeftHandSideExpression, + ), + ), + ), + Debug.checkDefined( + visitNode(node.argumentExpression, visitor, isExpression), + ), + ); } return visitEachChild(node, visitor, context); @@ -1224,11 +1456,24 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // .yield resumeLabel // .mark resumeLabel // _b.apply(_a, _c.concat([%sent%, 2])); - const { target, thisArg } = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true); + const { target, thisArg } = factory.createCallBinding( + node.expression, + hoistVariableDeclaration, + languageVersion, + /*cacheIdentifiers*/ true, + ); return setOriginalNode( setTextRange( factory.createFunctionApplyCall( - cacheExpression(Debug.checkDefined(visitNode(target, visitor, isLeftHandSideExpression))), + cacheExpression( + Debug.checkDefined( + visitNode( + target, + visitor, + isLeftHandSideExpression, + ), + ), + ), thisArg, visitElements(node.arguments), ), @@ -1254,12 +1499,19 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // .mark resumeLabel // new (_b.apply(_a, _c.concat([%sent%, 2]))); - const { target, thisArg } = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration); + const { target, thisArg } = factory.createCallBinding( + factory.createPropertyAccessExpression(node.expression, "bind"), + hoistVariableDeclaration, + ); return setOriginalNode( setTextRange( factory.createNewExpression( factory.createFunctionApplyCall( - cacheExpression(Debug.checkDefined(visitNode(target, visitor, isExpression))), + cacheExpression( + Debug.checkDefined( + visitNode(target, visitor, isExpression), + ), + ), thisArg, visitElements( node.arguments!, @@ -1277,7 +1529,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF return visitEachChild(node, visitor, context); } - function transformAndEmitStatements(statements: readonly Statement[], start = 0) { + function transformAndEmitStatements( + statements: readonly Statement[], + start = 0, + ) { const numStatements = statements.length; for (let i = start; i < numStatements; i++) { transformAndEmitStatement(statements[i]); @@ -1306,35 +1561,41 @@ export function transformGenerators(context: TransformationContext): (x: SourceF function transformAndEmitStatementWorker(node: Statement): void { switch (node.kind) { case SyntaxKind.Block: - return transformAndEmitBlock(node as Block); + return transformAndEmitBlock(node); case SyntaxKind.ExpressionStatement: - return transformAndEmitExpressionStatement(node as ExpressionStatement); + return transformAndEmitExpressionStatement( + node, + ); case SyntaxKind.IfStatement: - return transformAndEmitIfStatement(node as IfStatement); + return transformAndEmitIfStatement(node); case SyntaxKind.DoStatement: - return transformAndEmitDoStatement(node as DoStatement); + return transformAndEmitDoStatement(node); case SyntaxKind.WhileStatement: - return transformAndEmitWhileStatement(node as WhileStatement); + return transformAndEmitWhileStatement(node); case SyntaxKind.ForStatement: - return transformAndEmitForStatement(node as ForStatement); + return transformAndEmitForStatement(node); case SyntaxKind.ForInStatement: - return transformAndEmitForInStatement(node as ForInStatement); + return transformAndEmitForInStatement(node); case SyntaxKind.ContinueStatement: - return transformAndEmitContinueStatement(node as ContinueStatement); + return transformAndEmitContinueStatement( + node, + ); case SyntaxKind.BreakStatement: - return transformAndEmitBreakStatement(node as BreakStatement); + return transformAndEmitBreakStatement(node); case SyntaxKind.ReturnStatement: - return transformAndEmitReturnStatement(node as ReturnStatement); + return transformAndEmitReturnStatement(node); case SyntaxKind.WithStatement: - return transformAndEmitWithStatement(node as WithStatement); + return transformAndEmitWithStatement(node); case SyntaxKind.SwitchStatement: - return transformAndEmitSwitchStatement(node as SwitchStatement); + return transformAndEmitSwitchStatement(node); case SyntaxKind.LabeledStatement: - return transformAndEmitLabeledStatement(node as LabeledStatement); + return transformAndEmitLabeledStatement( + node, + ); case SyntaxKind.ThrowStatement: - return transformAndEmitThrowStatement(node as ThrowStatement); + return transformAndEmitThrowStatement(node); case SyntaxKind.TryStatement: - return transformAndEmitTryStatement(node as TryStatement); + return transformAndEmitTryStatement(node); default: return emitStatement(visitNode(node, visitor, isStatement)); } @@ -1353,7 +1614,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF emitStatement(visitNode(node, visitor, isStatement)); } - function transformAndEmitVariableDeclarationList(node: VariableDeclarationList): VariableDeclarationList | undefined { + function transformAndEmitVariableDeclarationList( + node: VariableDeclarationList, + ): VariableDeclarationList | undefined { for (const variable of node.declarations) { const name = factory.cloneNode(variable.name as Identifier); setCommentRange(name, variable.name); @@ -1367,7 +1630,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF while (variablesWritten < numVariables) { for (let i = variablesWritten; i < numVariables; i++) { const variable = variables[i]; - if (containsYield(variable.initializer) && pendingExpressions.length > 0) { + if ( + containsYield(variable.initializer) && + pendingExpressions.length > 0 + ) { break; } @@ -1375,7 +1641,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF } if (pendingExpressions.length) { - emitStatement(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))); + emitStatement( + factory.createExpressionStatement( + factory.inlineExpressions(pendingExpressions), + ), + ); variablesWritten += pendingExpressions.length; pendingExpressions = []; } @@ -1384,11 +1654,18 @@ export function transformGenerators(context: TransformationContext): (x: SourceF return undefined; } - function transformInitializedVariable(node: InitializedVariableDeclaration) { + function transformInitializedVariable( + node: InitializedVariableDeclaration, + ) { return setSourceMapRange( factory.createAssignment( - setSourceMapRange(factory.cloneNode(node.name) as Identifier, node.name), - Debug.checkDefined(visitNode(node.initializer, visitor, isExpression)), + setSourceMapRange( + factory.cloneNode(node.name) as Identifier, + node.name, + ), + Debug.checkDefined( + visitNode(node.initializer, visitor, isExpression), + ), ), node, ); @@ -1410,10 +1687,21 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // /*elseStatement*/ // .mark endLabel - if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) { + if ( + containsYield(node.thenStatement) || + containsYield(node.elseStatement) + ) { const endLabel = defineLabel(); - const elseLabel = node.elseStatement ? defineLabel() : undefined; - emitBreakWhenFalse(node.elseStatement ? elseLabel! : endLabel, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), /*location*/ node.expression); + const elseLabel = node.elseStatement + ? defineLabel() + : undefined; + emitBreakWhenFalse( + node.elseStatement ? elseLabel! : endLabel, + Debug.checkDefined( + visitNode(node.expression, visitor, isExpression), + ), + /*location*/ node.expression, + ); transformAndEmitEmbeddedStatement(node.thenStatement); if (node.elseStatement) { emitBreak(endLabel); @@ -1454,7 +1742,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF markLabel(loopLabel); transformAndEmitEmbeddedStatement(node.statement); markLabel(conditionLabel); - emitBreakWhenTrue(loopLabel, Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); + emitBreakWhenTrue( + loopLabel, + Debug.checkDefined( + visitNode(node.expression, visitor, isExpression), + ), + ); endLoopBlock(); } else { @@ -1493,7 +1786,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF const loopLabel = defineLabel(); const endLabel = beginLoopBlock(loopLabel); markLabel(loopLabel); - emitBreakWhenFalse(endLabel, Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); + emitBreakWhenFalse( + endLabel, + Debug.checkDefined( + visitNode(node.expression, visitor, isExpression), + ), + ); transformAndEmitEmbeddedStatement(node.statement); emitBreak(loopLabel); endLoopBlock(); @@ -1547,7 +1845,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF emitStatement( setTextRange( factory.createExpressionStatement( - Debug.checkDefined(visitNode(initializer, visitor, isExpression)), + Debug.checkDefined( + visitNode( + initializer, + visitor, + isExpression, + ), + ), ), initializer, ), @@ -1557,7 +1861,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF markLabel(conditionLabel); if (node.condition) { - emitBreakWhenFalse(endLabel, Debug.checkDefined(visitNode(node.condition, visitor, isExpression))); + emitBreakWhenFalse( + endLabel, + Debug.checkDefined( + visitNode(node.condition, visitor, isExpression), + ), + ); } transformAndEmitEmbeddedStatement(node.statement); @@ -1567,7 +1876,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF emitStatement( setTextRange( factory.createExpressionStatement( - Debug.checkDefined(visitNode(node.incrementor, visitor, isExpression)), + Debug.checkDefined( + visitNode( + node.incrementor, + visitor, + isExpression, + ), + ), ), node.incrementor, ), @@ -1596,7 +1911,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF node = factory.updateForStatement( node, variables.length > 0 - ? factory.inlineExpressions(map(variables, transformInitializedVariable)) + ? factory.inlineExpressions( + map(variables, transformInitializedVariable), + ) : undefined, visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, visitor, isExpression), @@ -1646,7 +1963,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF const keysIndex = factory.createLoopVariable(); // _i const initializer = node.initializer; hoistVariableDeclaration(keysIndex); - emitAssignment(obj, Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); + emitAssignment( + obj, + Debug.checkDefined( + visitNode(node.expression, visitor, isExpression), + ), + ); emitAssignment(keysArray, factory.createArrayLiteralExpression()); emitStatement( @@ -1655,7 +1977,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF obj, factory.createExpressionStatement( factory.createCallExpression( - factory.createPropertyAccessExpression(keysArray, "push"), + factory.createPropertyAccessExpression( + keysArray, + "push", + ), /*typeArguments*/ undefined, [key], ), @@ -1670,10 +1995,22 @@ export function transformGenerators(context: TransformationContext): (x: SourceF const endLoopLabel = beginLoopBlock(incrementLabel); markLabel(conditionLabel); - emitBreakWhenFalse(endLoopLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length"))); + emitBreakWhenFalse( + endLoopLabel, + factory.createLessThan( + keysIndex, + factory.createPropertyAccessExpression(keysArray, "length"), + ), + ); - emitAssignment(key, factory.createElementAccessExpression(keysArray, keysIndex)); - emitBreakWhenFalse(incrementLabel, factory.createBinaryExpression(key, SyntaxKind.InKeyword, obj)); + emitAssignment( + key, + factory.createElementAccessExpression(keysArray, keysIndex), + ); + emitBreakWhenFalse( + incrementLabel, + factory.createBinaryExpression(key, SyntaxKind.InKeyword, obj), + ); let variable: Expression; if (isVariableDeclarationList(initializer)) { @@ -1681,10 +2018,14 @@ export function transformGenerators(context: TransformationContext): (x: SourceF hoistVariableDeclaration(variable.name as Identifier); } - variable = factory.cloneNode(initializer.declarations[0].name) as Identifier; + variable = factory.cloneNode( + initializer.declarations[0].name, + ) as Identifier; } else { - variable = Debug.checkDefined(visitNode(initializer, visitor, isExpression)); + variable = Debug.checkDefined( + visitNode(initializer, visitor, isExpression), + ); Debug.assert(isLeftHandSideExpression(variable)); } @@ -1692,7 +2033,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF transformAndEmitEmbeddedStatement(node.statement); markLabel(incrementLabel); - emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex))); + emitStatement( + factory.createExpressionStatement( + factory.createPostfixIncrement(keysIndex), + ), + ); emitBreak(conditionLabel); endLoopBlock(); @@ -1726,7 +2071,21 @@ export function transformGenerators(context: TransformationContext): (x: SourceF hoistVariableDeclaration(variable.name as Identifier); } - node = factory.updateForInStatement(node, initializer.declarations[0].name as Identifier, Debug.checkDefined(visitNode(node.expression, visitor, isExpression)), Debug.checkDefined(visitNode(node.statement, visitor, isStatement, factory.liftToBlock))); + node = factory.updateForInStatement( + node, + initializer.declarations[0].name as Identifier, + Debug.checkDefined( + visitNode(node.expression, visitor, isExpression), + ), + Debug.checkDefined( + visitNode( + node.statement, + visitor, + isStatement, + factory.liftToBlock, + ), + ), + ); } else { node = visitEachChild(node, visitor, context); @@ -1740,7 +2099,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF } function transformAndEmitContinueStatement(node: ContinueStatement): void { - const label = findContinueTarget(node.label ? idText(node.label) : undefined); + const label = findContinueTarget( + node.label ? idText(node.label) : undefined, + ); if (label > 0) { emitBreak(label, /*location*/ node); } @@ -1762,7 +2123,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF } function transformAndEmitBreakStatement(node: BreakStatement): void { - const label = findBreakTarget(node.label ? idText(node.label) : undefined); + const label = findBreakTarget( + node.label ? idText(node.label) : undefined, + ); if (label > 0) { emitBreak(label, /*location*/ node); } @@ -1808,7 +2171,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // .with (x) // /*body*/ // .endwith - beginWithBlock(cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isExpression)))); + beginWithBlock( + cacheExpression( + Debug.checkDefined( + visitNode(node.expression, visitor, isExpression), + ), + ), + ); transformAndEmitEmbeddedStatement(node.statement); endWithBlock(); } @@ -1855,7 +2224,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF const numClauses = caseBlock.clauses.length; const endLabel = beginSwitchBlock(); - const expression = cacheExpression(Debug.checkDefined(visitNode(node.expression, visitor, isExpression))); + const expression = cacheExpression( + Debug.checkDefined( + visitNode(node.expression, visitor, isExpression), + ), + ); // Create labels for each clause and find the index of the first default clause. const clauseLabels: Label[] = []; @@ -1863,7 +2236,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF for (let i = 0; i < numClauses; i++) { const clause = caseBlock.clauses[i]; clauseLabels.push(defineLabel()); - if (clause.kind === SyntaxKind.DefaultClause && defaultClauseIndex === -1) { + if ( + clause.kind === SyntaxKind.DefaultClause && + defaultClauseIndex === -1 + ) { defaultClauseIndex = i; } } @@ -1878,15 +2254,27 @@ export function transformGenerators(context: TransformationContext): (x: SourceF for (let i = clausesWritten; i < numClauses; i++) { const clause = caseBlock.clauses[i]; if (clause.kind === SyntaxKind.CaseClause) { - if (containsYield(clause.expression) && pendingClauses.length > 0) { + if ( + containsYield(clause.expression) && + pendingClauses.length > 0 + ) { break; } pendingClauses.push( factory.createCaseClause( - Debug.checkDefined(visitNode(clause.expression, visitor, isExpression)), + Debug.checkDefined( + visitNode( + clause.expression, + visitor, + isExpression, + ), + ), [ - createInlineBreak(clauseLabels[i], /*location*/ clause.expression), + createInlineBreak( + clauseLabels[i], + /*location*/ clause.expression, + ), ], ), ); @@ -1897,7 +2285,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF } if (pendingClauses.length) { - emitStatement(factory.createSwitchStatement(expression, factory.createCaseBlock(pendingClauses))); + emitStatement( + factory.createSwitchStatement( + expression, + factory.createCaseBlock(pendingClauses), + ), + ); clausesWritten += pendingClauses.length; pendingClauses = []; } @@ -1978,7 +2371,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF function transformAndEmitThrowStatement(node: ThrowStatement): void { // TODO(rbuckton): `expression` should be required on `throw`. emitThrow( - Debug.checkDefined(visitNode(node.expression ?? factory.createVoidZero(), visitor, isExpression)), + Debug.checkDefined( + visitNode( + node.expression ?? factory.createVoidZero(), + visitor, + isExpression, + ), + ), /*location*/ node, ); } @@ -2035,7 +2434,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF } function containsYield(node: Node | undefined): boolean { - return !!node && (node.transformFlags & TransformFlags.ContainsYield) !== 0; + return ( + !!node && (node.transformFlags & TransformFlags.ContainsYield) !== 0 + ); } function countInitialNodesWithoutYield(nodes: NodeArray) { @@ -2065,15 +2466,24 @@ export function transformGenerators(context: TransformationContext): (x: SourceF } function substituteExpressionIdentifier(node: Identifier) { - if (!isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(idText(node))) { + if ( + !isGeneratedIdentifier(node) && + renamedCatchVariables && + renamedCatchVariables.has(idText(node)) + ) { const original = getOriginalNode(node); if (isIdentifier(original) && original.parent) { const declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - const name = renamedCatchVariableDeclarations[getOriginalNodeId(declaration)]; + const name = renamedCatchVariableDeclarations[ + getOriginalNodeId(declaration) + ]; if (name) { // TODO(rbuckton): Does this need to be parented? - const clone = setParent(setTextRange(factory.cloneNode(name), name), name.parent); + const clone = setParent( + setTextRange(factory.cloneNode(name), name), + name.parent, + ); setSourceMapRange(clone, node); setCommentRange(clone, node); return clone; @@ -2086,7 +2496,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF } function cacheExpression(node: Expression): Identifier { - if (isGeneratedIdentifier(node) || getEmitFlags(node) & EmitFlags.HelperName) { + if ( + isGeneratedIdentifier(node) || + getEmitFlags(node) & EmitFlags.HelperName + ) { return node as Identifier; } @@ -2258,7 +2671,14 @@ export function transformGenerators(context: TransformationContext): (x: SourceF exception.catchVariable = name; exception.catchLabel = catchLabel; - emitAssignment(name, factory.createCallExpression(factory.createPropertyAccessExpression(state, "sent"), /*typeArguments*/ undefined, [])); + emitAssignment( + name, + factory.createCallExpression( + factory.createPropertyAccessExpression(state, "sent"), + /*typeArguments*/ undefined, + [], + ), + ); emitNop(); } @@ -2417,9 +2837,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * * @param block A code block. */ - function supportsUnlabeledBreak(block: CodeBlock): block is SwitchBlock | LoopBlock { - return block.kind === CodeBlockKind.Switch - || block.kind === CodeBlockKind.Loop; + function supportsUnlabeledBreak( + block: CodeBlock, + ): block is SwitchBlock | LoopBlock { + return ( + block.kind === CodeBlockKind.Switch || + block.kind === CodeBlockKind.Loop + ); } /** @@ -2427,7 +2851,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * * @param block A code block. */ - function supportsLabeledBreakOrContinue(block: CodeBlock): block is LabeledBlock { + function supportsLabeledBreakOrContinue( + block: CodeBlock, + ): block is LabeledBlock { return block.kind === CodeBlockKind.Labeled; } @@ -2440,7 +2866,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF return block.kind === CodeBlockKind.Loop; } - function hasImmediateContainingLabeledBlock(labelText: string, start: number) { + function hasImmediateContainingLabeledBlock( + labelText: string, + start: number, + ) { for (let j = start; j >= 0; j--) { const containingBlock = blockStack![j]; if (supportsLabeledBreakOrContinue(containingBlock)) { @@ -2466,10 +2895,16 @@ export function transformGenerators(context: TransformationContext): (x: SourceF if (labelText) { for (let i = blockStack.length - 1; i >= 0; i--) { const block = blockStack[i]; - if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) { + if ( + supportsLabeledBreakOrContinue(block) && + block.labelText === labelText + ) { return block.breakLabel; } - else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + else if ( + supportsUnlabeledBreak(block) && + hasImmediateContainingLabeledBlock(labelText, i - 1) + ) { return block.breakLabel; } } @@ -2496,7 +2931,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF if (labelText) { for (let i = blockStack.length - 1; i >= 0; i--) { const block = blockStack[i]; - if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) { + if ( + supportsUnlabeledContinue(block) && + hasImmediateContainingLabeledBlock(labelText, i - 1) + ) { return block.continueLabel; } } @@ -2524,7 +2962,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF labelExpressions = []; } - const expression = factory.createNumericLiteral(Number.MAX_SAFE_INTEGER); + const expression = factory.createNumericLiteral( + Number.MAX_SAFE_INTEGER, + ); if (labelExpressions[label] === undefined) { labelExpressions[label] = [expression]; } @@ -2543,7 +2983,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF */ function createInstruction(instruction: Instruction): NumericLiteral { const literal = factory.createNumericLiteral(instruction); - addSyntheticTrailingComment(literal, SyntaxKind.MultiLineCommentTrivia, getInstructionName(instruction)); + addSyntheticTrailingComment( + literal, + SyntaxKind.MultiLineCommentTrivia, + getInstructionName(instruction), + ); return literal; } @@ -2553,7 +2997,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param label A label. * @param location An optional source map location for the statement. */ - function createInlineBreak(label: Label, location?: TextRange): ReturnStatement { + function createInlineBreak( + label: Label, + location?: TextRange, + ): ReturnStatement { Debug.assertLessThan(0, label, "Invalid label"); return setTextRange( factory.createReturnStatement( @@ -2572,7 +3019,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param expression The expression for the return statement. * @param location An optional source map location for the statement. */ - function createInlineReturn(expression?: Expression, location?: TextRange): ReturnStatement { + function createInlineReturn( + expression?: Expression, + location?: TextRange, + ): ReturnStatement { return setTextRange( factory.createReturnStatement( factory.createArrayLiteralExpression( @@ -2588,7 +3038,9 @@ export function transformGenerators(context: TransformationContext): (x: SourceF /** * Creates an expression that can be used to resume from a Yield operation. */ - function createGeneratorResume(location?: TextRange): LeftHandSideExpression { + function createGeneratorResume( + location?: TextRange, + ): LeftHandSideExpression { return setTextRange( factory.createCallExpression( factory.createPropertyAccessExpression(state, "sent"), @@ -2627,7 +3079,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param right The right-hand side of the assignment. * @param location An optional source map location for the assignment. */ - function emitAssignment(left: Expression, right: Expression, location?: TextRange): void { + function emitAssignment( + left: Expression, + right: Expression, + location?: TextRange, + ): void { emitWorker(OpCode.Assign, [left, right], location); } @@ -2649,7 +3105,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param condition The condition. * @param location An optional source map location for the assignment. */ - function emitBreakWhenTrue(label: Label, condition: Expression, location?: TextRange): void { + function emitBreakWhenTrue( + label: Label, + condition: Expression, + location?: TextRange, + ): void { emitWorker(OpCode.BreakWhenTrue, [label, condition], location); } @@ -2661,7 +3121,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param condition The condition. * @param location An optional source map location for the assignment. */ - function emitBreakWhenFalse(label: Label, condition: Expression, location?: TextRange): void { + function emitBreakWhenFalse( + label: Label, + condition: Expression, + location?: TextRange, + ): void { emitWorker(OpCode.BreakWhenFalse, [label, condition], location); } @@ -2671,7 +3135,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param expression An optional value for the yield operation. * @param location An optional source map location for the assignment. */ - function emitYieldStar(expression?: Expression, location?: TextRange): void { + function emitYieldStar( + expression?: Expression, + location?: TextRange, + ): void { emitWorker(OpCode.YieldStar, [expression], location); } @@ -2718,7 +3185,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param code The OpCode for the operation. * @param args The optional arguments for the operation. */ - function emitWorker(code: OpCode, args?: OperationArguments, location?: TextRange): void { + function emitWorker( + code: OpCode, + args?: OperationArguments, + location?: TextRange, + ): void { if (operations === undefined) { operations = []; operationArguments = []; @@ -2759,7 +3230,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, - [factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], + [ + factory.createParameterDeclaration( + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + state, + ), + ], /*type*/ undefined, factory.createBlock( buildResult, @@ -2776,7 +3253,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF */ function buildStatements(): Statement[] { if (operations) { - for (let operationIndex = 0; operationIndex < operations.length; operationIndex++) { + for ( + let operationIndex = 0; + operationIndex < operations.length; + operationIndex++ + ) { writeOperation(operationIndex); } @@ -2787,8 +3268,14 @@ export function transformGenerators(context: TransformationContext): (x: SourceF } if (clauses) { - const labelExpression = factory.createPropertyAccessExpression(state, "label"); - const switchStatement = factory.createSwitchStatement(labelExpression, factory.createCaseBlock(clauses)); + const labelExpression = factory.createPropertyAccessExpression( + state, + "label", + ); + const switchStatement = factory.createSwitchStatement( + labelExpression, + factory.createCaseBlock(clauses), + ); return [startOnNewLine(switchStatement)]; } @@ -2821,7 +3308,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF if (isFinalLabelReachable(operationIndex)) { tryEnterLabel(operationIndex); withBlockStack = undefined; - writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined); + writeReturn( + /*expression*/ undefined, + /*operationLocation*/ undefined, + ); } if (statements && clauses) { @@ -2851,7 +3341,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // if the label for this offset is referenced, then the final label // is reachable. for (let label = 0; label < labelOffsets.length; label++) { - if (labelOffsets[label] === operationIndex && labelExpressions[label]) { + if ( + labelOffsets[label] === operationIndex && + labelExpressions[label] + ) { return true; } } @@ -2877,7 +3370,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF // surround the statements in generated `with` blocks to create the same environment. for (let i = withBlockStack.length - 1; i >= 0; i--) { const withBlock = withBlockStack[i]; - statements = [factory.createWithStatement(withBlock.expression, factory.createBlock(statements))]; + statements = [ + factory.createWithStatement( + withBlock.expression, + factory.createBlock(statements), + ), + ]; } } @@ -2889,7 +3387,13 @@ export function transformGenerators(context: TransformationContext): (x: SourceF statements.unshift( factory.createExpressionStatement( factory.createCallExpression( - factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(state, "trys"), "push"), + factory.createPropertyAccessExpression( + factory.createPropertyAccessExpression( + state, + "trys", + ), + "push", + ), /*typeArguments*/ undefined, [ factory.createArrayLiteralExpression([ @@ -2912,7 +3416,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF statements.push( factory.createExpressionStatement( factory.createAssignment( - factory.createPropertyAccessExpression(state, "label"), + factory.createPropertyAccessExpression( + state, + "label", + ), factory.createNumericLiteral(labelNumber + 1), ), ), @@ -2959,7 +3466,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF */ function updateLabelExpressions() { if (labelExpressions !== undefined && labelNumbers !== undefined) { - for (let labelNumber = 0; labelNumber < labelNumbers.length; labelNumber++) { + for ( + let labelNumber = 0; + labelNumber < labelNumbers.length; + labelNumber++ + ) { const labels = labelNumbers[labelNumber]; if (labels !== undefined) { for (const label of labels) { @@ -2980,7 +3491,12 @@ export function transformGenerators(context: TransformationContext): (x: SourceF */ function tryEnterOrLeaveBlock(operationIndex: number): void { if (blocks) { - for (; blockIndex < blockActions!.length && blockOffsets![blockIndex] <= operationIndex; blockIndex++) { + for ( + ; + blockIndex < blockActions!.length && + blockOffsets![blockIndex] <= operationIndex; + blockIndex++ + ) { const block: CodeBlock = blocks[blockIndex]; const blockAction = blockActions![blockIndex]; switch (block.kind) { @@ -3052,13 +3568,25 @@ export function transformGenerators(context: TransformationContext): (x: SourceF const location = operationLocations![operationIndex]; switch (opcode) { case OpCode.Assign: - return writeAssign(args[0] as Expression, args[1] as Expression, location); + return writeAssign( + args[0] as Expression, + args[1] as Expression, + location, + ); case OpCode.Break: return writeBreak(args[0] as Label, location); case OpCode.BreakWhenTrue: - return writeBreakWhenTrue(args[0] as Label, args[1] as Expression, location); + return writeBreakWhenTrue( + args[0] as Label, + args[1] as Expression, + location, + ); case OpCode.BreakWhenFalse: - return writeBreakWhenFalse(args[0] as Label, args[1] as Expression, location); + return writeBreakWhenFalse( + args[0] as Label, + args[1] as Expression, + location, + ); case OpCode.Yield: return writeYield(args[0] as Expression, location); case OpCode.YieldStar: @@ -3093,8 +3621,19 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param right The right-hand side of the assignment. * @param operationLocation The source map location for the operation. */ - function writeAssign(left: Expression, right: Expression, operationLocation: TextRange | undefined): void { - writeStatement(setTextRange(factory.createExpressionStatement(factory.createAssignment(left, right)), operationLocation)); + function writeAssign( + left: Expression, + right: Expression, + operationLocation: TextRange | undefined, + ): void { + writeStatement( + setTextRange( + factory.createExpressionStatement( + factory.createAssignment(left, right), + ), + operationLocation, + ), + ); } /** @@ -3103,10 +3642,18 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param expression The value to throw. * @param operationLocation The source map location for the operation. */ - function writeThrow(expression: Expression, operationLocation: TextRange | undefined): void { + function writeThrow( + expression: Expression, + operationLocation: TextRange | undefined, + ): void { lastOperationWasAbrupt = true; lastOperationWasCompletion = true; - writeStatement(setTextRange(factory.createThrowStatement(expression), operationLocation)); + writeStatement( + setTextRange( + factory.createThrowStatement(expression), + operationLocation, + ), + ); } /** @@ -3115,7 +3662,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param expression The value to return. * @param operationLocation The source map location for the operation. */ - function writeReturn(expression: Expression | undefined, operationLocation: TextRange | undefined): void { + function writeReturn( + expression: Expression | undefined, + operationLocation: TextRange | undefined, + ): void { lastOperationWasAbrupt = true; lastOperationWasCompletion = true; writeStatement( @@ -3124,7 +3674,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createReturnStatement( factory.createArrayLiteralExpression( expression - ? [createInstruction(Instruction.Return), expression] + ? [ + createInstruction(Instruction.Return), + expression, + ] : [createInstruction(Instruction.Return)], ), ), @@ -3141,7 +3694,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param label The label for the Break. * @param operationLocation The source map location for the operation. */ - function writeBreak(label: Label, operationLocation: TextRange | undefined): void { + function writeBreak( + label: Label, + operationLocation: TextRange | undefined, + ): void { lastOperationWasAbrupt = true; writeStatement( setEmitFlags( @@ -3166,7 +3722,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param condition The condition for the Break. * @param operationLocation The source map location for the operation. */ - function writeBreakWhenTrue(label: Label, condition: Expression, operationLocation: TextRange | undefined): void { + function writeBreakWhenTrue( + label: Label, + condition: Expression, + operationLocation: TextRange | undefined, + ): void { writeStatement( setEmitFlags( factory.createIfStatement( @@ -3196,7 +3756,11 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param condition The condition for the Break. * @param operationLocation The source map location for the operation. */ - function writeBreakWhenFalse(label: Label, condition: Expression, operationLocation: TextRange | undefined): void { + function writeBreakWhenFalse( + label: Label, + condition: Expression, + operationLocation: TextRange | undefined, + ): void { writeStatement( setEmitFlags( factory.createIfStatement( @@ -3225,7 +3789,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param expression The expression to yield. * @param operationLocation The source map location for the operation. */ - function writeYield(expression: Expression, operationLocation: TextRange | undefined): void { + function writeYield( + expression: Expression, + operationLocation: TextRange | undefined, + ): void { lastOperationWasAbrupt = true; writeStatement( setEmitFlags( @@ -3233,7 +3800,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF factory.createReturnStatement( factory.createArrayLiteralExpression( expression - ? [createInstruction(Instruction.Yield), expression] + ? [ + createInstruction(Instruction.Yield), + expression, + ] : [createInstruction(Instruction.Yield)], ), ), @@ -3250,7 +3820,10 @@ export function transformGenerators(context: TransformationContext): (x: SourceF * @param expression The expression to yield. * @param operationLocation The source map location for the operation. */ - function writeYieldStar(expression: Expression, operationLocation: TextRange | undefined): void { + function writeYieldStar( + expression: Expression, + operationLocation: TextRange | undefined, + ): void { lastOperationWasAbrupt = true; writeStatement( setEmitFlags( diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 584cf837e180a..41741f72693ec 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -27,7 +27,7 @@ import { createTokenRange, createUnparsedSourceFile, Debug, - Declaration, + DeclarationBase, Decorator, ElementAccessExpression, EmitFlags, @@ -1060,7 +1060,7 @@ export function transformTypeScript(context: TransformationContext) { * * @param node The declaration node. */ - function getTypeMetadata(node: Declaration, container: ClassLikeDeclaration) { + function getTypeMetadata(node: DeclarationBase, container: ClassLikeDeclaration) { // Decorator metadata is not yet supported for ES decorators. if (!legacyDecorators) return undefined; return USE_NEW_TYPE_METADATA_FORMAT ? @@ -1068,7 +1068,7 @@ export function transformTypeScript(context: TransformationContext) { getOldTypeMetadata(node, container); } - function getOldTypeMetadata(node: Declaration, container: ClassLikeDeclaration) { + function getOldTypeMetadata(node: DeclarationBase, container: ClassLikeDeclaration) { if (typeSerializer) { let decorators: Decorator[] | undefined; if (shouldAddTypeMetadata(node)) { @@ -1087,7 +1087,7 @@ export function transformTypeScript(context: TransformationContext) { } } - function getNewTypeMetadata(node: Declaration, container: ClassLikeDeclaration) { + function getNewTypeMetadata(node: DeclarationBase, container: ClassLikeDeclaration) { if (typeSerializer) { let properties: ObjectLiteralElementLike[] | undefined; if (shouldAddTypeMetadata(node)) { @@ -1116,7 +1116,7 @@ export function transformTypeScript(context: TransformationContext) { * * @param node The node to test. */ - function shouldAddTypeMetadata(node: Declaration): node is MethodDeclaration | AccessorDeclaration | PropertyDeclaration { + function shouldAddTypeMetadata(node: DeclarationBase): node is MethodDeclaration | AccessorDeclaration | PropertyDeclaration { const kind = node.kind; return kind === SyntaxKind.MethodDeclaration || kind === SyntaxKind.GetAccessor @@ -1131,7 +1131,7 @@ export function transformTypeScript(context: TransformationContext) { * * @param node The node to test. */ - function shouldAddReturnTypeMetadata(node: Declaration): node is MethodDeclaration { + function shouldAddReturnTypeMetadata(node: DeclarationBase): node is MethodDeclaration { return node.kind === SyntaxKind.MethodDeclaration; } @@ -1142,7 +1142,7 @@ export function transformTypeScript(context: TransformationContext) { * * @param node The node to test. */ - function shouldAddParamTypesMetadata(node: Declaration): node is ClassLikeDeclaration & { _hasConstructorBrand: never; } | MethodDeclaration | AccessorDeclaration { + function shouldAddParamTypesMetadata(node: DeclarationBase): node is ClassLikeDeclaration & { _hasConstructorBrand: never; } | MethodDeclaration | AccessorDeclaration { switch (node.kind) { case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: diff --git a/src/compiler/transformers/typeSerializer.ts b/src/compiler/transformers/typeSerializer.ts index 5db6762696316..20b0be002dc41 100644 --- a/src/compiler/transformers/typeSerializer.ts +++ b/src/compiler/transformers/typeSerializer.ts @@ -7,7 +7,6 @@ import { CaseBlock, ClassLikeDeclaration, ConditionalExpression, - ConditionalTypeNode, Debug, EntityName, Expression, @@ -48,7 +47,6 @@ import { NumericLiteral, ParameterDeclaration, parseNodeFactory, - PrefixUnaryExpression, PropertyAccessEntityNameExpression, PropertyDeclaration, QualifiedName, @@ -61,11 +59,8 @@ import { SyntaxKind, TransformationContext, TypeNode, - TypeOperatorNode, - TypePredicateNode, TypeReferenceNode, TypeReferenceSerializationKind, - UnionOrIntersectionTypeNode, VoidExpression, } from "../_namespaces/ts"; @@ -290,7 +285,7 @@ export function createRuntimeTypeSerializer(context: TransformationContext): Run return factory.createIdentifier("Array"); case SyntaxKind.TypePredicate: - return (node as TypePredicateNode).assertsModifier ? + return node.assertsModifier ? factory.createVoidZero() : factory.createIdentifier("Boolean"); @@ -305,7 +300,7 @@ export function createRuntimeTypeSerializer(context: TransformationContext): Run return factory.createIdentifier("Object"); case SyntaxKind.LiteralType: - return serializeLiteralOfLiteralTypeNode((node as LiteralTypeNode).literal); + return serializeLiteralOfLiteralTypeNode(node.literal); case SyntaxKind.NumberKeyword: return factory.createIdentifier("Number"); @@ -317,20 +312,20 @@ export function createRuntimeTypeSerializer(context: TransformationContext): Run return getGlobalConstructor("Symbol", ScriptTarget.ES2015); case SyntaxKind.TypeReference: - return serializeTypeReferenceNode(node as TypeReferenceNode); + return serializeTypeReferenceNode(node); case SyntaxKind.IntersectionType: - return serializeUnionOrIntersectionConstituents((node as UnionOrIntersectionTypeNode).types, /*isIntersection*/ true); + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ true); case SyntaxKind.UnionType: - return serializeUnionOrIntersectionConstituents((node as UnionOrIntersectionTypeNode).types, /*isIntersection*/ false); + return serializeUnionOrIntersectionConstituents(node.types, /*isIntersection*/ false); case SyntaxKind.ConditionalType: - return serializeUnionOrIntersectionConstituents([(node as ConditionalTypeNode).trueType, (node as ConditionalTypeNode).falseType], /*isIntersection*/ false); + return serializeUnionOrIntersectionConstituents([node.trueType, node.falseType], /*isIntersection*/ false); case SyntaxKind.TypeOperator: - if ((node as TypeOperatorNode).operator === SyntaxKind.ReadonlyKeyword) { - return serializeTypeNode((node as TypeOperatorNode).type); + if (node.operator === SyntaxKind.ReadonlyKeyword) { + return serializeTypeNode(node.type); } break; @@ -371,7 +366,7 @@ export function createRuntimeTypeSerializer(context: TransformationContext): Run return factory.createIdentifier("String"); case SyntaxKind.PrefixUnaryExpression: { - const operand = (node as PrefixUnaryExpression).operand; + const operand = node.operand; switch (operand.kind) { case SyntaxKind.NumericLiteral: case SyntaxKind.BigIntLiteral: diff --git a/src/compiler/types.ts b/src/compiler/types.ts index e0e9be8dc3ba3..2cb702ab334dd 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -23,7 +23,11 @@ import { export type Path = string & { __pathBrand: any; }; /** @internal */ -export type MatchingKeys = K extends (TRecord[K] extends TMatch ? K : never) ? K : never; +export type MatchingKeys< + TRecord, + TMatch, + K extends keyof TRecord = keyof TRecord, +> = K extends (TRecord[K] extends TMatch ? K : never) ? K : never; export interface TextRange { pos: number; @@ -582,7 +586,9 @@ export type PunctuationSyntaxKind = | SyntaxKind.CaretEqualsToken; /** @internal */ -export type PunctuationOrKeywordSyntaxKind = PunctuationSyntaxKind | KeywordSyntaxKind; +export type PunctuationOrKeywordSyntaxKind = + | PunctuationSyntaxKind + | KeywordSyntaxKind; export type KeywordSyntaxKind = | SyntaxKind.AbstractKeyword @@ -703,59 +709,60 @@ export type KeywordTypeSyntaxKind = /** @internal */ export type TypeNodeSyntaxKind = | KeywordTypeSyntaxKind - | SyntaxKind.TypePredicate - | SyntaxKind.TypeReference - | SyntaxKind.FunctionType - | SyntaxKind.ConstructorType - | SyntaxKind.TypeQuery - | SyntaxKind.TypeLiteral | SyntaxKind.ArrayType - | SyntaxKind.TupleType - | SyntaxKind.NamedTupleMember - | SyntaxKind.OptionalType - | SyntaxKind.RestType - | SyntaxKind.UnionType - | SyntaxKind.IntersectionType | SyntaxKind.ConditionalType - | SyntaxKind.InferType - | SyntaxKind.ParenthesizedType - | SyntaxKind.ThisType - | SyntaxKind.TypeOperator - | SyntaxKind.IndexedAccessType - | SyntaxKind.MappedType - | SyntaxKind.LiteralType - | SyntaxKind.TemplateLiteralType - | SyntaxKind.TemplateLiteralTypeSpan - | SyntaxKind.ImportType + | SyntaxKind.ConstructorType | SyntaxKind.ExpressionWithTypeArguments - | SyntaxKind.JSDocTypeExpression + | SyntaxKind.FunctionType + | SyntaxKind.ImportType + | SyntaxKind.IndexedAccessType + | SyntaxKind.InferType + | SyntaxKind.IntersectionType | SyntaxKind.JSDocAllType - | SyntaxKind.JSDocUnknownType + | SyntaxKind.JSDocFunctionType + | SyntaxKind.JSDocNamepathType | SyntaxKind.JSDocNonNullableType | SyntaxKind.JSDocNullableType | SyntaxKind.JSDocOptionalType - | SyntaxKind.JSDocFunctionType - | SyntaxKind.JSDocVariadicType - | SyntaxKind.JSDocNamepathType | SyntaxKind.JSDocSignature - | SyntaxKind.JSDocTypeLiteral; + | SyntaxKind.JSDocTypeExpression + | SyntaxKind.JSDocTypeLiteral + | SyntaxKind.JSDocUnknownType + | SyntaxKind.JSDocVariadicType + | SyntaxKind.JSDocVariadicType + | SyntaxKind.LiteralType + | SyntaxKind.MappedType + | SyntaxKind.NamedTupleMember + | SyntaxKind.OptionalType + | SyntaxKind.ParenthesizedType + | SyntaxKind.RestType + | SyntaxKind.TemplateLiteralType + | SyntaxKind.TemplateLiteralTypeSpan + | SyntaxKind.ThisType + | SyntaxKind.TupleType + | SyntaxKind.TypeLiteral + | SyntaxKind.TypeOperator + | SyntaxKind.TypePredicate + | SyntaxKind.TypeQuery + | SyntaxKind.TypeReference + | SyntaxKind.UnionType; export type TokenSyntaxKind = - | SyntaxKind.Unknown - | SyntaxKind.EndOfFileToken - | TriviaSyntaxKind - | LiteralSyntaxKind - | PseudoLiteralSyntaxKind | PunctuationSyntaxKind - | SyntaxKind.Identifier - | KeywordSyntaxKind; + | RelationalOperator + | SyntaxKind.AssertsKeyword + | SyntaxKind.CommaToken + | SyntaxKind.DotToken + | SyntaxKind.EndOfFileToken + | SyntaxKind.Unknown + | TriviaSyntaxKind; export type JsxTokenSyntaxKind = | SyntaxKind.LessThanSlashToken | SyntaxKind.EndOfFileToken | SyntaxKind.ConflictMarkerTrivia - | SyntaxKind.JsxText - | SyntaxKind.JsxTextAllWhiteSpaces + // | SyntaxKind.JsxText + // | SyntaxKind.JsxTextAllWhiteSpaces | SyntaxKind.OpenBraceToken | SyntaxKind.LessThanToken; @@ -782,28 +789,28 @@ export type JSDocSyntaxKind = // dprint-ignore export const enum NodeFlags { - None = 0, - Let = 1 << 0, // Variable declaration - Const = 1 << 1, // Variable declaration - Using = 1 << 2, // Variable declaration - AwaitUsing = Const | Using, // Variable declaration (NOTE: on a single node these flags would otherwise be mutually exclusive) - NestedNamespace = 1 << 3, // Namespace declaration - Synthesized = 1 << 4, // Node was synthesized during transformation - Namespace = 1 << 5, // Namespace declaration - OptionalChain = 1 << 6, // Chained MemberExpression rooted to a pseudo-OptionalExpression - ExportContext = 1 << 7, // Export context (initialized by binding) - ContainsThis = 1 << 8, // Interface contains references to "this" - HasImplicitReturn = 1 << 9, // If function implicitly returns on one of codepaths (initialized by binding) - HasExplicitReturn = 1 << 10, // If function has explicit reachable return on one of codepaths (initialized by binding) - GlobalAugmentation = 1 << 11, // Set if module declaration is an augmentation for the global scope - HasAsyncFunctions = 1 << 12, // If the file has async functions (initialized by binding) - DisallowInContext = 1 << 13, // If node was parsed in a context where 'in-expressions' are not allowed - YieldContext = 1 << 14, // If node was parsed in the 'yield' context created when parsing a generator - DecoratorContext = 1 << 15, // If node was parsed as part of a decorator - AwaitContext = 1 << 16, // If node was parsed in the 'await' context created when parsing an async function + None = 0, + Let = 1 << 0, // Variable declaration + Const = 1 << 1, // Variable declaration + Using = 1 << 2, // Variable declaration + AwaitUsing = Const | Using, // Variable declaration (NOTE: on a single node these flags would otherwise be mutually exclusive) + NestedNamespace = 1 << 3, // Namespace declaration + Synthesized = 1 << 4, // Node was synthesized during transformation + Namespace = 1 << 5, // Namespace declaration + OptionalChain = 1 << 6, // Chained MemberExpression rooted to a pseudo-OptionalExpression + ExportContext = 1 << 7, // Export context (initialized by binding) + ContainsThis = 1 << 8, // Interface contains references to "this" + HasImplicitReturn = 1 << 9, // If function implicitly returns on one of codepaths (initialized by binding) + HasExplicitReturn = 1 << 10, // If function has explicit reachable return on one of codepaths (initialized by binding) + GlobalAugmentation = 1 << 11, // Set if module declaration is an augmentation for the global scope + HasAsyncFunctions = 1 << 12, // If the file has async functions (initialized by binding) + DisallowInContext = 1 << 13, // If node was parsed in a context where 'in-expressions' are not allowed + YieldContext = 1 << 14, // If node was parsed in the 'yield' context created when parsing a generator + DecoratorContext = 1 << 15, // If node was parsed as part of a decorator + AwaitContext = 1 << 16, // If node was parsed in the 'await' context created when parsing an async function DisallowConditionalTypesContext = 1 << 17, // If node was parsed in a context where conditional types are not allowed - ThisNodeHasError = 1 << 18, // If the parser encountered an error when parsing the code that created this node - JavaScriptFile = 1 << 19, // If node was parsed in a JavaScript + ThisNodeHasError = 1 << 18, // If the parser encountered an error when parsing the code that created this node + JavaScriptFile = 1 << 19, // If node was parsed in a JavaScript ThisNodeOrAnySubNodesHasError = 1 << 20, // If this node or any of its children had an error HasAggregatedChildData = 1 << 21, // If we've computed data from children and cached it in this node @@ -817,14 +824,14 @@ export const enum NodeFlags { // The advantage of this approach is its simplicity. For the case of batch compilation, // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. /** @internal */ PossiblyContainsDynamicImport = 1 << 22, - /** @internal */ PossiblyContainsImportMeta = 1 << 23, + /** @internal */ PossiblyContainsImportMeta = 1 << 23, - JSDoc = 1 << 24, // If node was parsed inside jsdoc - /** @internal */ Ambient = 1 << 25, // If node was inside an ambient context -- a declaration file, or inside something with the `declare` modifier. - /** @internal */ InWithStatement = 1 << 26, // If any ancestor of node was the `statement` of a WithStatement (not the `expression`) - JsonFile = 1 << 27, // If node was parsed in a Json - /** @internal */ TypeCached = 1 << 28, // If a type was cached for node at any point - /** @internal */ Deprecated = 1 << 29, // If has '@deprecated' JSDoc tag + JSDoc = 1 << 24, // If node was parsed inside jsdoc + /** @internal */ Ambient = 1 << 25, // If node was inside an ambient context -- a declaration file, or inside something with the `declare` modifier. + /** @internal */ InWithStatement = 1 << 26, // If any ancestor of node was the `statement` of a WithStatement (not the `expression`) + JsonFile = 1 << 27, // If node was parsed in a Json + /** @internal */ TypeCached = 1 << 28, // If a type was cached for node at any point + /** @internal */ Deprecated = 1 << 29, // If has '@deprecated' JSDoc tag BlockScoped = Let | Const | Using, Constant = Const | Using, @@ -833,7 +840,14 @@ export const enum NodeFlags { ReachabilityAndEmitFlags = ReachabilityCheckFlags | HasAsyncFunctions, // Parsing context flags - ContextFlags = DisallowInContext | DisallowConditionalTypesContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile | InWithStatement | Ambient, + ContextFlags = DisallowInContext | + DisallowConditionalTypesContext | + YieldContext | + DecoratorContext | + AwaitContext | + JavaScriptFile | + InWithStatement | + Ambient, // Exclude these flags when parsing a Type TypeExcludesFlags = YieldContext | AwaitContext, @@ -841,7 +855,8 @@ export const enum NodeFlags { // Represents all flags that are potentially set once and // never cleared on SourceFiles which get re-used in between incremental parses. // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`. - /** @internal */ PermanentlySetIncrementalFlags = PossiblyContainsDynamicImport | PossiblyContainsImportMeta, + /** @internal */ PermanentlySetIncrementalFlags = PossiblyContainsDynamicImport | + PossiblyContainsImportMeta, // The following flags repurpose other NodeFlags as different meanings for Identifier nodes /** @internal */ IdentifierHasExtendedUnicodeEscape = ContainsThis, // Indicates whether the identifier contains an extended unicode escape sequence @@ -850,36 +865,61 @@ export const enum NodeFlags { // dprint-ignore export const enum ModifierFlags { - None = 0, - Export = 1 << 0, // Declarations - Ambient = 1 << 1, // Declarations - Public = 1 << 2, // Property/Method - Private = 1 << 3, // Property/Method - Protected = 1 << 4, // Property/Method - Static = 1 << 5, // Property/Method - Readonly = 1 << 6, // Property/Method - Accessor = 1 << 7, // Property - Abstract = 1 << 8, // Class/Method/ConstructSignature - Async = 1 << 9, // Property/Method/Function - Default = 1 << 10, // Function/Class (export default declaration) - Const = 1 << 11, // Const enum + None = 0, + Export = 1 << 0, // Declarations + Ambient = 1 << 1, // Declarations + Public = 1 << 2, // Property/Method + Private = 1 << 3, // Property/Method + Protected = 1 << 4, // Property/Method + Static = 1 << 5, // Property/Method + Readonly = 1 << 6, // Property/Method + Accessor = 1 << 7, // Property + Abstract = 1 << 8, // Class/Method/ConstructSignature + Async = 1 << 9, // Property/Method/Function + Default = 1 << 10, // Function/Class (export default declaration) + Const = 1 << 11, // Const enum HasComputedJSDocModifiers = 1 << 12, // Indicates the computed modifier flags include modifiers from JSDoc. - Deprecated = 1 << 13, // Deprecated tag. - Override = 1 << 14, // Override method. - In = 1 << 15, // Contravariance modifier - Out = 1 << 16, // Covariance modifier - Decorator = 1 << 17, // Contains a decorator. - HasComputedFlags = 1 << 29, // Modifier flags have been computed + Deprecated = 1 << 13, // Deprecated tag. + Override = 1 << 14, // Override method. + In = 1 << 15, // Contravariance modifier + Out = 1 << 16, // Covariance modifier + Decorator = 1 << 17, // Contains a decorator. + HasComputedFlags = 1 << 29, // Modifier flags have been computed AccessibilityModifier = Public | Private | Protected, // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. ParameterPropertyModifier = AccessibilityModifier | Readonly | Override, NonPublicAccessibilityModifier = Private | Protected, - TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const | Override | In | Out, + TypeScriptModifier = Ambient | + Public | + Private | + Protected | + Readonly | + Abstract | + Const | + Override | + In | + Out, ExportDefault = Export | Default, - All = Export | Ambient | Public | Private | Protected | Static | Readonly | Abstract | Accessor | Async | Default | Const | Deprecated | Override | In | Out | Decorator, + All = Export | + Ambient | + Public | + Private | + Protected | + Static | + Readonly | + Abstract | + Accessor | + Async | + Default | + Const | + Deprecated | + Override | + In | + Out | + Decorator, Modifier = All & ~Decorator, } @@ -896,19 +936,19 @@ export const enum JsxFlags { // dprint-ignore /** @internal */ export const enum RelationComparisonResult { - Succeeded = 1 << 0, // Should be truthy - Failed = 1 << 1, - Reported = 1 << 2, + Succeeded = 1 << 0, // Should be truthy + Failed = 1 << 1, + Reported = 1 << 2, ReportsUnmeasurable = 1 << 3, - ReportsUnreliable = 1 << 4, - ReportsMask = ReportsUnmeasurable | ReportsUnreliable, + ReportsUnreliable = 1 << 4, + ReportsMask = ReportsUnmeasurable | ReportsUnreliable, } /** @internal */ export type NodeId = number; -export interface Node extends ReadonlyTextRange { +export interface NodeBase extends ReadonlyTextRange { readonly kind: SyntaxKind; readonly flags: NodeFlags; /** @internal */ modifierFlagsCache: ModifierFlags; @@ -923,7 +963,465 @@ export interface Node extends ReadonlyTextRange { // see: https://github.com/microsoft/TypeScript/pull/51682 } -export interface JSDocContainer extends Node { +export type Node = + | Token + | AbstractKeyword + | AccessorKeyword + | AmpersandAmpersandEqualsToken + | ArrayBindingPattern + | ArrayLiteralExpression + | ArrayTypeNode + | ArrowFunction + | AsExpression + | AssertKeyword + | AssertsKeyword + | AsteriskToken + | AsyncKeyword + | AwaitExpression + | AwaitKeyword + | BarBarEqualsToken + | BigIntLiteral + | BinaryExpression + | BinaryOperatorToken + | BindingElement + | Block + | BooleanLiteral + | BreakStatement + | Bundle + | CallExpression + | CallSignatureDeclaration + | CaseBlock + | CaseClause + | CaseKeyword + | CatchClause + | ClassDeclaration + | ClassExpression + | ClassStaticBlockDeclaration + | ColonToken + | CommaListExpression + | ComputedPropertyName + | ConditionalExpression + | ConditionalTypeNode + | ConstKeyword + | ConstructorDeclaration + | ConstructorTypeNode + | ConstructSignatureDeclaration + | ContinueStatement + | DebuggerStatement + | DeclareKeyword + | Decorator + | DefaultClause + | DefaultKeyword + | DeleteExpression + | DoStatement + | DotDotDotToken + | DotToken + | ElementAccessExpression + | EmptyStatement + | EndOfFileToken + | EnumDeclaration + | EnumMember + | EqualsGreaterThanToken + | EqualsToken + | ExclamationToken + | ExportAssignment + | ExportDeclaration + | ExportKeyword + | ExportSpecifier + | Expression + | ExpressionStatement + | ExpressionWithTypeArguments + | ExternalModuleReference + | ForInStatement + | ForOfStatement + | ForStatement + | FunctionDeclaration + | FunctionExpression + | FunctionTypeNode + | GetAccessorDeclaration + | HeritageClause + | Identifier + | IfStatement + | ImportAttribute + | ImportAttributes + | ImportClause + | ImportDeclaration + | ImportEqualsDeclaration + | ImportExpression + | ImportSpecifier + | ImportTypeAssertionContainer + | ImportTypeNode + | IndexedAccessTypeNode + | IndexSignatureDeclaration + | InferTypeNode + | InKeyword + | InputFiles + | InterfaceDeclaration + | IntersectionTypeNode + | JSDoc + | JSDocAllType + | JSDocAugmentsTag + | JSDocAuthorTag + | JSDocCallbackTag + | JSDocClassTag + | JSDocDeprecatedTag + | JSDocEnumTag + | JSDocFunctionType + | JSDocImplementsTag + | JSDocLink + | JSDocLinkCode + | JSDocLinkPlain + | JSDocMemberName + | JSDocNamepathType + | JSDocNameReference + | JSDocNonNullableType + | JSDocNullableType + | JSDocOptionalType + | JSDocOverloadTag + | JSDocOverrideTag + | JSDocParameterTag + | JSDocPrivateTag + | JSDocPropertyTag + | JSDocProtectedTag + | JSDocPublicTag + | JSDocReadonlyTag + | JSDocReturnTag + | JSDocSatisfiesTag + | JSDocSeeTag + | JSDocSignature + | JSDocTemplateTag + | JSDocText + | JSDocThisTag + | JSDocThrowsTag + | JSDocTypedefTag + | JSDocTypeExpression + | JSDocTypeLiteral + | JSDocTypeTag + | JSDocUnknownTag + | JSDocUnknownType + | JSDocVariadicType + | JsxAttribute + | JsxAttributes + | JsxChild + | JsxClosingElement + | JsxClosingFragment + | JsxElement + | JsxExpression + | JsxFragment + | JsxNamespacedName + | JsxOpeningElement + | JsxOpeningFragment + | JsxSelfClosingElement + | JsxSpreadAttribute + | KeywordToken + | LabeledStatement + | LiteralTypeNode + | MappedTypeNode + | MetaProperty + | MethodDeclaration + | MethodSignature + | MinusToken + | MissingDeclaration + | ModuleBlock + | ModuleDeclaration + | NamedExports + | NamedImports + | NamedTupleMember + | NamespaceExport + | NamespaceExportDeclaration + | NamespaceImport + | NewExpression + | NonNullExpression + | NoSubstitutionTemplateLiteral + | NotEmittedStatement + | NullLiteral + | NumericLiteral + | ObjectBindingPattern + | ObjectLiteralExpression + | OmittedExpression + | OptionalTypeNode + | OutKeyword + | OverrideKeyword + | ParameterDeclaration + | ParenthesizedExpression + | ParenthesizedTypeNode + | PartiallyEmittedExpression + | PlusToken + | PostfixUnaryExpression + | PrefixUnaryExpression + | PrivateIdentifier + | PrivateKeyword + | PropertyAccessExpression + | PropertyAssignment + | PropertyDeclaration + | PropertySignature + | ProtectedKeyword + | PublicKeyword + | QualifiedName + | QuestionDotToken + | QuestionQuestionEqualsToken + | QuestionToken + | ReadonlyKeyword + | RegularExpressionLiteral + | RestTypeNode + | ReturnStatement + | SatisfiesExpression + | SemicolonClassElement + | SetAccessorDeclaration + | ShorthandPropertyAssignment + | SourceFile + | SpreadAssignment + | SpreadElement + | StaticKeyword + | StringLiteral + | SuperExpression + | SwitchStatement + | SyntaxList + | SyntheticExpression + | SyntheticReferenceExpression + | TaggedTemplateExpression + | TemplateExpression + | TemplateHead + | TemplateLiteral + | UnparsedSource + | TemplateLiteralTypeNode + | TemplateLiteralTypeSpan + | TemplateMiddle + | TemplateSpan + | TemplateTail + | ThisExpression + | ThisTypeNode + | ThrowStatement + | TryStatement + | TupleTypeNode + | TypeAliasDeclaration + | TypeAssertion + | TypeLiteralNode + | TypeOfExpression + | TypeOperatorNode + | TypeParameterDeclaration + | TypePredicateNode + | TypeQueryNode + | TypeReferenceNode + | UnionTypeNode + | UnparsedPrepend + | UnparsedPrologue + | UnparsedSource + | UnparsedSyntheticReference + | UnparsedTextLike + | VariableDeclaration + | VariableDeclarationList + | VariableStatement + | VoidExpression + | WhileStatement + | WithStatement + | YieldExpression; + +export type Declaration = + | ArrowFunction + | BinaryExpression + | BindingElement + | CallExpression + | CallSignatureDeclaration + | ClassDeclaration + | ClassExpression + | ClassStaticBlockDeclaration + | ConstructorDeclaration + | ConstructorTypeNode + | ConstructSignatureDeclaration + | ElementAccessExpression + | EnumDeclaration + | EnumMember + | ExportAssignment + | ExportDeclaration + | ExportSpecifier + | FunctionDeclaration + | FunctionExpression + | FunctionTypeNode + | GetAccessorDeclaration + | Identifier + | ImportClause + | ImportDeclaration + | ImportEqualsDeclaration + | ImportSpecifier + | IndexSignatureDeclaration + | InterfaceDeclaration + | JSDocCallbackTag + | JSDocEnumTag + | JSDocFunctionType + | JSDocParameterTag + | JSDocPropertyTag + | JSDocSignature + | JSDocTypedefTag + | JSDocTypeLiteral + | JsxAttribute + | JsxAttributes + | JsxSpreadAttribute + | MappedTypeNode + | MethodDeclaration + | MethodSignature + | MissingDeclaration + | ModuleDeclaration + | NamedTupleMember + | NamespaceExport + | NamespaceExportDeclaration + | NamespaceImport + | NewExpression + | NoSubstitutionTemplateLiteral + | NumericLiteral + | ObjectLiteralExpression + | ParameterDeclaration + | PropertyAccessExpression + | PropertyAssignment + | PropertyDeclaration + | PropertySignature + | SetAccessorDeclaration + | ShorthandPropertyAssignment + | SourceFile + | SpreadAssignment + | StringLiteral + | TypeAliasDeclaration + | TypeLiteralNode + | TypeParameterDeclaration + | VariableDeclaration; + +export type Expression = + | KeywordToken // ?! + | ArrayLiteralExpression + | ArrowFunction // ?! + | AsExpression + | AwaitExpression + | BigIntLiteral + | BinaryExpression + | BooleanLiteral + | CallExpression + | ClassExpression + | CommaListExpression + | ConditionalExpression + | DeleteExpression + | ElementAccessExpression + | ExpressionWithTypeArguments + | FunctionExpression + | Identifier + | ImportExpression + | JSDocEnumTag + | JSDocParameterTag + | JSDocPropertyTag + | JSDocTypedefTag + | JSDocTypeExpression + | JsxAttributes + | JsxAttributeValue + | JsxExpression + | JsxText + | MetaProperty + | NewExpression + | NonNullExpression + | NoSubstitutionTemplateLiteral + | NullLiteral + | NumericLiteral + | ObjectLiteralExpression + | OmittedExpression + | ParenthesizedExpression + | PartiallyEmittedExpression + | PostfixUnaryExpression + | PrefixUnaryExpression + | PrivateIdentifier + | PropertyAccessExpression + | RegularExpressionLiteral + | SatisfiesExpression + | SpreadElement + | StringLiteral + | SuperExpression + | SyntheticExpression + | SyntheticReferenceExpression + | TaggedTemplateExpression + | TemplateExpression + | TemplateHead + | TemplateLiteral + | TemplateMiddle + | TemplateTail + | ThisExpression + | TypeAssertion + | TypeOfExpression + | VoidExpression + | YieldExpression; + +export type LeftHandSideExpression = + | KeywordToken // ?! + | PrivateIdentifier + | TaggedTemplateExpression + | TemplateExpression + | ArrayLiteralExpression + | BigIntLiteral + | CallExpression + | ClassExpression + | ElementAccessExpression + | ExpressionWithTypeArguments + | FunctionExpression + | Identifier + | ImportExpression + | JsxAttributes + | JsxElement + | JsxFragment + | JsxSelfClosingElement + | JsxTagNamePropertyAccess + | MetaProperty + | NewExpression + | NonNullExpression + | ObjectLiteralExpression + | ParenthesizedExpression + | PropertyAccessEntityNameExpression + | PropertyAccessExpression + | StringLiteral + | SuperExpression + | SyntheticReferenceExpression + | ThisExpression; + +export type MemberExpression = + | ArrayLiteralExpression + | ElementAccessExpression + | ExpressionWithTypeArguments + | FalseLiteral + | FunctionExpression + | Identifier + | ImportExpression + | JsxAttributes + | JsxElement + | JsxFragment + | JsxSelfClosingElement + | MetaProperty + | NewExpression + | NullLiteral + | ObjectLiteralExpression + | ParenthesizedExpression + | PrivateIdentifier + | PropertyAccessExpression + | SuperExpression + | TaggedTemplateExpression + | TemplateExpression + | ThisExpression + | TrueLiteral; + +export type UnaryExpression = + | ArrayLiteralExpression // ?! + | CallExpression // ?! + | JsxElement // ?! + | JsxFragment // ?! + | JsxSelfClosingElement // ?! + | UpdateExpression // ?! + | AwaitExpression + | BigIntLiteral + | DeleteExpression + | Identifier + | NumericLiteral + | ParenthesizedExpression + | PrefixUnaryExpression + | PropertyAccessExpression + | TypeAssertion + | TypeOfExpression + | VoidExpression; + +export interface JSDocContainer extends NodeBase { _jsdocContainerBrand: any; /** @internal */ jsDoc?: JSDocArray; // JSDoc that directly precedes this node } @@ -933,13 +1431,13 @@ export interface JSDocArray extends Array { jsDocCache?: readonly JSDocTag[]; // Cache for getJSDocTags } -export interface LocalsContainer extends Node { +export interface LocalsContainer extends NodeBase { _localsContainerBrand: any; /** @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding) /** @internal */ nextContainer?: HasLocals; // Next container in declaration order (initialized by binding) } -export interface FlowContainer extends Node { +export interface FlowContainer extends NodeBase { _flowContainerBrand: any; /** @internal */ flowNode?: FlowNode; // Associated FlowNode (initialized by binding) } @@ -1252,9 +1750,7 @@ export type HasType = // NOTE: Changing the following list requires changes to: // - `canHaveIllegalType` in factory/utilities.ts /** @internal */ -export type HasIllegalType = - | ConstructorDeclaration - | SetAccessorDeclaration; +export type HasIllegalType = ConstructorDeclaration | SetAccessorDeclaration; // NOTE: Changing the following list requires changes to: // - `canHaveIllegalTypeParameters` in factory/utilities.ts @@ -1464,9 +1960,7 @@ export type IsFunctionLike = * * @internal */ -export type IsFunctionExpression = - | FunctionExpression - | ArrowFunction; +export type IsFunctionExpression = FunctionExpression | ArrowFunction; /** * Nodes that can have local symbols. Corresponds with `ContainerFlags.HasLocals`. Constituents should extend @@ -1539,26 +2033,24 @@ export type HasContainerFlags = | IsObjectLiteralOrClassExpressionMethodOrAccessor; /** @internal */ -export interface MutableNodeArray extends Array, TextRange { +export interface MutableNodeArray extends Array, TextRange { hasTrailingComma: boolean; /** @internal */ transformFlags: TransformFlags; // Flags for transforms, possibly undefined } -export interface NodeArray extends ReadonlyArray, ReadonlyTextRange { +export interface NodeArray extends ReadonlyArray, ReadonlyTextRange { readonly hasTrailingComma: boolean; /** @internal */ transformFlags: TransformFlags; // Flags for transforms, possibly undefined } -// TODO(rbuckton): Constraint 'TKind' to 'TokenSyntaxKind' -export interface Token extends Node { +export interface Token extends NodeBase { readonly kind: TKind; } export type EndOfFileToken = Token & JSDocContainer; // Punctuation -export interface PunctuationToken extends Token { -} +export interface PunctuationToken extends Token {} export type DotToken = PunctuationToken; export type DotDotDotToken = PunctuationToken; @@ -1576,16 +2068,14 @@ export type MinusToken = PunctuationToken; export type QuestionDotToken = PunctuationToken; // Keywords -export interface KeywordToken extends Token { -} +export interface KeywordToken extends Token {} export type AssertsKeyword = KeywordToken; export type AssertKeyword = KeywordToken; export type AwaitKeyword = KeywordToken; export type CaseKeyword = KeywordToken; -export interface ModifierToken extends KeywordToken { -} +export interface ModifierToken extends KeywordToken {} export type AbstractKeyword = ModifierToken; export type AccessorKeyword = ModifierToken; @@ -1627,9 +2117,7 @@ export type AccessibilityModifier = | PrivateKeyword | ProtectedKeyword; -export type ParameterPropertyModifier = - | AccessibilityModifier - | ReadonlyKeyword; +export type ParameterPropertyModifier = AccessibilityModifier | ReadonlyKeyword; export type ClassMemberModifier = | AccessibilityModifier @@ -1642,21 +2130,21 @@ export type ModifiersArray = NodeArray; // dprint-ignore export const enum GeneratedIdentifierFlags { // Kinds - None = 0, // Not automatically generated. - /** @internal */ Auto = 1, // Automatically generated identifier. - /** @internal */ Loop = 2, // Automatically generated identifier with a preference for '_i'. - /** @internal */ Unique = 3, // Unique name based on the 'text' property. - /** @internal */ Node = 4, // Unique name based on the node in the 'original' property. - /** @internal */ KindMask = 7, // Mask to extract the kind of identifier from its flags. + None = 0, // Not automatically generated. + /** @internal */ Auto = 1, // Automatically generated identifier. + /** @internal */ Loop = 2, // Automatically generated identifier with a preference for '_i'. + /** @internal */ Unique = 3, // Unique name based on the 'text' property. + /** @internal */ Node = 4, // Unique name based on the node in the 'original' property. + /** @internal */ KindMask = 7, // Mask to extract the kind of identifier from its flags. // Flags - ReservedInNestedScopes = 1 << 3, // Reserve the generated name in nested scopes - Optimistic = 1 << 4, // First instance won't use '_#' if there's no conflict - FileLevel = 1 << 5, // Use only the file identifiers list and not generated names to search for conflicts + ReservedInNestedScopes = 1 << 3, // Reserve the generated name in nested scopes + Optimistic = 1 << 4, // First instance won't use '_#' if there's no conflict + FileLevel = 1 << 5, // Use only the file identifiers list and not generated names to search for conflicts AllowNameSubstitution = 1 << 6, // Used by `module.ts` to indicate generated nodes which can have substitutions performed upon them (as they were generated by an earlier transform phase) } -export interface Identifier extends PrimaryExpression, Declaration, JSDocContainer, FlowContainer { +export interface Identifier extends PrimaryExpressionBase, DeclarationBase, JSDocContainer, FlowContainer { readonly kind: SyntaxKind.Identifier; /** * Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.) @@ -1673,8 +2161,8 @@ export interface TransientIdentifier extends Identifier { // dprint-ignore /** @internal */ export interface AutoGenerateInfo { - flags: GeneratedIdentifierFlags; // Specifies whether to auto-generate the text for an identifier. - readonly id: number; // Ensures unique generated identifiers get unique names, but clones get the same name. + flags: GeneratedIdentifierFlags; // Specifies whether to auto-generate the text for an identifier. + readonly id: number; // Ensures unique generated identifiers get unique names, but clones get the same name. readonly prefix?: string | GeneratedNamePart; readonly suffix?: string; } @@ -1684,7 +2172,7 @@ export interface GeneratedIdentifier extends Identifier { readonly emitNode: EmitNode & { autoGenerate: AutoGenerateInfo; }; } -export interface QualifiedName extends Node, FlowContainer { +export interface QualifiedName extends NodeBase, FlowContainer { readonly kind: SyntaxKind.QualifiedName; readonly left: EntityName; readonly right: Identifier; @@ -1692,7 +2180,13 @@ export interface QualifiedName extends Node, FlowContainer { export type EntityName = Identifier | QualifiedName; -export type PropertyName = Identifier | StringLiteral | NoSubstitutionTemplateLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; +export type PropertyName = + | Identifier + | StringLiteral + | NoSubstitutionTemplateLiteral + | NumericLiteral + | ComputedPropertyName + | PrivateIdentifier; export type MemberName = Identifier | PrivateIdentifier; @@ -1704,23 +2198,45 @@ export type DeclarationName = | BindingPattern | EntityNameExpression; -export interface Declaration extends Node { +export interface DeclarationBase extends NodeBase { _declarationBrand: any; /** @internal */ symbol: Symbol; // Symbol declared by node (initialized by binding) /** @internal */ localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes) } -export interface NamedDeclaration extends Declaration { +export type NamedDeclaration = + | BindingElement + | ClassElement + | ClassLikeDeclaration + | DeclarationStatement + | EnumMember + | ExportSpecifier + | ImportClause + // | ImportDeclaration + | ImportSpecifier + | JSDocCallbackTag + | JSDocTypedefTag + | NamespaceExport + | NamespaceImport + // | ObjectLiteralElement + | ParameterDeclaration + | PropertyAccessExpression + | SignatureDeclaration + | TypeElement + | TypeParameterDeclaration + | VariableDeclaration; + +export interface NamedDeclarationBase extends DeclarationBase { readonly name?: DeclarationName; } /** @internal */ -export interface DynamicNamedDeclaration extends NamedDeclaration { +export interface DynamicNamedDeclaration extends NamedDeclarationBase { readonly name: ComputedPropertyName; } /** @internal */ -export interface DynamicNamedBinaryExpression extends BinaryExpression { +export interface DynamicNamedBinaryExpressionBase extends BinaryExpression { readonly left: ElementAccessExpression; } @@ -1731,7 +2247,7 @@ export interface LateBoundDeclaration extends DynamicNamedDeclaration { } /** @internal */ -export interface LateBoundBinaryExpressionDeclaration extends DynamicNamedBinaryExpression { +export interface LateBoundBinaryExpressionDeclarationBase extends DynamicNamedBinaryExpressionBase { readonly left: LateBoundElementAccessExpression; } @@ -1740,18 +2256,18 @@ export interface LateBoundElementAccessExpression extends ElementAccessExpressio readonly argumentExpression: EntityNameExpression; } -export interface DeclarationStatement extends NamedDeclaration, Statement { +export interface DeclarationStatementBase extends NamedDeclarationBase, StatementBase { readonly name?: Identifier | StringLiteral | NumericLiteral; } -export interface ComputedPropertyName extends Node { +export interface ComputedPropertyName extends NodeBase { readonly kind: SyntaxKind.ComputedPropertyName; readonly parent: Declaration; readonly expression: Expression; } // Typed as a PrimaryExpression due to its presence in BinaryExpressions (#field in expr) -export interface PrivateIdentifier extends PrimaryExpression { +export interface PrivateIdentifier extends PrimaryExpressionBase { readonly kind: SyntaxKind.PrivateIdentifier; // escaping not strictly necessary // avoids gotchas in transforms and utils @@ -1769,13 +2285,13 @@ export interface LateBoundName extends ComputedPropertyName { readonly expression: EntityNameExpression; } -export interface Decorator extends Node { +export interface Decorator extends NodeBase { readonly kind: SyntaxKind.Decorator; - readonly parent: NamedDeclaration; + readonly parent: NamedDeclarationBase & Node; readonly expression: LeftHandSideExpression; } -export interface TypeParameterDeclaration extends NamedDeclaration, JSDocContainer { +export interface TypeParameterDeclaration extends NamedDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.TypeParameter; readonly parent: DeclarationWithTypeParameterChildren | InferTypeNode; readonly modifiers?: NodeArray; @@ -1788,7 +2304,7 @@ export interface TypeParameterDeclaration extends NamedDeclaration, JSDocContain expression?: Expression; } -export interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer { +export interface SignatureDeclarationBase extends NamedDeclarationBase, JSDocContainer { readonly kind: SignatureDeclaration["kind"]; readonly name?: PropertyName; readonly typeParameters?: NodeArray | undefined; @@ -1812,83 +2328,98 @@ export type SignatureDeclaration = | FunctionExpression | ArrowFunction; -export interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement, LocalsContainer { +export type TypeElement = + | CallSignatureDeclaration + | ConstructSignatureDeclaration + | GetAccessorDeclaration + | IndexSignatureDeclaration + | MethodSignature + | PropertySignature + | SetAccessorDeclaration; + +export interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElementBase, LocalsContainer { readonly kind: SyntaxKind.CallSignature; } -export interface ConstructSignatureDeclaration extends SignatureDeclarationBase, TypeElement, LocalsContainer { +export interface ConstructSignatureDeclaration extends SignatureDeclarationBase, TypeElementBase, LocalsContainer { readonly kind: SyntaxKind.ConstructSignature; } export type BindingName = Identifier | BindingPattern; // dprint-ignore -export interface VariableDeclaration extends NamedDeclaration, JSDocContainer { +export interface VariableDeclaration extends NamedDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.VariableDeclaration; readonly parent: VariableDeclarationList | CatchClause; - readonly name: BindingName; // Declared variable name - readonly exclamationToken?: ExclamationToken; // Optional definite assignment assertion - readonly type?: TypeNode; // Optional type annotation - readonly initializer?: Expression; // Optional initializer + readonly name: BindingName; // Declared variable name + readonly exclamationToken?: ExclamationToken; // Optional definite assignment assertion + readonly type?: TypeNode; // Optional type annotation + readonly initializer?: Expression; // Optional initializer } /** @internal */ -export type InitializedVariableDeclaration = VariableDeclaration & { readonly initializer: Expression; }; +export type InitializedVariableDeclaration = VariableDeclaration & { + readonly initializer: Expression; +}; -export interface VariableDeclarationList extends Node { +export interface VariableDeclarationList extends NodeBase { readonly kind: SyntaxKind.VariableDeclarationList; - readonly parent: VariableStatement | ForStatement | ForOfStatement | ForInStatement; + readonly parent: + | VariableStatement + | ForStatement + | ForOfStatement + | ForInStatement; readonly declarations: NodeArray; } // dprint-ignore -export interface ParameterDeclaration extends NamedDeclaration, JSDocContainer { +export interface ParameterDeclaration extends NamedDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.Parameter; readonly parent: SignatureDeclaration; readonly modifiers?: NodeArray; - readonly dotDotDotToken?: DotDotDotToken; // Present on rest parameter - readonly name: BindingName; // Declared parameter name. - readonly questionToken?: QuestionToken; // Present on optional parameter - readonly type?: TypeNode; // Optional type annotation - readonly initializer?: Expression; // Optional initializer + readonly dotDotDotToken?: DotDotDotToken; // Present on rest parameter + readonly name: BindingName; // Declared parameter name. + readonly questionToken?: QuestionToken; // Present on optional parameter + readonly type?: TypeNode; // Optional type annotation + readonly initializer?: Expression; // Optional initializer } // dprint-ignore -export interface BindingElement extends NamedDeclaration, FlowContainer { +export interface BindingElement extends NamedDeclarationBase, FlowContainer { readonly kind: SyntaxKind.BindingElement; readonly parent: BindingPattern; - readonly propertyName?: PropertyName; // Binding property name (in object binding pattern) - readonly dotDotDotToken?: DotDotDotToken; // Present on rest element (in object binding pattern) - readonly name: BindingName; // Declared binding element name - readonly initializer?: Expression; // Optional initializer + readonly propertyName?: PropertyName; // Binding property name (in object binding pattern) + readonly dotDotDotToken?: DotDotDotToken; // Present on rest element (in object binding pattern) + readonly name: BindingName; // Declared binding element name + readonly initializer?: Expression; // Optional initializer } /** @internal */ export type BindingElementGrandparent = BindingElement["parent"]["parent"]; // dprint-ignore -export interface PropertySignature extends TypeElement, JSDocContainer { +export interface PropertySignature extends TypeElementBase, JSDocContainer { readonly kind: SyntaxKind.PropertySignature; readonly parent: TypeLiteralNode | InterfaceDeclaration; readonly modifiers?: NodeArray; - readonly name: PropertyName; // Declared property name - readonly questionToken?: QuestionToken; // Present on optional property - readonly type?: TypeNode; // Optional type annotation + readonly name: PropertyName; // Declared property name + readonly questionToken?: QuestionToken; // Present on optional property + readonly type?: TypeNode; // Optional type annotation // The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts) /** @internal */ readonly initializer?: Expression | undefined; // A property signature cannot have an initializer } // dprint-ignore -export interface PropertyDeclaration extends ClassElement, JSDocContainer { +export interface PropertyDeclaration extends ClassElementBase, JSDocContainer { readonly kind: SyntaxKind.PropertyDeclaration; readonly parent: ClassLikeDeclaration; readonly modifiers?: NodeArray; readonly name: PropertyName; - readonly questionToken?: QuestionToken; // Present for use with reporting a grammar error for auto-accessors (see `isGrammarError` in utilities.ts) + readonly questionToken?: QuestionToken; // Present for use with reporting a grammar error for auto-accessors (see `isGrammarError` in utilities.ts) readonly exclamationToken?: ExclamationToken; readonly type?: TypeNode; - readonly initializer?: Expression; // Optional initializer + readonly initializer?: Expression; // Optional initializer } export interface AutoAccessorPropertyDeclaration extends PropertyDeclaration { @@ -1916,7 +2447,9 @@ export interface PrivateIdentifierSetAccessorDeclaration extends SetAccessorDecl name: PrivateIdentifier; } /** @internal */ -export type PrivateIdentifierAccessorDeclaration = PrivateIdentifierGetAccessorDeclaration | PrivateIdentifierSetAccessorDeclaration; +export type PrivateIdentifierAccessorDeclaration = + | PrivateIdentifierGetAccessorDeclaration + | PrivateIdentifierSetAccessorDeclaration; /** @internal */ export type PrivateClassElementDeclaration = | PrivateIdentifierPropertyDeclaration @@ -1926,14 +2459,26 @@ export type PrivateClassElementDeclaration = | PrivateIdentifierSetAccessorDeclaration; /** @internal */ -export type InitializedPropertyDeclaration = PropertyDeclaration & { readonly initializer: Expression; }; +export type InitializedPropertyDeclaration = PropertyDeclaration & { + readonly initializer: Expression; +}; + +export type ObjectLiteralElement = + | GetAccessorDeclaration + | JsxSpreadAttribute + | MethodDeclaration + | ObjectLiteralExpression + | PropertyAssignment + | SetAccessorDeclaration + | ShorthandPropertyAssignment + | SpreadAssignment; -export interface ObjectLiteralElement extends NamedDeclaration { +export interface ObjectLiteralElementBase extends NamedDeclarationBase { _objectLiteralBrand: any; readonly name?: PropertyName; } -/** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */ +/** Unlike ObjectLiteralElementBase, excludes JSXAttribute and JSXSpreadAttribute. */ export type ObjectLiteralElementLike = | PropertyAssignment | ShorthandPropertyAssignment @@ -1941,7 +2486,7 @@ export type ObjectLiteralElementLike = | MethodDeclaration | AccessorDeclaration; -export interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer { +export interface PropertyAssignment extends ObjectLiteralElementBase, JSDocContainer { readonly kind: SyntaxKind.PropertyAssignment; readonly parent: ObjectLiteralExpression; readonly name: PropertyName; @@ -1953,7 +2498,7 @@ export interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer /** @internal */ readonly exclamationToken?: ExclamationToken | undefined; // property assignment cannot have an exclamation token } -export interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer { +export interface ShorthandPropertyAssignment extends ObjectLiteralElementBase, JSDocContainer { readonly kind: SyntaxKind.ShorthandPropertyAssignment; readonly parent: ObjectLiteralExpression; readonly name: Identifier; @@ -1968,7 +2513,7 @@ export interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDoc /** @internal */ readonly exclamationToken?: ExclamationToken | undefined; // shorthand property assignment cannot have an exclamation token } -export interface SpreadAssignment extends ObjectLiteralElement, JSDocContainer { +export interface SpreadAssignment extends ObjectLiteralElementBase, JSDocContainer { readonly kind: SyntaxKind.SpreadAssignment; readonly parent: ObjectLiteralExpression; readonly expression: Expression; @@ -1987,15 +2532,21 @@ export type VariableLikeDeclaration = | JSDocPropertyTag | JSDocParameterTag; -export interface ObjectBindingPattern extends Node { +export interface ObjectBindingPattern extends NodeBase { readonly kind: SyntaxKind.ObjectBindingPattern; - readonly parent: VariableDeclaration | ParameterDeclaration | BindingElement; + readonly parent: + | VariableDeclaration + | ParameterDeclaration + | BindingElement; readonly elements: NodeArray; } -export interface ArrayBindingPattern extends Node { +export interface ArrayBindingPattern extends NodeBase { readonly kind: SyntaxKind.ArrayBindingPattern; - readonly parent: VariableDeclaration | ParameterDeclaration | BindingElement; + readonly parent: + | VariableDeclaration + | ParameterDeclaration + | BindingElement; readonly elements: NodeArray; } @@ -2033,21 +2584,21 @@ export type FunctionLikeDeclaration = /** @deprecated Use SignatureDeclaration */ export type FunctionLike = SignatureDeclaration; -export interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement, LocalsContainer { +export interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatementBase, LocalsContainer { readonly kind: SyntaxKind.FunctionDeclaration; readonly modifiers?: NodeArray; readonly name?: Identifier; readonly body?: FunctionBody; } -export interface MethodSignature extends SignatureDeclarationBase, TypeElement, LocalsContainer { +export interface MethodSignature extends SignatureDeclarationBase, TypeElementBase, LocalsContainer { readonly kind: SyntaxKind.MethodSignature; readonly parent: TypeLiteralNode | InterfaceDeclaration; readonly modifiers?: NodeArray; readonly name: PropertyName; } -// Note that a MethodDeclaration is considered both a ClassElement and an ObjectLiteralElement. +// Note that a MethodDeclaration is considered both a ClassElementBase and an ObjectLiteralElementBase. // Both the grammars for ClassDeclaration and ObjectLiteralExpression allow for MethodDeclarations // as child elements, and so a MethodDeclaration satisfies both interfaces. This avoids the // alternative where we would need separate kinds/types for ClassMethodDeclaration and @@ -2056,7 +2607,7 @@ export interface MethodSignature extends SignatureDeclarationBase, TypeElement, // Because of this, it may be necessary to determine what sort of MethodDeclaration you have // at later stages of the compiler pipeline. In that case, you can either check the parent kind // of the method, or use helpers like isObjectLiteralMethodDeclaration -export interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer, LocalsContainer, FlowContainer { +export interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElementBase, ObjectLiteralElementBase, JSDocContainer, LocalsContainer, FlowContainer { readonly kind: SyntaxKind.MethodDeclaration; readonly parent: ClassLikeDeclaration | ObjectLiteralExpression; readonly modifiers?: NodeArray | undefined; @@ -2067,7 +2618,7 @@ export interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassEle /** @internal */ readonly exclamationToken?: ExclamationToken | undefined; // A method cannot have an exclamation token } -export interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer, LocalsContainer { +export interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElementBase, JSDocContainer, LocalsContainer { readonly kind: SyntaxKind.Constructor; readonly parent: ClassLikeDeclaration; readonly modifiers?: NodeArray | undefined; @@ -2079,48 +2630,62 @@ export interface ConstructorDeclaration extends FunctionLikeDeclarationBase, Cla } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ -export interface SemicolonClassElement extends ClassElement, JSDocContainer { +export interface SemicolonClassElement extends ClassElementBase, JSDocContainer { readonly kind: SyntaxKind.SemicolonClassElement; readonly parent: ClassLikeDeclaration; } // See the comment on MethodDeclaration for the intuition behind GetAccessorDeclaration being a -// ClassElement and an ObjectLiteralElement. -export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer, LocalsContainer, FlowContainer { +// ClassElementBase and an ObjectLiteralElementBase. +export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElementBase, TypeElementBase, ObjectLiteralElementBase, JSDocContainer, LocalsContainer, FlowContainer { readonly kind: SyntaxKind.GetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; + readonly parent: + | ClassLikeDeclaration + | ObjectLiteralExpression + | TypeLiteralNode + | InterfaceDeclaration; readonly modifiers?: NodeArray; readonly name: PropertyName; readonly body?: FunctionBody; // The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts) - /** @internal */ readonly typeParameters?: NodeArray | undefined; // A get accessor cannot have type parameters + /** @internal */ readonly typeParameters?: + | NodeArray + | undefined; // A get accessor cannot have type parameters } // See the comment on MethodDeclaration for the intuition behind SetAccessorDeclaration being a -// ClassElement and an ObjectLiteralElement. -export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer, LocalsContainer, FlowContainer { +// ClassElementBase and an ObjectLiteralElementBase. +export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElementBase, TypeElementBase, ObjectLiteralElementBase, JSDocContainer, LocalsContainer, FlowContainer { readonly kind: SyntaxKind.SetAccessor; - readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration; + readonly parent: + | ClassLikeDeclaration + | ObjectLiteralExpression + | TypeLiteralNode + | InterfaceDeclaration; readonly modifiers?: NodeArray; readonly name: PropertyName; readonly body?: FunctionBody; // The following properties are used only to report grammar errors (see `isGrammarError` in utilities.ts) - /** @internal */ readonly typeParameters?: NodeArray | undefined; // A set accessor cannot have type parameters + /** @internal */ readonly typeParameters?: + | NodeArray + | undefined; // A set accessor cannot have type parameters /** @internal */ readonly type?: TypeNode | undefined; // A set accessor cannot have a return type } -export type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; +export type AccessorDeclaration = + | GetAccessorDeclaration + | SetAccessorDeclaration; -export interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement, LocalsContainer { +export interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElementBase, TypeElementBase, LocalsContainer { readonly kind: SyntaxKind.IndexSignature; readonly parent: ObjectTypeDeclaration; readonly modifiers?: NodeArray; readonly type: TypeNode; } -export interface ClassStaticBlockDeclaration extends ClassElement, JSDocContainer, LocalsContainer { +export interface ClassStaticBlockDeclaration extends ClassElementBase, JSDocContainer, LocalsContainer { readonly kind: SyntaxKind.ClassStaticBlockDeclaration; readonly parent: ClassDeclaration | ClassExpression; readonly body: Block; @@ -2132,28 +2697,67 @@ export interface ClassStaticBlockDeclaration extends ClassElement, JSDocContaine /** @internal */ readonly modifiers?: NodeArray | undefined; } -export interface TypeNode extends Node { +export type TypeNode = + | ArrayTypeNode + | ConditionalTypeNode + | ConstructorTypeNode + | FunctionTypeNode + | ImportTypeNode + | IndexedAccessTypeNode + | InferTypeNode + | IntersectionTypeNode + | JSDocAllType + | JSDocFunctionType + | JSDocNamepathType + | JSDocNonNullableType + | JSDocNullableType + | JSDocOptionalType + | JSDocTypeExpression + | JSDocVariadicType + | JSDocUnknownType + | JSDocVariadicType + | KeywordTypeNode + | LiteralTypeNode + | MappedTypeNode + | NamedTupleMember + | OptionalTypeNode + | ParenthesizedTypeNode + | RestTypeNode + | TemplateLiteralTypeNode + | TemplateLiteralTypeSpan + | ThisTypeNode + | TupleTypeNode + | TypeLiteralNode + | TypeOperatorNode + | TypePredicateNode + | TypeQueryNode + | TypeReferenceNode + | UnionTypeNode; + +export interface TypeNodeBase extends NodeBase { _typeNodeBrand: any; } /** @internal */ -export interface TypeNode extends Node { +export interface TypeNodeBase extends NodeBase { readonly kind: TypeNodeSyntaxKind; } -export interface KeywordTypeNode extends KeywordToken, TypeNode { +export interface KeywordTypeNode< + TKind extends KeywordTypeSyntaxKind = KeywordTypeSyntaxKind, +> extends KeywordToken, TypeNodeBase { readonly kind: TKind; } /** @deprecated */ -export interface ImportTypeAssertionContainer extends Node { +export interface ImportTypeAssertionContainer extends NodeBase { readonly kind: SyntaxKind.ImportTypeAssertionContainer; readonly parent: ImportTypeNode; /** @deprecated */ readonly assertClause: AssertClause; readonly multiLine?: boolean; } -export interface ImportTypeNode extends NodeWithTypeArguments { +export interface ImportTypeNode extends NodeWithTypeArgumentsBase { readonly kind: SyntaxKind.ImportType; readonly isTypeOf: boolean; readonly argument: TypeNode; @@ -2163,15 +2767,19 @@ export interface ImportTypeNode extends NodeWithTypeArguments { } /** @internal */ -export type LiteralImportTypeNode = ImportTypeNode & { readonly argument: LiteralTypeNode & { readonly literal: StringLiteral; }; }; +export type LiteralImportTypeNode = ImportTypeNode & { + readonly argument: LiteralTypeNode & { readonly literal: StringLiteral; }; +}; -export interface ThisTypeNode extends TypeNode { +export interface ThisTypeNode extends TypeNodeBase { readonly kind: SyntaxKind.ThisType; } -export type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode; +export type FunctionOrConstructorTypeNode = + | FunctionTypeNode + | ConstructorTypeNode; -export interface FunctionOrConstructorTypeNodeBase extends TypeNode, SignatureDeclarationBase { +export interface FunctionOrConstructorTypeNodeBase extends TypeNodeBase, SignatureDeclarationBase { readonly kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; readonly type: TypeNode; } @@ -2188,18 +2796,25 @@ export interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase, readonly modifiers?: NodeArray; } -export interface NodeWithTypeArguments extends TypeNode { +export type NodeWithTypeArguments = + | ExpressionWithTypeArguments + | ImportTypeNode + // | NodeWithTypeArgumentsBase + | TypeQueryNode + | TypeReferenceNode; + +export interface NodeWithTypeArgumentsBase extends TypeNodeBase { readonly typeArguments?: NodeArray; } export type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments; -export interface TypeReferenceNode extends NodeWithTypeArguments { +export interface TypeReferenceNode extends NodeWithTypeArgumentsBase { readonly kind: SyntaxKind.TypeReference; readonly typeName: EntityName; } -export interface TypePredicateNode extends TypeNode { +export interface TypePredicateNode extends TypeNodeBase { readonly kind: SyntaxKind.TypePredicate; readonly parent: SignatureDeclaration | JSDocTypeExpression; readonly assertsModifier?: AssertsKeyword; @@ -2207,28 +2822,28 @@ export interface TypePredicateNode extends TypeNode { readonly type?: TypeNode; } -export interface TypeQueryNode extends NodeWithTypeArguments { +export interface TypeQueryNode extends NodeWithTypeArgumentsBase { readonly kind: SyntaxKind.TypeQuery; readonly exprName: EntityName; } // A TypeLiteral is the declaration node for an anonymous symbol. -export interface TypeLiteralNode extends TypeNode, Declaration { +export interface TypeLiteralNode extends TypeNodeBase, DeclarationBase { readonly kind: SyntaxKind.TypeLiteral; readonly members: NodeArray; } -export interface ArrayTypeNode extends TypeNode { +export interface ArrayTypeNode extends TypeNodeBase { readonly kind: SyntaxKind.ArrayType; readonly elementType: TypeNode; } -export interface TupleTypeNode extends TypeNode { +export interface TupleTypeNode extends TypeNodeBase { readonly kind: SyntaxKind.TupleType; readonly elements: NodeArray; } -export interface NamedTupleMember extends TypeNode, Declaration, JSDocContainer { +export interface NamedTupleMember extends TypeNodeBase, DeclarationBase, JSDocContainer { readonly kind: SyntaxKind.NamedTupleMember; readonly dotDotDotToken?: Token; readonly name: Identifier; @@ -2236,29 +2851,29 @@ export interface NamedTupleMember extends TypeNode, Declaration, JSDocContainer readonly type: TypeNode; } -export interface OptionalTypeNode extends TypeNode { +export interface OptionalTypeNode extends TypeNodeBase { readonly kind: SyntaxKind.OptionalType; readonly type: TypeNode; } -export interface RestTypeNode extends TypeNode { +export interface RestTypeNode extends TypeNodeBase { readonly kind: SyntaxKind.RestType; readonly type: TypeNode; } export type UnionOrIntersectionTypeNode = UnionTypeNode | IntersectionTypeNode; -export interface UnionTypeNode extends TypeNode { +export interface UnionTypeNode extends TypeNodeBase { readonly kind: SyntaxKind.UnionType; readonly types: NodeArray; } -export interface IntersectionTypeNode extends TypeNode { +export interface IntersectionTypeNode extends TypeNodeBase { readonly kind: SyntaxKind.IntersectionType; readonly types: NodeArray; } -export interface ConditionalTypeNode extends TypeNode, LocalsContainer { +export interface ConditionalTypeNode extends TypeNodeBase, LocalsContainer { readonly kind: SyntaxKind.ConditionalType; readonly checkType: TypeNode; readonly extendsType: TypeNode; @@ -2266,19 +2881,22 @@ export interface ConditionalTypeNode extends TypeNode, LocalsContainer { readonly falseType: TypeNode; } -export interface InferTypeNode extends TypeNode { +export interface InferTypeNode extends TypeNodeBase { readonly kind: SyntaxKind.InferType; readonly typeParameter: TypeParameterDeclaration; } -export interface ParenthesizedTypeNode extends TypeNode { +export interface ParenthesizedTypeNode extends TypeNodeBase { readonly kind: SyntaxKind.ParenthesizedType; readonly type: TypeNode; } -export interface TypeOperatorNode extends TypeNode { +export interface TypeOperatorNode extends TypeNodeBase { readonly kind: SyntaxKind.TypeOperator; - readonly operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword; + readonly operator: + | SyntaxKind.KeyOfKeyword + | SyntaxKind.UniqueKeyword + | SyntaxKind.ReadonlyKeyword; readonly type: TypeNode; } @@ -2287,13 +2905,13 @@ export interface UniqueTypeOperatorNode extends TypeOperatorNode { readonly operator: SyntaxKind.UniqueKeyword; } -export interface IndexedAccessTypeNode extends TypeNode { +export interface IndexedAccessTypeNode extends TypeNodeBase { readonly kind: SyntaxKind.IndexedAccessType; readonly objectType: TypeNode; readonly indexType: TypeNode; } -export interface MappedTypeNode extends TypeNode, Declaration, LocalsContainer { +export interface MappedTypeNode extends TypeNodeBase, DeclarationBase, LocalsContainer { readonly kind: SyntaxKind.MappedType; readonly readonlyToken?: ReadonlyKeyword | PlusToken | MinusToken; readonly typeParameter: TypeParameterDeclaration; @@ -2304,14 +2922,33 @@ export interface MappedTypeNode extends TypeNode, Declaration, LocalsContainer { readonly members?: NodeArray; } -export interface LiteralTypeNode extends TypeNode { +export type LiteralLikeNode = + | BigIntLiteral + | BooleanLiteral + // | LiteralExpression // ?! + | JsxText + | NoSubstitutionTemplateLiteral + | NullLiteral + | NumericLiteral + | PrefixUnaryExpression + | RegularExpressionLiteral + | StringLiteral + | PseudoLiteralToken // ?! +; + +export interface LiteralTypeNode extends TypeNodeBase { readonly kind: SyntaxKind.LiteralType; - readonly literal: NullLiteral | BooleanLiteral | LiteralExpression | PrefixUnaryExpression; + readonly literal: LiteralLikeNode; } -export interface StringLiteral extends LiteralExpression, Declaration { +export interface StringLiteral extends LiteralExpressionBase, DeclarationBase { readonly kind: SyntaxKind.StringLiteral; - /** @internal */ readonly textSourceNode?: Identifier | StringLiteralLike | NumericLiteral | PrivateIdentifier | JsxNamespacedName; // Allows a StringLiteral to get its text from another node (used by transforms). + /** @internal */ readonly textSourceNode?: + | Identifier + | StringLiteralLike + | NumericLiteral + | PrivateIdentifier + | JsxNamespacedName; // Allows a StringLiteral to get its text from another node (used by transforms). /** * Note: this is only set when synthesizing a node, not during parsing. * @@ -2321,15 +2958,19 @@ export interface StringLiteral extends LiteralExpression, Declaration { } export type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral; -export type PropertyNameLiteral = Identifier | StringLiteralLike | NumericLiteral | JsxNamespacedName; +export type PropertyNameLiteral = + | Identifier + | StringLiteralLike + | NumericLiteral + | JsxNamespacedName; -export interface TemplateLiteralTypeNode extends TypeNode { +export interface TemplateLiteralTypeNode extends TypeNodeBase { kind: SyntaxKind.TemplateLiteralType; readonly head: TemplateHead; readonly templateSpans: NodeArray; } -export interface TemplateLiteralTypeSpan extends TypeNode { +export interface TemplateLiteralTypeSpan extends TypeNodeBase { readonly kind: SyntaxKind.TemplateLiteralTypeSpan; readonly parent: TemplateLiteralTypeNode; readonly type: TypeNode; @@ -2343,33 +2984,38 @@ export interface TemplateLiteralTypeSpan extends TypeNode { // checker actually thinks you have something of the right type. Note: the brands are // never actually given values. At runtime they have zero cost. -export interface Expression extends Node { +export interface ExpressionBase extends NodeBase { _expressionBrand: any; } -export interface OmittedExpression extends Expression { +export interface OmittedExpression extends ExpressionBase { readonly kind: SyntaxKind.OmittedExpression; } // Represents an expression that is elided as part of a transformation to emit comments on a // not-emitted node. The 'expression' property of a PartiallyEmittedExpression should be emitted. -export interface PartiallyEmittedExpression extends LeftHandSideExpression { +export interface PartiallyEmittedExpression extends LeftHandSideExpressionBase { readonly kind: SyntaxKind.PartiallyEmittedExpression; readonly expression: Expression; } -export interface UnaryExpression extends Expression { +export interface UnaryExpressionBase extends ExpressionBase { _unaryExpressionBrand: any; } -/** Deprecated, please use UpdateExpression */ -export type IncrementExpression = UpdateExpression; -export interface UpdateExpression extends UnaryExpression { +export type UpdateExpression = + | PrefixUnaryExpression + | PostfixUnaryExpression + | LeftHandSideExpression; + +/** Deprecated, please use UpdateExpressionBase */ +export type IncrementExpression = UpdateExpressionBase; +export interface UpdateExpressionBase extends UnaryExpressionBase { _updateExpressionBrand: any; } -// see: https://tc39.github.io/ecma262/#prod-UpdateExpression -// see: https://tc39.github.io/ecma262/#prod-UnaryExpression +// see: https://tc39.github.io/ecma262/#prod-UpdateExpressionBase +// see: https://tc39.github.io/ecma262/#prod-UnaryExpressionBase export type PrefixUnaryOperator = | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken @@ -2378,88 +3024,112 @@ export type PrefixUnaryOperator = | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; -export interface PrefixUnaryExpression extends UpdateExpression { +export interface PrefixUnaryExpression extends UpdateExpressionBase { readonly kind: SyntaxKind.PrefixUnaryExpression; readonly operator: PrefixUnaryOperator; readonly operand: UnaryExpression; } -// see: https://tc39.github.io/ecma262/#prod-UpdateExpression +// see: https://tc39.github.io/ecma262/#prod-UpdateExpressionBase export type PostfixUnaryOperator = | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; -export interface PostfixUnaryExpression extends UpdateExpression { +export interface PostfixUnaryExpression extends UpdateExpressionBase { readonly kind: SyntaxKind.PostfixUnaryExpression; readonly operand: LeftHandSideExpression; readonly operator: PostfixUnaryOperator; } -export interface LeftHandSideExpression extends UpdateExpression { +export interface LeftHandSideExpressionBase extends UpdateExpressionBase { _leftHandSideExpressionBrand: any; } -export interface MemberExpression extends LeftHandSideExpression { +export interface MemberExpressionBase extends LeftHandSideExpressionBase { _memberExpressionBrand: any; } -export interface PrimaryExpression extends MemberExpression { +export type PrimaryExpression = + | ArrayLiteralExpression + | ClassExpression + | FalseLiteral + | FunctionExpression + | Identifier + | ImportExpression + | JsxAttributes + | JsxElement + | JsxFragment + | JsxSelfClosingElement + | LiteralExpression + | MetaProperty + | MissingDeclaration + | NewExpression + | NullLiteral + | ObjectLiteralExpression + | ParenthesizedExpression + | PrivateIdentifier + | SuperExpression + | TemplateExpression + | ThisExpression + | TrueLiteral; + +export interface PrimaryExpressionBase extends MemberExpressionBase { _primaryExpressionBrand: any; } -export interface NullLiteral extends PrimaryExpression { +export interface NullLiteral extends PrimaryExpressionBase { readonly kind: SyntaxKind.NullKeyword; } -export interface TrueLiteral extends PrimaryExpression { +export interface TrueLiteral extends PrimaryExpressionBase { readonly kind: SyntaxKind.TrueKeyword; } -export interface FalseLiteral extends PrimaryExpression { +export interface FalseLiteral extends PrimaryExpressionBase { readonly kind: SyntaxKind.FalseKeyword; } export type BooleanLiteral = TrueLiteral | FalseLiteral; -export interface ThisExpression extends PrimaryExpression, FlowContainer { +export interface ThisExpression extends PrimaryExpressionBase, FlowContainer { readonly kind: SyntaxKind.ThisKeyword; } -export interface SuperExpression extends PrimaryExpression, FlowContainer { +export interface SuperExpression extends PrimaryExpressionBase, FlowContainer { readonly kind: SyntaxKind.SuperKeyword; } -export interface ImportExpression extends PrimaryExpression { +export interface ImportExpression extends PrimaryExpressionBase { readonly kind: SyntaxKind.ImportKeyword; } -export interface DeleteExpression extends UnaryExpression { +export interface DeleteExpression extends UnaryExpressionBase { readonly kind: SyntaxKind.DeleteExpression; readonly expression: UnaryExpression; } -export interface TypeOfExpression extends UnaryExpression { +export interface TypeOfExpression extends UnaryExpressionBase { readonly kind: SyntaxKind.TypeOfExpression; readonly expression: UnaryExpression; } -export interface VoidExpression extends UnaryExpression { +export interface VoidExpression extends UnaryExpressionBase { readonly kind: SyntaxKind.VoidExpression; readonly expression: UnaryExpression; } -export interface AwaitExpression extends UnaryExpression { +export interface AwaitExpression extends UnaryExpressionBase { readonly kind: SyntaxKind.AwaitExpression; readonly expression: UnaryExpression; } -export interface YieldExpression extends Expression { +export interface YieldExpression extends ExpressionBase { readonly kind: SyntaxKind.YieldExpression; readonly asteriskToken?: AsteriskToken; readonly expression?: Expression; } -export interface SyntheticExpression extends Expression { +export interface SyntheticExpression extends ExpressionBase { readonly kind: SyntaxKind.SyntheticExpression; readonly isSpread: boolean; readonly type: Type; @@ -2481,9 +3151,7 @@ export type MultiplicativeOperatorOrHigher = | MultiplicativeOperator; // see: https://tc39.github.io/ecma262/#prod-AdditiveExpression -export type AdditiveOperator = - | SyntaxKind.PlusToken - | SyntaxKind.MinusToken; +export type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; // see: https://tc39.github.io/ecma262/#prod-AdditiveExpression export type AdditiveOperatorOrHigher = @@ -2497,9 +3165,7 @@ export type ShiftOperator = | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; // see: https://tc39.github.io/ecma262/#prod-ShiftExpression -export type ShiftOperatorOrHigher = - | AdditiveOperatorOrHigher - | ShiftOperator; +export type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; // see: https://tc39.github.io/ecma262/#prod-RelationalExpression export type RelationalOperator = @@ -2550,9 +3216,7 @@ export type LogicalOperator = // see: https://tc39.github.io/ecma262/#prod-LogicalANDExpression // see: https://tc39.github.io/ecma262/#prod-LogicalORExpression -export type LogicalOperatorOrHigher = - | BitwiseOperatorOrHigher - | LogicalOperator; +export type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; // see: https://tc39.github.io/ecma262/#prod-AssignmentOperator export type CompoundAssignmentOperator = @@ -2584,9 +3248,7 @@ export type AssignmentOperatorOrHigher = | AssignmentOperator; // see: https://tc39.github.io/ecma262/#prod-Expression -export type BinaryOperator = - | AssignmentOperatorOrHigher - | SyntaxKind.CommaToken; +export type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; export type LogicalOrCoalescingAssignmentOperator = | SyntaxKind.AmpersandAmpersandEqualsToken @@ -2595,7 +3257,7 @@ export type LogicalOrCoalescingAssignmentOperator = export type BinaryOperatorToken = Token; -export interface BinaryExpression extends Expression, Declaration, JSDocContainer { +export interface BinaryExpression extends ExpressionBase, DeclarationBase, JSDocContainer { readonly kind: SyntaxKind.BinaryExpression; readonly left: Expression; readonly operatorToken: BinaryOperatorToken; @@ -2631,11 +3293,13 @@ export type ObjectBindingOrAssignmentElement = | BindingElement | PropertyAssignment // AssignmentProperty | ShorthandPropertyAssignment // AssignmentProperty - | SpreadAssignment // AssignmentRestProperty -; + | SpreadAssignment; // AssignmentRestProperty /** @internal */ -export type ObjectAssignmentElement = Exclude; +export type ObjectAssignmentElement = Exclude< + ObjectBindingOrAssignmentElement, + BindingElement +>; export type ArrayBindingOrAssignmentElement = | BindingElement @@ -2646,17 +3310,18 @@ export type ArrayBindingOrAssignmentElement = | AssignmentExpression // AssignmentElement | Identifier // DestructuringAssignmentTarget | PropertyAccessExpression // DestructuringAssignmentTarget - | ElementAccessExpression // DestructuringAssignmentTarget -; + | ElementAccessExpression; // DestructuringAssignmentTarget /** @internal */ -export type ArrayAssignmentElement = Exclude; +export type ArrayAssignmentElement = Exclude< + ArrayBindingOrAssignmentElement, + BindingElement +>; export type BindingOrAssignmentElementRestIndicator = | DotDotDotToken // from BindingElement | SpreadElement // AssignmentRestElement - | SpreadAssignment // AssignmentRestProperty -; + | SpreadAssignment; // AssignmentRestProperty export type BindingOrAssignmentElementTarget = | BindingOrAssignmentPattern @@ -2666,23 +3331,28 @@ export type BindingOrAssignmentElementTarget = | OmittedExpression; /** @internal */ -export type AssignmentElementTarget = Exclude; +export type AssignmentElementTarget = Exclude< + BindingOrAssignmentElementTarget, + BindingPattern +>; export type ObjectBindingOrAssignmentPattern = | ObjectBindingPattern - | ObjectLiteralExpression // ObjectAssignmentPattern -; + | ObjectLiteralExpression; // ObjectAssignmentPattern export type ArrayBindingOrAssignmentPattern = | ArrayBindingPattern - | ArrayLiteralExpression // ArrayAssignmentPattern -; + | ArrayLiteralExpression; // ArrayAssignmentPattern -export type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; +export type AssignmentPattern = + | ObjectLiteralExpression + | ArrayLiteralExpression; -export type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern; +export type BindingOrAssignmentPattern = + | ObjectBindingOrAssignmentPattern + | ArrayBindingOrAssignmentPattern; -export interface ConditionalExpression extends Expression { +export interface ConditionalExpression extends ExpressionBase { readonly kind: SyntaxKind.ConditionalExpression; readonly condition: Expression; readonly questionToken: QuestionToken; @@ -2694,14 +3364,14 @@ export interface ConditionalExpression extends Expression { export type FunctionBody = Block; export type ConciseBody = FunctionBody | Expression; -export interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer, LocalsContainer, FlowContainer { +export interface FunctionExpression extends PrimaryExpressionBase, FunctionLikeDeclarationBase, JSDocContainer, LocalsContainer, FlowContainer { readonly kind: SyntaxKind.FunctionExpression; readonly modifiers?: NodeArray; readonly name?: Identifier; readonly body: FunctionBody; // Required, whereas the member inherited from FunctionDeclaration is optional } -export interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer, LocalsContainer, FlowContainer { +export interface ArrowFunction extends ExpressionBase, FunctionLikeDeclarationBase, JSDocContainer, LocalsContainer, FlowContainer { readonly kind: SyntaxKind.ArrowFunction; readonly modifiers?: NodeArray; readonly equalsGreaterThanToken: EqualsGreaterThanToken; @@ -2709,33 +3379,49 @@ export interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, readonly name: never; } -// The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral, +// The text property of a LiteralExpressionBase stores the interpreted value of the literal in text form. For a StringLiteral, // or any literal of a template, this means quotes have been removed and escapes have been converted to actual characters. // For a NumericLiteral, the stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1". -export interface LiteralLikeNode extends Node { +export interface LiteralLikeNodeBase extends NodeBase { text: string; isUnterminated?: boolean; hasExtendedUnicodeEscape?: boolean; } -export interface TemplateLiteralLikeNode extends LiteralLikeNode { +export type TemplateLiteralLikeNode = + | NoSubstitutionTemplateLiteral + | TemplateHead + | TemplateMiddle + | TemplateTail; + +export interface TemplateLiteralLikeNodeBase extends LiteralLikeNodeBase { rawText?: string; /** @internal */ templateFlags?: TokenFlags; } +export type LiteralExpression = + | ArrayDestructuringAssignment + | ArrayLiteralExpression + | BigIntLiteral + | NoSubstitutionTemplateLiteral + | NumericLiteral + | ObjectLiteralExpression + | RegularExpressionLiteral + | StringLiteral; + // The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral, // or any literal of a template, this means quotes have been removed and escapes have been converted to actual characters. // For a NumericLiteral, the stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1". -export interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { - _literalExpressionBrand: any; +export interface LiteralExpressionBase extends LiteralLikeNodeBase, PrimaryExpressionBase { + _literalExpressionBaseBrand: any; } -export interface RegularExpressionLiteral extends LiteralExpression { +export interface RegularExpressionLiteral extends LiteralExpressionBase { readonly kind: SyntaxKind.RegularExpressionLiteral; } -export interface NoSubstitutionTemplateLiteral extends LiteralExpression, TemplateLiteralLikeNode, Declaration { +export interface NoSubstitutionTemplateLiteral extends LiteralExpressionBase, TemplateLiteralLikeNodeBase, DeclarationBase { readonly kind: SyntaxKind.NoSubstitutionTemplateLiteral; /** @internal */ templateFlags?: TokenFlags; @@ -2751,22 +3437,22 @@ export const enum TokenFlags { /** @internal */ Unterminated = 1 << 2, /** @internal */ - ExtendedUnicodeEscape = 1 << 3, // e.g. `\u{10ffff}` - Scientific = 1 << 4, // e.g. `10e2` - Octal = 1 << 5, // e.g. `0777` - HexSpecifier = 1 << 6, // e.g. `0x00000000` - BinarySpecifier = 1 << 7, // e.g. `0b0110010000000000` - OctalSpecifier = 1 << 8, // e.g. `0o777` + ExtendedUnicodeEscape = 1 << 3, // e.g. `\u{10ffff}` + Scientific = 1 << 4, // e.g. `10e2` + Octal = 1 << 5, // e.g. `0777` + HexSpecifier = 1 << 6, // e.g. `0x00000000` + BinarySpecifier = 1 << 7, // e.g. `0b0110010000000000` + OctalSpecifier = 1 << 8, // e.g. `0o777` /** @internal */ - ContainsSeparator = 1 << 9, // e.g. `0b1100_0101` + ContainsSeparator = 1 << 9, // e.g. `0b1100_0101` /** @internal */ - UnicodeEscape = 1 << 10, // e.g. `\u00a0` + UnicodeEscape = 1 << 10, // e.g. `\u00a0` /** @internal */ - ContainsInvalidEscape = 1 << 11, // e.g. `\uhello` + ContainsInvalidEscape = 1 << 11, // e.g. `\uhello` /** @internal */ - HexEscape = 1 << 12, // e.g. `\xa0` + HexEscape = 1 << 12, // e.g. `\xa0` /** @internal */ - ContainsLeadingZero = 1 << 13, // e.g. `0888` + ContainsLeadingZero = 1 << 13, // e.g. `0888` /** @internal */ ContainsInvalidSeparator = 1 << 14, // e.g. `0_1` /** @internal */ @@ -2774,22 +3460,36 @@ export const enum TokenFlags { /** @internal */ WithSpecifier = HexSpecifier | BinaryOrOctalSpecifier, /** @internal */ - StringLiteralFlags = HexEscape | UnicodeEscape | ExtendedUnicodeEscape | ContainsInvalidEscape, + StringLiteralFlags = HexEscape | + UnicodeEscape | + ExtendedUnicodeEscape | + ContainsInvalidEscape, /** @internal */ - NumericLiteralFlags = Scientific | Octal | ContainsLeadingZero | WithSpecifier | ContainsSeparator | ContainsInvalidSeparator, + NumericLiteralFlags = Scientific | + Octal | + ContainsLeadingZero | + WithSpecifier | + ContainsSeparator | + ContainsInvalidSeparator, /** @internal */ - TemplateLiteralLikeFlags = HexEscape | UnicodeEscape | ExtendedUnicodeEscape | ContainsInvalidEscape, + TemplateLiteralLikeFlags = HexEscape | + UnicodeEscape | + ExtendedUnicodeEscape | + ContainsInvalidEscape, /** @internal */ - IsInvalid = Octal | ContainsLeadingZero | ContainsInvalidSeparator | ContainsInvalidEscape, + IsInvalid = Octal | + ContainsLeadingZero | + ContainsInvalidSeparator | + ContainsInvalidEscape, } -export interface NumericLiteral extends LiteralExpression, Declaration { +export interface NumericLiteral extends LiteralExpressionBase, DeclarationBase { readonly kind: SyntaxKind.NumericLiteral; /** @internal */ readonly numericLiteralFlags: TokenFlags; } -export interface BigIntLiteral extends LiteralExpression { +export interface BigIntLiteral extends LiteralExpressionBase { readonly kind: SyntaxKind.BigIntLiteral; } @@ -2801,21 +3501,21 @@ export type LiteralToken = | RegularExpressionLiteral | NoSubstitutionTemplateLiteral; -export interface TemplateHead extends TemplateLiteralLikeNode { +export interface TemplateHead extends TemplateLiteralLikeNodeBase { readonly kind: SyntaxKind.TemplateHead; readonly parent: TemplateExpression | TemplateLiteralTypeNode; /** @internal */ templateFlags?: TokenFlags; } -export interface TemplateMiddle extends TemplateLiteralLikeNode { +export interface TemplateMiddle extends TemplateLiteralLikeNodeBase { readonly kind: SyntaxKind.TemplateMiddle; readonly parent: TemplateSpan | TemplateLiteralTypeSpan; /** @internal */ templateFlags?: TokenFlags; } -export interface TemplateTail extends TemplateLiteralLikeNode { +export interface TemplateTail extends TemplateLiteralLikeNodeBase { readonly kind: SyntaxKind.TemplateTail; readonly parent: TemplateSpan | TemplateLiteralTypeSpan; /** @internal */ @@ -2831,7 +3531,7 @@ export type TemplateLiteralToken = | NoSubstitutionTemplateLiteral | PseudoLiteralToken; -export interface TemplateExpression extends PrimaryExpression { +export interface TemplateExpression extends PrimaryExpressionBase { readonly kind: SyntaxKind.TemplateExpression; readonly head: TemplateHead; readonly templateSpans: NodeArray; @@ -2843,14 +3543,14 @@ export type TemplateLiteral = // Each of these corresponds to a substitution expression and a template literal, in that order. // The template literal must have kind TemplateMiddleLiteral or TemplateTailLiteral. -export interface TemplateSpan extends Node { +export interface TemplateSpan extends NodeBase { readonly kind: SyntaxKind.TemplateSpan; readonly parent: TemplateExpression; readonly expression: Expression; readonly literal: TemplateMiddle | TemplateTail; } -export interface ParenthesizedExpression extends PrimaryExpression, JSDocContainer { +export interface ParenthesizedExpression extends PrimaryExpressionBase, JSDocContainer { readonly kind: SyntaxKind.ParenthesizedExpression; readonly expression: Expression; } @@ -2860,14 +3560,14 @@ export interface JSDocTypeAssertion extends ParenthesizedExpression { readonly _jsDocTypeAssertionBrand: never; } -export interface ArrayLiteralExpression extends PrimaryExpression { +export interface ArrayLiteralExpression extends PrimaryExpressionBase { readonly kind: SyntaxKind.ArrayLiteralExpression; readonly elements: NodeArray; /** @internal */ multiLine?: boolean; } -export interface SpreadElement extends Expression { +export interface SpreadElement extends ExpressionBase { readonly kind: SyntaxKind.SpreadElement; readonly parent: ArrayLiteralExpression | CallExpression | NewExpression; readonly expression: Expression; @@ -2879,7 +3579,7 @@ export interface SpreadElement extends Expression { * JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type * ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.) */ -export interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { +export interface ObjectLiteralExpressionBase extends PrimaryExpressionBase, DeclarationBase { readonly properties: NodeArray; } @@ -2890,11 +3590,17 @@ export interface ObjectLiteralExpression extends ObjectLiteralExpressionBase; + readonly arguments: + & readonly [ + BindableStaticNameExpression, + StringLiteralLike | NumericLiteral, + ObjectLiteralExpression, + ] + & Readonly; }; /** @internal */ @@ -2990,9 +3704,12 @@ export type BindableStaticNameExpression = | BindableStaticElementAccessExpression; /** @internal */ -export type LiteralLikeElementAccessExpression = ElementAccessExpression & Declaration & { - readonly argumentExpression: StringLiteralLike | NumericLiteral; -}; +export type LiteralLikeElementAccessExpression = + & ElementAccessExpression + & DeclarationBase + & { + readonly argumentExpression: StringLiteralLike | NumericLiteral; + }; /** @internal */ export type BindableStaticElementAccessExpression = LiteralLikeElementAccessExpression & { @@ -3033,19 +3750,19 @@ export interface ImportCall extends CallExpression { readonly expression: ImportExpression; } -export interface ExpressionWithTypeArguments extends MemberExpression, NodeWithTypeArguments { +export interface ExpressionWithTypeArguments extends MemberExpressionBase, NodeWithTypeArgumentsBase { readonly kind: SyntaxKind.ExpressionWithTypeArguments; readonly expression: LeftHandSideExpression; } -export interface NewExpression extends PrimaryExpression, Declaration { +export interface NewExpression extends PrimaryExpressionBase, DeclarationBase { readonly kind: SyntaxKind.NewExpression; readonly expression: LeftHandSideExpression; readonly typeArguments?: NodeArray; readonly arguments?: NodeArray; } -export interface TaggedTemplateExpression extends MemberExpression { +export interface TaggedTemplateExpression extends MemberExpressionBase { readonly kind: SyntaxKind.TaggedTemplateExpression; readonly tag: LeftHandSideExpression; readonly typeArguments?: NodeArray; @@ -3065,29 +3782,27 @@ export type CallLikeExpression = | JsxOpeningLikeElement | InstanceofExpression; -export interface AsExpression extends Expression { +export interface AsExpression extends ExpressionBase { readonly kind: SyntaxKind.AsExpression; readonly expression: Expression; readonly type: TypeNode; } -export interface TypeAssertion extends UnaryExpression { +export interface TypeAssertion extends UnaryExpressionBase { readonly kind: SyntaxKind.TypeAssertionExpression; readonly type: TypeNode; readonly expression: UnaryExpression; } -export interface SatisfiesExpression extends Expression { +export interface SatisfiesExpression extends ExpressionBase { readonly kind: SyntaxKind.SatisfiesExpression; readonly expression: Expression; readonly type: TypeNode; } -export type AssertionExpression = - | TypeAssertion - | AsExpression; +export type AssertionExpression = TypeAssertion | AsExpression; -export interface NonNullExpression extends LeftHandSideExpression { +export interface NonNullExpression extends LeftHandSideExpressionBase { readonly kind: SyntaxKind.NonNullExpression; readonly expression: Expression; } @@ -3098,7 +3813,7 @@ export interface NonNullChain extends NonNullExpression { // NOTE: MetaProperty is really a MemberExpression, but we consider it a PrimaryExpression // for the same reasons we treat NewExpression as a PrimaryExpression. -export interface MetaProperty extends PrimaryExpression, FlowContainer { +export interface MetaProperty extends PrimaryExpressionBase, FlowContainer { readonly kind: SyntaxKind.MetaProperty; readonly keywordToken: SyntaxKind.NewKeyword | SyntaxKind.ImportKeyword; readonly name: Identifier; @@ -3111,7 +3826,7 @@ export interface ImportMetaProperty extends MetaProperty { } /// A JSX expression of the form ... -export interface JsxElement extends PrimaryExpression { +export interface JsxElement extends PrimaryExpressionBase { readonly kind: SyntaxKind.JsxElement; readonly openingElement: JsxOpeningElement; readonly children: NodeArray; @@ -3119,17 +3834,11 @@ export interface JsxElement extends PrimaryExpression { } /// Either the opening tag in a ... pair or the lone in a self-closing form -export type JsxOpeningLikeElement = - | JsxSelfClosingElement - | JsxOpeningElement; +export type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; -export type JsxAttributeLike = - | JsxAttribute - | JsxSpreadAttribute; +export type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; -export type JsxAttributeName = - | Identifier - | JsxNamespacedName; +export type JsxAttributeName = Identifier | JsxNamespacedName; export type JsxTagNameExpression = | Identifier @@ -3141,20 +3850,20 @@ export interface JsxTagNamePropertyAccess extends PropertyAccessExpression { readonly expression: Identifier | ThisExpression | JsxTagNamePropertyAccess; } -export interface JsxAttributes extends PrimaryExpression, Declaration { +export interface JsxAttributes extends PrimaryExpressionBase, DeclarationBase { readonly properties: NodeArray; readonly kind: SyntaxKind.JsxAttributes; readonly parent: JsxOpeningLikeElement; } -export interface JsxNamespacedName extends Node { +export interface JsxNamespacedName extends NodeBase { readonly kind: SyntaxKind.JsxNamespacedName; readonly name: Identifier; readonly namespace: Identifier; } /// The opening element of a ... JsxElement -export interface JsxOpeningElement extends Expression { +export interface JsxOpeningElement extends ExpressionBase { readonly kind: SyntaxKind.JsxOpeningElement; readonly parent: JsxElement; readonly tagName: JsxTagNameExpression; @@ -3163,7 +3872,7 @@ export interface JsxOpeningElement extends Expression { } /// A JSX expression of the form -export interface JsxSelfClosingElement extends PrimaryExpression { +export interface JsxSelfClosingElement extends PrimaryExpressionBase { readonly kind: SyntaxKind.JsxSelfClosingElement; readonly tagName: JsxTagNameExpression; readonly typeArguments?: NodeArray; @@ -3171,7 +3880,7 @@ export interface JsxSelfClosingElement extends PrimaryExpression { } /// A JSX expression of the form <>... -export interface JsxFragment extends PrimaryExpression { +export interface JsxFragment extends PrimaryExpressionBase { readonly kind: SyntaxKind.JsxFragment; readonly openingFragment: JsxOpeningFragment; readonly children: NodeArray; @@ -3179,18 +3888,18 @@ export interface JsxFragment extends PrimaryExpression { } /// The opening element of a <>... JsxFragment -export interface JsxOpeningFragment extends Expression { +export interface JsxOpeningFragment extends ExpressionBase { readonly kind: SyntaxKind.JsxOpeningFragment; readonly parent: JsxFragment; } /// The closing element of a <>... JsxFragment -export interface JsxClosingFragment extends Expression { +export interface JsxClosingFragment extends ExpressionBase { readonly kind: SyntaxKind.JsxClosingFragment; readonly parent: JsxFragment; } -export interface JsxAttribute extends Declaration { +export interface JsxAttribute extends DeclarationBase { readonly kind: SyntaxKind.JsxAttribute; readonly parent: JsxAttributes; readonly name: JsxAttributeName; @@ -3205,26 +3914,26 @@ export type JsxAttributeValue = | JsxSelfClosingElement | JsxFragment; -export interface JsxSpreadAttribute extends ObjectLiteralElement { +export interface JsxSpreadAttribute extends ObjectLiteralElementBase { readonly kind: SyntaxKind.JsxSpreadAttribute; readonly parent: JsxAttributes; readonly expression: Expression; } -export interface JsxClosingElement extends Node { +export interface JsxClosingElement extends NodeBase { readonly kind: SyntaxKind.JsxClosingElement; readonly parent: JsxElement; readonly tagName: JsxTagNameExpression; } -export interface JsxExpression extends Expression { +export interface JsxExpression extends ExpressionBase { readonly kind: SyntaxKind.JsxExpression; readonly parent: JsxElement | JsxFragment | JsxAttributeLike; readonly dotDotDotToken?: Token; readonly expression?: Expression; } -export interface JsxText extends LiteralLikeNode { +export interface JsxText extends LiteralLikeNodeBase { readonly kind: SyntaxKind.JsxText; readonly parent: JsxElement | JsxFragment; readonly containsOnlyTriviaWhiteSpaces: boolean; @@ -3237,40 +3946,78 @@ export type JsxChild = | JsxSelfClosingElement | JsxFragment; -export interface Statement extends Node, JSDocContainer { +export type Statement = + | Block + | BreakStatement + | ContinueStatement + | DebuggerStatement + | DeclarationStatement + | DoStatement + | EmptyStatement + | ExpressionStatement + | ForInStatement + | ForOfStatement + | ForStatement + | IfStatement + | ImportDeclaration + | LabeledStatement + | ModuleBlock + | NotEmittedStatement + | ReturnStatement + | SwitchStatement + | ThrowStatement + | TryStatement + | VariableStatement + | WhileStatement + | WithStatement; + +export interface StatementBase extends NodeBase, JSDocContainer { _statementBrand: any; } // Represents a statement that is elided as part of a transformation to emit comments on a // not-emitted node. -export interface NotEmittedStatement extends Statement { +export interface NotEmittedStatement extends StatementBase { readonly kind: SyntaxKind.NotEmittedStatement; } /** * A list of comma-separated expressions. This node is only created by transformations. */ -export interface CommaListExpression extends Expression { +export interface CommaListExpression extends ExpressionBase { readonly kind: SyntaxKind.CommaListExpression; readonly elements: NodeArray; } /** @internal */ -export interface SyntheticReferenceExpression extends LeftHandSideExpression { +export interface SyntheticReferenceExpression extends LeftHandSideExpressionBase { readonly kind: SyntaxKind.SyntheticReferenceExpression; readonly expression: Expression; readonly thisArg: Expression; } -export interface EmptyStatement extends Statement { +export interface EmptyStatement extends StatementBase { readonly kind: SyntaxKind.EmptyStatement; } -export interface DebuggerStatement extends Statement, FlowContainer { +export interface DebuggerStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.DebuggerStatement; } -export interface MissingDeclaration extends DeclarationStatement, PrimaryExpression { +export type DeclarationStatement = + | ClassDeclaration + | EnumDeclaration + | ExportAssignment + | ExportDeclaration + | FunctionDeclaration + | ImportEqualsDeclaration + | InterfaceDeclaration + | MissingDeclaration + | ModuleDeclaration + | NamespaceExportDeclaration + | TypeAliasDeclaration; + +export interface MissingDeclaration extends DeclarationStatementBase, PrimaryExpressionBase { readonly kind: SyntaxKind.MissingDeclaration; readonly name?: Identifier; @@ -3278,25 +4025,21 @@ export interface MissingDeclaration extends DeclarationStatement, PrimaryExpress /** @internal */ readonly modifiers?: NodeArray | undefined; } -export type BlockLike = - | SourceFile - | Block - | ModuleBlock - | CaseOrDefaultClause; +export type BlockLike = SourceFile | Block | ModuleBlock | CaseOrDefaultClause; -export interface Block extends Statement, LocalsContainer { +export interface Block extends StatementBase, LocalsContainer { readonly kind: SyntaxKind.Block; readonly statements: NodeArray; /** @internal */ multiLine?: boolean; } -export interface VariableStatement extends Statement, FlowContainer { +export interface VariableStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.VariableStatement; readonly modifiers?: NodeArray; readonly declarationList: VariableDeclarationList; } -export interface ExpressionStatement extends Statement, FlowContainer { +export interface ExpressionStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.ExpressionStatement; readonly expression: Expression; } @@ -3306,94 +4049,95 @@ export interface PrologueDirective extends ExpressionStatement { readonly expression: StringLiteral; } -export interface IfStatement extends Statement, FlowContainer { +export interface IfStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.IfStatement; readonly expression: Expression; readonly thenStatement: Statement; readonly elseStatement?: Statement; } -export interface IterationStatement extends Statement { +export type IterationStatement = + | DoStatement + | ForInStatement + | ForOfStatement + | ForStatement + | WhileStatement; + +export interface IterationStatementBase extends StatementBase { readonly statement: Statement; } -export interface DoStatement extends IterationStatement, FlowContainer { +export interface DoStatement extends IterationStatementBase, FlowContainer { readonly kind: SyntaxKind.DoStatement; readonly expression: Expression; } -export interface WhileStatement extends IterationStatement, FlowContainer { +export interface WhileStatement extends IterationStatementBase, FlowContainer { readonly kind: SyntaxKind.WhileStatement; readonly expression: Expression; } -export type ForInitializer = - | VariableDeclarationList - | Expression; +export type ForInitializer = VariableDeclarationList | Expression; -export interface ForStatement extends IterationStatement, LocalsContainer, FlowContainer { +export interface ForStatement extends IterationStatementBase, LocalsContainer, FlowContainer { readonly kind: SyntaxKind.ForStatement; readonly initializer?: ForInitializer; readonly condition?: Expression; readonly incrementor?: Expression; } -export type ForInOrOfStatement = - | ForInStatement - | ForOfStatement; +export type ForInOrOfStatement = ForInStatement | ForOfStatement; -export interface ForInStatement extends IterationStatement, LocalsContainer, FlowContainer { +export interface ForInStatement extends IterationStatementBase, LocalsContainer, FlowContainer { readonly kind: SyntaxKind.ForInStatement; readonly initializer: ForInitializer; readonly expression: Expression; } -export interface ForOfStatement extends IterationStatement, LocalsContainer, FlowContainer { +export interface ForOfStatement extends IterationStatementBase, LocalsContainer, FlowContainer { readonly kind: SyntaxKind.ForOfStatement; readonly awaitModifier?: AwaitKeyword; readonly initializer: ForInitializer; readonly expression: Expression; } -export interface BreakStatement extends Statement, FlowContainer { +export interface BreakStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.BreakStatement; readonly label?: Identifier; } -export interface ContinueStatement extends Statement, FlowContainer { +export interface ContinueStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.ContinueStatement; readonly label?: Identifier; } -export type BreakOrContinueStatement = - | BreakStatement - | ContinueStatement; +export type BreakOrContinueStatement = BreakStatement | ContinueStatement; -export interface ReturnStatement extends Statement, FlowContainer { +export interface ReturnStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.ReturnStatement; readonly expression?: Expression; } -export interface WithStatement extends Statement, FlowContainer { +export interface WithStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.WithStatement; readonly expression: Expression; readonly statement: Statement; } -export interface SwitchStatement extends Statement, FlowContainer { +export interface SwitchStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.SwitchStatement; readonly expression: Expression; readonly caseBlock: CaseBlock; possiblyExhaustive?: boolean; // initialized by binding } -export interface CaseBlock extends Node, LocalsContainer { +export interface CaseBlock extends NodeBase, LocalsContainer { readonly kind: SyntaxKind.CaseBlock; readonly parent: SwitchStatement; readonly clauses: NodeArray; } -export interface CaseClause extends Node, JSDocContainer { +export interface CaseClause extends NodeBase, JSDocContainer { readonly kind: SyntaxKind.CaseClause; readonly parent: CaseBlock; readonly expression: Expression; @@ -3401,36 +4145,34 @@ export interface CaseClause extends Node, JSDocContainer { /** @internal */ fallthroughFlowNode?: FlowNode; } -export interface DefaultClause extends Node { +export interface DefaultClause extends NodeBase { readonly kind: SyntaxKind.DefaultClause; readonly parent: CaseBlock; readonly statements: NodeArray; /** @internal */ fallthroughFlowNode?: FlowNode; } -export type CaseOrDefaultClause = - | CaseClause - | DefaultClause; +export type CaseOrDefaultClause = CaseClause | DefaultClause; -export interface LabeledStatement extends Statement, FlowContainer { +export interface LabeledStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.LabeledStatement; readonly label: Identifier; readonly statement: Statement; } -export interface ThrowStatement extends Statement, FlowContainer { +export interface ThrowStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.ThrowStatement; readonly expression: Expression; } -export interface TryStatement extends Statement, FlowContainer { +export interface TryStatement extends StatementBase, FlowContainer { readonly kind: SyntaxKind.TryStatement; readonly tryBlock: Block; readonly catchClause?: CatchClause; readonly finallyBlock?: Block; } -export interface CatchClause extends Node, LocalsContainer { +export interface CatchClause extends NodeBase, LocalsContainer { readonly kind: SyntaxKind.CatchClause; readonly parent: TryStatement; readonly variableDeclaration?: VariableDeclaration; @@ -3455,7 +4197,7 @@ export type DeclarationWithTypeParameterChildren = | TypeAliasDeclaration | JSDocTemplateTag; -export interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer { +export interface ClassLikeDeclarationBase extends NamedDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression; readonly name?: Identifier; readonly typeParameters?: NodeArray; @@ -3463,34 +4205,42 @@ export interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContain readonly members: NodeArray; } -export interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement { +export interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatementBase { readonly kind: SyntaxKind.ClassDeclaration; readonly modifiers?: NodeArray; /** May be undefined in `export default class { ... }`. */ readonly name?: Identifier; } -export interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression { +export interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpressionBase { readonly kind: SyntaxKind.ClassExpression; readonly modifiers?: NodeArray; } -export type ClassLikeDeclaration = - | ClassDeclaration - | ClassExpression; +export type ClassLikeDeclaration = ClassDeclaration | ClassExpression; + +export type ClassElement = + | ClassStaticBlockDeclaration + | ConstructorDeclaration + | GetAccessorDeclaration + | IndexSignatureDeclaration + | MethodDeclaration + | PropertyDeclaration + | SemicolonClassElement + | SetAccessorDeclaration; -export interface ClassElement extends NamedDeclaration { +export interface ClassElementBase extends NamedDeclarationBase { _classElementBrand: any; readonly name?: PropertyName; } -export interface TypeElement extends NamedDeclaration { +export interface TypeElementBase extends NamedDeclarationBase { _typeElementBrand: any; readonly name?: PropertyName; readonly questionToken?: QuestionToken | undefined; } -export interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer { +export interface InterfaceDeclaration extends DeclarationStatementBase, JSDocContainer { readonly kind: SyntaxKind.InterfaceDeclaration; readonly modifiers?: NodeArray; readonly name: Identifier; @@ -3499,14 +4249,14 @@ export interface InterfaceDeclaration extends DeclarationStatement, JSDocContain readonly members: NodeArray; } -export interface HeritageClause extends Node { +export interface HeritageClause extends NodeBase { readonly kind: SyntaxKind.HeritageClause; readonly parent: InterfaceDeclaration | ClassLikeDeclaration; readonly token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword; readonly types: NodeArray; } -export interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer, LocalsContainer { +export interface TypeAliasDeclaration extends DeclarationStatementBase, JSDocContainer, LocalsContainer { readonly kind: SyntaxKind.TypeAliasDeclaration; readonly modifiers?: NodeArray; readonly name: Identifier; @@ -3514,7 +4264,7 @@ export interface TypeAliasDeclaration extends DeclarationStatement, JSDocContain readonly type: TypeNode; } -export interface EnumMember extends NamedDeclaration, JSDocContainer { +export interface EnumMember extends NamedDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.EnumMember; readonly parent: EnumDeclaration; // This does include ComputedPropertyName, but the parser will give an error @@ -3523,27 +4273,23 @@ export interface EnumMember extends NamedDeclaration, JSDocContainer { readonly initializer?: Expression; } -export interface EnumDeclaration extends DeclarationStatement, JSDocContainer { +export interface EnumDeclaration extends DeclarationStatementBase, JSDocContainer { readonly kind: SyntaxKind.EnumDeclaration; readonly modifiers?: NodeArray; readonly name: Identifier; readonly members: NodeArray; } -export type ModuleName = - | Identifier - | StringLiteral; +export type ModuleName = Identifier | StringLiteral; -export type ModuleBody = - | NamespaceBody - | JSDocNamespaceBody; +export type ModuleBody = NamespaceBody | JSDocNamespaceBody; /** @internal */ export interface AmbientModuleDeclaration extends ModuleDeclaration { readonly body?: ModuleBlock; } -export interface ModuleDeclaration extends DeclarationStatement, JSDocContainer, LocalsContainer { +export interface ModuleDeclaration extends DeclarationStatementBase, JSDocContainer, LocalsContainer { readonly kind: SyntaxKind.ModuleDeclaration; readonly parent: ModuleBody | SourceFile; readonly modifiers?: NodeArray; @@ -3551,40 +4297,34 @@ export interface ModuleDeclaration extends DeclarationStatement, JSDocContainer, readonly body?: ModuleBody | JSDocNamespaceDeclaration; } -export type NamespaceBody = - | ModuleBlock - | NamespaceDeclaration; +export type NamespaceBody = ModuleBlock | NamespaceDeclaration; export interface NamespaceDeclaration extends ModuleDeclaration { readonly name: Identifier; readonly body: NamespaceBody; } -export type JSDocNamespaceBody = - | Identifier - | JSDocNamespaceDeclaration; +export type JSDocNamespaceBody = Identifier | JSDocNamespaceDeclaration; export interface JSDocNamespaceDeclaration extends ModuleDeclaration { readonly name: Identifier; readonly body?: JSDocNamespaceBody; } -export interface ModuleBlock extends Node, Statement { +export interface ModuleBlock extends NodeBase, StatementBase { readonly kind: SyntaxKind.ModuleBlock; readonly parent: ModuleDeclaration; readonly statements: NodeArray; } -export type ModuleReference = - | EntityName - | ExternalModuleReference; +export type ModuleReference = EntityName | ExternalModuleReference; /** * One of: * - import x = require("mod"); * - import x = M.x; */ -export interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer { +export interface ImportEqualsDeclaration extends DeclarationStatementBase, JSDocContainer { readonly kind: SyntaxKind.ImportEqualsDeclaration; readonly parent: SourceFile | ModuleBlock; readonly modifiers?: NodeArray; @@ -3596,7 +4336,7 @@ export interface ImportEqualsDeclaration extends DeclarationStatement, JSDocCont readonly moduleReference: ModuleReference; } -export interface ExternalModuleReference extends Node { +export interface ExternalModuleReference extends NodeBase { readonly kind: SyntaxKind.ExternalModuleReference; readonly parent: ImportEqualsDeclaration; readonly expression: Expression; @@ -3606,7 +4346,7 @@ export interface ExternalModuleReference extends Node { // import "mod" => importClause = undefined, moduleSpecifier = "mod" // In rest of the cases, module specifier is string literal corresponding to module // ImportClause information is shown at its declaration below. -export interface ImportDeclaration extends Statement { +export interface ImportDeclaration extends DeclarationBase, StatementBase { readonly kind: SyntaxKind.ImportDeclaration; readonly parent: SourceFile | ModuleBlock; readonly modifiers?: NodeArray; @@ -3617,13 +4357,9 @@ export interface ImportDeclaration extends Statement { readonly attributes?: ImportAttributes; } -export type NamedImportBindings = - | NamespaceImport - | NamedImports; +export type NamedImportBindings = NamespaceImport | NamedImports; -export type NamedExportBindings = - | NamespaceExport - | NamedExports; +export type NamedExportBindings = NamespaceExport | NamedExports; // In case of: // import d from "mod" => name = d, namedBinding = undefined @@ -3631,7 +4367,7 @@ export type NamedExportBindings = // import d, * as ns from "mod" => name = d, namedBinding: NamespaceImport = { name: ns } // import { a, b as x } from "mod" => name = undefined, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} // import d, { a, b as x } from "mod" => name = d, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} -export interface ImportClause extends NamedDeclaration { +export interface ImportClause extends NamedDeclarationBase { readonly kind: SyntaxKind.ImportClause; readonly parent: ImportDeclaration; readonly isTypeOnly: boolean; @@ -3650,14 +4386,14 @@ export type AssertClause = ImportAttributes; export type ImportAttributeName = Identifier | StringLiteral; -export interface ImportAttribute extends Node { +export interface ImportAttribute extends NodeBase { readonly kind: SyntaxKind.ImportAttribute; readonly parent: ImportAttributes; readonly name: ImportAttributeName; readonly value: Expression; } -export interface ImportAttributes extends Node { +export interface ImportAttributes extends NodeBase { readonly token: SyntaxKind.WithKeyword | SyntaxKind.AssertKeyword; readonly kind: SyntaxKind.ImportAttributes; readonly parent: ImportDeclaration | ExportDeclaration; @@ -3665,19 +4401,19 @@ export interface ImportAttributes extends Node { readonly multiLine?: boolean; } -export interface NamespaceImport extends NamedDeclaration { +export interface NamespaceImport extends NamedDeclarationBase { readonly kind: SyntaxKind.NamespaceImport; readonly parent: ImportClause; readonly name: Identifier; } -export interface NamespaceExport extends NamedDeclaration { +export interface NamespaceExport extends NamedDeclarationBase { readonly kind: SyntaxKind.NamespaceExport; readonly parent: ExportDeclaration; readonly name: Identifier; } -export interface NamespaceExportDeclaration extends DeclarationStatement, JSDocContainer { +export interface NamespaceExportDeclaration extends DeclarationStatementBase, JSDocContainer { readonly kind: SyntaxKind.NamespaceExportDeclaration; readonly name: Identifier; @@ -3685,7 +4421,7 @@ export interface NamespaceExportDeclaration extends DeclarationStatement, JSDocC /** @internal */ readonly modifiers?: NodeArray | undefined; } -export interface ExportDeclaration extends DeclarationStatement, JSDocContainer { +export interface ExportDeclaration extends DeclarationStatementBase, JSDocContainer { readonly kind: SyntaxKind.ExportDeclaration; readonly parent: SourceFile | ModuleBlock; readonly modifiers?: NodeArray; @@ -3698,13 +4434,13 @@ export interface ExportDeclaration extends DeclarationStatement, JSDocContainer readonly attributes?: ImportAttributes; } -export interface NamedImports extends Node { +export interface NamedImports extends NodeBase { readonly kind: SyntaxKind.NamedImports; readonly parent: ImportClause; readonly elements: NodeArray; } -export interface NamedExports extends Node { +export interface NamedExports extends NodeBase { readonly kind: SyntaxKind.NamedExports; readonly parent: ExportDeclaration; readonly elements: NodeArray; @@ -3712,7 +4448,7 @@ export interface NamedExports extends Node { export type NamedImportsOrExports = NamedImports | NamedExports; -export interface ImportSpecifier extends NamedDeclaration { +export interface ImportSpecifier extends NamedDeclarationBase { readonly kind: SyntaxKind.ImportSpecifier; readonly parent: NamedImports; readonly propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) @@ -3720,7 +4456,7 @@ export interface ImportSpecifier extends NamedDeclaration { readonly isTypeOnly: boolean; } -export interface ExportSpecifier extends NamedDeclaration, JSDocContainer { +export interface ExportSpecifier extends NamedDeclarationBase, JSDocContainer { readonly kind: SyntaxKind.ExportSpecifier; readonly parent: NamedExports; readonly isTypeOnly: boolean; @@ -3728,9 +4464,7 @@ export interface ExportSpecifier extends NamedDeclaration, JSDocContainer { readonly name: Identifier; // Declared name } -export type ImportOrExportSpecifier = - | ImportSpecifier - | ExportSpecifier; +export type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; export type TypeOnlyCompatibleAliasDeclaration = | ImportClause @@ -3741,24 +4475,59 @@ export type TypeOnlyCompatibleAliasDeclaration = | NamespaceExport; export type TypeOnlyImportDeclaration = - | ImportClause & { readonly isTypeOnly: true; readonly name: Identifier; } - | ImportEqualsDeclaration & { readonly isTypeOnly: true; } - | NamespaceImport & { readonly parent: ImportClause & { readonly isTypeOnly: true; }; } - | ImportSpecifier & ({ readonly isTypeOnly: true; } | { readonly parent: NamedImports & { readonly parent: ImportClause & { readonly isTypeOnly: true; }; }; }); + | (ImportClause & { readonly isTypeOnly: true; readonly name: Identifier; }) + | (ImportEqualsDeclaration & { readonly isTypeOnly: true; }) + | (NamespaceImport & { + readonly parent: ImportClause & { readonly isTypeOnly: true; }; + }) + | ( + & ImportSpecifier + & ( + | { readonly isTypeOnly: true; } + | { + readonly parent: NamedImports & { + readonly parent: ImportClause & { + readonly isTypeOnly: true; + }; + }; + } + ) + ); export type TypeOnlyExportDeclaration = - | ExportSpecifier & ({ readonly isTypeOnly: true; } | { readonly parent: NamedExports & { readonly parent: ExportDeclaration & { readonly isTypeOnly: true; }; }; }) - | ExportDeclaration & { readonly isTypeOnly: true; readonly moduleSpecifier: Expression; } // export * from "mod" - | NamespaceExport & { readonly parent: ExportDeclaration & { readonly isTypeOnly: true; readonly moduleSpecifier: Expression; }; } // export * as ns from "mod" -; - -export type TypeOnlyAliasDeclaration = TypeOnlyImportDeclaration | TypeOnlyExportDeclaration; + | ( + & ExportSpecifier + & ( + | { readonly isTypeOnly: true; } + | { + readonly parent: NamedExports & { + readonly parent: ExportDeclaration & { + readonly isTypeOnly: true; + }; + }; + } + ) + ) + | (ExportDeclaration & { + readonly isTypeOnly: true; + readonly moduleSpecifier: Expression; + }) // export * from "mod" + | (NamespaceExport & { + readonly parent: ExportDeclaration & { + readonly isTypeOnly: true; + readonly moduleSpecifier: Expression; + }; + }); // export * as ns from "mod" + +export type TypeOnlyAliasDeclaration = + | TypeOnlyImportDeclaration + | TypeOnlyExportDeclaration; /** * This is either an `export =` or an `export default` declaration. * Unless `isExportEquals` is set, this node was parsed as an `export default`. */ -export interface ExportAssignment extends DeclarationStatement, JSDocContainer { +export interface ExportAssignment extends DeclarationStatementBase, JSDocContainer { readonly kind: SyntaxKind.ExportAssignment; readonly parent: SourceFile; readonly modifiers?: NodeArray; @@ -3775,7 +4544,9 @@ export interface CheckJsDirective extends TextRange { enabled: boolean; } -export type CommentKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia; +export type CommentKind = + | SyntaxKind.SingleLineCommentTrivia + | SyntaxKind.MultiLineCommentTrivia; export interface CommentRange extends TextRange { hasTrailingNewLine?: boolean; @@ -3790,62 +4561,74 @@ export interface SynthesizedComment extends CommentRange { } // represents a top level: { type } expression in a JSDoc comment. -export interface JSDocTypeExpression extends TypeNode { +export interface JSDocTypeExpression extends TypeNodeBase { readonly kind: SyntaxKind.JSDocTypeExpression; readonly type: TypeNode; } -export interface JSDocNameReference extends Node { +export interface JSDocNameReference extends NodeBase { readonly kind: SyntaxKind.JSDocNameReference; readonly name: EntityName | JSDocMemberName; } /** Class#method reference in JSDoc */ -export interface JSDocMemberName extends Node { +export interface JSDocMemberName extends NodeBase { readonly kind: SyntaxKind.JSDocMemberName; readonly left: EntityName | JSDocMemberName; readonly right: Identifier; } -export interface JSDocType extends TypeNode { +export type JSDocType = + | JSDocAllType + | JSDocUnknownType + | JSDocNonNullableType + | JSDocNullableType + | JSDocOptionalType + | JSDocFunctionType + | JSDocVariadicType + | JSDocNamepathType + | JSDocSignature + | JSDocTypeLiteral; + +export interface JSDocTypeBase extends TypeNodeBase { _jsDocTypeBrand: any; } -export interface JSDocAllType extends JSDocType { +export interface JSDocAllType extends JSDocTypeBase { readonly kind: SyntaxKind.JSDocAllType; } -export interface JSDocUnknownType extends JSDocType { +export interface JSDocUnknownType extends JSDocTypeBase { readonly kind: SyntaxKind.JSDocUnknownType; } -export interface JSDocNonNullableType extends JSDocType { +export interface JSDocNonNullableType extends JSDocTypeBase { readonly kind: SyntaxKind.JSDocNonNullableType; readonly type: TypeNode; readonly postfix: boolean; } -export interface JSDocNullableType extends JSDocType { +export interface JSDocNullableType extends JSDocTypeBase { readonly kind: SyntaxKind.JSDocNullableType; readonly type: TypeNode; readonly postfix: boolean; } -export interface JSDocOptionalType extends JSDocType { +export interface JSDocOptionalType extends JSDocTypeBase { readonly kind: SyntaxKind.JSDocOptionalType; readonly type: TypeNode; } -export interface JSDocFunctionType extends JSDocType, SignatureDeclarationBase, LocalsContainer { +export interface JSDocFunctionType extends JSDocTypeBase, SignatureDeclarationBase, LocalsContainer { readonly kind: SyntaxKind.JSDocFunctionType; } -export interface JSDocVariadicType extends JSDocType { +export interface JSDocVariadicType extends JSDocTypeBase { readonly kind: SyntaxKind.JSDocVariadicType; readonly type: TypeNode; } -export interface JSDocNamepathType extends JSDocType { +export interface JSDocNamepathType extends JSDocTypeBase { readonly kind: SyntaxKind.JSDocNamepathType; readonly type: TypeNode; } @@ -3856,45 +4639,74 @@ export type JSDocTypeReferencingNode = | JSDocNullableType | JSDocNonNullableType; -export interface JSDoc extends Node { +export interface JSDoc extends NodeBase { readonly kind: SyntaxKind.JSDoc; readonly parent: HasJSDoc; readonly tags?: NodeArray; readonly comment?: string | NodeArray; } -export interface JSDocTag extends Node { - readonly parent: JSDoc | JSDocTypeLiteral; +export type JSDocTag = + | JSDocAugmentsTag + | JSDocAuthorTag + | JSDocCallbackTag + | JSDocClassTag + | JSDocDeprecatedTag + | JSDocEnumTag + | JSDocImplementsTag + | JSDocOverloadTag + | JSDocOverrideTag + | JSDocPrivateTag + | JSDocPropertyLikeTag + | JSDocProtectedTag + | JSDocPublicTag + | JSDocReadonlyTag + | JSDocReturnTag + | JSDocSatisfiesTag + | JSDocSeeTag + | JSDocTemplateTag + | JSDocThisTag + | JSDocThrowsTag + | JSDocTypedefTag + | JSDocTypeTag + | JSDocUnknownTag; + +export interface JSDocTagBase extends NodeBase { + readonly parent: JSDoc | JSDocPropertyLikeParent | JSDocTypeLiteral; readonly tagName: Identifier; readonly comment?: string | NodeArray; } -export interface JSDocLink extends Node { +export interface JSDocLink extends NodeBase { readonly kind: SyntaxKind.JSDocLink; readonly name?: EntityName | JSDocMemberName; text: string; } -export interface JSDocLinkCode extends Node { +export interface JSDocLinkCode extends NodeBase { readonly kind: SyntaxKind.JSDocLinkCode; readonly name?: EntityName | JSDocMemberName; text: string; } -export interface JSDocLinkPlain extends Node { +export interface JSDocLinkPlain extends NodeBase { readonly kind: SyntaxKind.JSDocLinkPlain; readonly name?: EntityName | JSDocMemberName; text: string; } -export type JSDocComment = JSDocText | JSDocLink | JSDocLinkCode | JSDocLinkPlain; +export type JSDocComment = + | JSDocText + | JSDocLink + | JSDocLinkCode + | JSDocLinkPlain; -export interface JSDocText extends Node { +export interface JSDocText extends NodeBase { readonly kind: SyntaxKind.JSDocText; text: string; } -export interface JSDocUnknownTag extends JSDocTag { +export interface JSDocUnknownTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocTag; } @@ -3902,81 +4714,85 @@ export interface JSDocUnknownTag extends JSDocTag { * Note that `@extends` is a synonym of `@augments`. * Both tags are represented by this interface. */ -export interface JSDocAugmentsTag extends JSDocTag { +export interface JSDocAugmentsTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocAugmentsTag; - readonly class: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; }; + readonly class: ExpressionWithTypeArguments & { + readonly expression: Identifier | PropertyAccessEntityNameExpression; + }; } -export interface JSDocImplementsTag extends JSDocTag { +export interface JSDocImplementsTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocImplementsTag; - readonly class: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression; }; + readonly class: ExpressionWithTypeArguments & { + readonly expression: Identifier | PropertyAccessEntityNameExpression; + }; } -export interface JSDocAuthorTag extends JSDocTag { +export interface JSDocAuthorTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocAuthorTag; } -export interface JSDocDeprecatedTag extends JSDocTag { +export interface JSDocDeprecatedTag extends JSDocTagBase { kind: SyntaxKind.JSDocDeprecatedTag; } -export interface JSDocClassTag extends JSDocTag { +export interface JSDocClassTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocClassTag; } -export interface JSDocPublicTag extends JSDocTag { +export interface JSDocPublicTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocPublicTag; } -export interface JSDocPrivateTag extends JSDocTag { +export interface JSDocPrivateTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocPrivateTag; } -export interface JSDocProtectedTag extends JSDocTag { +export interface JSDocProtectedTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocProtectedTag; } -export interface JSDocReadonlyTag extends JSDocTag { +export interface JSDocReadonlyTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocReadonlyTag; } -export interface JSDocOverrideTag extends JSDocTag { +export interface JSDocOverrideTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocOverrideTag; } -export interface JSDocEnumTag extends JSDocTag, Declaration, LocalsContainer { +export interface JSDocEnumTag extends JSDocTagBase, DeclarationBase, LocalsContainer { readonly kind: SyntaxKind.JSDocEnumTag; readonly parent: JSDoc; readonly typeExpression: JSDocTypeExpression; } -export interface JSDocThisTag extends JSDocTag { +export interface JSDocThisTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocThisTag; readonly typeExpression: JSDocTypeExpression; } -export interface JSDocTemplateTag extends JSDocTag { +export interface JSDocTemplateTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocTemplateTag; readonly constraint: JSDocTypeExpression | undefined; readonly typeParameters: NodeArray; } -export interface JSDocSeeTag extends JSDocTag { +export interface JSDocSeeTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocSeeTag; readonly name?: JSDocNameReference; } -export interface JSDocReturnTag extends JSDocTag { +export interface JSDocReturnTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocReturnTag; readonly typeExpression?: JSDocTypeExpression; } -export interface JSDocTypeTag extends JSDocTag { +export interface JSDocTypeTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocTypeTag; readonly typeExpression: JSDocTypeExpression; } -export interface JSDocTypedefTag extends JSDocTag, NamedDeclaration, LocalsContainer { +export interface JSDocTypedefTag extends JSDocTagBase, NamedDeclarationBase, LocalsContainer { readonly kind: SyntaxKind.JSDocTypedefTag; readonly parent: JSDoc; readonly fullName?: JSDocNamespaceDeclaration | Identifier; @@ -3984,7 +4800,7 @@ export interface JSDocTypedefTag extends JSDocTag, NamedDeclaration, LocalsConta readonly typeExpression?: JSDocTypeExpression | JSDocTypeLiteral; } -export interface JSDocCallbackTag extends JSDocTag, NamedDeclaration, LocalsContainer { +export interface JSDocCallbackTag extends JSDocTagBase, NamedDeclarationBase, LocalsContainer { readonly kind: SyntaxKind.JSDocCallbackTag; readonly parent: JSDoc; readonly fullName?: JSDocNamespaceDeclaration | Identifier; @@ -3992,26 +4808,35 @@ export interface JSDocCallbackTag extends JSDocTag, NamedDeclaration, LocalsCont readonly typeExpression: JSDocSignature; } -export interface JSDocOverloadTag extends JSDocTag { +export interface JSDocOverloadTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocOverloadTag; readonly parent: JSDoc; readonly typeExpression: JSDocSignature; } -export interface JSDocThrowsTag extends JSDocTag { +export interface JSDocThrowsTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocThrowsTag; readonly typeExpression?: JSDocTypeExpression; } -export interface JSDocSignature extends JSDocType, Declaration, JSDocContainer, LocalsContainer { +export interface JSDocSignature extends JSDocTypeBase, DeclarationBase, JSDocContainer, LocalsContainer { readonly kind: SyntaxKind.JSDocSignature; readonly typeParameters?: readonly JSDocTemplateTag[]; readonly parameters: readonly JSDocParameterTag[]; readonly type: JSDocReturnTag | undefined; } -export interface JSDocPropertyLikeTag extends JSDocTag, Declaration { - readonly parent: JSDoc; +export type JSDocPropertyLikeParent = + | JSDocSignature + | JSDocTypeLiteral + | JSDocPropertyLikeTag; + +export type JSDocPropertyLikeTag = + | JSDocParameterTag + | JSDocPropertyTag; + +export interface JSDocPropertyLikeTagBase extends JSDocTagBase, DeclarationBase { + readonly parent: JSDocPropertyLikeParent; readonly name: EntityName; readonly typeExpression?: JSDocTypeExpression; /** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */ @@ -4019,22 +4844,22 @@ export interface JSDocPropertyLikeTag extends JSDocTag, Declaration { readonly isBracketed: boolean; } -export interface JSDocPropertyTag extends JSDocPropertyLikeTag { +export interface JSDocPropertyTag extends JSDocPropertyLikeTagBase { readonly kind: SyntaxKind.JSDocPropertyTag; } -export interface JSDocParameterTag extends JSDocPropertyLikeTag { +export interface JSDocParameterTag extends JSDocPropertyLikeTagBase { readonly kind: SyntaxKind.JSDocParameterTag; } -export interface JSDocTypeLiteral extends JSDocType, Declaration { +export interface JSDocTypeLiteral extends JSDocTypeBase, DeclarationBase { readonly kind: SyntaxKind.JSDocTypeLiteral; readonly jsDocPropertyTags?: readonly JSDocPropertyLikeTag[]; /** If true, then this type literal represents an *array* of its type. */ readonly isArrayType: boolean; } -export interface JSDocSatisfiesTag extends JSDocTag { +export interface JSDocSatisfiesTag extends JSDocTagBase { readonly kind: SyntaxKind.JSDocSatisfiesTag; readonly typeExpression: JSDocTypeExpression; } @@ -4047,19 +4872,19 @@ export interface JSDocSatisfiesExpression extends ParenthesizedExpression { // NOTE: Ensure this is up-to-date with src/debug/debug.ts // dprint-ignore export const enum FlowFlags { - Unreachable = 1 << 0, // Unreachable code - Start = 1 << 1, // Start of flow graph - BranchLabel = 1 << 2, // Non-looping junction - LoopLabel = 1 << 3, // Looping junction - Assignment = 1 << 4, // Assignment - TrueCondition = 1 << 5, // Condition known to be true - FalseCondition = 1 << 6, // Condition known to be false - SwitchClause = 1 << 7, // Switch statement clause - ArrayMutation = 1 << 8, // Potential array mutation - Call = 1 << 9, // Potential assertion call - ReduceLabel = 1 << 10, // Temporarily reduce antecedents of label - Referenced = 1 << 11, // Referenced as antecedent once - Shared = 1 << 12, // Referenced as antecedent more than once + Unreachable = 1 << 0, // Unreachable code + Start = 1 << 1, // Start of flow graph + BranchLabel = 1 << 2, // Non-looping junction + LoopLabel = 1 << 3, // Looping junction + Assignment = 1 << 4, // Assignment + TrueCondition = 1 << 5, // Condition known to be true + FalseCondition = 1 << 6, // Condition known to be false + SwitchClause = 1 << 7, // Switch statement clause + ArrayMutation = 1 << 8, // Potential array mutation + Call = 1 << 9, // Potential assertion call + ReduceLabel = 1 << 10, // Temporarily reduce antecedents of label + Referenced = 1 << 11, // Referenced as antecedent once + Shared = 1 << 12, // Referenced as antecedent more than once Label = BranchLabel | LoopLabel, Condition = TrueCondition | FalseCondition, @@ -4084,7 +4909,12 @@ export interface FlowNodeBase { // function, the node property references the function (which in turn has a flowNode // property for the containing control flow). export interface FlowStart extends FlowNodeBase { - node?: FunctionExpression | ArrowFunction | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration; + node?: + | FunctionExpression + | ArrowFunction + | MethodDeclaration + | GetAccessorDeclaration + | SetAccessorDeclaration; } // FlowLabel represents a junction with multiple possible preceding control flows. @@ -4114,8 +4944,8 @@ export interface FlowCondition extends FlowNodeBase { // dprint-ignore export interface FlowSwitchClause extends FlowNodeBase { switchStatement: SwitchStatement; - clauseStart: number; // Start index of case/default clause range - clauseEnd: number; // End index of case/default clause range + clauseStart: number; // Start index of case/default clause range + clauseEnd: number; // End index of case/default clause range antecedent: FlowNode; } @@ -4139,8 +4969,8 @@ export type FlowType = Type | IncompleteType; // objects are internal to the getFlowTypeOfReference function and never escape it. // dprint-ignore export interface IncompleteType { - flags: TypeFlags | 0; // No flags set - type: Type; // The type marked incomplete + flags: TypeFlags | 0; // No flags set + type: Type; // The type marked incomplete } export interface AmdDependency { @@ -4156,7 +4986,11 @@ export interface SourceFileLike { /** @internal */ lineMap?: readonly number[]; /** @internal */ - getPositionOfLineAndCharacter?(line: number, character: number, allowEdits?: true): number; + getPositionOfLineAndCharacter?( + line: number, + character: number, + allowEdits?: true, + ): number; } /** @internal */ @@ -4170,13 +5004,16 @@ export interface RedirectInfo { readonly unredirected: SourceFile; } -export type ResolutionMode = ModuleKind.ESNext | ModuleKind.CommonJS | undefined; +export type ResolutionMode = + | ModuleKind.ESNext + | ModuleKind.CommonJS + | undefined; // Source files are declarations when they are external modules. -export interface SourceFile extends Declaration, LocalsContainer { +export interface SourceFile extends DeclarationBase, LocalsContainer { readonly kind: SyntaxKind.SourceFile; readonly statements: NodeArray; - readonly endOfFileToken: Token; + readonly endOfFileToken: EndOfFileToken; fileName: string; /** @internal */ path: Path; @@ -4302,7 +5139,10 @@ export interface SourceFile extends Declaration, LocalsContainer { /** @internal */ commentDirectives?: CommentDirective[]; /** @internal */ imports: readonly StringLiteralLike[]; // Identifier only if `declare global` - /** @internal */ moduleAugmentations: readonly (StringLiteral | Identifier)[]; + /** @internal */ moduleAugmentations: readonly ( + | StringLiteral + | Identifier + )[]; /** @internal */ patternAmbientModules?: PatternAmbientModule[]; /** @internal */ ambientModuleNames: readonly string[]; /** @internal */ checkJsDirective?: CheckJsDirective; @@ -4359,9 +5199,12 @@ export const enum CommentDirectiveType { /** @internal */ export type ExportedModulesFromDeclarationEmit = readonly Symbol[]; -export interface Bundle extends Node { +export interface Bundle extends NodeBase { readonly kind: SyntaxKind.Bundle; - /** @deprecated */ readonly prepends: readonly (InputFiles | UnparsedSource)[]; + /** @deprecated */ readonly prepends: readonly ( + | InputFiles + | UnparsedSource + )[]; readonly sourceFiles: readonly SourceFile[]; /** @internal */ syntheticFileReferences?: readonly FileReference[]; /** @internal */ syntheticTypeReferences?: readonly FileReference[]; @@ -4370,7 +5213,7 @@ export interface Bundle extends Node { } /** @deprecated */ -export interface InputFiles extends Node { +export interface InputFiles extends NodeBase { readonly kind: SyntaxKind.InputFiles; javascriptPath?: string; javascriptText: string; @@ -4386,7 +5229,7 @@ export interface InputFiles extends Node { } /** @deprecated */ -export interface UnparsedSource extends Node { +export interface UnparsedSource extends NodeBase { readonly kind: SyntaxKind.UnparsedSource; fileName: string; text: string; @@ -4411,9 +5254,7 @@ export interface UnparsedSource extends Node { } /** @deprecated */ -export type UnparsedSourceText = - | UnparsedPrepend - | UnparsedTextLike; +export type UnparsedSourceText = UnparsedPrepend | UnparsedTextLike; /** @deprecated */ export type UnparsedNode = @@ -4422,7 +5263,7 @@ export type UnparsedNode = | UnparsedSyntheticReference; /** @deprecated */ -export interface UnparsedSection extends Node { +export interface UnparsedSection extends NodeBase { readonly kind: SyntaxKind; readonly parent: UnparsedSource; readonly data?: string; @@ -4453,7 +5294,9 @@ export interface UnparsedTextLike extends UnparsedSection { export interface UnparsedSyntheticReference extends UnparsedSection { readonly kind: SyntaxKind.UnparsedSyntheticReference; readonly parent: UnparsedSource; - /** @internal */ readonly section: BundleFileHasNoDefaultLib | BundleFileReference; + /** @internal */ readonly section: + | BundleFileHasNoDefaultLib + | BundleFileReference; } export interface JsonSourceFile extends SourceFile { @@ -4494,7 +5337,13 @@ export interface ScriptReferenceHost { export interface ParseConfigHost extends ModuleResolutionHost { useCaseSensitiveFileNames: boolean; - readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): readonly string[]; + readDirectory( + rootDir: string, + extensions: readonly string[], + excludes: readonly string[] | undefined, + includes: readonly string[], + depth?: number, + ): readonly string[]; /** * Gets a value indicating whether the specified path exists and is a file. @@ -4511,7 +5360,9 @@ export interface ParseConfigHost extends ModuleResolutionHost { * specified like "./blah" to an absolute path to an actual * tsconfig file, e.g. "/root/blah/tsconfig.json" */ -export type ResolvedConfigFileName = string & { _isResolvedConfigFileName: never; }; +export type ResolvedConfigFileName = string & { + _isResolvedConfigFileName: never; +}; export interface WriteFileCallbackData { /** @internal */ sourceMapUrlPos?: number; @@ -4633,7 +5484,10 @@ export interface ResolutionDiagnostics { } /** @internal */ -export type FilePreprocessingDiagnostics = FilePreprocessingReferencedDiagnostic | FilePreprocessingFileExplainingDiagnostic | ResolutionDiagnostics; +export type FilePreprocessingDiagnostics = + | FilePreprocessingReferencedDiagnostic + | FilePreprocessingFileExplainingDiagnostic + | ResolutionDiagnostics; /** @internal */ export const enum EmitOnly { @@ -4642,7 +5496,9 @@ export const enum EmitOnly { } /** @internal */ -export interface LibResolution { +export interface LibResolution< + T extends ResolvedModuleWithFailedLookupLocations = ResolvedModuleWithFailedLookupLocations, +> { resolution: T; actual: string; } @@ -4671,21 +5527,46 @@ export interface Program extends ScriptReferenceHost { getFilesByNameMap(): Map; /** @internal */ - resolvedModules: Map> | undefined; + resolvedModules: + | Map> + | undefined; /** @internal */ - resolvedTypeReferenceDirectiveNames: Map> | undefined; + resolvedTypeReferenceDirectiveNames: + | Map< + Path, + ModeAwareCache + > + | undefined; /** @internal */ - getResolvedModule(f: SourceFile, moduleName: string, mode: ResolutionMode): ResolvedModuleWithFailedLookupLocations | undefined; + getResolvedModule( + f: SourceFile, + moduleName: string, + mode: ResolutionMode, + ): ResolvedModuleWithFailedLookupLocations | undefined; /** @internal */ - getResolvedTypeReferenceDirective(f: SourceFile, typeDirectiveName: string, mode: ResolutionMode): ResolvedTypeReferenceDirectiveWithFailedLookupLocations | undefined; + getResolvedTypeReferenceDirective( + f: SourceFile, + typeDirectiveName: string, + mode: ResolutionMode, + ): ResolvedTypeReferenceDirectiveWithFailedLookupLocations | undefined; /** @internal */ forEachResolvedModule( - callback: (resolution: ResolvedModuleWithFailedLookupLocations, moduleName: string, mode: ResolutionMode, filePath: Path) => void, + callback: ( + resolution: ResolvedModuleWithFailedLookupLocations, + moduleName: string, + mode: ResolutionMode, + filePath: Path, + ) => void, file?: SourceFile, ): void; /** @internal */ forEachResolvedTypeReferenceDirective( - callback: (resolution: ResolvedTypeReferenceDirectiveWithFailedLookupLocations, moduleName: string, mode: ResolutionMode, filePath: Path) => void, + callback: ( + resolution: ResolvedTypeReferenceDirectiveWithFailedLookupLocations, + moduleName: string, + mode: ResolutionMode, + filePath: Path, + ) => void, file?: SourceFile, ): void; @@ -4699,21 +5580,56 @@ export interface Program extends ScriptReferenceHost { * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter * will be invoked when writing the JavaScript and declaration files. */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; - /** @internal */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnly?: boolean | EmitOnly, customTransformers?: CustomTransformers, forceDtsEmit?: boolean): EmitResult; - - getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; - getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[]; - getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; + emit( + targetSourceFile?: SourceFile, + writeFile?: WriteFileCallback, + cancellationToken?: CancellationToken, + emitOnlyDtsFiles?: boolean, + customTransformers?: CustomTransformers, + ): EmitResult; + /** @internal */ + emit( + targetSourceFile?: SourceFile, + writeFile?: WriteFileCallback, + cancellationToken?: CancellationToken, + emitOnly?: boolean | EmitOnly, + customTransformers?: CustomTransformers, + forceDtsEmit?: boolean, + ): EmitResult; + + getOptionsDiagnostics( + cancellationToken?: CancellationToken, + ): readonly Diagnostic[]; + getGlobalDiagnostics( + cancellationToken?: CancellationToken, + ): readonly Diagnostic[]; + getSyntacticDiagnostics( + sourceFile?: SourceFile, + cancellationToken?: CancellationToken, + ): readonly DiagnosticWithLocation[]; /** The first time this is called, it will return global diagnostics (no location). */ - getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; - getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; + getSemanticDiagnostics( + sourceFile?: SourceFile, + cancellationToken?: CancellationToken, + ): readonly Diagnostic[]; + getDeclarationDiagnostics( + sourceFile?: SourceFile, + cancellationToken?: CancellationToken, + ): readonly DiagnosticWithLocation[]; getConfigFileParsingDiagnostics(): readonly Diagnostic[]; - /** @internal */ getSuggestionDiagnostics(sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; - - /** @internal */ getBindAndCheckDiagnostics(sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; - /** @internal */ getProgramDiagnostics(sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; + /** @internal */ getSuggestionDiagnostics( + sourceFile: SourceFile, + cancellationToken?: CancellationToken, + ): readonly DiagnosticWithLocation[]; + + /** @internal */ getBindAndCheckDiagnostics( + sourceFile: SourceFile, + cancellationToken?: CancellationToken, + ): readonly Diagnostic[]; + /** @internal */ getProgramDiagnostics( + sourceFile: SourceFile, + cancellationToken?: CancellationToken, + ): readonly Diagnostic[]; /** * Gets a type checker that can be used to semantically analyze source files in the program. @@ -4722,7 +5638,9 @@ export interface Program extends ScriptReferenceHost { /** @internal */ getCommonSourceDirectory(): string; - /** @internal */ getCachedSemanticDiagnostics(sourceFile?: SourceFile): readonly Diagnostic[] | undefined; + /** @internal */ getCachedSemanticDiagnostics( + sourceFile?: SourceFile, + ): readonly Diagnostic[] | undefined; /** @internal */ getClassifiableNames(): Set<__String>; @@ -4731,9 +5649,16 @@ export interface Program extends ScriptReferenceHost { getSymbolCount(): number; getTypeCount(): number; getInstantiationCount(): number; - getRelationCacheSizes(): { assignable: number; identity: number; subtype: number; strictSubtype: number; }; - - /** @internal */ getFileProcessingDiagnostics(): FilePreprocessingDiagnostics[] | undefined; + getRelationCacheSizes(): { + assignable: number; + identity: number; + subtype: number; + strictSubtype: number; + }; + + /** @internal */ getFileProcessingDiagnostics(): + | FilePreprocessingDiagnostics[] + | undefined; /** @internal */ getResolvedTypeReferenceDirectives(): ModeAwareCache; /** @internal */ getAutomaticTypeDirectiveNames(): string[]; /** @internal */ getAutomaticTypeDirectiveResolutions(): ModeAwareCache; @@ -4744,8 +5669,13 @@ export interface Program extends ScriptReferenceHost { // This is set on created program to let us know how the program was created using old program /** @internal */ readonly structureIsReused: StructureIsReused; - /** @internal */ getSourceFileFromReference(referencingFile: SourceFile | UnparsedSource, ref: FileReference): SourceFile | undefined; - /** @internal */ getLibFileFromReference(ref: FileReference): SourceFile | undefined; + /** @internal */ getSourceFileFromReference( + referencingFile: SourceFile | UnparsedSource, + ref: FileReference, + ): SourceFile | undefined; + /** @internal */ getLibFileFromReference( + ref: FileReference, + ): SourceFile | undefined; /** * Given a source file, get the name of the package it was imported from. @@ -4782,14 +5712,33 @@ export interface Program extends ScriptReferenceHost { /** @internal */ getCanonicalFileName: GetCanonicalFileName; getProjectReferences(): readonly ProjectReference[] | undefined; - getResolvedProjectReferences(): readonly (ResolvedProjectReference | undefined)[] | undefined; - /** @internal */ getProjectReferenceRedirect(fileName: string): string | undefined; - /** @internal */ getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined; - /** @internal */ forEachResolvedProjectReference(cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined): T | undefined; - /** @internal */ getResolvedProjectReferenceByPath(projectReferencePath: Path): ResolvedProjectReference | undefined; - /** @internal */ isSourceOfProjectReferenceRedirect(fileName: string): boolean; - /** @internal */ getBuildInfo?(bundle: BundleBuildInfo | undefined): BuildInfo; - /** @internal */ emitBuildInfo(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + getResolvedProjectReferences(): + | readonly (ResolvedProjectReference | undefined)[] + | undefined; + /** @internal */ getProjectReferenceRedirect( + fileName: string, + ): string | undefined; + /** @internal */ getResolvedProjectReferenceToRedirect( + fileName: string, + ): ResolvedProjectReference | undefined; + /** @internal */ forEachResolvedProjectReference( + cb: ( + resolvedProjectReference: ResolvedProjectReference, + ) => T | undefined, + ): T | undefined; + /** @internal */ getResolvedProjectReferenceByPath( + projectReferencePath: Path, + ): ResolvedProjectReference | undefined; + /** @internal */ isSourceOfProjectReferenceRedirect( + fileName: string, + ): boolean; + /** @internal */ getBuildInfo?( + bundle: BundleBuildInfo | undefined, + ): BuildInfo; + /** @internal */ emitBuildInfo( + writeFile?: WriteFileCallback, + cancellationToken?: CancellationToken, + ): EmitResult; /** * This implementation handles file exists to be true if file is source of project reference redirect when program is created using useSourceOfProjectReferenceRedirect * @@ -4805,8 +5754,7 @@ export interface Program extends ScriptReferenceHost { } /** @internal */ -export interface Program extends TypeCheckerHost, ModuleSpecifierResolutionHost { -} +export interface Program extends TypeCheckerHost, ModuleSpecifierResolutionHost {} /** @internal */ export type RedirectTargetsMap = ReadonlyMap; @@ -4824,7 +5772,9 @@ export const enum StructureIsReused { Completely, } -export type CustomTransformerFactory = (context: TransformationContext) => CustomTransformer; +export type CustomTransformerFactory = ( + context: TransformationContext, +) => CustomTransformer; export interface CustomTransformer { transformSourceFile(node: SourceFile): SourceFile; @@ -4837,7 +5787,10 @@ export interface CustomTransformers { /** Custom transformers to evaluate after built-in .js transformations. */ after?: (TransformerFactory | CustomTransformerFactory)[]; /** Custom transformers to evaluate after built-in .d.ts transformations. */ - afterDeclarations?: (TransformerFactory | CustomTransformerFactory)[]; + afterDeclarations?: ( + | TransformerFactory + | CustomTransformerFactory + )[]; } /** @internal */ @@ -4905,7 +5858,11 @@ export interface TypeCheckerHost extends ModuleSpecifierResolutionHost { getProjectReferenceRedirect(fileName: string): string | undefined; isSourceOfProjectReferenceRedirect(fileName: string): boolean; - getResolvedModule(f: SourceFile, moduleName: string, mode: ResolutionMode): ResolvedModuleWithFailedLookupLocations | undefined; + getResolvedModule( + f: SourceFile, + moduleName: string, + mode: ResolutionMode, + ): ResolvedModuleWithFailedLookupLocations | undefined; readonly redirectTargetsMap: RedirectTargetsMap; @@ -4919,8 +5876,15 @@ export interface TypeChecker { getDeclaredTypeOfSymbol(symbol: Symbol): Type; getPropertiesOfType(type: Type): Symbol[]; getPropertyOfType(type: Type, propertyName: string): Symbol | undefined; - getPrivateIdentifierPropertyOfType(leftType: Type, name: string, location: Node): Symbol | undefined; - /** @internal */ getTypeOfPropertyOfType(type: Type, propertyName: string): Type | undefined; + getPrivateIdentifierPropertyOfType( + leftType: Type, + name: string, + location: Node, + ): Symbol | undefined; + /** @internal */ getTypeOfPropertyOfType( + type: Type, + propertyName: string, + ): Type | undefined; getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; getIndexInfosOfType(type: Type): readonly IndexInfo[]; getIndexInfosOfIndexSymbol: (indexSymbol: Symbol) => IndexInfo[]; @@ -4944,7 +5908,16 @@ export interface TypeChecker { * @internal */ getParameterType(signature: Signature, parameterIndex: number): Type; - /** @internal */ getParameterIdentifierInfoAtPosition(signature: Signature, parameterIndex: number): { parameter: Identifier; parameterName: __String; isRestParameter: boolean; } | undefined; + /** @internal */ getParameterIdentifierInfoAtPosition( + signature: Signature, + parameterIndex: number, + ): + | { + parameter: Identifier; + parameterName: __String; + isRestParameter: boolean; + } + | undefined; getNullableType(type: Type, flags: TypeFlags): Type; getNonNullableType(type: Type): Type; /** @internal */ getNonOptionalType(type: Type): Type; @@ -4953,42 +5926,111 @@ export interface TypeChecker { // TODO: GH#18217 `xToDeclaration` calls are frequently asserted as defined. /** Note that the resulting nodes cannot be checked. */ - typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeNode | undefined; - /** @internal */ typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): TypeNode | undefined; // eslint-disable-line @typescript-eslint/unified-signatures + typeToTypeNode( + type: Type, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + ): TypeNode | undefined; + /** @internal */ typeToTypeNode( + type: Type, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + tracker?: SymbolTracker, + ): TypeNode | undefined; // eslint-disable-line @typescript-eslint/unified-signatures /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): SignatureDeclaration & { typeArguments?: NodeArray; } | undefined; - /** @internal */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): SignatureDeclaration & { typeArguments?: NodeArray; } | undefined; // eslint-disable-line @typescript-eslint/unified-signatures + signatureToSignatureDeclaration( + signature: Signature, + kind: SyntaxKind, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + ): + | (SignatureDeclaration & { typeArguments?: NodeArray; }) + | undefined; + /** @internal */ signatureToSignatureDeclaration( + signature: Signature, + kind: SyntaxKind, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + tracker?: SymbolTracker, + ): + | (SignatureDeclaration & { typeArguments?: NodeArray; }) + | undefined; // eslint-disable-line @typescript-eslint/unified-signatures /** Note that the resulting nodes cannot be checked. */ - indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): IndexSignatureDeclaration | undefined; - /** @internal */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): IndexSignatureDeclaration | undefined; // eslint-disable-line @typescript-eslint/unified-signatures + indexInfoToIndexSignatureDeclaration( + indexInfo: IndexInfo, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + ): IndexSignatureDeclaration | undefined; + /** @internal */ indexInfoToIndexSignatureDeclaration( + indexInfo: IndexInfo, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + tracker?: SymbolTracker, + ): IndexSignatureDeclaration | undefined; // eslint-disable-line @typescript-eslint/unified-signatures /** Note that the resulting nodes cannot be checked. */ - symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): EntityName | undefined; + symbolToEntityName( + symbol: Symbol, + meaning: SymbolFlags, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + ): EntityName | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): Expression | undefined; + symbolToExpression( + symbol: Symbol, + meaning: SymbolFlags, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + ): Expression | undefined; /** * Note that the resulting nodes cannot be checked. * * @internal */ - symbolToNode(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): Node | undefined; + symbolToNode( + symbol: Symbol, + meaning: SymbolFlags, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + ): Node | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): NodeArray | undefined; + symbolToTypeParameterDeclarations( + symbol: Symbol, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + ): NodeArray | undefined; /** Note that the resulting nodes cannot be checked. */ - symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): ParameterDeclaration | undefined; + symbolToParameterDeclaration( + symbol: Symbol, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + ): ParameterDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ - typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeParameterDeclaration | undefined; + typeParameterToDeclaration( + parameter: TypeParameter, + enclosingDeclaration: Node | undefined, + flags: NodeBuilderFlags | undefined, + ): TypeParameterDeclaration | undefined; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; - /** @internal */ getIndexInfosAtLocation(node: Node): readonly IndexInfo[] | undefined; - getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; + /** @internal */ getIndexInfosAtLocation( + node: Node, + ): readonly IndexInfo[] | undefined; + getSymbolsOfParameterPropertyDeclaration( + parameter: ParameterDeclaration, + parameterName: string, + ): Symbol[]; /** * The function returns the value (local variable) symbol of an identifier in the short-hand property assignment. * This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value. */ - getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined; + getShorthandAssignmentValueSymbol( + location: Node | undefined, + ): Symbol | undefined; - getExportSpecifierLocalTargetSymbol(location: ExportSpecifier | Identifier): Symbol | undefined; + getExportSpecifierLocalTargetSymbol( + location: ExportSpecifier | Identifier, + ): Symbol | undefined; /** * If a symbol is a local symbol with an associated exported symbol, returns the exported symbol. * Otherwise returns its input. @@ -4998,61 +6040,151 @@ export interface TypeChecker { * - Calling `getExportSymbolOfSymbol` on that local symbol will return the exported symbol. */ getExportSymbolOfSymbol(symbol: Symbol): Symbol; - getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined; + getPropertySymbolOfDestructuringAssignment( + location: Identifier, + ): Symbol | undefined; getTypeOfAssignmentPattern(pattern: AssignmentPattern): Type; getTypeAtLocation(node: Node): Type; getTypeFromTypeNode(node: TypeNode): Type; - signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; - typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; - typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - - /** @internal */ writeSignature(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind, writer?: EmitTextWriter): string; - /** @internal */ writeType(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags, writer?: EmitTextWriter): string; - /** @internal */ writeSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags, writer?: EmitTextWriter): string; - /** @internal */ writeTypePredicate(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags, writer?: EmitTextWriter): string; + signatureToString( + signature: Signature, + enclosingDeclaration?: Node, + flags?: TypeFormatFlags, + kind?: SignatureKind, + ): string; + typeToString( + type: Type, + enclosingDeclaration?: Node, + flags?: TypeFormatFlags, + ): string; + symbolToString( + symbol: Symbol, + enclosingDeclaration?: Node, + meaning?: SymbolFlags, + flags?: SymbolFormatFlags, + ): string; + typePredicateToString( + predicate: TypePredicate, + enclosingDeclaration?: Node, + flags?: TypeFormatFlags, + ): string; + + /** @internal */ writeSignature( + signature: Signature, + enclosingDeclaration?: Node, + flags?: TypeFormatFlags, + kind?: SignatureKind, + writer?: EmitTextWriter, + ): string; + /** @internal */ writeType( + type: Type, + enclosingDeclaration?: Node, + flags?: TypeFormatFlags, + writer?: EmitTextWriter, + ): string; + /** @internal */ writeSymbol( + symbol: Symbol, + enclosingDeclaration?: Node, + meaning?: SymbolFlags, + flags?: SymbolFormatFlags, + writer?: EmitTextWriter, + ): string; + /** @internal */ writeTypePredicate( + predicate: TypePredicate, + enclosingDeclaration?: Node, + flags?: TypeFormatFlags, + writer?: EmitTextWriter, + ): string; getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; getRootSymbols(symbol: Symbol): readonly Symbol[]; - getSymbolOfExpando(node: Node, allowDeclaration: boolean): Symbol | undefined; + getSymbolOfExpando( + node: Node, + allowDeclaration: boolean, + ): Symbol | undefined; getContextualType(node: Expression): Type | undefined; - /** @internal */ getContextualType(node: Expression, contextFlags?: ContextFlags): Type | undefined; // eslint-disable-line @typescript-eslint/unified-signatures - /** @internal */ getContextualTypeForObjectLiteralElement(element: ObjectLiteralElementLike): Type | undefined; - /** @internal */ getContextualTypeForArgumentAtIndex(call: CallLikeExpression, argIndex: number): Type | undefined; - /** @internal */ getContextualTypeForJsxAttribute(attribute: JsxAttribute | JsxSpreadAttribute): Type | undefined; - /** @internal */ isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElementLike | JsxAttributeLike): boolean; - /** @internal */ getTypeOfPropertyOfContextualType(type: Type, name: __String): Type | undefined; + /** @internal */ getContextualType( + node: Expression, + contextFlags?: ContextFlags, + ): Type | undefined; // eslint-disable-line @typescript-eslint/unified-signatures + /** @internal */ getContextualTypeForObjectLiteralElement( + element: ObjectLiteralElementLike, + ): Type | undefined; + /** @internal */ getContextualTypeForArgumentAtIndex( + call: CallLikeExpression, + argIndex: number, + ): Type | undefined; + /** @internal */ getContextualTypeForJsxAttribute( + attribute: JsxAttribute | JsxSpreadAttribute, + ): Type | undefined; + /** @internal */ isContextSensitive( + node: + | Expression + | MethodDeclaration + | ObjectLiteralElementLike + | JsxAttributeLike, + ): boolean; + /** @internal */ getTypeOfPropertyOfContextualType( + type: Type, + name: __String, + ): Type | undefined; /** * returns unknownSignature in the case of an error. * returns undefined if the node is not valid. * @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`. */ - getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; - /** @internal */ getResolvedSignatureForSignatureHelp(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined; - /** @internal */ getCandidateSignaturesForStringLiteralCompletions(call: CallLikeExpression, editingArgument: Node): Signature[]; - /** @internal */ getExpandedParameters(sig: Signature): readonly (readonly Symbol[])[]; + getResolvedSignature( + node: CallLikeExpression, + candidatesOutArray?: Signature[], + argumentCount?: number, + ): Signature | undefined; + /** @internal */ getResolvedSignatureForSignatureHelp( + node: CallLikeExpression, + candidatesOutArray?: Signature[], + argumentCount?: number, + ): Signature | undefined; + /** @internal */ getCandidateSignaturesForStringLiteralCompletions( + call: CallLikeExpression, + editingArgument: Node, + ): Signature[]; + /** @internal */ getExpandedParameters( + sig: Signature, + ): readonly (readonly Symbol[])[]; /** @internal */ hasEffectiveRestParameter(sig: Signature): boolean; - /** @internal */ containsArgumentsReference(declaration: SignatureDeclaration): boolean; + /** @internal */ containsArgumentsReference( + declaration: SignatureDeclaration, + ): boolean; - getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined; + getSignatureFromDeclaration( + declaration: SignatureDeclaration, + ): Signature | undefined; isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; isUnknownSymbol(symbol: Symbol): boolean; /** @internal */ getMergedSymbol(symbol: Symbol): Symbol; - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; - isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean; + getConstantValue( + node: EnumMember | PropertyAccessExpression | ElementAccessExpression, + ): string | number | undefined; + isValidPropertyAccess( + node: PropertyAccessExpression | QualifiedName | ImportTypeNode, + propertyName: string, + ): boolean; /** * Exclude accesses to private properties. * * @internal */ - isValidPropertyAccessForCompletions(node: PropertyAccessExpression | ImportTypeNode | QualifiedName, type: Type, property: Symbol): boolean; + isValidPropertyAccessForCompletions( + node: PropertyAccessExpression | ImportTypeNode | QualifiedName, + type: Type, + property: Symbol, + ): boolean; /** Follow all aliases to get the original symbol. */ getAliasedSymbol(symbol: Symbol): Symbol; /** Follow a *single* alias to get the immediately aliased symbol. */ @@ -5064,28 +6196,63 @@ export interface TypeChecker { * @internal */ getExportsAndPropertiesOfModule(moduleSymbol: Symbol): Symbol[]; - /** @internal */ forEachExportAndPropertyOfModule(moduleSymbol: Symbol, cb: (symbol: Symbol, key: __String) => void): void; + /** @internal */ forEachExportAndPropertyOfModule( + moduleSymbol: Symbol, + cb: (symbol: Symbol, key: __String) => void, + ): void; getJsxIntrinsicTagNamesAt(location: Node): Symbol[]; isOptionalParameter(node: ParameterDeclaration): boolean; getAmbientModules(): Symbol[]; - tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined; + tryGetMemberInModuleExports( + memberName: string, + moduleSymbol: Symbol, + ): Symbol | undefined; /** * Unlike `tryGetMemberInModuleExports`, this includes properties of an `export =` value. * Does *not* return properties of primitive types. * * @internal */ - tryGetMemberInModuleExportsAndProperties(memberName: string, moduleSymbol: Symbol): Symbol | undefined; + tryGetMemberInModuleExportsAndProperties( + memberName: string, + moduleSymbol: Symbol, + ): Symbol | undefined; getApparentType(type: Type): Type; - /** @internal */ getSuggestedSymbolForNonexistentProperty(name: MemberName | string, containingType: Type): Symbol | undefined; - /** @internal */ getSuggestedSymbolForNonexistentJSXAttribute(name: Identifier | string, containingType: Type): Symbol | undefined; - /** @internal */ getSuggestionForNonexistentProperty(name: MemberName | string, containingType: Type): string | undefined; - /** @internal */ getSuggestedSymbolForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): Symbol | undefined; - /** @internal */ getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined; - /** @internal */ getSuggestedSymbolForNonexistentModule(node: Identifier, target: Symbol): Symbol | undefined; - /** @internal */ getSuggestedSymbolForNonexistentClassMember(name: string, baseType: Type): Symbol | undefined; - /** @internal */ getSuggestionForNonexistentExport(node: Identifier, target: Symbol): string | undefined; + /** @internal */ getSuggestedSymbolForNonexistentProperty( + name: MemberName | string, + containingType: Type, + ): Symbol | undefined; + /** @internal */ getSuggestedSymbolForNonexistentJSXAttribute( + name: Identifier | string, + containingType: Type, + ): Symbol | undefined; + /** @internal */ getSuggestionForNonexistentProperty( + name: MemberName | string, + containingType: Type, + ): string | undefined; + /** @internal */ getSuggestedSymbolForNonexistentSymbol( + location: Node, + name: string, + meaning: SymbolFlags, + ): Symbol | undefined; + /** @internal */ getSuggestionForNonexistentSymbol( + location: Node, + name: string, + meaning: SymbolFlags, + ): string | undefined; + /** @internal */ getSuggestedSymbolForNonexistentModule( + node: Identifier, + target: Symbol, + ): Symbol | undefined; + /** @internal */ getSuggestedSymbolForNonexistentClassMember( + name: string, + baseType: Type, + ): Symbol | undefined; + /** @internal */ getSuggestionForNonexistentExport( + node: Identifier, + target: Symbol, + ): string | undefined; getBaseConstraintOfType(type: Type): Type | undefined; getDefaultFromTypeParameter(type: Type): Type | undefined; @@ -5130,16 +6297,27 @@ export interface TypeChecker { */ getNeverType(): Type; /** @internal */ getOptionalType(): Type; - /** @internal */ getUnionType(types: Type[], subtypeReduction?: UnionReduction): Type; + /** @internal */ getUnionType( + types: Type[], + subtypeReduction?: UnionReduction, + ): Type; /** @internal */ createArrayType(elementType: Type): Type; - /** @internal */ getElementTypeOfArrayType(arrayType: Type): Type | undefined; + /** @internal */ getElementTypeOfArrayType( + arrayType: Type, + ): Type | undefined; /** @internal */ createPromiseType(type: Type): Type; /** @internal */ getPromiseType(): Type; /** @internal */ getPromiseLikeType(): Type; /** @internal */ getAsyncIterableType(): Type | undefined; /** @internal */ isTypeAssignableTo(source: Type, target: Type): boolean; - /** @internal */ createAnonymousType(symbol: Symbol | undefined, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], indexInfos: IndexInfo[]): Type; + /** @internal */ createAnonymousType( + symbol: Symbol | undefined, + members: SymbolTable, + callSignatures: Signature[], + constructSignatures: Signature[], + indexInfos: IndexInfo[], + ): Type; /** @internal */ createSignature( declaration: SignatureDeclaration | undefined, typeParameters: readonly TypeParameter[] | undefined, @@ -5150,27 +6328,62 @@ export interface TypeChecker { minArgumentCount: number, flags: SignatureFlags, ): Signature; - /** @internal */ createSymbol(flags: SymbolFlags, name: __String): TransientSymbol; - /** @internal */ createIndexInfo(keyType: Type, type: Type, isReadonly: boolean, declaration?: SignatureDeclaration): IndexInfo; - /** @internal */ isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; - /** @internal */ tryFindAmbientModule(moduleName: string): Symbol | undefined; - /** @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol | undefined; - - /** @internal */ getSymbolWalker(accept?: (symbol: Symbol) => boolean): SymbolWalker; + /** @internal */ createSymbol( + flags: SymbolFlags, + name: __String, + ): TransientSymbol; + /** @internal */ createIndexInfo( + keyType: Type, + type: Type, + isReadonly: boolean, + declaration?: SignatureDeclaration, + ): IndexInfo; + /** @internal */ isSymbolAccessible( + symbol: Symbol, + enclosingDeclaration: Node | undefined, + meaning: SymbolFlags, + shouldComputeAliasToMarkVisible: boolean, + ): SymbolAccessibilityResult; + /** @internal */ tryFindAmbientModule( + moduleName: string, + ): Symbol | undefined; + /** @internal */ tryFindAmbientModuleWithoutAugmentations( + moduleName: string, + ): Symbol | undefined; + + /** @internal */ getSymbolWalker( + accept?: (symbol: Symbol) => boolean, + ): SymbolWalker; // Should not be called directly. Should only be accessed through the Program instance. - /** @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + /** @internal */ getDiagnostics( + sourceFile?: SourceFile, + cancellationToken?: CancellationToken, + ): Diagnostic[]; /** @internal */ getGlobalDiagnostics(): Diagnostic[]; - /** @internal */ getEmitResolver(sourceFile?: SourceFile, cancellationToken?: CancellationToken): EmitResolver; + /** @internal */ getEmitResolver( + sourceFile?: SourceFile, + cancellationToken?: CancellationToken, + ): EmitResolver; /** @internal */ getNodeCount(): number; /** @internal */ getIdentifierCount(): number; /** @internal */ getSymbolCount(): number; /** @internal */ getTypeCount(): number; /** @internal */ getInstantiationCount(): number; - /** @internal */ getRelationCacheSizes(): { assignable: number; identity: number; subtype: number; strictSubtype: number; }; + /** @internal */ getRelationCacheSizes(): { + assignable: number; + identity: number; + subtype: number; + strictSubtype: number; + }; /** @internal */ getRecursionIdentity(type: Type): object | undefined; - /** @internal */ getUnmatchedProperties(source: Type, target: Type, requireOptionalProperties: boolean, matchDiscriminantProperties: boolean): IterableIterator; + /** @internal */ getUnmatchedProperties( + source: Type, + target: Type, + requireOptionalProperties: boolean, + matchDiscriminantProperties: boolean, + ): IterableIterator; /** * True if this type is the `Array` or `ReadonlyArray` type from lib.d.ts. @@ -5194,7 +6407,10 @@ export interface TypeChecker { * * @internal */ - isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes): boolean; + isTypeInvalidDueToUnionDiscriminant( + contextualType: Type, + obj: ObjectLiteralExpression | JsxAttributes, + ): boolean; /** @internal */ getExactOptionalProperties(type: Type): Symbol[]; /** * For a union, will include a property if it's defined in *any* of the member types. @@ -5204,7 +6420,12 @@ export interface TypeChecker { * @internal */ getAllPossiblePropertiesOfTypes(type: readonly Type[]): Symbol[]; - /** @internal */ resolveName(name: string, location: Node | undefined, meaning: SymbolFlags, excludeGlobals: boolean): Symbol | undefined; + /** @internal */ resolveName( + name: string, + location: Node | undefined, + meaning: SymbolFlags, + excludeGlobals: boolean, + ): Symbol | undefined; /** @internal */ getJsxNamespace(location?: Node): string; /** @internal */ getJsxFragmentFactory(location: Node): string | undefined; @@ -5219,9 +6440,18 @@ export interface TypeChecker { * * @internal */ - getAccessibleSymbolChain(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags, useOnlyExternalAliasing: boolean): Symbol[] | undefined; - getTypePredicateOfSignature(signature: Signature): TypePredicate | undefined; - /** @internal */ resolveExternalModuleName(moduleSpecifier: Expression): Symbol | undefined; + getAccessibleSymbolChain( + symbol: Symbol, + enclosingDeclaration: Node | undefined, + meaning: SymbolFlags, + useOnlyExternalAliasing: boolean, + ): Symbol[] | undefined; + getTypePredicateOfSignature( + signature: Signature, + ): TypePredicate | undefined; + /** @internal */ resolveExternalModuleName( + moduleSpecifier: Expression, + ): Symbol | undefined; /** * An external module with an 'export =' declaration resolves to the target of the 'export =' declaration, * and an external module with no 'export =' declaration resolves to the module itself. @@ -5234,8 +6464,14 @@ export interface TypeChecker { * * @internal */ - tryGetThisTypeAt(node: Node, includeGlobalThis?: boolean, container?: ThisContainer): Type | undefined; - /** @internal */ getTypeArgumentConstraint(node: TypeNode): Type | undefined; + tryGetThisTypeAt( + node: Node, + includeGlobalThis?: boolean, + container?: ThisContainer, + ): Type | undefined; + /** @internal */ getTypeArgumentConstraint( + node: TypeNode, + ): Type | undefined; /** * Does *not* get *all* suggestion diagnostics, just the ones that were convenient to report in the checker. @@ -5243,21 +6479,46 @@ export interface TypeChecker { * * @internal */ - getSuggestionDiagnostics(file: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[]; + getSuggestionDiagnostics( + file: SourceFile, + cancellationToken?: CancellationToken, + ): readonly DiagnosticWithLocation[]; /** * Depending on the operation performed, it may be appropriate to throw away the checker * if the cancellation token is triggered. Typically, if it is used for error checking * and the operation is cancelled, then it should be discarded, otherwise it is safe to keep. */ - runWithCancellationToken(token: CancellationToken, cb: (checker: TypeChecker) => T): T; - - /** @internal */ getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol: Symbol): readonly TypeParameter[] | undefined; - /** @internal */ isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean; - /** @internal */ isPropertyAccessible(node: Node, isSuper: boolean, isWrite: boolean, containingType: Type, property: Symbol): boolean; - /** @internal */ getTypeOnlyAliasDeclaration(symbol: Symbol): TypeOnlyAliasDeclaration | undefined; - /** @internal */ getMemberOverrideModifierStatus(node: ClassLikeDeclaration, member: ClassElement, memberSymbol: Symbol): MemberOverrideStatus; - /** @internal */ isTypeParameterPossiblyReferenced(tp: TypeParameter, node: Node): boolean; + runWithCancellationToken( + token: CancellationToken, + cb: (checker: TypeChecker) => T, + ): T; + + /** @internal */ getLocalTypeParametersOfClassOrInterfaceOrTypeAlias( + symbol: Symbol, + ): readonly TypeParameter[] | undefined; + /** @internal */ isDeclarationVisible( + node: DeclarationBase | AnyImportSyntax, + ): boolean; + /** @internal */ isPropertyAccessible( + node: Node, + isSuper: boolean, + isWrite: boolean, + containingType: Type, + property: Symbol, + ): boolean; + /** @internal */ getTypeOnlyAliasDeclaration( + symbol: Symbol, + ): TypeOnlyAliasDeclaration | undefined; + /** @internal */ getMemberOverrideModifierStatus( + node: ClassLikeDeclaration, + member: ClassElementBase, + memberSymbol: Symbol, + ): MemberOverrideStatus; + /** @internal */ isTypeParameterPossiblyReferenced( + tp: TypeParameter, + node: Node, + ): boolean; /** @internal */ typeHasCallOrConstructSignatures(type: Type): boolean; } @@ -5278,125 +6539,143 @@ export const enum UnionReduction { // dprint-ignore /** @internal */ export const enum ContextFlags { - None = 0, - Signature = 1 << 0, // Obtaining contextual signature - NoConstraints = 1 << 1, // Don't obtain type variable constraints - Completions = 1 << 2, // Ignore inference to current node and parent nodes out to the containing call for completions + None = 0, + Signature = 1 << 0, // Obtaining contextual signature + NoConstraints = 1 << 1, // Don't obtain type variable constraints + Completions = 1 << 2, // Ignore inference to current node and parent nodes out to the containing call for completions SkipBindingPatterns = 1 << 3, // Ignore contextual types applied by binding patterns } // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! // dprint-ignore export const enum NodeBuilderFlags { - None = 0, + None = 0, // Options - NoTruncation = 1 << 0, // Don't truncate result - WriteArrayAsGenericType = 1 << 1, // Write Array instead T[] - GenerateNamesForShadowedTypeParams = 1 << 2, // When a type parameter T is shadowing another T, generate a name for it so it can still be referenced - UseStructuralFallback = 1 << 3, // When an alias cannot be named by its symbol, rather than report an error, fallback to a structural printout if possible - ForbidIndexedAccessSymbolReferences = 1 << 4, // Forbid references like `I["a"]["b"]` - print `typeof I.a.b` instead - WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature - UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type) - UseOnlyExternalAliasing = 1 << 7, // Only use external aliases for a symbol - SuppressAnyReturnType = 1 << 8, // If the return type is any-like and can be elided, don't offer a return type. - WriteTypeParametersInQualifiedName = 1 << 9, - MultilineObjectLiterals = 1 << 10, // Always write object literals across multiple lines - WriteClassExpressionAsTypeLiteral = 1 << 11, // Write class {} as { new(): {} } - used for mixin declaration emit - UseTypeOfFunction = 1 << 12, // Build using typeof instead of function type literal - OmitParameterModifiers = 1 << 13, // Omit modifiers on parameters - UseAliasDefinedOutsideCurrentScope = 1 << 14, // Allow non-visible aliases - UseSingleQuotesForStringLiteralType = 1 << 28, // Use single quotes for string literal type - NoTypeReduction = 1 << 29, // Don't call getReducedType - OmitThisParameter = 1 << 25, + NoTruncation = 1 << 0, // Don't truncate result + WriteArrayAsGenericType = 1 << 1, // Write Array instead T[] + GenerateNamesForShadowedTypeParams = 1 << 2, // When a type parameter T is shadowing another T, generate a name for it so it can still be referenced + UseStructuralFallback = 1 << 3, // When an alias cannot be named by its symbol, rather than report an error, fallback to a structural printout if possible + ForbidIndexedAccessSymbolReferences = 1 << 4, // Forbid references like `I["a"]["b"]` - print `typeof I.a.b` instead + WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature + UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type) + UseOnlyExternalAliasing = 1 << 7, // Only use external aliases for a symbol + SuppressAnyReturnType = 1 << 8, // If the return type is any-like and can be elided, don't offer a return type. + WriteTypeParametersInQualifiedName = 1 << 9, + MultilineObjectLiterals = 1 << 10, // Always write object literals across multiple lines + WriteClassExpressionAsTypeLiteral = 1 << 11, // Write class {} as { new(): {} } - used for mixin declaration emit + UseTypeOfFunction = 1 << 12, // Build using typeof instead of function type literal + OmitParameterModifiers = 1 << 13, // Omit modifiers on parameters + UseAliasDefinedOutsideCurrentScope = 1 << 14, // Allow non-visible aliases + UseSingleQuotesForStringLiteralType = 1 << 28, // Use single quotes for string literal type + NoTypeReduction = 1 << 29, // Don't call getReducedType + OmitThisParameter = 1 << 25, // Error handling - AllowThisInObjectLiteral = 1 << 15, - AllowQualifiedNameInPlaceOfIdentifier = 1 << 16, - AllowAnonymousIdentifier = 1 << 17, - AllowEmptyUnionOrIntersection = 1 << 18, - AllowEmptyTuple = 1 << 19, - AllowUniqueESSymbolType = 1 << 20, - AllowEmptyIndexInfoType = 1 << 21, - /** @internal */ WriteComputedProps = 1 << 30, // { [E.A]: 1 } + AllowThisInObjectLiteral = 1 << 15, + AllowQualifiedNameInPlaceOfIdentifier = 1 << 16, + AllowAnonymousIdentifier = 1 << 17, + AllowEmptyUnionOrIntersection = 1 << 18, + AllowEmptyTuple = 1 << 19, + AllowUniqueESSymbolType = 1 << 20, + AllowEmptyIndexInfoType = 1 << 21, + /** @internal */ WriteComputedProps = 1 << 30, // { [E.A]: 1 } // Errors (cont.) - AllowNodeModulesRelativePaths = 1 << 26, - /** @internal */ DoNotIncludeSymbolChain = 1 << 27, // Skip looking up and printing an accessible symbol chain + AllowNodeModulesRelativePaths = 1 << 26, + /** @internal */ DoNotIncludeSymbolChain = 1 << 27, // Skip looking up and printing an accessible symbol chain - IgnoreErrors = AllowThisInObjectLiteral | AllowQualifiedNameInPlaceOfIdentifier | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple | AllowEmptyIndexInfoType | AllowNodeModulesRelativePaths, + IgnoreErrors = AllowThisInObjectLiteral | + AllowQualifiedNameInPlaceOfIdentifier | + AllowAnonymousIdentifier | + AllowEmptyUnionOrIntersection | + AllowEmptyTuple | + AllowEmptyIndexInfoType | + AllowNodeModulesRelativePaths, // State - InObjectTypeLiteral = 1 << 22, - InTypeAlias = 1 << 23, // Writing type in type alias declaration - InInitialEntityName = 1 << 24, // Set when writing the LHS of an entity name or entity name expression + InObjectTypeLiteral = 1 << 22, + InTypeAlias = 1 << 23, // Writing type in type alias declaration + InInitialEntityName = 1 << 24, // Set when writing the LHS of an entity name or entity name expression } // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment // dprint-ignore export const enum TypeFormatFlags { - None = 0, - NoTruncation = 1 << 0, // Don't truncate typeToString result - WriteArrayAsGenericType = 1 << 1, // Write Array instead T[] + None = 0, + NoTruncation = 1 << 0, // Don't truncate typeToString result + WriteArrayAsGenericType = 1 << 1, // Write Array instead T[] // hole because there's a hole in node builder flags - UseStructuralFallback = 1 << 3, // When an alias cannot be named by its symbol, rather than report an error, fallback to a structural printout if possible + UseStructuralFallback = 1 << 3, // When an alias cannot be named by its symbol, rather than report an error, fallback to a structural printout if possible // hole because there's a hole in node builder flags - WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature - UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type) + WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature + UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type) // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead - SuppressAnyReturnType = 1 << 8, // If the return type is any-like, don't offer a return type. + SuppressAnyReturnType = 1 << 8, // If the return type is any-like, don't offer a return type. // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead - MultilineObjectLiterals = 1 << 10, // Always print object literals across multiple lines (only used to map into node builder flags) - WriteClassExpressionAsTypeLiteral = 1 << 11, // Write a type literal instead of (Anonymous class) - UseTypeOfFunction = 1 << 12, // Write typeof instead of function type literal - OmitParameterModifiers = 1 << 13, // Omit modifiers on parameters + MultilineObjectLiterals = 1 << 10, // Always print object literals across multiple lines (only used to map into node builder flags) + WriteClassExpressionAsTypeLiteral = 1 << 11, // Write a type literal instead of (Anonymous class) + UseTypeOfFunction = 1 << 12, // Write typeof instead of function type literal + OmitParameterModifiers = 1 << 13, // Omit modifiers on parameters - UseAliasDefinedOutsideCurrentScope = 1 << 14, // For a `type T = ... ` defined in a different file, write `T` instead of its value, even though `T` can't be accessed in the current scope. - UseSingleQuotesForStringLiteralType = 1 << 28, // Use single quotes for string literal type - NoTypeReduction = 1 << 29, // Don't call getReducedType - OmitThisParameter = 1 << 25, + UseAliasDefinedOutsideCurrentScope = 1 << 14, // For a `type T = ... ` defined in a different file, write `T` instead of its value, even though `T` can't be accessed in the current scope. + UseSingleQuotesForStringLiteralType = 1 << 28, // Use single quotes for string literal type + NoTypeReduction = 1 << 29, // Don't call getReducedType + OmitThisParameter = 1 << 25, // Error Handling - AllowUniqueESSymbolType = 1 << 20, // This is bit 20 to align with the same bit in `NodeBuilderFlags` + AllowUniqueESSymbolType = 1 << 20, // This is bit 20 to align with the same bit in `NodeBuilderFlags` // TypeFormatFlags exclusive - AddUndefined = 1 << 17, // Add undefined to types of initialized, non-optional parameters - WriteArrowStyleSignature = 1 << 18, // Write arrow style signature + AddUndefined = 1 << 17, // Add undefined to types of initialized, non-optional parameters + WriteArrowStyleSignature = 1 << 18, // Write arrow style signature // State - InArrayType = 1 << 19, // Writing an array element type - InElementType = 1 << 21, // Writing an array or union element type - InFirstTypeArgument = 1 << 22, // Writing first type argument of the instantiated type - InTypeAlias = 1 << 23, // Writing type in type alias declaration - - NodeBuilderFlagsMask = NoTruncation | WriteArrayAsGenericType | UseStructuralFallback | WriteTypeArgumentsOfSignature | - UseFullyQualifiedType | SuppressAnyReturnType | MultilineObjectLiterals | WriteClassExpressionAsTypeLiteral | - UseTypeOfFunction | OmitParameterModifiers | UseAliasDefinedOutsideCurrentScope | AllowUniqueESSymbolType | InTypeAlias | - UseSingleQuotesForStringLiteralType | NoTypeReduction | OmitThisParameter, + InArrayType = 1 << 19, // Writing an array element type + InElementType = 1 << 21, // Writing an array or union element type + InFirstTypeArgument = 1 << 22, // Writing first type argument of the instantiated type + InTypeAlias = 1 << 23, // Writing type in type alias declaration + + NodeBuilderFlagsMask = NoTruncation | + WriteArrayAsGenericType | + UseStructuralFallback | + WriteTypeArgumentsOfSignature | + UseFullyQualifiedType | + SuppressAnyReturnType | + MultilineObjectLiterals | + WriteClassExpressionAsTypeLiteral | + UseTypeOfFunction | + OmitParameterModifiers | + UseAliasDefinedOutsideCurrentScope | + AllowUniqueESSymbolType | + InTypeAlias | + UseSingleQuotesForStringLiteralType | + NoTypeReduction | + OmitThisParameter, } // dprint-ignore export const enum SymbolFormatFlags { - None = 0, + None = 0, // Write symbols's type argument if it is instantiated symbol // eg. class C { p: T } <-- Show p as C.p here // var a: C; // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p - WriteTypeParametersOrArguments = 1 << 0, + WriteTypeParametersOrArguments = 1 << 0, // Use only external alias information to get the symbol name in the given context // eg. module m { export class c { } } import x = m.c; // When this flag is specified m.c will be used to refer to the class instead of alias symbol x - UseOnlyExternalAliasing = 1 << 1, + UseOnlyExternalAliasing = 1 << 1, // Build symbol name using any nodes needed, instead of just components of an entity name - AllowAnyNodeKind = 1 << 2, + AllowAnyNodeKind = 1 << 2, // Prefer aliases which are not directly visible - UseAliasDefinedOutsideCurrentScope = 1 << 3, + UseAliasDefinedOutsideCurrentScope = 1 << 3, // { [E.A]: 1 } - /** @internal */ WriteComputedProps = 1 << 4, + /** @internal */ WriteComputedProps = 1 << 4, // Skip building an accessible symbol chain /** @internal */ DoNotIncludeSymbolChain = 1 << 5, @@ -5405,9 +6684,15 @@ export const enum SymbolFormatFlags { /** @internal */ export interface SymbolWalker { /** Note: Return values are not ordered. */ - walkType(root: Type): { visitedTypes: readonly Type[]; visitedSymbols: readonly Symbol[]; }; + walkType(root: Type): { + visitedTypes: readonly Type[]; + visitedSymbols: readonly Symbol[]; + }; /** Note: Return values are not ordered. */ - walkSymbol(root: Symbol): { visitedTypes: readonly Type[]; visitedSymbols: readonly Symbol[]; }; + walkSymbol(root: Symbol): { + visitedTypes: readonly Type[]; + visitedSymbols: readonly Symbol[]; + }; } // This was previously deprecated in our public API, but is still used internally @@ -5480,24 +6765,29 @@ export interface AssertsIdentifierTypePredicate extends TypePredicateBase { type: Type | undefined; } -export type TypePredicate = ThisTypePredicate | IdentifierTypePredicate | AssertsThisTypePredicate | AssertsIdentifierTypePredicate; +export type TypePredicate = + | ThisTypePredicate + | IdentifierTypePredicate + | AssertsThisTypePredicate + | AssertsIdentifierTypePredicate; /** @internal */ export type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration; /** @internal */ -export type AnyImportOrRequire = AnyImportSyntax | VariableDeclarationInitializedTo; +export type AnyImportOrRequire = + | AnyImportSyntax + | VariableDeclarationInitializedTo; /** @internal */ -export type AnyImportOrBareOrAccessedRequire = AnyImportSyntax | VariableDeclarationInitializedTo; +export type AnyImportOrBareOrAccessedRequire = + | AnyImportSyntax + | VariableDeclarationInitializedTo; /** @internal */ export type AliasDeclarationNode = | ImportEqualsDeclaration - | VariableDeclarationInitializedTo< - | RequireOrImportCall - | AccessExpression - > + | VariableDeclarationInitializedTo | ImportClause | NamespaceImport | ImportSpecifier @@ -5506,10 +6796,18 @@ export type AliasDeclarationNode = | BindingElementOfBareOrAccessedRequire; /** @internal */ -export type BindingElementOfBareOrAccessedRequire = BindingElement & { parent: { parent: VariableDeclarationInitializedTo; }; }; +export type BindingElementOfBareOrAccessedRequire = BindingElement & { + parent: { + parent: VariableDeclarationInitializedTo< + RequireOrImportCall | AccessExpression + >; + }; +}; /** @internal */ -export type AnyImportOrRequireStatement = AnyImportSyntax | RequireVariableStatement; +export type AnyImportOrRequireStatement = + | AnyImportSyntax + | RequireVariableStatement; /** @internal */ export type AnyImportOrReExport = AnyImportSyntax | ExportDeclaration; @@ -5521,13 +6819,22 @@ export interface ValidImportTypeNode extends ImportTypeNode { /** @internal */ export type AnyValidImportOrReExport = - | (ImportDeclaration | ExportDeclaration) & { moduleSpecifier: StringLiteral; } - | ImportEqualsDeclaration & { moduleReference: ExternalModuleReference & { expression: StringLiteral; }; } + | ((ImportDeclaration | ExportDeclaration) & { + moduleSpecifier: StringLiteral; + }) + | (ImportEqualsDeclaration & { + moduleReference: ExternalModuleReference & { + expression: StringLiteral; + }; + }) | RequireOrImportCall | ValidImportTypeNode; /** @internal */ -export type RequireOrImportCall = CallExpression & { expression: Identifier; arguments: [StringLiteralLike]; }; +export type RequireOrImportCall = CallExpression & { + expression: Identifier; + arguments: [StringLiteralLike]; +}; /** @internal */ export interface VariableDeclarationInitializedTo extends VariableDeclaration { @@ -5541,7 +6848,9 @@ export interface RequireVariableStatement extends VariableStatement { /** @internal */ export interface RequireVariableDeclarationList extends VariableDeclarationList { - readonly declarations: NodeArray>; + readonly declarations: NodeArray< + VariableDeclarationInitializedTo + >; } /** @internal */ @@ -5634,89 +6943,219 @@ export enum TypeReferenceSerializationKind { /** @internal */ export interface EmitResolver { hasGlobalName(name: string): boolean; - getReferencedExportContainer(node: Identifier, prefixLocals?: boolean): SourceFile | ModuleDeclaration | EnumDeclaration | undefined; + getReferencedExportContainer( + node: Identifier, + prefixLocals?: boolean, + ): SourceFile | ModuleDeclaration | EnumDeclaration | undefined; getReferencedImportDeclaration(node: Identifier): Declaration | undefined; - getReferencedDeclarationWithCollidingName(node: Identifier): Declaration | undefined; - isDeclarationWithCollidingName(node: Declaration): boolean; + getReferencedDeclarationWithCollidingName( + node: Identifier, + ): Declaration | undefined; + isDeclarationWithCollidingName(node: DeclarationBase): boolean; isValueAliasDeclaration(node: Node): boolean; isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean; - isTopLevelValueImportEqualsWithEntityName(node: ImportEqualsDeclaration): boolean; + isTopLevelValueImportEqualsWithEntityName( + node: ImportEqualsDeclaration, + ): boolean; getNodeCheckFlags(node: Node): NodeCheckFlags; - isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean; - isLateBound(node: Declaration): node is LateBoundDeclaration; - collectLinkedAliases(node: Identifier, setVisibility?: boolean): Node[] | undefined; + isDeclarationVisible(node: DeclarationBase | AnyImportSyntax): boolean; + isLateBound(node: DeclarationBase): node is LateBoundDeclaration; + collectLinkedAliases( + node: Identifier, + setVisibility?: boolean, + ): Node[] | undefined; isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined; isRequiredInitializedParameter(node: ParameterDeclaration): boolean; - isOptionalUninitializedParameterProperty(node: ParameterDeclaration): boolean; + isOptionalUninitializedParameterProperty( + node: ParameterDeclaration, + ): boolean; isExpandoFunctionDeclaration(node: FunctionDeclaration): boolean; - getPropertiesOfContainerFunction(node: Declaration): Symbol[]; - createTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration | PropertyAccessExpression | ElementAccessExpression | BinaryExpression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker, addUndefined?: boolean): TypeNode | undefined; - createReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined; - createTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined; - createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, tracker: SymbolTracker): Expression; - isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags | undefined, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; - isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; + getPropertiesOfContainerFunction(node: DeclarationBase): Symbol[]; + createTypeOfDeclaration( + declaration: + | AccessorDeclaration + | VariableLikeDeclaration + | PropertyAccessExpression + | ElementAccessExpression + | BinaryExpression, + enclosingDeclaration: Node, + flags: NodeBuilderFlags, + tracker: SymbolTracker, + addUndefined?: boolean, + ): TypeNode | undefined; + createReturnTypeOfSignatureDeclaration( + signatureDeclaration: SignatureDeclaration, + enclosingDeclaration: Node, + flags: NodeBuilderFlags, + tracker: SymbolTracker, + ): TypeNode | undefined; + createTypeOfExpression( + expr: Expression, + enclosingDeclaration: Node, + flags: NodeBuilderFlags, + tracker: SymbolTracker, + ): TypeNode | undefined; + createLiteralConstValue( + node: + | VariableDeclaration + | PropertyDeclaration + | PropertySignature + | ParameterDeclaration, + tracker: SymbolTracker, + ): Expression; + isSymbolAccessible( + symbol: Symbol, + enclosingDeclaration: Node | undefined, + meaning: SymbolFlags | undefined, + shouldComputeAliasToMarkVisible: boolean, + ): SymbolAccessibilityResult; + isEntityNameVisible( + entityName: EntityNameOrEntityNameExpression, + enclosingDeclaration: Node, + ): SymbolVisibilityResult; // Returns the constant value this property access resolves to, or 'undefined' for a non-constant - getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined; - getReferencedValueDeclaration(reference: Identifier): Declaration | undefined; - getReferencedValueDeclarations(reference: Identifier): Declaration[] | undefined; - getTypeReferenceSerializationKind(typeName: EntityName, location?: Node): TypeReferenceSerializationKind; + getConstantValue( + node: EnumMember | PropertyAccessExpression | ElementAccessExpression, + ): string | number | undefined; + getReferencedValueDeclaration( + reference: Identifier, + ): Declaration | undefined; + getReferencedValueDeclarations( + reference: Identifier, + ): Declaration[] | undefined; + getTypeReferenceSerializationKind( + typeName: EntityName, + location?: Node, + ): TypeReferenceSerializationKind; isOptionalParameter(node: ParameterDeclaration): boolean; moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean; isArgumentsLocalBinding(node: Identifier): boolean; - getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration | ImportTypeNode | ImportCall): SourceFile | undefined; - getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): [specifier: string, mode: ResolutionMode][] | undefined; - getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): [specifier: string, mode: ResolutionMode][] | undefined; - isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean; + getExternalModuleFileFromDeclaration( + declaration: + | ImportEqualsDeclaration + | ImportDeclaration + | ExportDeclaration + | ModuleDeclaration + | ImportTypeNode + | ImportCall, + ): SourceFile | undefined; + getTypeReferenceDirectivesForEntityName( + name: EntityNameOrEntityNameExpression, + ): [specifier: string, mode: ResolutionMode][] | undefined; + getTypeReferenceDirectivesForSymbol( + symbol: Symbol, + meaning?: SymbolFlags, + ): [specifier: string, mode: ResolutionMode][] | undefined; + isLiteralConstDeclaration( + node: + | VariableDeclaration + | PropertyDeclaration + | PropertySignature + | ParameterDeclaration, + ): boolean; getJsxFactoryEntity(location?: Node): EntityName | undefined; getJsxFragmentFactoryEntity(location?: Node): EntityName | undefined; - getAllAccessorDeclarations(declaration: AccessorDeclaration): AllAccessorDeclarations; - getSymbolOfExternalModuleSpecifier(node: StringLiteralLike): Symbol | undefined; - isBindingCapturedByNode(node: Node, decl: VariableDeclaration | BindingElement): boolean; - getDeclarationStatementsForSourceFile(node: SourceFile, flags: NodeBuilderFlags, tracker: SymbolTracker, bundled?: boolean): Statement[] | undefined; + getAllAccessorDeclarations( + declaration: AccessorDeclaration, + ): AllAccessorDeclarations; + getSymbolOfExternalModuleSpecifier( + node: StringLiteralLike, + ): Symbol | undefined; + isBindingCapturedByNode( + node: Node, + decl: VariableDeclaration | BindingElement, + ): boolean; + getDeclarationStatementsForSourceFile( + node: SourceFile, + flags: NodeBuilderFlags, + tracker: SymbolTracker, + bundled?: boolean, + ): Statement[] | undefined; isImportRequiredByAugmentation(decl: ImportDeclaration): boolean; - tryFindAmbientModule(moduleReferenceExpression: Expression): Symbol | undefined; + tryFindAmbientModule( + moduleReferenceExpression: Expression, + ): Symbol | undefined; } // dprint-ignore export const enum SymbolFlags { - None = 0, - FunctionScopedVariable = 1 << 0, // Variable (var) or parameter - BlockScopedVariable = 1 << 1, // A block-scoped variable (let or const) - Property = 1 << 2, // Property or enum member - EnumMember = 1 << 3, // Enum member - Function = 1 << 4, // Function - Class = 1 << 5, // Class - Interface = 1 << 6, // Interface - ConstEnum = 1 << 7, // Const enum - RegularEnum = 1 << 8, // Enum - ValueModule = 1 << 9, // Instantiated module - NamespaceModule = 1 << 10, // Uninstantiated module - TypeLiteral = 1 << 11, // Type Literal or mapped type - ObjectLiteral = 1 << 12, // Object Literal - Method = 1 << 13, // Method - Constructor = 1 << 14, // Constructor - GetAccessor = 1 << 15, // Get accessor - SetAccessor = 1 << 16, // Set accessor - Signature = 1 << 17, // Call, construct, or index signature - TypeParameter = 1 << 18, // Type parameter - TypeAlias = 1 << 19, // Type alias - ExportValue = 1 << 20, // Exported value marker (see comment in declareModuleMember in binder) - Alias = 1 << 21, // An alias for another symbol (see comment in isAliasSymbolDeclaration in checker) - Prototype = 1 << 22, // Prototype property (no source representation) - ExportStar = 1 << 23, // Export * declaration - Optional = 1 << 24, // Optional property - Transient = 1 << 25, // Transient symbol (created during type check) - Assignment = 1 << 26, // Assignment treated as declaration (eg `this.prop = 1`) - ModuleExports = 1 << 27, // Symbol for CommonJS `module` of `module.exports` - /** @internal */ - All = FunctionScopedVariable | BlockScopedVariable | Property | EnumMember | Function | Class | Interface | ConstEnum | RegularEnum | ValueModule | NamespaceModule | TypeLiteral - | ObjectLiteral | Method | Constructor | GetAccessor | SetAccessor | Signature | TypeParameter | TypeAlias | ExportValue | Alias | Prototype | ExportStar | Optional | Transient, + None = 0, + FunctionScopedVariable = 1 << 0, // Variable (var) or parameter + BlockScopedVariable = 1 << 1, // A block-scoped variable (let or const) + Property = 1 << 2, // Property or enum member + EnumMember = 1 << 3, // Enum member + Function = 1 << 4, // Function + Class = 1 << 5, // Class + Interface = 1 << 6, // Interface + ConstEnum = 1 << 7, // Const enum + RegularEnum = 1 << 8, // Enum + ValueModule = 1 << 9, // Instantiated module + NamespaceModule = 1 << 10, // Uninstantiated module + TypeLiteral = 1 << 11, // Type Literal or mapped type + ObjectLiteral = 1 << 12, // Object Literal + Method = 1 << 13, // Method + Constructor = 1 << 14, // Constructor + GetAccessor = 1 << 15, // Get accessor + SetAccessor = 1 << 16, // Set accessor + Signature = 1 << 17, // Call, construct, or index signature + TypeParameter = 1 << 18, // Type parameter + TypeAlias = 1 << 19, // Type alias + ExportValue = 1 << 20, // Exported value marker (see comment in declareModuleMember in binder) + Alias = 1 << 21, // An alias for another symbol (see comment in isAliasSymbolDeclaration in checker) + Prototype = 1 << 22, // Prototype property (no source representation) + ExportStar = 1 << 23, // Export * declaration + Optional = 1 << 24, // Optional property + Transient = 1 << 25, // Transient symbol (created during type check) + Assignment = 1 << 26, // Assignment treated as declaration (eg `this.prop = 1`) + ModuleExports = 1 << 27, // Symbol for CommonJS `module` of `module.exports` + /** @internal */ + All = FunctionScopedVariable | + BlockScopedVariable | + Property | + EnumMember | + Function | + Class | + Interface | + ConstEnum | + RegularEnum | + ValueModule | + NamespaceModule | + TypeLiteral | + ObjectLiteral | + Method | + Constructor | + GetAccessor | + SetAccessor | + Signature | + TypeParameter | + TypeAlias | + ExportValue | + Alias | + Prototype | + ExportStar | + Optional | + Transient, Enum = RegularEnum | ConstEnum, Variable = FunctionScopedVariable | BlockScopedVariable, - Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor, - Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias, + Value = Variable | + Property | + EnumMember | + ObjectLiteral | + Function | + Class | + Enum | + ValueModule | + Method | + GetAccessor | + SetAccessor, + Type = Class | + Interface | + Enum | + EnumMember | + TypeLiteral | + TypeParameter | + TypeAlias, Namespace = ValueModule | NamespaceModule | Enum, Module = ValueModule | NamespaceModule, Accessor = GetAccessor | SetAccessor, @@ -5737,7 +7176,8 @@ export const enum SymbolFlags { InterfaceExcludes = Type & ~(Interface | Class), RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums - ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule), + ValueModuleExcludes = Value & + ~(Function | Class | RegularEnum | ValueModule), NamespaceModuleExcludes = 0, MethodExcludes = Value & ~Method, GetAccessorExcludes = Value & ~SetAccessor, @@ -5747,7 +7187,14 @@ export const enum SymbolFlags { TypeAliasExcludes = Type, AliasExcludes = Alias, - ModuleMember = Variable | Function | Class | Interface | Enum | Module | TypeAlias | Alias, + ModuleMember = Variable | + Function | + Class | + Interface | + Enum | + Module | + TypeAlias | + Alias, ExportHasLocal = Function | Class | Enum | ValueModule, @@ -5766,10 +7213,20 @@ export const enum SymbolFlags { /** @internal */ // The set of things we consider semantically classifiable. Used to speed up the LS during // classification. - Classifiable = Class | Enum | TypeAlias | Interface | TypeParameter | Module | Alias, + Classifiable = Class | + Enum | + TypeAlias | + Interface | + TypeParameter | + Module | + Alias, /** @internal */ - LateBindingContainer = Class | Interface | TypeLiteral | ObjectLiteral | Function, + LateBindingContainer = Class | + Interface | + TypeLiteral | + ObjectLiteral | + Function, } /** @internal */ @@ -5777,75 +7234,84 @@ export type SymbolId = number; // dprint-ignore export interface Symbol { - flags: SymbolFlags; // Symbol flags - escapedName: __String; // Name of symbol - declarations?: Declaration[]; // Declarations associated with this symbol - valueDeclaration?: Declaration; // First value declaration of the symbol - members?: SymbolTable; // Class, interface or object literal instance members - exports?: SymbolTable; // Module exports - globalExports?: SymbolTable; // Conditional global UMD exports - /** @internal */ id: SymbolId; // Unique id (used to look up SymbolLinks) - /** @internal */ mergeId: number; // Merge id (used to look up merged symbol) - /** @internal */ parent?: Symbol; // Parent symbol + flags: SymbolFlags; // Symbol flags + escapedName: __String; // Name of symbol + declarations?: Declaration[]; // Declarations associated with this symbol + valueDeclaration?: Declaration; // First value declaration of the symbol + members?: SymbolTable; // Class, interface or object literal instance members + exports?: SymbolTable; // Module exports + globalExports?: SymbolTable; // Conditional global UMD exports + /** @internal */ id: SymbolId; // Unique id (used to look up SymbolLinks) + /** @internal */ mergeId: number; // Merge id (used to look up merged symbol) + /** @internal */ parent?: Symbol; // Parent symbol /** @internal */ exportSymbol?: Symbol; // Exported symbol associated with this symbol /** @internal */ constEnumOnlyModule: boolean | undefined; // True if module contains only const enums or other modules with only const enums /** @internal */ isReferenced?: SymbolFlags; // True if the symbol is referenced elsewhere. Keeps track of the meaning of a reference in case a symbol is both a type parameter and parameter. /** @internal */ isReplaceableByMethod?: boolean; // Can this Javascript class property be replaced by a method symbol? - /** @internal */ isAssigned?: boolean; // True if the symbol is a parameter with assignments - /** @internal */ assignmentDeclarationMembers?: Map; // detected late-bound assignment declarations associated with the symbol + /** @internal */ isAssigned?: boolean; // True if the symbol is a parameter with assignments + /** @internal */ assignmentDeclarationMembers?: Map< + number, + Declaration + >; // detected late-bound assignment declarations associated with the symbol } // dprint-ignore /** @internal */ export interface SymbolLinks { _symbolLinksBrand: any; - immediateTarget?: Symbol; // Immediate target of an alias. May be another alias. Do not access directly, use `checker.getImmediateAliasedSymbol` instead. - aliasTarget?: Symbol, // Resolved (non-alias) target of an alias - target?: Symbol; // Original version of an instantiated symbol - type?: Type; // Type of value symbol - writeType?: Type; // Type of value symbol in write contexts - nameType?: Type; // Type associated with a late-bound symbol - uniqueESSymbolType?: Type; // UniqueESSymbol type for a symbol - declaredType?: Type; // Type of class, interface, enum, type alias, or type parameter - typeParameters?: TypeParameter[]; // Type parameters of type alias (undefined if non-generic) - outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type - instantiations?: Map; // Instantiations of generic type alias (undefined if non-generic) - aliasSymbol?: Symbol; // Alias associated with generic type alias instantiation - aliasTypeArguments?: readonly Type[] // Alias type arguments (if any) + immediateTarget?: Symbol; // Immediate target of an alias. May be another alias. Do not access directly, use `checker.getImmediateAliasedSymbol` instead. + aliasTarget?: Symbol; // Resolved (non-alias) target of an alias + target?: Symbol; // Original version of an instantiated symbol + type?: Type; // Type of value symbol + writeType?: Type; // Type of value symbol in write contexts + nameType?: Type; // Type associated with a late-bound symbol + uniqueESSymbolType?: Type; // UniqueESSymbol type for a symbol + declaredType?: Type; // Type of class, interface, enum, type alias, or type parameter + typeParameters?: TypeParameter[]; // Type parameters of type alias (undefined if non-generic) + outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type + instantiations?: Map; // Instantiations of generic type alias (undefined if non-generic) + aliasSymbol?: Symbol; // Alias associated with generic type alias instantiation + aliasTypeArguments?: readonly Type[]; // Alias type arguments (if any) inferredClassSymbol?: Map; // Symbol of an inferred ES5 constructor function - mapper?: TypeMapper; // Type mapper for instantiation alias - referenced?: boolean; // True if alias symbol has been referenced as a value that can be emitted - constEnumReferenced?: boolean; // True if alias symbol resolves to a const enum and is referenced as a value ('referenced' will be false) - containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property - leftSpread?: Symbol; // Left source for synthetic spread property - rightSpread?: Symbol; // Right source for synthetic spread property - syntheticOrigin?: Symbol; // For a property on a mapped or spread type, points back to the original property - isDiscriminantProperty?: boolean; // True if discriminant synthetic property - resolvedExports?: SymbolTable; // Resolved exports of module or combined early- and late-bound static members of a class. - resolvedMembers?: SymbolTable; // Combined early- and late-bound members of a symbol - exportsChecked?: boolean; // True if exports of external module have been checked - typeParametersChecked?: boolean; // True if type parameters of merged class and interface declarations have been checked. - isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration - bindingElement?: BindingElement; // Binding element associated with property symbol - exportsSomeValue?: boolean; // True if module exports some value (not just types) - enumKind?: EnumKind; // Enum declaration classification + mapper?: TypeMapper; // Type mapper for instantiation alias + referenced?: boolean; // True if alias symbol has been referenced as a value that can be emitted + constEnumReferenced?: boolean; // True if alias symbol resolves to a const enum and is referenced as a value ('referenced' will be false) + containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property + leftSpread?: Symbol; // Left source for synthetic spread property + rightSpread?: Symbol; // Right source for synthetic spread property + syntheticOrigin?: Symbol; // For a property on a mapped or spread type, points back to the original property + isDiscriminantProperty?: boolean; // True if discriminant synthetic property + resolvedExports?: SymbolTable; // Resolved exports of module or combined early- and late-bound static members of a class. + resolvedMembers?: SymbolTable; // Combined early- and late-bound members of a symbol + exportsChecked?: boolean; // True if exports of external module have been checked + typeParametersChecked?: boolean; // True if type parameters of merged class and interface declarations have been checked. + isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration + bindingElement?: BindingElement; // Binding element associated with property symbol + exportsSomeValue?: boolean; // True if module exports some value (not just types) + enumKind?: EnumKind; // Enum declaration classification originatingImport?: ImportDeclaration | ImportCall; // Import declaration which produced the symbol, present if the symbol is marked as uncallable but had call signatures in `resolveESModuleSymbol` - lateSymbol?: Symbol; // Late-bound symbol for a computed property + lateSymbol?: Symbol; // Late-bound symbol for a computed property specifierCache?: Map; // For symbols corresponding to external modules, a cache of incoming path -> module specifier name mappings - extendedContainers?: Symbol[]; // Containers (other than the parent) which this symbol is aliased in + extendedContainers?: Symbol[]; // Containers (other than the parent) which this symbol is aliased in extendedContainersByFile?: Map; // Containers (other than the parent) which this symbol is aliased in - variances?: VarianceFlags[]; // Alias symbol type argument variance cache - deferralConstituents?: Type[]; // Calculated list of constituents for a deferred type - deferralWriteConstituents?: Type[]; // Constituents of a deferred `writeType` - deferralParent?: Type; // Source union/intersection of a deferred type - cjsExportMerged?: Symbol; // Version of the symbol with all non export= exports merged with the export= target + variances?: VarianceFlags[]; // Alias symbol type argument variance cache + deferralConstituents?: Type[]; // Calculated list of constituents for a deferred type + deferralWriteConstituents?: Type[]; // Constituents of a deferred `writeType` + deferralParent?: Type; // Source union/intersection of a deferred type + cjsExportMerged?: Symbol; // Version of the symbol with all non export= exports merged with the export= target typeOnlyDeclaration?: TypeOnlyAliasDeclaration | false; // First resolved alias declaration that makes the symbol only usable in type constructs - typeOnlyExportStarMap?: Map<__String, ExportDeclaration & { readonly isTypeOnly: true, readonly moduleSpecifier: Expression }>; // Set on a module symbol when some of its exports were resolved through a 'export type * from "mod"' declaration - typeOnlyExportStarName?: __String; // Set to the name of the symbol re-exported by an 'export type *' declaration, when different from the symbol name - isConstructorDeclaredProperty?: boolean; // Property declared through 'this.x = ...' assignment in constructor + typeOnlyExportStarMap?: Map< + __String, + ExportDeclaration & { + readonly isTypeOnly: true; + readonly moduleSpecifier: Expression; + } + >; // Set on a module symbol when some of its exports were resolved through a 'export type * from "mod"' declaration + typeOnlyExportStarName?: __String; // Set to the name of the symbol re-exported by an 'export type *' declaration, when different from the symbol name + isConstructorDeclaredProperty?: boolean; // Property declared through 'this.x = ...' assignment in constructor tupleLabelDeclaration?: NamedTupleMember | ParameterDeclaration; // Declaration associated with the tuple's label accessibleChainCache?: Map; - filteredIndexSymbolCache?: Map //Symbol with applicable declarations + filteredIndexSymbolCache?: Map; //Symbol with applicable declarations } /** @internal */ @@ -5857,28 +7323,28 @@ export const enum EnumKind { // dprint-ignore /** @internal */ export const enum CheckFlags { - None = 0, - Instantiated = 1 << 0, // Instantiated symbol - SyntheticProperty = 1 << 1, // Property in union or intersection type - SyntheticMethod = 1 << 2, // Method in union or intersection type - Readonly = 1 << 3, // Readonly transient symbol - ReadPartial = 1 << 4, // Synthetic property present in some but not all constituents - WritePartial = 1 << 5, // Synthetic property present in some but only satisfied by an index signature in others - HasNonUniformType = 1 << 6, // Synthetic property with non-uniform type in constituents - HasLiteralType = 1 << 7, // Synthetic property with at least one literal type in constituents - ContainsPublic = 1 << 8, // Synthetic property with public constituent(s) - ContainsProtected = 1 << 9, // Synthetic property with protected constituent(s) - ContainsPrivate = 1 << 10, // Synthetic property with private constituent(s) - ContainsStatic = 1 << 11, // Synthetic property with static constituent(s) - Late = 1 << 12, // Late-bound symbol for a computed property with a dynamic name - ReverseMapped = 1 << 13, // Property of reverse-inferred homomorphic mapped type - OptionalParameter = 1 << 14, // Optional parameter - RestParameter = 1 << 15, // Rest parameter - DeferredType = 1 << 16, // Calculation of the type of this symbol is deferred due to processing costs, should be fetched with `getTypeOfSymbolWithDeferredType` - HasNeverType = 1 << 17, // Synthetic property with at least one never type in constituents - Mapped = 1 << 18, // Property of mapped type - StripOptional = 1 << 19, // Strip optionality in mapped property - Unresolved = 1 << 20, // Unresolved type alias symbol + None = 0, + Instantiated = 1 << 0, // Instantiated symbol + SyntheticProperty = 1 << 1, // Property in union or intersection type + SyntheticMethod = 1 << 2, // Method in union or intersection type + Readonly = 1 << 3, // Readonly transient symbol + ReadPartial = 1 << 4, // Synthetic property present in some but not all constituents + WritePartial = 1 << 5, // Synthetic property present in some but only satisfied by an index signature in others + HasNonUniformType = 1 << 6, // Synthetic property with non-uniform type in constituents + HasLiteralType = 1 << 7, // Synthetic property with at least one literal type in constituents + ContainsPublic = 1 << 8, // Synthetic property with public constituent(s) + ContainsProtected = 1 << 9, // Synthetic property with protected constituent(s) + ContainsPrivate = 1 << 10, // Synthetic property with private constituent(s) + ContainsStatic = 1 << 11, // Synthetic property with static constituent(s) + Late = 1 << 12, // Late-bound symbol for a computed property with a dynamic name + ReverseMapped = 1 << 13, // Property of reverse-inferred homomorphic mapped type + OptionalParameter = 1 << 14, // Optional parameter + RestParameter = 1 << 15, // Rest parameter + DeferredType = 1 << 16, // Calculation of the type of this symbol is deferred due to processing costs, should be fetched with `getTypeOfSymbolWithDeferredType` + HasNeverType = 1 << 17, // Synthetic property with at least one never type in constituents + Mapped = 1 << 18, // Property of mapped type + StripOptional = 1 << 19, // Strip optionality in mapped property + Unresolved = 1 << 20, // Unresolved type alias symbol Synthetic = SyntheticProperty | SyntheticMethod, Discriminant = HasNonUniformType | HasLiteralType, Partial = ReadPartial | WritePartial, @@ -5945,7 +7411,10 @@ export const enum InternalSymbolName { * with a normal string (which is good, it cannot be misused on assignment or on usage), * while still being comparable with a normal string via === (also good) and castable from a string. */ -export type __String = (string & { __escapedIdentifier: void; }) | (void & { __escapedIdentifier: void; }) | InternalSymbolName; +export type __String = + | (string & { __escapedIdentifier: void; }) + | (void & { __escapedIdentifier: void; }) + | InternalSymbolName; /** @deprecated Use ReadonlyMap<__String, T> instead. */ export type ReadonlyUnderscoreEscapedMap = ReadonlyMap<__String, T>; @@ -5969,66 +7438,66 @@ export interface PatternAmbientModule { // dprint-ignore /** @internal */ export const enum NodeCheckFlags { - None = 0, - TypeChecked = 1 << 0, // Node has been type checked - LexicalThis = 1 << 1, // Lexical 'this' reference - CaptureThis = 1 << 2, // Lexical 'this' used in body - CaptureNewTarget = 1 << 3, // Lexical 'new.target' used in body - SuperInstance = 1 << 4, // Instance 'super' reference - SuperStatic = 1 << 5, // Static 'super' reference - ContextChecked = 1 << 6, // Contextual types have been assigned - MethodWithSuperPropertyAccessInAsync = 1 << 7, // A method that contains a SuperProperty access in an async context. - MethodWithSuperPropertyAssignmentInAsync = 1 << 8, // A method that contains a SuperProperty assignment in an async context. - CaptureArguments = 1 << 9, // Lexical 'arguments' used in body - EnumValuesComputed = 1 << 10, // Values for enum members have been computed, and any errors have been reported for them. - LexicalModuleMergesWithClass = 1 << 11, // Instantiated lexical module declaration is merged with a previous class declaration. - LoopWithCapturedBlockScopedBinding = 1 << 12, // Loop that contains block scoped variable captured in closure - ContainsCapturedBlockScopeBinding = 1 << 13, // Part of a loop that contains block scoped variable captured in closure - CapturedBlockScopedBinding = 1 << 14, // Block-scoped binding that is captured in some function - BlockScopedBindingInLoop = 1 << 15, // Block-scoped binding with declaration nested inside iteration statement - NeedsLoopOutParameter = 1 << 16, // Block scoped binding whose value should be explicitly copied outside of the converted loop - AssignmentsMarked = 1 << 17, // Parameter assignments have been marked - ContainsConstructorReference = 1 << 18, // Class or class element that contains a binding that references the class constructor. - ConstructorReference = 1 << 29, // Binding to a class constructor inside of the class's body. - ContainsClassWithPrivateIdentifiers = 1 << 20, // Marked on all block-scoped containers containing a class with private identifiers. - ContainsSuperPropertyInStaticInitializer = 1 << 21, // Marked on all block-scoped containers containing a static initializer with 'super.x' or 'super[x]'. - InCheckIdentifier = 1 << 22, + None = 0, + TypeChecked = 1 << 0, // Node has been type checked + LexicalThis = 1 << 1, // Lexical 'this' reference + CaptureThis = 1 << 2, // Lexical 'this' used in body + CaptureNewTarget = 1 << 3, // Lexical 'new.target' used in body + SuperInstance = 1 << 4, // Instance 'super' reference + SuperStatic = 1 << 5, // Static 'super' reference + ContextChecked = 1 << 6, // Contextual types have been assigned + MethodWithSuperPropertyAccessInAsync = 1 << 7, // A method that contains a SuperProperty access in an async context. + MethodWithSuperPropertyAssignmentInAsync = 1 << 8, // A method that contains a SuperProperty assignment in an async context. + CaptureArguments = 1 << 9, // Lexical 'arguments' used in body + EnumValuesComputed = 1 << 10, // Values for enum members have been computed, and any errors have been reported for them. + LexicalModuleMergesWithClass = 1 << 11, // Instantiated lexical module declaration is merged with a previous class declaration. + LoopWithCapturedBlockScopedBinding = 1 << 12, // Loop that contains block scoped variable captured in closure + ContainsCapturedBlockScopeBinding = 1 << 13, // Part of a loop that contains block scoped variable captured in closure + CapturedBlockScopedBinding = 1 << 14, // Block-scoped binding that is captured in some function + BlockScopedBindingInLoop = 1 << 15, // Block-scoped binding with declaration nested inside iteration statement + NeedsLoopOutParameter = 1 << 16, // Block scoped binding whose value should be explicitly copied outside of the converted loop + AssignmentsMarked = 1 << 17, // Parameter assignments have been marked + ContainsConstructorReference = 1 << 18, // Class or class element that contains a binding that references the class constructor. + ConstructorReference = 1 << 29, // Binding to a class constructor inside of the class's body. + ContainsClassWithPrivateIdentifiers = 1 << 20, // Marked on all block-scoped containers containing a class with private identifiers. + ContainsSuperPropertyInStaticInitializer = 1 << 21, // Marked on all block-scoped containers containing a static initializer with 'super.x' or 'super[x]'. + InCheckIdentifier = 1 << 22, } // dprint-ignore /** @internal */ export interface NodeLinks { - flags: NodeCheckFlags; // Set of flags specific to Node - resolvedType?: Type; // Cached type of type node - resolvedEnumType?: Type; // Cached constraint type from enum jsdoc tag - resolvedSignature?: Signature; // Cached signature of signature node or call expression - resolvedSymbol?: Symbol; // Cached name resolution result - resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result - effectsSignature?: Signature; // Signature with possible control flow effects - enumMemberValue?: string | number; // Constant value of enum member - isVisible?: boolean; // Is this node visible + flags: NodeCheckFlags; // Set of flags specific to Node + resolvedType?: Type; // Cached type of type node + resolvedEnumType?: Type; // Cached constraint type from enum jsdoc tag + resolvedSignature?: Signature; // Cached signature of signature node or call expression + resolvedSymbol?: Symbol; // Cached name resolution result + resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result + effectsSignature?: Signature; // Signature with possible control flow effects + enumMemberValue?: string | number; // Constant value of enum member + isVisible?: boolean; // Is this node visible containsArgumentsReference?: boolean; // Whether a function-like declaration contains an 'arguments' reference hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context - jsxFlags: JsxFlags; // flags for knowing what kind of element/attributes we're dealing with + jsxFlags: JsxFlags; // flags for knowing what kind of element/attributes we're dealing with resolvedJsxElementAttributesType?: Type; // resolved element attributes type of a JSX openinglike element resolvedJsxElementAllAttributesType?: Type; // resolved all element attributes type of a JSX openinglike element - resolvedJSDocType?: Type; // Resolved type of a JSDoc type reference - switchTypes?: Type[]; // Cached array of switch case expression types - jsxNamespace?: Symbol | false; // Resolved jsx namespace symbol for this node + resolvedJSDocType?: Type; // Resolved type of a JSDoc type reference + switchTypes?: Type[]; // Cached array of switch case expression types + jsxNamespace?: Symbol | false; // Resolved jsx namespace symbol for this node jsxImplicitImportContainer?: Symbol | false; // Resolved module symbol the implicit jsx import of this file should refer to - contextFreeType?: Type; // Cached context-free type used by the first pass of inference; used when a function's return is partially contextually sensitive - deferredNodes?: Set; // Set of nodes whose checking has been deferred + contextFreeType?: Type; // Cached context-free type used by the first pass of inference; used when a function's return is partially contextually sensitive + deferredNodes?: Set; // Set of nodes whose checking has been deferred capturedBlockScopeBindings?: Symbol[]; // Block-scoped bindings captured beneath this part of an IterationStatement outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type - isExhaustive?: boolean | 0; // Is node an exhaustive switch statement (0 indicates in-process resolution) - skipDirectInference?: true; // Flag set by the API `getContextualType` call on a node when `Completions` is passed to force the checker to skip making inferences to a node's type + isExhaustive?: boolean | 0; // Is node an exhaustive switch statement (0 indicates in-process resolution) + skipDirectInference?: true; // Flag set by the API `getContextualType` call on a node when `Completions` is passed to force the checker to skip making inferences to a node's type declarationRequiresScopeChange?: boolean; // Set by `useOuterVariableScopeInParameter` in checker when downlevel emit would change the name resolution scope inside of a parameter. serializedTypes?: Map; // Collection of types serialized at this location - decoratorSignature?: Signature; // Signature for decorator as if invoked by the runtime. - spreadIndices?: { first: number | undefined, last: number | undefined }; // Indices of first and last spread elements in array literal + decoratorSignature?: Signature; // Signature for decorator as if invoked by the runtime. + spreadIndices?: { first: number | undefined; last: number | undefined }; // Indices of first and last spread elements in array literal parameterInitializerContainsUndefined?: boolean; // True if this is a parameter declaration whose type annotation contains "undefined". fakeScopeForSignatureDeclaration?: boolean; // True if this is a fake scope injected into an enclosing declaration chain. - assertionExpressionType?: Type; // Cached type of the expression of a type assertion + assertionExpressionType?: Type; // Cached type of the expression of a type assertion } /** @internal */ @@ -6040,35 +7509,35 @@ export interface SerializedTypeEntry { // dprint-ignore export const enum TypeFlags { - Any = 1 << 0, - Unknown = 1 << 1, - String = 1 << 2, - Number = 1 << 3, - Boolean = 1 << 4, - Enum = 1 << 5, // Numeric computed enum member value - BigInt = 1 << 6, - StringLiteral = 1 << 7, - NumberLiteral = 1 << 8, - BooleanLiteral = 1 << 9, - EnumLiteral = 1 << 10, // Always combined with StringLiteral, NumberLiteral, or Union - BigIntLiteral = 1 << 11, - ESSymbol = 1 << 12, // Type of symbol primitive introduced in ES6 - UniqueESSymbol = 1 << 13, // unique symbol - Void = 1 << 14, - Undefined = 1 << 15, - Null = 1 << 16, - Never = 1 << 17, // Never type - TypeParameter = 1 << 18, // Type parameter - Object = 1 << 19, // Object type - Union = 1 << 20, // Union (T | U) - Intersection = 1 << 21, // Intersection (T & U) - Index = 1 << 22, // keyof T - IndexedAccess = 1 << 23, // T[K] - Conditional = 1 << 24, // T extends U ? X : Y - Substitution = 1 << 25, // Type parameter substitution - NonPrimitive = 1 << 26, // intrinsic object type - TemplateLiteral = 1 << 27, // Template literal type - StringMapping = 1 << 28, // Uppercase/Lowercase type + Any = 1 << 0, + Unknown = 1 << 1, + String = 1 << 2, + Number = 1 << 3, + Boolean = 1 << 4, + Enum = 1 << 5, // Numeric computed enum member value + BigInt = 1 << 6, + StringLiteral = 1 << 7, + NumberLiteral = 1 << 8, + BooleanLiteral = 1 << 9, + EnumLiteral = 1 << 10, // Always combined with StringLiteral, NumberLiteral, or Union + BigIntLiteral = 1 << 11, + ESSymbol = 1 << 12, // Type of symbol primitive introduced in ES6 + UniqueESSymbol = 1 << 13, // unique symbol + Void = 1 << 14, + Undefined = 1 << 15, + Null = 1 << 16, + Never = 1 << 17, // Never type + TypeParameter = 1 << 18, // Type parameter + Object = 1 << 19, // Object type + Union = 1 << 20, // Union (T | U) + Intersection = 1 << 21, // Intersection (T & U) + Index = 1 << 22, // keyof T + IndexedAccess = 1 << 23, // T[K] + Conditional = 1 << 24, // T extends U ? X : Y + Substitution = 1 << 25, // Type parameter substitution + NonPrimitive = 1 << 26, // intrinsic object type + TemplateLiteral = 1 << 27, // Template literal type + StringMapping = 1 << 28, // Uppercase/Lowercase type /** @internal */ AnyOrUnknown = Any | Unknown, @@ -6079,12 +7548,32 @@ export const enum TypeFlags { Freshable = Enum | Literal, StringOrNumberLiteral = StringLiteral | NumberLiteral, /** @internal */ - StringOrNumberLiteralOrUnique = StringLiteral | NumberLiteral | UniqueESSymbol, - /** @internal */ - DefinitelyFalsy = StringLiteral | NumberLiteral | BigIntLiteral | BooleanLiteral | Void | Undefined | Null, + StringOrNumberLiteralOrUnique = StringLiteral | + NumberLiteral | + UniqueESSymbol, + /** @internal */ + DefinitelyFalsy = StringLiteral | + NumberLiteral | + BigIntLiteral | + BooleanLiteral | + Void | + Undefined | + Null, PossiblyFalsy = DefinitelyFalsy | String | Number | BigInt | Boolean, /** @internal */ - Intrinsic = Any | Unknown | String | Number | BigInt | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never | NonPrimitive, + Intrinsic = Any | + Unknown | + String | + Number | + BigInt | + Boolean | + BooleanLiteral | + ESSymbol | + Void | + Undefined | + Null | + Never | + NonPrimitive, StringLike = String | StringLiteral | TemplateLiteral | StringMapping, NumberLike = Number | NumberLiteral | Enum, BigIntLike = BigInt | BigIntLiteral, @@ -6093,11 +7582,32 @@ export const enum TypeFlags { ESSymbolLike = ESSymbol | UniqueESSymbol, VoidLike = Void | Undefined, /** @internal */ - Primitive = StringLike | NumberLike | BigIntLike | BooleanLike | EnumLike | ESSymbolLike | VoidLike | Null, - /** @internal */ - DefinitelyNonNullable = StringLike | NumberLike | BigIntLike | BooleanLike | EnumLike | ESSymbolLike | Object | NonPrimitive, - /** @internal */ - DisjointDomains = NonPrimitive | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbolLike | VoidLike | Null, + Primitive = StringLike | + NumberLike | + BigIntLike | + BooleanLike | + EnumLike | + ESSymbolLike | + VoidLike | + Null, + /** @internal */ + DefinitelyNonNullable = StringLike | + NumberLike | + BigIntLike | + BooleanLike | + EnumLike | + ESSymbolLike | + Object | + NonPrimitive, + /** @internal */ + DisjointDomains = NonPrimitive | + StringLike | + NumberLike | + BigIntLike | + BooleanLike | + ESSymbolLike | + VoidLike | + Null, UnionOrIntersection = Union | Intersection, StructuredType = Object | Union | Intersection, TypeVariable = TypeParameter | IndexedAccess, @@ -6106,17 +7616,51 @@ export const enum TypeFlags { Instantiable = InstantiableNonPrimitive | InstantiablePrimitive, StructuredOrInstantiable = StructuredType | Instantiable, /** @internal */ - ObjectFlagsType = Any | Nullable | Never | Object | Union | Intersection | TemplateLiteral, + ObjectFlagsType = Any | + Nullable | + Never | + Object | + Union | + Intersection | + TemplateLiteral, /** @internal */ Simplifiable = IndexedAccess | Conditional, /** @internal */ - Singleton = Any | Unknown | String | Number | Boolean | BigInt | ESSymbol | Void | Undefined | Null | Never | NonPrimitive, + Singleton = Any | + Unknown | + String | + Number | + Boolean | + BigInt | + ESSymbol | + Void | + Undefined | + Null | + Never | + NonPrimitive, // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never - Narrowable = Any | Unknown | StructuredOrInstantiable | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbol | UniqueESSymbol | NonPrimitive, + Narrowable = Any | + Unknown | + StructuredOrInstantiable | + StringLike | + NumberLike | + BigIntLike | + BooleanLike | + ESSymbol | + UniqueESSymbol | + NonPrimitive, // The following flags are aggregated during union and intersection type construction /** @internal */ - IncludesMask = Any | Unknown | Primitive | Never | Object | Union | Intersection | NonPrimitive | TemplateLiteral, + IncludesMask = Any | + Unknown | + Primitive | + Never | + Object | + Union | + Intersection | + NonPrimitive | + TemplateLiteral, // The following flags are used for different purposes during union and intersection type construction /** @internal */ IncludesMissingType = TypeParameter, @@ -6129,10 +7673,19 @@ export const enum TypeFlags { /** @internal */ IncludesInstantiable = Substitution, /** @internal */ - NotPrimitiveUnion = Any | Unknown | Void | Never | Object | Intersection | IncludesInstantiable, + NotPrimitiveUnion = Any | + Unknown | + Void | + Never | + Object | + Intersection | + IncludesInstantiable, } -export type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; +export type DestructuringPattern = + | BindingPattern + | ObjectLiteralExpression + | ArrayLiteralExpression; /** @internal */ export type TypeId = number; @@ -6140,19 +7693,19 @@ export type TypeId = number; // Properties common to all types // dprint-ignore export interface Type { - flags: TypeFlags; // Flags - /** @internal */ id: TypeId; // Unique ID + flags: TypeFlags; // Flags + /** @internal */ id: TypeId; // Unique ID /** @internal */ checker: TypeChecker; - symbol: Symbol; // Symbol associated with type (if any) - pattern?: DestructuringPattern; // Destructuring pattern represented by type (if any) - aliasSymbol?: Symbol; // Alias associated with type + symbol: Symbol; // Symbol associated with type (if any) + pattern?: DestructuringPattern; // Destructuring pattern represented by type (if any) + aliasSymbol?: Symbol; // Alias associated with type aliasTypeArguments?: readonly Type[]; // Alias type arguments (if any) /** @internal */ - permissiveInstantiation?: Type; // Instantiation with type parameters mapped to wildcard type + permissiveInstantiation?: Type; // Instantiation with type parameters mapped to wildcard type /** @internal */ restrictiveInstantiation?: Type; // Instantiation with type parameters mapped to unconstrained form /** @internal */ - immediateBaseConstraint?: Type; // Immediate base constraint cache + immediateBaseConstraint?: Type; // Immediate base constraint cache /** @internal */ widened?: Type; // Cached widened form of the type } @@ -6176,8 +7729,7 @@ export interface FreshableType extends Type { } /** @internal */ -export interface FreshableIntrinsicType extends FreshableType, IntrinsicType { -} +export interface FreshableIntrinsicType extends FreshableType, IntrinsicType {} // String literal types (TypeFlags.StringLiteral) // Numeric literal types (TypeFlags.NumberLiteral) @@ -6205,32 +7757,31 @@ export interface BigIntLiteralType extends LiteralType { } // Enum types (TypeFlags.Enum) -export interface EnumType extends FreshableType { -} +export interface EnumType extends FreshableType {} // Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags // are specific to certain types and reuse the same bit position. Those ObjectFlags require a check // for a certain TypeFlags value to determine their meaning. // dprint-ignore export const enum ObjectFlags { - None = 0, - Class = 1 << 0, // Class - Interface = 1 << 1, // Interface - Reference = 1 << 2, // Generic type reference - Tuple = 1 << 3, // Synthesized generic tuple type - Anonymous = 1 << 4, // Anonymous - Mapped = 1 << 5, // Mapped - Instantiated = 1 << 6, // Instantiated anonymous or mapped type - ObjectLiteral = 1 << 7, // Originates in an object literal - EvolvingArray = 1 << 8, // Evolving array type - ObjectLiteralPatternWithComputedProperties = 1 << 9, // Object literal pattern with computed properties - ReverseMapped = 1 << 10, // Object contains a property from a reverse-mapped type - JsxAttributes = 1 << 11, // Jsx attributes type - JSLiteral = 1 << 12, // Object type declared in JS - disables errors on read/write of nonexisting members - FreshLiteral = 1 << 13, // Fresh object literal - ArrayLiteral = 1 << 14, // Originates in an array literal - /** @internal */ - PrimitiveUnion = 1 << 15, // Union of only primitive types + None = 0, + Class = 1 << 0, // Class + Interface = 1 << 1, // Interface + Reference = 1 << 2, // Generic type reference + Tuple = 1 << 3, // Synthesized generic tuple type + Anonymous = 1 << 4, // Anonymous + Mapped = 1 << 5, // Mapped + Instantiated = 1 << 6, // Instantiated anonymous or mapped type + ObjectLiteral = 1 << 7, // Originates in an object literal + EvolvingArray = 1 << 8, // Evolving array type + ObjectLiteralPatternWithComputedProperties = 1 << 9, // Object literal pattern with computed properties + ReverseMapped = 1 << 10, // Object contains a property from a reverse-mapped type + JsxAttributes = 1 << 11, // Jsx attributes type + JSLiteral = 1 << 12, // Object type declared in JS - disables errors on read/write of nonexisting members + FreshLiteral = 1 << 13, // Fresh object literal + ArrayLiteral = 1 << 14, // Originates in an array literal + /** @internal */ + PrimitiveUnion = 1 << 15, // Union of only primitive types /** @internal */ ContainsWideningType = 1 << 16, // Type is or contains undefined or null widening type /** @internal */ @@ -6246,17 +7797,25 @@ export const enum ObjectFlags { /** @internal */ RequiresWidening = ContainsWideningType | ContainsObjectOrArrayLiteral, /** @internal */ - PropagatingFlags = ContainsWideningType | ContainsObjectOrArrayLiteral | NonInferrableType, + PropagatingFlags = ContainsWideningType | + ContainsObjectOrArrayLiteral | + NonInferrableType, /** @internal */ InstantiatedMapped = Mapped | Instantiated, // Object flags that uniquely identify the kind of ObjectType /** @internal */ - ObjectTypeKindMask = ClassOrInterface | Reference | Tuple | Anonymous | Mapped | ReverseMapped | EvolvingArray, + ObjectTypeKindMask = ClassOrInterface | + Reference | + Tuple | + Anonymous | + Mapped | + ReverseMapped | + EvolvingArray, // Flags that require TypeFlags.Object - ContainsSpread = 1 << 21, // Object literal contains spread operation - ObjectRestType = 1 << 22, // Originates in object rest declaration - InstantiationExpressionType = 1 << 23, // Originates in instantiation expression + ContainsSpread = 1 << 21, // Object literal contains spread operation + ObjectRestType = 1 << 22, // Originates in object rest declaration + InstantiationExpressionType = 1 << 23, // Originates in instantiation expression /** @internal */ IsClassInstanceClone = 1 << 24, // Type is a clone of a class instance type // Flags that require TypeFlags.Object and ObjectFlags.Reference @@ -6292,31 +7851,36 @@ export const enum ObjectFlags { } /** @internal */ -export type ObjectFlagsType = NullableType | ObjectType | UnionType | IntersectionType | TemplateLiteralType; +export type ObjectFlagsType = + | NullableType + | ObjectType + | UnionType + | IntersectionType + | TemplateLiteralType; // Object types (TypeFlags.ObjectType) // dprint-ignore export interface ObjectType extends Type { objectFlags: ObjectFlags; - /** @internal */ members?: SymbolTable; // Properties by name - /** @internal */ properties?: Symbol[]; // Properties - /** @internal */ callSignatures?: readonly Signature[]; // Call signatures of type + /** @internal */ members?: SymbolTable; // Properties by name + /** @internal */ properties?: Symbol[]; // Properties + /** @internal */ callSignatures?: readonly Signature[]; // Call signatures of type /** @internal */ constructSignatures?: readonly Signature[]; // Construct signatures of type - /** @internal */ indexInfos?: readonly IndexInfo[]; // Index signatures + /** @internal */ indexInfos?: readonly IndexInfo[]; // Index signatures /** @internal */ objectTypeWithoutAbstractConstructSignatures?: ObjectType; } /** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */ // dprint-ignore export interface InterfaceType extends ObjectType { - typeParameters: TypeParameter[] | undefined; // Type parameters (undefined if non-generic) + typeParameters: TypeParameter[] | undefined; // Type parameters (undefined if non-generic) outerTypeParameters: TypeParameter[] | undefined; // Outer type parameters (undefined if none) localTypeParameters: TypeParameter[] | undefined; // Local type parameters (undefined if none) - thisType: TypeParameter | undefined; // The "this" type (undefined if none) + thisType: TypeParameter | undefined; // The "this" type (undefined if none) /** @internal */ - resolvedBaseConstructorType?: Type; // Resolved base constructor type of class + resolvedBaseConstructorType?: Type; // Resolved base constructor type of class /** @internal */ - resolvedBaseTypes: BaseType[]; // Resolved base types + resolvedBaseTypes: BaseType[]; // Resolved base types /** @internal */ baseTypesResolved?: boolean; } @@ -6326,10 +7890,10 @@ export type BaseType = ObjectType | IntersectionType | TypeVariable; // Also `an // dprint-ignore export interface InterfaceTypeWithDeclaredMembers extends InterfaceType { - declaredProperties: Symbol[]; // Declared members - declaredCallSignatures: Signature[]; // Declared call signatures - declaredConstructSignatures: Signature[]; // Declared construct signatures - declaredIndexInfos: IndexInfo[]; // Declared index signatures + declaredProperties: Symbol[]; // Declared members + declaredCallSignatures: Signature[]; // Declared call signatures + declaredConstructSignatures: Signature[]; // Declared construct signatures + declaredIndexInfos: IndexInfo[]; // Declared index signatures } /** @@ -6367,14 +7931,14 @@ export interface DeferredTypeReference extends TypeReference { // dprint-ignore /** @internal */ export const enum VarianceFlags { - Invariant = 0, // Neither covariant nor contravariant - Covariant = 1 << 0, // Covariant - Contravariant = 1 << 1, // Contravariant - Bivariant = Covariant | Contravariant, // Both covariant and contravariant - Independent = 1 << 2, // Unwitnessed type parameter - VarianceMask = Invariant | Covariant | Contravariant | Independent, // Mask containing all measured variances without the unmeasurable flag - Unmeasurable = 1 << 3, // Variance result is unusable - relationship relies on structural comparisons which are not reflected in generic relationships - Unreliable = 1 << 4, // Variance result is unreliable - checking may produce false negatives, but not false positives + Invariant = 0, // Neither covariant nor contravariant + Covariant = 1 << 0, // Covariant + Contravariant = 1 << 1, // Contravariant + Bivariant = Covariant | Contravariant, // Both covariant and contravariant + Independent = 1 << 2, // Unwitnessed type parameter + VarianceMask = Invariant | Covariant | Contravariant | Independent, // Mask containing all measured variances without the unmeasurable flag + Unmeasurable = 1 << 3, // Variance result is unusable - relationship relies on structural comparisons which are not reflected in generic relationships + Unreliable = 1 << 4, // Variance result is unreliable - checking may produce false negatives, but not false positives AllowsStructuralFallback = Unmeasurable | Unreliable, } @@ -6388,14 +7952,14 @@ export interface GenericType extends InterfaceType, TypeReference { // dprint-ignore export const enum ElementFlags { - Required = 1 << 0, // T - Optional = 1 << 1, // T? - Rest = 1 << 2, // ...T[] - Variadic = 1 << 3, // ...T - Fixed = Required | Optional, - Variable = Rest | Variadic, + Required = 1 << 0, // T + Optional = 1 << 1, // T? + Rest = 1 << 2, // ...T[] + Variadic = 1 << 3, // ...T + Fixed = Required | Optional, + Variable = Rest | Variadic, NonRequired = Optional | Rest | Variadic, - NonRest = Required | Optional | Variadic, + NonRest = Required | Optional | Variadic, } export interface TupleType extends GenericType { @@ -6408,7 +7972,11 @@ export interface TupleType extends GenericType { hasRestElement: boolean; combinedFlags: ElementFlags; readonly: boolean; - labeledElementDeclarations?: readonly (NamedTupleMember | ParameterDeclaration | undefined)[]; + labeledElementDeclarations?: readonly ( + | NamedTupleMember + | ParameterDeclaration + | undefined + )[]; } export interface TupleTypeReference extends TypeReference { @@ -6467,7 +8035,7 @@ export interface AnonymousType extends ObjectType { /** @internal */ export interface InstantiationExpressionType extends AnonymousType { - node: NodeWithTypeArguments; + node: NodeWithTypeArgumentsBase; } /** @internal */ @@ -6498,11 +8066,11 @@ export interface ReverseMappedType extends ObjectType { // Resolved object, union, or intersection type // dprint-ignore export interface ResolvedType extends ObjectType, UnionOrIntersectionType { - members: SymbolTable; // Properties by name - properties: Symbol[]; // Properties - callSignatures: readonly Signature[]; // Call signatures of type + members: SymbolTable; // Properties by name + properties: Symbol[]; // Properties + callSignatures: readonly Signature[]; // Call signatures of type constructSignatures: readonly Signature[]; // Construct signatures of type - indexInfos: readonly IndexInfo[]; // Index signatures + indexInfos: readonly IndexInfo[]; // Index signatures } /** @internal */ @@ -6562,13 +8130,13 @@ export interface TypeParameter extends InstantiableType { * * @internal */ - constraint?: Type; // Constraint + constraint?: Type; // Constraint /** @internal */ default?: Type; /** @internal */ - target?: TypeParameter; // Instantiation target + target?: TypeParameter; // Instantiation target /** @internal */ - mapper?: TypeMapper; // Instantiation mapper + mapper?: TypeMapper; // Instantiation mapper /** @internal */ isThisType?: boolean; /** @internal */ @@ -6692,21 +8260,25 @@ export const enum SignatureFlags { None = 0, // Propagating flags - HasRestParameter = 1 << 0, // Indicates last parameter is rest parameter - HasLiteralTypes = 1 << 1, // Indicates signature is specialized - Abstract = 1 << 2, // Indicates signature comes from an abstract class, abstract construct signature, or abstract constructor type + HasRestParameter = 1 << 0, // Indicates last parameter is rest parameter + HasLiteralTypes = 1 << 1, // Indicates signature is specialized + Abstract = 1 << 2, // Indicates signature comes from an abstract class, abstract construct signature, or abstract constructor type // Non-propagating flags - IsInnerCallChain = 1 << 3, // Indicates signature comes from a CallChain nested in an outer OptionalChain - IsOuterCallChain = 1 << 4, // Indicates signature comes from a CallChain that is the outermost chain of an optional expression + IsInnerCallChain = 1 << 3, // Indicates signature comes from a CallChain nested in an outer OptionalChain + IsOuterCallChain = 1 << 4, // Indicates signature comes from a CallChain that is the outermost chain of an optional expression IsUntypedSignatureInJSFile = 1 << 5, // Indicates signature is from a js file and has no types - IsNonInferrable = 1 << 6, // Indicates signature comes from a non-inferrable type + IsNonInferrable = 1 << 6, // Indicates signature comes from a non-inferrable type IsSignatureCandidateForOverloadFailure = 1 << 7, // We do not propagate `IsInnerCallChain` or `IsOuterCallChain` to instantiated signatures, as that would result in us // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when // instantiating the return type. - PropagatingFlags = HasRestParameter | HasLiteralTypes | Abstract | IsUntypedSignatureInJSFile | IsSignatureCandidateForOverloadFailure, + PropagatingFlags = HasRestParameter | + HasLiteralTypes | + Abstract | + IsUntypedSignatureInJSFile | + IsSignatureCandidateForOverloadFailure, CallChainFlags = IsInnerCallChain | IsOuterCallChain, } @@ -6716,41 +8288,41 @@ export interface Signature { /** @internal */ flags: SignatureFlags; /** @internal */ checker?: TypeChecker; declaration?: SignatureDeclaration | JSDocSignature; // Originating declaration - typeParameters?: readonly TypeParameter[]; // Type parameters (undefined if non-generic) - parameters: readonly Symbol[]; // Parameters - thisParameter?: Symbol; // symbol of this-type parameter + typeParameters?: readonly TypeParameter[]; // Type parameters (undefined if non-generic) + parameters: readonly Symbol[]; // Parameters + thisParameter?: Symbol; // symbol of this-type parameter /** @internal */ // See comment in `instantiateSignature` for why these are set lazily. - resolvedReturnType?: Type; // Lazily set by `getReturnTypeOfSignature`. + resolvedReturnType?: Type; // Lazily set by `getReturnTypeOfSignature`. /** @internal */ // Lazily set by `getTypePredicateOfSignature`. // `undefined` indicates a type predicate that has not yet been computed. // Uses a special `noTypePredicate` sentinel value to indicate that there is no type predicate. This looks like a TypePredicate at runtime to avoid polymorphism. resolvedTypePredicate?: TypePredicate; /** @internal */ - minArgumentCount: number; // Number of non-optional parameters + minArgumentCount: number; // Number of non-optional parameters /** @internal */ - resolvedMinArgumentCount?: number; // Number of non-optional parameters (excluding trailing `void`) + resolvedMinArgumentCount?: number; // Number of non-optional parameters (excluding trailing `void`) /** @internal */ - target?: Signature; // Instantiation target + target?: Signature; // Instantiation target /** @internal */ - mapper?: TypeMapper; // Instantiation mapper + mapper?: TypeMapper; // Instantiation mapper /** @internal */ - compositeSignatures?: Signature[]; // Underlying signatures of a union/intersection signature + compositeSignatures?: Signature[]; // Underlying signatures of a union/intersection signature /** @internal */ - compositeKind?: TypeFlags; // TypeFlags.Union if the underlying signatures are from union members, otherwise TypeFlags.Intersection + compositeKind?: TypeFlags; // TypeFlags.Union if the underlying signatures are from union members, otherwise TypeFlags.Intersection /** @internal */ - erasedSignatureCache?: Signature; // Erased version of signature (deferred) + erasedSignatureCache?: Signature; // Erased version of signature (deferred) /** @internal */ canonicalSignatureCache?: Signature; // Canonical version of signature (deferred) /** @internal */ - baseSignatureCache?: Signature; // Base version of signature (deferred) + baseSignatureCache?: Signature; // Base version of signature (deferred) /** @internal */ - optionalCallSignatureCache?: { inner?: Signature, outer?: Signature }; // Optional chained call version of signature (deferred) + optionalCallSignatureCache?: { inner?: Signature; outer?: Signature }; // Optional chained call version of signature (deferred) /** @internal */ isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison /** @internal */ - instantiations?: Map; // Generic signature instantiation cache + instantiations?: Map; // Generic signature instantiation cache } export const enum IndexKind { @@ -6778,50 +8350,68 @@ export const enum TypeMapKind { /** @internal */ export type TypeMapper = | { kind: TypeMapKind.Simple; source: Type; target: Type; } - | { kind: TypeMapKind.Array; sources: readonly Type[]; targets: readonly Type[] | undefined; } - | { kind: TypeMapKind.Deferred; sources: readonly Type[]; targets: (() => Type)[]; } - | { kind: TypeMapKind.Function; func: (t: Type) => Type; debugInfo?: () => string; } - | { kind: TypeMapKind.Composite | TypeMapKind.Merged; mapper1: TypeMapper; mapper2: TypeMapper; }; + | { + kind: TypeMapKind.Array; + sources: readonly Type[]; + targets: readonly Type[] | undefined; + } + | { + kind: TypeMapKind.Deferred; + sources: readonly Type[]; + targets: (() => Type)[]; + } + | { + kind: TypeMapKind.Function; + func: (t: Type) => Type; + debugInfo?: () => string; + } + | { + kind: TypeMapKind.Composite | TypeMapKind.Merged; + mapper1: TypeMapper; + mapper2: TypeMapper; + }; // dprint-ignore export const enum InferencePriority { - None = 0, - NakedTypeVariable = 1 << 0, // Naked type variable in union or intersection type - SpeculativeTuple = 1 << 1, // Speculative tuple inference - SubstituteSource = 1 << 2, // Source of inference originated within a substitution type's substitute - HomomorphicMappedType = 1 << 3, // Reverse inference for homomorphic mapped type - PartialHomomorphicMappedType = 1 << 4, // Partial reverse inference for homomorphic mapped type - MappedTypeConstraint = 1 << 5, // Reverse inference for mapped type - ContravariantConditional = 1 << 6, // Conditional type in contravariant position - ReturnType = 1 << 7, // Inference made from return type of generic function - LiteralKeyof = 1 << 8, // Inference made from a string literal to a keyof T - NoConstraints = 1 << 9, // Don't infer from constraints of instantiable types - AlwaysStrict = 1 << 10, // Always use strict rules for contravariant inferences - MaxValue = 1 << 11, // Seed for inference priority tracking - - PriorityImpliesCombination = ReturnType | MappedTypeConstraint | LiteralKeyof, // These priorities imply that the resulting type should be a combination of all candidates - Circularity = -1, // Inference circularity (value less than all other priorities) + None = 0, + NakedTypeVariable = 1 << 0, // Naked type variable in union or intersection type + SpeculativeTuple = 1 << 1, // Speculative tuple inference + SubstituteSource = 1 << 2, // Source of inference originated within a substitution type's substitute + HomomorphicMappedType = 1 << 3, // Reverse inference for homomorphic mapped type + PartialHomomorphicMappedType = 1 << 4, // Partial reverse inference for homomorphic mapped type + MappedTypeConstraint = 1 << 5, // Reverse inference for mapped type + ContravariantConditional = 1 << 6, // Conditional type in contravariant position + ReturnType = 1 << 7, // Inference made from return type of generic function + LiteralKeyof = 1 << 8, // Inference made from a string literal to a keyof T + NoConstraints = 1 << 9, // Don't infer from constraints of instantiable types + AlwaysStrict = 1 << 10, // Always use strict rules for contravariant inferences + MaxValue = 1 << 11, // Seed for inference priority tracking + + PriorityImpliesCombination = ReturnType | + MappedTypeConstraint | + LiteralKeyof, // These priorities imply that the resulting type should be a combination of all candidates + Circularity = -1, // Inference circularity (value less than all other priorities) } // dprint-ignore /** @internal */ export interface InferenceInfo { - typeParameter: TypeParameter; // Type parameter for which inferences are being made - candidates: Type[] | undefined; // Candidates in covariant positions (or undefined) - contraCandidates: Type[] | undefined; // Candidates in contravariant positions (or undefined) - inferredType?: Type; // Cache for resolved inferred type - priority?: InferencePriority; // Priority of current inference set - topLevel: boolean; // True if all inferences are to top level occurrences - isFixed: boolean; // True if inferences are fixed + typeParameter: TypeParameter; // Type parameter for which inferences are being made + candidates: Type[] | undefined; // Candidates in covariant positions (or undefined) + contraCandidates: Type[] | undefined; // Candidates in contravariant positions (or undefined) + inferredType?: Type; // Cache for resolved inferred type + priority?: InferencePriority; // Priority of current inference set + topLevel: boolean; // True if all inferences are to top level occurrences + isFixed: boolean; // True if inferences are fixed impliedArity?: number; } // dprint-ignore /** @internal */ export const enum InferenceFlags { - None = 0, // No special inference behaviors - NoDefault = 1 << 0, // Infer silentNeverType for no inferences (otherwise anyType or unknownType) - AnyDefault = 1 << 1, // Infer anyType (in JS files) for no inferences (otherwise unknownType) + None = 0, // No special inference behaviors + NoDefault = 1 << 0, // Infer silentNeverType for no inferences (otherwise anyType or unknownType) + AnyDefault = 1 << 1, // Infer anyType (in JS files) for no inferences (otherwise unknownType) SkippedGenericFunction = 1 << 2, // A generic function was skipped during inference } @@ -6843,18 +8433,22 @@ export const enum Ternary { } /** @internal */ -export type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary; +export type TypeComparer = ( + s: Type, + t: Type, + reportErrors?: boolean, +) => Ternary; // dprint-ignore /** @internal */ export interface InferenceContext { - inferences: InferenceInfo[]; // Inferences made for each type parameter - signature?: Signature; // Generic signature for which inferences are made (if any) - flags: InferenceFlags; // Inference flags - compareTypes: TypeComparer; // Type comparer function - mapper: TypeMapper; // Mapper that fixes inferences - nonFixingMapper: TypeMapper; // Mapper that doesn't fix inferences - returnMapper?: TypeMapper; // Type mapper for inferences from return types (if any) + inferences: InferenceInfo[]; // Inferences made for each type parameter + signature?: Signature; // Generic signature for which inferences are made (if any) + flags: InferenceFlags; // Inference flags + compareTypes: TypeComparer; // Type comparer function + mapper: TypeMapper; // Mapper that fixes inferences + nonFixingMapper: TypeMapper; // Mapper that doesn't fix inferences + returnMapper?: TypeMapper; // Type mapper for inferences from return types (if any) inferredTypeParameters?: readonly TypeParameter[]; // Inferred type parameters for function result intraExpressionInferenceSites?: IntraExpressionInferenceSite[]; } @@ -6868,10 +8462,10 @@ export interface IntraExpressionInferenceSite { // dprint-ignore /** @internal */ export interface WideningContext { - parent?: WideningContext; // Parent context - propertyName?: __String; // Name of property in parent - siblings?: Type[]; // Types of siblings - resolvedProperties?: Symbol[]; // Properties occurring in sibling object literals + parent?: WideningContext; // Parent context + propertyName?: __String; // Name of property in parent + siblings?: Type[]; // Types of siblings + resolvedProperties?: Symbol[]; // Properties occurring in sibling object literals } /** @internal */ @@ -6957,7 +8551,10 @@ export interface Diagnostic extends DiagnosticRelatedInformation { export type DiagnosticArguments = (string | number)[]; /** @internal */ -export type DiagnosticAndArguments = [message: DiagnosticMessage, ...args: DiagnosticArguments]; +export type DiagnosticAndArguments = [ + message: DiagnosticMessage, + ...args: DiagnosticArguments, +]; export interface DiagnosticRelatedInformation { category: DiagnosticCategory; @@ -6989,7 +8586,10 @@ export enum DiagnosticCategory { Message, } /** @internal */ -export function diagnosticCategoryName(d: { category: DiagnosticCategory; }, lowerCase = true): string { +export function diagnosticCategoryName( + d: { category: DiagnosticCategory; }, + lowerCase = true, +): string { const name = DiagnosticCategory[d.category]; return lowerCase ? name.toLowerCase() : name; } @@ -7066,7 +8666,17 @@ export enum PollingWatchKind { FixedChunkSize, } -export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike | PluginImport[] | ProjectReference[] | null | undefined; +export type CompilerOptionsValue = + | string + | number + | boolean + | (string | number)[] + | string[] + | MapLike + | PluginImport[] + | ProjectReference[] + | null + | undefined; export interface CompilerOptions { /** @internal */ all?: boolean; @@ -7360,7 +8970,11 @@ export interface ConfigFileSpecs { /** @internal */ export type ModuleImportResult = | { module: T; modulePath?: string; error: undefined; } - | { module: undefined; modulePath?: undefined; error: { stack?: string; message?: string; }; }; + | { + module: undefined; + modulePath?: undefined; + error: { stack?: string; message?: string; }; + }; export interface CreateProgramOptions { rootNames: readonly string[]; @@ -7377,29 +8991,38 @@ export interface CreateProgramOptions { /** @internal */ export interface CommandLineOptionBase { name: string; - type: "string" | "number" | "boolean" | "object" | "list" | "listOrElement" | Map; // a value of a primitive type, or an object literal mapping named values to actual values - isFilePath?: boolean; // True if option value is a path or fileName - shortName?: string; // A short mnemonic for convenience - for instance, 'h' can be used in place of 'help' - description?: DiagnosticMessage; // The message describing what the command line switch does. - defaultValueDescription?: string | number | boolean | DiagnosticMessage; // The message describing what the dafault value is. string type is prepared for fixed chosen like "false" which do not need I18n. - paramType?: DiagnosticMessage; // The name to be used for a non-boolean option's parameter - isTSConfigOnly?: boolean; // True if option can only be specified via tsconfig.json file + type: + | "string" + | "number" + | "boolean" + | "object" + | "list" + | "listOrElement" + | Map; // a value of a primitive type, or an object literal mapping named values to actual values + isFilePath?: boolean; // True if option value is a path or fileName + shortName?: string; // A short mnemonic for convenience - for instance, 'h' can be used in place of 'help' + description?: DiagnosticMessage; // The message describing what the command line switch does. + defaultValueDescription?: string | number | boolean | DiagnosticMessage; // The message describing what the dafault value is. string type is prepared for fixed chosen like "false" which do not need I18n. + paramType?: DiagnosticMessage; // The name to be used for a non-boolean option's parameter + isTSConfigOnly?: boolean; // True if option can only be specified via tsconfig.json file isCommandLineOnly?: boolean; showInSimplifiedHelpView?: boolean; category?: DiagnosticMessage; - strictFlag?: true; // true if the option is one of the flag under strict + strictFlag?: true; // true if the option is one of the flag under strict allowJsFlag?: true; - affectsSourceFile?: true; // true if we should recreate SourceFiles after this option changes - affectsModuleResolution?: true; // currently same effect as `affectsSourceFile` - affectsBindDiagnostics?: true; // true if this affects binding (currently same effect as `affectsSourceFile`) - affectsSemanticDiagnostics?: true; // true if option affects semantic diagnostics - affectsEmit?: true; // true if the options affects emit - affectsProgramStructure?: true; // true if program should be reconstructed from root files if option changes and does not affect module resolution as affectsModuleResolution indirectly means program needs to reconstructed - affectsDeclarationPath?: true; // true if the options affects declaration file path computed - affectsBuildInfo?: true; // true if this options should be emitted in buildInfo - transpileOptionValue?: boolean | undefined; // If set this means that the option should be set to this value when transpiling - extraValidation?: (value: CompilerOptionsValue) => [DiagnosticMessage, ...string[]] | undefined; // Additional validation to be performed for the value to be valid - disallowNullOrUndefined?: true; // If set option does not allow setting null + affectsSourceFile?: true; // true if we should recreate SourceFiles after this option changes + affectsModuleResolution?: true; // currently same effect as `affectsSourceFile` + affectsBindDiagnostics?: true; // true if this affects binding (currently same effect as `affectsSourceFile`) + affectsSemanticDiagnostics?: true; // true if option affects semantic diagnostics + affectsEmit?: true; // true if the options affects emit + affectsProgramStructure?: true; // true if program should be reconstructed from root files if option changes and does not affect module resolution as affectsModuleResolution indirectly means program needs to reconstructed + affectsDeclarationPath?: true; // true if the options affects declaration file path computed + affectsBuildInfo?: true; // true if this options should be emitted in buildInfo + transpileOptionValue?: boolean | undefined; // If set this means that the option should be set to this value when transpiling + extraValidation?: ( + value: CompilerOptionsValue + ) => [DiagnosticMessage, ...string[]] | undefined; // Additional validation to be performed for the value to be valid + disallowNullOrUndefined?: true; // If set option does not allow setting null } /** @internal */ @@ -7451,28 +9074,39 @@ export interface TsConfigOnlyOption extends CommandLineOptionBase { /** @internal */ export interface CommandLineOptionOfListType extends CommandLineOptionBase { type: "list" | "listOrElement"; - element: CommandLineOptionOfCustomType | CommandLineOptionOfStringType | CommandLineOptionOfNumberType | CommandLineOptionOfBooleanType | TsConfigOnlyOption; + element: + | CommandLineOptionOfCustomType + | CommandLineOptionOfStringType + | CommandLineOptionOfNumberType + | CommandLineOptionOfBooleanType + | TsConfigOnlyOption; listPreserveFalsyValues?: boolean; } /** @internal */ -export type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfStringType | CommandLineOptionOfNumberType | CommandLineOptionOfBooleanType | TsConfigOnlyOption | CommandLineOptionOfListType; +export type CommandLineOption = + | CommandLineOptionOfCustomType + | CommandLineOptionOfStringType + | CommandLineOptionOfNumberType + | CommandLineOptionOfBooleanType + | TsConfigOnlyOption + | CommandLineOptionOfListType; // dprint-ignore /** @internal */ export const enum CharacterCodes { nullCharacter = 0, - maxAsciiCharacter = 0x7F, + maxAsciiCharacter = 0x7f, - lineFeed = 0x0A, // \n - carriageReturn = 0x0D, // \r + lineFeed = 0x0a, // \n + carriageReturn = 0x0d, // \r lineSeparator = 0x2028, paragraphSeparator = 0x2029, nextLine = 0x0085, // Unicode 3.0 space characters - space = 0x0020, // " " - nonBreakingSpace = 0x00A0, // + space = 0x0020, // " " + nonBreakingSpace = 0x00a0, // enQuad = 0x2000, emQuad = 0x2001, enSpace = 0x2002, @@ -7483,17 +9117,17 @@ export const enum CharacterCodes { figureSpace = 0x2007, punctuationSpace = 0x2008, thinSpace = 0x2009, - hairSpace = 0x200A, - zeroWidthSpace = 0x200B, - narrowNoBreakSpace = 0x202F, + hairSpace = 0x200a, + zeroWidthSpace = 0x200b, + narrowNoBreakSpace = 0x202f, ideographicSpace = 0x3000, - mathematicalSpace = 0x205F, + mathematicalSpace = 0x205f, ogham = 0x1680, // Unicode replacement character produced when a byte sequence is invalid - replacementCharacter = 0xFFFD, + replacementCharacter = 0xfffd, - _ = 0x5F, + _ = 0x5f, $ = 0x24, _0 = 0x30, @@ -7516,12 +9150,12 @@ export const enum CharacterCodes { g = 0x67, h = 0x68, i = 0x69, - j = 0x6A, - k = 0x6B, - l = 0x6C, - m = 0x6D, - n = 0x6E, - o = 0x6F, + j = 0x6a, + k = 0x6b, + l = 0x6c, + m = 0x6d, + n = 0x6e, + o = 0x6f, p = 0x70, q = 0x71, r = 0x72, @@ -7532,7 +9166,7 @@ export const enum CharacterCodes { w = 0x77, x = 0x78, y = 0x79, - z = 0x7A, + z = 0x7a, A = 0x41, B = 0x42, @@ -7543,12 +9177,12 @@ export const enum CharacterCodes { G = 0x47, H = 0x48, I = 0x49, - J = 0x4A, - K = 0x4B, - L = 0x4C, - M = 0x4D, - N = 0x4E, - O = 0x4F, + J = 0x4a, + K = 0x4b, + L = 0x4c, + M = 0x4d, + N = 0x4e, + O = 0x4f, P = 0x50, Q = 0x51, R = 0x52, @@ -7561,42 +9195,42 @@ export const enum CharacterCodes { Y = 0x59, Z = 0x5a, - ampersand = 0x26, // & - asterisk = 0x2A, // * - at = 0x40, // @ - backslash = 0x5C, // \ - backtick = 0x60, // ` - bar = 0x7C, // | - caret = 0x5E, // ^ - closeBrace = 0x7D, // } - closeBracket = 0x5D, // ] - closeParen = 0x29, // ) - colon = 0x3A, // : - comma = 0x2C, // , - dot = 0x2E, // . - doubleQuote = 0x22, // " - equals = 0x3D, // = - exclamation = 0x21, // ! - greaterThan = 0x3E, // > - hash = 0x23, // # - lessThan = 0x3C, // < - minus = 0x2D, // - - openBrace = 0x7B, // { - openBracket = 0x5B, // [ - openParen = 0x28, // ( - percent = 0x25, // % - plus = 0x2B, // + - question = 0x3F, // ? - semicolon = 0x3B, // ; - singleQuote = 0x27, // ' - slash = 0x2F, // / - tilde = 0x7E, // ~ - - backspace = 0x08, // \b - formFeed = 0x0C, // \f - byteOrderMark = 0xFEFF, - tab = 0x09, // \t - verticalTab = 0x0B, // \v + ampersand = 0x26, // & + asterisk = 0x2a, // * + at = 0x40, // @ + backslash = 0x5c, // \ + backtick = 0x60, // ` + bar = 0x7c, // | + caret = 0x5e, // ^ + closeBrace = 0x7d, // } + closeBracket = 0x5d, // ] + closeParen = 0x29, // ) + colon = 0x3a, // : + comma = 0x2c, // , + dot = 0x2e, // . + doubleQuote = 0x22, // " + equals = 0x3d, // = + exclamation = 0x21, // ! + greaterThan = 0x3e, // > + hash = 0x23, // # + lessThan = 0x3c, // < + minus = 0x2d, // - + openBrace = 0x7b, // { + openBracket = 0x5b, // [ + openParen = 0x28, // ( + percent = 0x25, // % + plus = 0x2b, // + + question = 0x3f, // ? + semicolon = 0x3b, // ; + singleQuote = 0x27, // ' + slash = 0x2f, // / + tilde = 0x7e, // ~ + + backspace = 0x08, // \b + formFeed = 0x0c, // \f + byteOrderMark = 0xfeff, + tab = 0x09, // \t + verticalTab = 0x0b, // \v } export interface ModuleResolutionHost { @@ -7733,7 +9367,9 @@ export interface ResolvedTypeReferenceDirective { } export interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations { - readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined; + readonly resolvedTypeReferenceDirective: + | ResolvedTypeReferenceDirective + | undefined; /** @internal */ failedLookupLocations?: string[]; /** @internal */ affectingLocations?: string[]; /** @internal */ resolutionDiagnostics?: Diagnostic[]; @@ -7747,8 +9383,19 @@ export type HasInvalidatedLibResolutions = (libFileName: string) => boolean; export type HasChangedAutomaticTypeDirectiveNames = () => boolean; export interface CompilerHost extends ModuleResolutionHost { - getSourceFile(fileName: string, languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; - getSourceFileByPath?(fileName: string, path: Path, languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined; + getSourceFile( + fileName: string, + languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, + onError?: (message: string) => void, + shouldCreateNewSourceFile?: boolean, + ): SourceFile | undefined; + getSourceFileByPath?( + fileName: string, + path: Path, + languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, + onError?: (message: string) => void, + shouldCreateNewSourceFile?: boolean, + ): SourceFile | undefined; getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; getDefaultLibLocation?(): string; @@ -7757,7 +9404,13 @@ export interface CompilerHost extends ModuleResolutionHost { getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; - readDirectory?(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): string[]; + readDirectory?( + rootDir: string, + extensions: readonly string[], + excludes: readonly string[] | undefined, + includes: readonly string[], + depth?: number, + ): string[]; /* * CompilerHost must either implement resolveModuleNames (in case if it wants to be completely in charge of @@ -7767,7 +9420,14 @@ export interface CompilerHost extends ModuleResolutionHost { * 'throw new Error("NotImplemented")' */ /** @deprecated supply resolveModuleNameLiterals instead for resolution that can handle newer resolution modes like nodenext */ - resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile?: SourceFile): (ResolvedModule | undefined)[]; + resolveModuleNames?( + moduleNames: string[], + containingFile: string, + reusedNames: string[] | undefined, + redirectedReference: ResolvedProjectReference | undefined, + options: CompilerOptions, + containingSourceFile?: SourceFile, + ): (ResolvedModule | undefined)[]; /** * Returns the module resolution cache used by a provided `resolveModuleNames` implementation so that any non-name module resolution operations (eg, package.json lookup) can reuse it */ @@ -7777,7 +9437,13 @@ export interface CompilerHost extends ModuleResolutionHost { * * This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files */ - resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingFileMode?: ResolutionMode): (ResolvedTypeReferenceDirective | undefined)[]; + resolveTypeReferenceDirectives?( + typeReferenceDirectiveNames: string[] | readonly FileReference[], + containingFile: string, + redirectedReference: ResolvedProjectReference | undefined, + options: CompilerOptions, + containingFileMode?: ResolutionMode, + ): (ResolvedTypeReferenceDirective | undefined)[]; resolveModuleNameLiterals?( moduleLiterals: readonly StringLiteralLike[], containingFile: string, @@ -7807,8 +9473,16 @@ export interface CompilerHost extends ModuleResolutionHost { */ hasInvalidatedLibResolutions?(libFileName: string): boolean; getEnvironmentVariable?(name: string): string | undefined; - /** @internal */ onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions, hasSourceFileByPath: boolean): void; - /** @internal */ onReleaseParsedCommandLine?(configFileName: string, oldResolvedRef: ResolvedProjectReference | undefined, optionOptions: CompilerOptions): void; + /** @internal */ onReleaseOldSourceFile?( + oldSourceFile: SourceFile, + oldOptions: CompilerOptions, + hasSourceFileByPath: boolean, + ): void; + /** @internal */ onReleaseParsedCommandLine?( + configFileName: string, + oldResolvedRef: ResolvedProjectReference | undefined, + optionOptions: CompilerOptions, + ): void; /** If provided along with custom resolveModuleNames or resolveTypeReferenceDirectives, used to determine if unchanged file path needs to re-resolve modules/type reference directives */ hasInvalidatedResolutions?(filePath: Path): boolean; /** @internal */ hasChangedAutomaticTypeDirectiveNames?: HasChangedAutomaticTypeDirectiveNames; @@ -7822,7 +9496,10 @@ export interface CompilerHost extends ModuleResolutionHost { // For testing: /** @internal */ storeFilesChangingSignatureDuringEmit?: boolean; - /** @internal */ getBuildInfo?(fileName: string, configFilePath: string | undefined): BuildInfo | undefined; + /** @internal */ getBuildInfo?( + fileName: string, + configFilePath: string | undefined, + ): BuildInfo | undefined; jsDocParsingMode?: JSDocParsingMode; } @@ -7834,8 +9511,14 @@ export type SourceOfProjectReferenceRedirect = string | true; /** @internal */ export interface ResolvedProjectReferenceCallbacks { - getSourceOfProjectReferenceRedirect(fileName: string): SourceOfProjectReferenceRedirect | undefined; - forEachResolvedProjectReference(cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined): T | undefined; + getSourceOfProjectReferenceRedirect( + fileName: string, + ): SourceOfProjectReferenceRedirect | undefined; + forEachResolvedProjectReference( + cb: ( + resolvedProjectReference: ResolvedProjectReference, + ) => T | undefined, + ): T | undefined; } /** @internal */ @@ -7902,17 +9585,67 @@ export const enum TransformFlags { OuterExpressionExcludes = HasComputedFlags, PropertyAccessExcludes = OuterExpressionExcludes, NodeExcludes = PropertyAccessExcludes, - ArrowFunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsBlockScopedBinding | ContainsYield | ContainsAwait | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread | ContainsPossibleTopLevelAwait, - FunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsLexicalSuper | ContainsBlockScopedBinding | ContainsYield | ContainsAwait | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread | ContainsPossibleTopLevelAwait, - ConstructorExcludes = NodeExcludes | ContainsLexicalThis | ContainsLexicalSuper | ContainsBlockScopedBinding | ContainsYield | ContainsAwait | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread | ContainsPossibleTopLevelAwait, - MethodOrAccessorExcludes = NodeExcludes | ContainsLexicalThis | ContainsLexicalSuper | ContainsBlockScopedBinding | ContainsYield | ContainsAwait | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread, - PropertyExcludes = NodeExcludes | ContainsLexicalThis | ContainsLexicalSuper, - ClassExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsComputedPropertyName, - ModuleExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsLexicalSuper | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion | ContainsPossibleTopLevelAwait, + ArrowFunctionExcludes = NodeExcludes | + ContainsTypeScriptClassSyntax | + ContainsBlockScopedBinding | + ContainsYield | + ContainsAwait | + ContainsHoistedDeclarationOrCompletion | + ContainsBindingPattern | + ContainsObjectRestOrSpread | + ContainsPossibleTopLevelAwait, + FunctionExcludes = NodeExcludes | + ContainsTypeScriptClassSyntax | + ContainsLexicalThis | + ContainsLexicalSuper | + ContainsBlockScopedBinding | + ContainsYield | + ContainsAwait | + ContainsHoistedDeclarationOrCompletion | + ContainsBindingPattern | + ContainsObjectRestOrSpread | + ContainsPossibleTopLevelAwait, + ConstructorExcludes = NodeExcludes | + ContainsLexicalThis | + ContainsLexicalSuper | + ContainsBlockScopedBinding | + ContainsYield | + ContainsAwait | + ContainsHoistedDeclarationOrCompletion | + ContainsBindingPattern | + ContainsObjectRestOrSpread | + ContainsPossibleTopLevelAwait, + MethodOrAccessorExcludes = NodeExcludes | + ContainsLexicalThis | + ContainsLexicalSuper | + ContainsBlockScopedBinding | + ContainsYield | + ContainsAwait | + ContainsHoistedDeclarationOrCompletion | + ContainsBindingPattern | + ContainsObjectRestOrSpread, + PropertyExcludes = NodeExcludes | + ContainsLexicalThis | + ContainsLexicalSuper, + ClassExcludes = NodeExcludes | + ContainsTypeScriptClassSyntax | + ContainsComputedPropertyName, + ModuleExcludes = NodeExcludes | + ContainsTypeScriptClassSyntax | + ContainsLexicalThis | + ContainsLexicalSuper | + ContainsBlockScopedBinding | + ContainsHoistedDeclarationOrCompletion | + ContainsPossibleTopLevelAwait, TypeExcludes = ~ContainsTypeScript, - ObjectLiteralExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsComputedPropertyName | ContainsObjectRestOrSpread, + ObjectLiteralExcludes = NodeExcludes | + ContainsTypeScriptClassSyntax | + ContainsComputedPropertyName | + ContainsObjectRestOrSpread, ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsRestOrSpread, - VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRestOrSpread, + VariableDeclarationListExcludes = NodeExcludes | + ContainsBindingPattern | + ContainsObjectRestOrSpread, ParameterExcludes = NodeExcludes, CatchClauseExcludes = NodeExcludes | ContainsObjectRestOrSpread, BindingPatternExcludes = NodeExcludes | ContainsRestOrSpread, @@ -7940,23 +9673,23 @@ export interface SourceMapSource { // NOTE: Any new properties should be accounted for in `mergeEmitNode` in factory/nodeFactory.ts // dprint-ignore export interface EmitNode { - flags: EmitFlags; // Flags that customize emit - internalFlags: InternalEmitFlags; // Internal flags that customize emit - annotatedNodes?: Node[]; // Tracks Parse-tree nodes with EmitNodes for eventual cleanup. - leadingComments?: SynthesizedComment[]; // Synthesized leading comments + flags: EmitFlags; // Flags that customize emit + internalFlags: InternalEmitFlags; // Internal flags that customize emit + annotatedNodes?: Node[]; // Tracks Parse-tree nodes with EmitNodes for eventual cleanup. + leadingComments?: SynthesizedComment[]; // Synthesized leading comments trailingComments?: SynthesizedComment[]; // Synthesized trailing comments - commentRange?: TextRange; // The text range to use when emitting leading or trailing comments - sourceMapRange?: SourceMapRange; // The text range to use when emitting leading or trailing source mappings + commentRange?: TextRange; // The text range to use when emitting leading or trailing comments + sourceMapRange?: SourceMapRange; // The text range to use when emitting leading or trailing source mappings tokenSourceMapRanges?: (SourceMapRange | undefined)[]; // The text range to use when emitting source mappings for tokens - constantValue?: string | number; // The constant value of an expression - externalHelpersModuleName?: Identifier; // The local name for an imported helpers module + constantValue?: string | number; // The constant value of an expression + externalHelpersModuleName?: Identifier; // The local name for an imported helpers module externalHelpers?: boolean; - helpers?: EmitHelper[]; // Emit helpers for the node - startsOnNewLine?: boolean; // If the node should begin on a new line - snippetElement?: SnippetElement; // Snippet element of the node - typeNode?: TypeNode; // VariableDeclaration type - classThis?: Identifier; // Identifier that points to a captured static `this` for a class which may be updated after decorators are applied - assignedName?: Expression; // Expression used as the assigned name of a class or function + helpers?: EmitHelper[]; // Emit helpers for the node + startsOnNewLine?: boolean; // If the node should begin on a new line + snippetElement?: SnippetElement; // Snippet element of the node + typeNode?: TypeNode; // VariableDeclaration type + classThis?: Identifier; // Identifier that points to a captured static `this` for a class which may be updated after decorators are applied + assignedName?: Expression; // Expression used as the assigned name of a class or function identifierTypeArguments?: NodeArray; // Only defined on synthesized identifiers. Though not syntactically valid, used in emitting diagnostics, quickinfo, and signature help. autoGenerate: AutoGenerateInfo | undefined; // Used for auto-generated identifiers and private identifiers. generatedImportReference?: ImportSpecifier; // Reference to the generated import specifier this identifier refers to @@ -7981,43 +9714,43 @@ export interface Placeholder { // dprint-ignore /** @internal */ export const enum SnippetKind { - TabStop, // `$1`, `$2` - Placeholder, // `${1:foo}` - Choice, // `${1|one,two,three|}` - Variable, // `$name`, `${name:default}` + TabStop, // `$1`, `$2` + Placeholder, // `${1:foo}` + Choice, // `${1|one,two,three|}` + Variable, // `$name`, `${name:default}` } // dprint-ignore export const enum EmitFlags { None = 0, - SingleLine = 1 << 0, // The contents of this node should be emitted on a single line. + SingleLine = 1 << 0, // The contents of this node should be emitted on a single line. MultiLine = 1 << 1, - AdviseOnEmitNode = 1 << 2, // The printer should invoke the onEmitNode callback when printing this node. - NoSubstitution = 1 << 3, // Disables further substitution of an expression. - CapturesThis = 1 << 4, // The function captures a lexical `this` - NoLeadingSourceMap = 1 << 5, // Do not emit a leading source map location for this node. - NoTrailingSourceMap = 1 << 6, // Do not emit a trailing source map location for this node. + AdviseOnEmitNode = 1 << 2, // The printer should invoke the onEmitNode callback when printing this node. + NoSubstitution = 1 << 3, // Disables further substitution of an expression. + CapturesThis = 1 << 4, // The function captures a lexical `this` + NoLeadingSourceMap = 1 << 5, // Do not emit a leading source map location for this node. + NoTrailingSourceMap = 1 << 6, // Do not emit a trailing source map location for this node. NoSourceMap = NoLeadingSourceMap | NoTrailingSourceMap, // Do not emit a source map location for this node. - NoNestedSourceMaps = 1 << 7, // Do not emit source map locations for children of this node. - NoTokenLeadingSourceMaps = 1 << 8, // Do not emit leading source map location for token nodes. - NoTokenTrailingSourceMaps = 1 << 9, // Do not emit trailing source map location for token nodes. + NoNestedSourceMaps = 1 << 7, // Do not emit source map locations for children of this node. + NoTokenLeadingSourceMaps = 1 << 8, // Do not emit leading source map location for token nodes. + NoTokenTrailingSourceMaps = 1 << 9, // Do not emit trailing source map location for token nodes. NoTokenSourceMaps = NoTokenLeadingSourceMaps | NoTokenTrailingSourceMaps, // Do not emit source map locations for tokens of this node. - NoLeadingComments = 1 << 10, // Do not emit leading comments for this node. - NoTrailingComments = 1 << 11, // Do not emit trailing comments for this node. + NoLeadingComments = 1 << 10, // Do not emit leading comments for this node. + NoTrailingComments = 1 << 11, // Do not emit trailing comments for this node. NoComments = NoLeadingComments | NoTrailingComments, // Do not emit comments for this node. NoNestedComments = 1 << 12, - HelperName = 1 << 13, // The Identifier refers to an *unscoped* emit helper (one that is emitted at the top of the file) - ExportName = 1 << 14, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal). - LocalName = 1 << 15, // Ensure an export prefix is not added for an identifier that points to an exported declaration. - InternalName = 1 << 16, // The name is internal to an ES5 class body function. - Indented = 1 << 17, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter). - NoIndentation = 1 << 18, // Do not indent the node. + HelperName = 1 << 13, // The Identifier refers to an *unscoped* emit helper (one that is emitted at the top of the file) + ExportName = 1 << 14, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal). + LocalName = 1 << 15, // Ensure an export prefix is not added for an identifier that points to an exported declaration. + InternalName = 1 << 16, // The name is internal to an ES5 class body function. + Indented = 1 << 17, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter). + NoIndentation = 1 << 18, // Do not indent the node. AsyncFunctionBody = 1 << 19, - ReuseTempVariableScope = 1 << 20, // Reuse the existing temp variable scope during emit. - CustomPrologue = 1 << 21, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed). - NoHoisting = 1 << 22, // Do not hoist this declaration in --module system - Iterator = 1 << 23, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable. - NoAsciiEscaping = 1 << 24, // When synthesizing nodes that lack an original node or textSourceNode, we want to write the text on the node with ASCII escaping substitutions. + ReuseTempVariableScope = 1 << 20, // Reuse the existing temp variable scope during emit. + CustomPrologue = 1 << 21, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed). + NoHoisting = 1 << 22, // Do not hoist this declaration in --module system + Iterator = 1 << 23, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable. + NoAsciiEscaping = 1 << 24, // When synthesizing nodes that lack an original node or textSourceNode, we want to write the text on the node with ASCII escaping substitutions. } // dprint-ignore @@ -8026,19 +9759,19 @@ export const enum InternalEmitFlags { None = 0, TypeScriptClassWrapper = 1 << 0, // The node is an IIFE class wrapper created by the ts transform. NeverApplyImportHelper = 1 << 1, // Indicates the node should never be wrapped with an import star helper (because, for example, it imports tslib itself) - IgnoreSourceNewlines = 1 << 2, // Overrides `printerOptions.preserveSourceNewlines` to print this node (and all descendants) with default whitespace. - Immutable = 1 << 3, // Indicates a node is a singleton intended to be reused in multiple locations. Any attempt to make further changes to the node will result in an error. - IndirectCall = 1 << 4, // Emit CallExpression as an indirect call: `(0, f)()` + IgnoreSourceNewlines = 1 << 2, // Overrides `printerOptions.preserveSourceNewlines` to print this node (and all descendants) with default whitespace. + Immutable = 1 << 3, // Indicates a node is a singleton intended to be reused in multiple locations. Any attempt to make further changes to the node will result in an error. + IndirectCall = 1 << 4, // Emit CallExpression as an indirect call: `(0, f)()` TransformPrivateStaticElements = 1 << 5, // Indicates static private elements in a file or class should be transformed regardless of --target (used by esDecorators transform) } // dprint-ignore export interface EmitHelperBase { - readonly name: string; // A unique name for this helper. - readonly scoped: boolean; // Indicates whether the helper MUST be emitted in the current scope. - readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); // ES3-compatible raw script text, or a function yielding such a string - readonly priority?: number; // Helpers with a higher priority are emitted earlier than other helpers on the node. - readonly dependencies?: EmitHelper[] + readonly name: string; // A unique name for this helper. + readonly scoped: boolean; // Indicates whether the helper MUST be emitted in the current scope. + readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); // ES3-compatible raw script text, or a function yielding such a string + readonly priority?: number; // Helpers with a higher priority are emitted earlier than other helpers on the node. + readonly dependencies?: EmitHelper[]; } export interface ScopedEmitHelper extends EmitHelperBase { @@ -8047,16 +9780,20 @@ export interface ScopedEmitHelper extends EmitHelperBase { // dprint-ignore export interface UnscopedEmitHelper extends EmitHelperBase { - readonly scoped: false; // Indicates whether the helper MUST be emitted in the current scope. + readonly scoped: false; // Indicates whether the helper MUST be emitted in the current scope. /** @internal */ - readonly importName?: string; // The name of the helper to use when importing via `--importHelpers`. - readonly text: string; // ES3-compatible raw script text, or a function yielding such a string + readonly importName?: string; // The name of the helper to use when importing via `--importHelpers`. + readonly text: string; // ES3-compatible raw script text, or a function yielding such a string } export type EmitHelper = ScopedEmitHelper | UnscopedEmitHelper; /** @internal */ -export type UniqueNameHandler = (baseName: string, checkFn?: (name: string) => boolean, optimistic?: boolean) => string; +export type UniqueNameHandler = ( + baseName: string, + checkFn?: (name: string) => boolean, + optimistic?: boolean, +) => string; export type EmitHelperUniqueNameCallback = (name: string) => string; @@ -8068,32 +9805,32 @@ export type EmitHelperUniqueNameCallback = (name: string) => string; * @internal */ export const enum ExternalEmitHelpers { - Extends = 1 << 0, // __extends (used by the ES2015 class transformation) - Assign = 1 << 1, // __assign (used by Jsx and ESNext object spread transformations) - Rest = 1 << 2, // __rest (used by ESNext object rest transformation) - Decorate = 1 << 3, // __decorate (used by TypeScript decorators transformation) + Extends = 1 << 0, // __extends (used by the ES2015 class transformation) + Assign = 1 << 1, // __assign (used by Jsx and ESNext object spread transformations) + Rest = 1 << 2, // __rest (used by ESNext object rest transformation) + Decorate = 1 << 3, // __decorate (used by TypeScript decorators transformation) ESDecorateAndRunInitializers = Decorate, // __esDecorate and __runInitializers (used by ECMAScript decorators transformation) - Metadata = 1 << 4, // __metadata (used by TypeScript decorators transformation) - Param = 1 << 5, // __param (used by TypeScript decorators transformation) - Awaiter = 1 << 6, // __awaiter (used by ES2017 async functions transformation) - Generator = 1 << 7, // __generator (used by ES2015 generator transformation) - Values = 1 << 8, // __values (used by ES2015 for..of and yield* transformations) - Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation) - SpreadArray = 1 << 10, // __spreadArray (used by ES2015 array spread and argument list spread transformations) - Await = 1 << 11, // __await (used by ES2017 async generator transformation) - AsyncGenerator = 1 << 12, // __asyncGenerator (used by ES2017 async generator transformation) - AsyncDelegator = 1 << 13, // __asyncDelegator (used by ES2017 async generator yield* transformation) - AsyncValues = 1 << 14, // __asyncValues (used by ES2017 for..await..of transformation) - ExportStar = 1 << 15, // __exportStar (used by CommonJS/AMD/UMD module transformation) - ImportStar = 1 << 16, // __importStar (used by CommonJS/AMD/UMD module transformation) - ImportDefault = 1 << 17, // __importStar (used by CommonJS/AMD/UMD module transformation) - MakeTemplateObject = 1 << 18, // __makeTemplateObject (used for constructing template string array objects) + Metadata = 1 << 4, // __metadata (used by TypeScript decorators transformation) + Param = 1 << 5, // __param (used by TypeScript decorators transformation) + Awaiter = 1 << 6, // __awaiter (used by ES2017 async functions transformation) + Generator = 1 << 7, // __generator (used by ES2015 generator transformation) + Values = 1 << 8, // __values (used by ES2015 for..of and yield* transformations) + Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation) + SpreadArray = 1 << 10, // __spreadArray (used by ES2015 array spread and argument list spread transformations) + Await = 1 << 11, // __await (used by ES2017 async generator transformation) + AsyncGenerator = 1 << 12, // __asyncGenerator (used by ES2017 async generator transformation) + AsyncDelegator = 1 << 13, // __asyncDelegator (used by ES2017 async generator yield* transformation) + AsyncValues = 1 << 14, // __asyncValues (used by ES2017 for..await..of transformation) + ExportStar = 1 << 15, // __exportStar (used by CommonJS/AMD/UMD module transformation) + ImportStar = 1 << 16, // __importStar (used by CommonJS/AMD/UMD module transformation) + ImportDefault = 1 << 17, // __importStar (used by CommonJS/AMD/UMD module transformation) + MakeTemplateObject = 1 << 18, // __makeTemplateObject (used for constructing template string array objects) ClassPrivateFieldGet = 1 << 19, // __classPrivateFieldGet (used by the class private field transformation) ClassPrivateFieldSet = 1 << 20, // __classPrivateFieldSet (used by the class private field transformation) - ClassPrivateFieldIn = 1 << 21, // __classPrivateFieldIn (used by the class private field transformation) - CreateBinding = 1 << 22, // __createBinding (use by the module transform for (re)exports and namespace imports) - SetFunctionName = 1 << 23, // __setFunctionName (used by class fields and ECMAScript decorators) - PropKey = 1 << 24, // __propKey (used by class fields and ECMAScript decorators) + ClassPrivateFieldIn = 1 << 21, // __classPrivateFieldIn (used by the class private field transformation) + CreateBinding = 1 << 22, // __createBinding (use by the module transform for (re)exports and namespace imports) + SetFunctionName = 1 << 23, // __setFunctionName (used by class fields and ECMAScript decorators) + PropKey = 1 << 24, // __propKey (used by class fields and ECMAScript decorators) AddDisposableResourceAndDisposeResources = 1 << 25, // __addDisposableResource and __disposeResources (used by ESNext transformations) FirstEmitHelper = Extends, @@ -8117,20 +9854,22 @@ export const enum ExternalEmitHelpers { // dprint-ignore export const enum EmitHint { - SourceFile, // Emitting a SourceFile - Expression, // Emitting an Expression - IdentifierName, // Emitting an IdentifierName + SourceFile, // Emitting a SourceFile + Expression, // Emitting an Expression + IdentifierName, // Emitting an IdentifierName MappedTypeParameter, // Emitting a TypeParameterDeclaration inside of a MappedTypeNode - Unspecified, // Emitting an otherwise unspecified node - EmbeddedStatement, // Emitting an embedded statement - JsxAttributeValue, // Emitting a JSX attribute value + Unspecified, // Emitting an otherwise unspecified node + EmbeddedStatement, // Emitting an embedded statement + JsxAttributeValue, // Emitting a JSX attribute value } /** @internal */ export interface SourceFileMayBeEmittedHost { getCompilerOptions(): CompilerOptions; isSourceFileFromExternalLibrary(file: SourceFile): boolean; - getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined; + getResolvedProjectReferenceToRedirect( + fileName: string, + ): ResolvedProjectReference | undefined; isSourceOfProjectReferenceRedirect(fileName: string): boolean; getCurrentDirectory(): string; getCanonicalFileName: GetCanonicalFileName; @@ -8150,7 +9889,10 @@ export interface EmitHost extends ScriptReferenceHost, ModuleSpecifierResolution isEmitBlocked(emitFileName: string): boolean; - /** @deprecated */ getPrependNodes(): readonly (InputFiles | UnparsedSource)[]; + /** @deprecated */ getPrependNodes(): readonly ( + | InputFiles + | UnparsedSource + )[]; writeFile: WriteFileCallback; getBuildInfo(bundle: BundleBuildInfo | undefined): BuildInfo | undefined; @@ -8192,11 +9934,20 @@ export type OuterExpression = /** @internal */ export type WrappedExpression = - | OuterExpression & { readonly expression: WrappedExpression; } + | (OuterExpression & { readonly expression: WrappedExpression; }) | T; /** @internal */ -export type TypeOfTag = "null" | "undefined" | "number" | "bigint" | "boolean" | "string" | "symbol" | "object" | "function"; +export type TypeOfTag = + | "null" + | "undefined" + | "number" + | "bigint" + | "boolean" + | "string" + | "symbol" + | "object" + | "function"; /** @internal */ export interface CallBinding { @@ -8206,21 +9957,49 @@ export interface CallBinding { /** @internal */ export interface ParenthesizerRules { - getParenthesizeLeftSideOfBinaryForOperator(binaryOperator: SyntaxKind): (leftSide: Expression) => Expression; - getParenthesizeRightSideOfBinaryForOperator(binaryOperator: SyntaxKind): (rightSide: Expression) => Expression; - parenthesizeLeftSideOfBinary(binaryOperator: SyntaxKind, leftSide: Expression): Expression; - parenthesizeRightSideOfBinary(binaryOperator: SyntaxKind, leftSide: Expression | undefined, rightSide: Expression): Expression; - parenthesizeExpressionOfComputedPropertyName(expression: Expression): Expression; - parenthesizeConditionOfConditionalExpression(condition: Expression): Expression; + getParenthesizeLeftSideOfBinaryForOperator( + binaryOperator: SyntaxKind, + ): (leftSide: Expression) => Expression; + getParenthesizeRightSideOfBinaryForOperator( + binaryOperator: SyntaxKind, + ): (rightSide: Expression) => Expression; + parenthesizeLeftSideOfBinary( + binaryOperator: SyntaxKind, + leftSide: Expression, + ): Expression; + parenthesizeRightSideOfBinary( + binaryOperator: SyntaxKind, + leftSide: Expression | undefined, + rightSide: Expression, + ): Expression; + parenthesizeExpressionOfComputedPropertyName( + expression: Expression, + ): Expression; + parenthesizeConditionOfConditionalExpression( + condition: Expression, + ): Expression; parenthesizeBranchOfConditionalExpression(branch: Expression): Expression; parenthesizeExpressionOfExportDefault(expression: Expression): Expression; - parenthesizeExpressionOfNew(expression: Expression): LeftHandSideExpression; - parenthesizeLeftSideOfAccess(expression: Expression, optionalChain?: boolean): LeftHandSideExpression; - parenthesizeOperandOfPostfixUnary(operand: Expression): LeftHandSideExpression; + parenthesizeExpressionOfNew( + expression: Expression, + ): LeftHandSideExpression; + parenthesizeLeftSideOfAccess( + expression: Expression, + optionalChain?: boolean, + ): LeftHandSideExpression; + parenthesizeOperandOfPostfixUnary( + operand: Expression, + ): LeftHandSideExpression; parenthesizeOperandOfPrefixUnary(operand: Expression): UnaryExpression; - parenthesizeExpressionsOfCommaDelimitedList(elements: readonly Expression[]): NodeArray; - parenthesizeExpressionForDisallowedComma(expression: Expression): Expression; - parenthesizeExpressionOfExpressionStatement(expression: Expression): Expression; + parenthesizeExpressionsOfCommaDelimitedList( + elements: readonly Expression[], + ): NodeArray; + parenthesizeExpressionForDisallowedComma( + expression: Expression, + ): Expression; + parenthesizeExpressionOfExpressionStatement( + expression: Expression, + ): Expression; parenthesizeConciseBodyOfArrowFunction(body: Expression): Expression; parenthesizeConciseBodyOfArrowFunction(body: ConciseBody): ConciseBody; parenthesizeCheckTypeOfConditionalType(type: TypeNode): TypeNode; @@ -8228,15 +10007,25 @@ export interface ParenthesizerRules { parenthesizeOperandOfTypeOperator(type: TypeNode): TypeNode; parenthesizeOperandOfReadonlyTypeOperator(type: TypeNode): TypeNode; parenthesizeNonArrayTypeOfPostfixType(type: TypeNode): TypeNode; - parenthesizeElementTypesOfTupleType(types: readonly (TypeNode | NamedTupleMember)[]): NodeArray; - parenthesizeElementTypeOfTupleType(type: TypeNode | NamedTupleMember): TypeNode | NamedTupleMember; + parenthesizeElementTypesOfTupleType( + types: readonly (TypeNode | NamedTupleMember)[], + ): NodeArray; + parenthesizeElementTypeOfTupleType( + type: TypeNode | NamedTupleMember, + ): TypeNode | NamedTupleMember; parenthesizeTypeOfOptionalType(type: TypeNode): TypeNode; parenthesizeConstituentTypeOfUnionType(type: TypeNode): TypeNode; - parenthesizeConstituentTypesOfUnionType(constituents: readonly TypeNode[]): NodeArray; + parenthesizeConstituentTypesOfUnionType( + constituents: readonly TypeNode[], + ): NodeArray; parenthesizeConstituentTypeOfIntersectionType(type: TypeNode): TypeNode; - parenthesizeConstituentTypesOfIntersectionType(constituents: readonly TypeNode[]): NodeArray; + parenthesizeConstituentTypesOfIntersectionType( + constituents: readonly TypeNode[], + ): NodeArray; parenthesizeLeadingTypeArgument(typeNode: TypeNode): TypeNode; - parenthesizeTypeArguments(typeParameters: readonly TypeNode[] | undefined): NodeArray | undefined; + parenthesizeTypeArguments( + typeParameters: readonly TypeNode[] | undefined, + ): NodeArray | undefined; } /** @internal */ @@ -8244,12 +10033,24 @@ export interface NodeConverters { convertToFunctionBlock(node: ConciseBody, multiLine?: boolean): Block; convertToFunctionExpression(node: FunctionDeclaration): FunctionExpression; convertToClassExpression(node: ClassDeclaration): ClassExpression; - convertToArrayAssignmentElement(element: ArrayBindingOrAssignmentElement): Expression; - convertToObjectAssignmentElement(element: ObjectBindingOrAssignmentElement): ObjectLiteralElementLike; - convertToAssignmentPattern(node: BindingOrAssignmentPattern): AssignmentPattern; - convertToObjectAssignmentPattern(node: ObjectBindingOrAssignmentPattern): ObjectLiteralExpression; - convertToArrayAssignmentPattern(node: ArrayBindingOrAssignmentPattern): ArrayLiteralExpression; - convertToAssignmentElementTarget(node: BindingOrAssignmentElementTarget): Expression; + convertToArrayAssignmentElement( + element: ArrayBindingOrAssignmentElement, + ): Expression; + convertToObjectAssignmentElement( + element: ObjectBindingOrAssignmentElement, + ): ObjectLiteralElementLike; + convertToAssignmentPattern( + node: BindingOrAssignmentPattern, + ): AssignmentPattern; + convertToObjectAssignmentPattern( + node: ObjectBindingOrAssignmentPattern, + ): ObjectLiteralExpression; + convertToArrayAssignmentPattern( + node: ArrayBindingOrAssignmentPattern, + ): ArrayLiteralExpression; + convertToAssignmentElementTarget( + node: BindingOrAssignmentElementTarget, + ): Expression; } /** @internal */ @@ -8261,8 +10062,14 @@ export interface GeneratedNamePart { suffix?: string; } -export type ImmediatelyInvokedFunctionExpression = CallExpression & { readonly expression: FunctionExpression; }; -export type ImmediatelyInvokedArrowFunction = CallExpression & { readonly expression: ParenthesizedExpression & { readonly expression: ArrowFunction; }; }; +export type ImmediatelyInvokedFunctionExpression = CallExpression & { + readonly expression: FunctionExpression; +}; +export type ImmediatelyInvokedArrowFunction = CallExpression & { + readonly expression: ParenthesizedExpression & { + readonly expression: ArrowFunction; + }; +}; export interface NodeFactory { /** @internal */ readonly parenthesizer: ParenthesizerRules; @@ -8270,17 +10077,30 @@ export interface NodeFactory { /** @internal */ readonly baseFactory: BaseNodeFactory; /** @internal */ readonly flags: NodeFactoryFlags; - createNodeArray(elements?: readonly T[], hasTrailingComma?: boolean): NodeArray; + createNodeArray( + elements?: readonly T[], + hasTrailingComma?: boolean, + ): NodeArray; // // Literals // - createNumericLiteral(value: string | number, numericLiteralFlags?: TokenFlags): NumericLiteral; + createNumericLiteral( + value: string | number, + numericLiteralFlags?: TokenFlags, + ): NumericLiteral; createBigIntLiteral(value: string | PseudoBigInt): BigIntLiteral; createStringLiteral(text: string, isSingleQuote?: boolean): StringLiteral; - /** @internal */ createStringLiteral(text: string, isSingleQuote?: boolean, hasExtendedUnicodeEscape?: boolean): StringLiteral; // eslint-disable-line @typescript-eslint/unified-signatures - createStringLiteralFromNode(sourceNode: PropertyNameLiteral | PrivateIdentifier, isSingleQuote?: boolean): StringLiteral; + /** @internal */ createStringLiteral( + text: string, + isSingleQuote?: boolean, + hasExtendedUnicodeEscape?: boolean, + ): StringLiteral; // eslint-disable-line @typescript-eslint/unified-signatures + createStringLiteralFromNode( + sourceNode: PropertyNameLiteral | PrivateIdentifier, + isSingleQuote?: boolean, + ): StringLiteral; createRegularExpressionLiteral(text: string): RegularExpressionLiteral; // @@ -8288,7 +10108,11 @@ export interface NodeFactory { // createIdentifier(text: string): Identifier; - /** @internal */ createIdentifier(text: string, originalKeywordKind?: SyntaxKind, hasExtendedUnicodeEscape?: boolean): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures + /** @internal */ createIdentifier( + text: string, + originalKeywordKind?: SyntaxKind, + hasExtendedUnicodeEscape?: boolean, + ): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures /** * Create a unique temporary variable. @@ -8299,8 +10123,16 @@ export interface NodeFactory { * during emit so that the variable can be referenced in a nested function body. This is an alternative to * setting `EmitFlags.ReuseTempVariableScope` on the nested function itself. */ - createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): Identifier; - /** @internal */ createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean, prefix?: string | GeneratedNamePart, suffix?: string): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures + createTempVariable( + recordTempVariable: ((node: Identifier) => void) | undefined, + reservedInNestedScopes?: boolean, + ): Identifier; + /** @internal */ createTempVariable( + recordTempVariable: ((node: Identifier) => void) | undefined, + reservedInNestedScopes?: boolean, + prefix?: string | GeneratedNamePart, + suffix?: string, + ): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures /** * Create a unique temporary variable for use in a loop. @@ -8311,18 +10143,42 @@ export interface NodeFactory { createLoopVariable(reservedInNestedScopes?: boolean): Identifier; /** Create a unique name based on the supplied text. */ - createUniqueName(text: string, flags?: GeneratedIdentifierFlags): Identifier; - /** @internal */ createUniqueName(text: string, flags?: GeneratedIdentifierFlags, prefix?: string | GeneratedNamePart, suffix?: string): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures + createUniqueName( + text: string, + flags?: GeneratedIdentifierFlags, + ): Identifier; + /** @internal */ createUniqueName( + text: string, + flags?: GeneratedIdentifierFlags, + prefix?: string | GeneratedNamePart, + suffix?: string, + ): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures /** Create a unique name generated for a node. */ - getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier; - /** @internal */ getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags, prefix?: string | GeneratedNamePart, suffix?: string): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures + getGeneratedNameForNode( + node: Node | undefined, + flags?: GeneratedIdentifierFlags, + ): Identifier; + /** @internal */ getGeneratedNameForNode( + node: Node | undefined, + flags?: GeneratedIdentifierFlags, + prefix?: string | GeneratedNamePart, + suffix?: string, + ): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures createPrivateIdentifier(text: string): PrivateIdentifier; createUniquePrivateName(text?: string): PrivateIdentifier; - /** @internal */ createUniquePrivateName(text?: string, prefix?: string | GeneratedNamePart, suffix?: string): PrivateIdentifier; // eslint-disable-line @typescript-eslint/unified-signatures + /** @internal */ createUniquePrivateName( + text?: string, + prefix?: string | GeneratedNamePart, + suffix?: string, + ): PrivateIdentifier; // eslint-disable-line @typescript-eslint/unified-signatures getGeneratedPrivateNameForNode(node: Node): PrivateIdentifier; - /** @internal */ getGeneratedPrivateNameForNode(node: Node, prefix?: string | GeneratedNamePart, suffix?: string): PrivateIdentifier; // eslint-disable-line @typescript-eslint/unified-signatures + /** @internal */ getGeneratedPrivateNameForNode( + node: Node, + prefix?: string | GeneratedNamePart, + suffix?: string, + ): PrivateIdentifier; // eslint-disable-line @typescript-eslint/unified-signatures // // Punctuation @@ -8335,11 +10191,21 @@ export interface NodeFactory { createToken(token: SyntaxKind.FalseKeyword): FalseLiteral; createToken(token: SyntaxKind.EndOfFileToken): EndOfFileToken; createToken(token: SyntaxKind.Unknown): Token; - createToken(token: TKind): PunctuationToken; - createToken(token: TKind): KeywordTypeNode; - createToken(token: TKind): ModifierToken; - createToken(token: TKind): KeywordToken; - /** @internal */ createToken(token: TKind): Token; + createToken( + token: TKind, + ): PunctuationToken; + createToken( + token: TKind, + ): KeywordTypeNode; + createToken( + token: TKind, + ): ModifierToken; + createToken( + token: TKind, + ): KeywordToken; + /** @internal */ createToken( + token: TKind, + ): Token; // // Reserved words @@ -8356,25 +10222,63 @@ export interface NodeFactory { // createModifier(kind: T): ModifierToken; - createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[] | undefined; + createModifiersFromModifierFlags( + flags: ModifierFlags, + ): Modifier[] | undefined; // // Names // - createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; - updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; + createQualifiedName( + left: EntityName, + right: string | Identifier, + ): QualifiedName; + updateQualifiedName( + node: QualifiedName, + left: EntityName, + right: Identifier, + ): QualifiedName; createComputedPropertyName(expression: Expression): ComputedPropertyName; - updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; + updateComputedPropertyName( + node: ComputedPropertyName, + expression: Expression, + ): ComputedPropertyName; // // Signature elements // - createTypeParameterDeclaration(modifiers: readonly Modifier[] | undefined, name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration; - updateTypeParameterDeclaration(node: TypeParameterDeclaration, modifiers: readonly Modifier[] | undefined, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration; - createParameterDeclaration(modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration; - updateParameterDeclaration(node: ParameterDeclaration, modifiers: readonly ModifierLike[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration; + createTypeParameterDeclaration( + modifiers: readonly Modifier[] | undefined, + name: string | Identifier, + constraint?: TypeNode, + defaultType?: TypeNode, + ): TypeParameterDeclaration; + updateTypeParameterDeclaration( + node: TypeParameterDeclaration, + modifiers: readonly Modifier[] | undefined, + name: Identifier, + constraint: TypeNode | undefined, + defaultType: TypeNode | undefined, + ): TypeParameterDeclaration; + createParameterDeclaration( + modifiers: readonly ModifierLike[] | undefined, + dotDotDotToken: DotDotDotToken | undefined, + name: string | BindingName, + questionToken?: QuestionToken, + type?: TypeNode, + initializer?: Expression, + ): ParameterDeclaration; + updateParameterDeclaration( + node: ParameterDeclaration, + modifiers: readonly ModifierLike[] | undefined, + dotDotDotToken: DotDotDotToken | undefined, + name: string | BindingName, + questionToken: QuestionToken | undefined, + type: TypeNode | undefined, + initializer: Expression | undefined, + ): ParameterDeclaration; createDecorator(expression: Expression): Decorator; updateDecorator(node: Decorator, expression: Expression): Decorator; @@ -8382,182 +10286,769 @@ export interface NodeFactory { // Type Elements // - createPropertySignature(modifiers: readonly Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature; - updatePropertySignature(node: PropertySignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature; - createPropertyDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; - updatePropertyDeclaration(node: PropertyDeclaration, modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration; - createMethodSignature(modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): MethodSignature; - updateMethodSignature(node: MethodSignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): MethodSignature; - createMethodDeclaration(modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; - updateMethodDeclaration(node: MethodDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration; - createConstructorDeclaration(modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; - updateConstructorDeclaration(node: ConstructorDeclaration, modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration; - createGetAccessorDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - updateGetAccessorDeclaration(node: GetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration; - createSetAccessorDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; - updateSetAccessorDeclaration(node: SetAccessorDeclaration, modifiers: readonly ModifierLike[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration; - createCallSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration; - updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): CallSignatureDeclaration; - createConstructSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration; - updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode | undefined): ConstructSignatureDeclaration; - createIndexSignature(modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - /** @internal */ createIndexSignature(modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): IndexSignatureDeclaration; // eslint-disable-line @typescript-eslint/unified-signatures - updateIndexSignature(node: IndexSignatureDeclaration, modifiers: readonly ModifierLike[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration; - createTemplateLiteralTypeSpan(type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan; - updateTemplateLiteralTypeSpan(node: TemplateLiteralTypeSpan, type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan; + createPropertySignature( + modifiers: readonly Modifier[] | undefined, + name: PropertyName | string, + questionToken: QuestionToken | undefined, + type: TypeNode | undefined, + ): PropertySignature; + updatePropertySignature( + node: PropertySignature, + modifiers: readonly Modifier[] | undefined, + name: PropertyName, + questionToken: QuestionToken | undefined, + type: TypeNode | undefined, + ): PropertySignature; + createPropertyDeclaration( + modifiers: readonly ModifierLike[] | undefined, + name: string | PropertyName, + questionOrExclamationToken: + | QuestionToken + | ExclamationToken + | undefined, + type: TypeNode | undefined, + initializer: Expression | undefined, + ): PropertyDeclaration; + updatePropertyDeclaration( + node: PropertyDeclaration, + modifiers: readonly ModifierLike[] | undefined, + name: string | PropertyName, + questionOrExclamationToken: + | QuestionToken + | ExclamationToken + | undefined, + type: TypeNode | undefined, + initializer: Expression | undefined, + ): PropertyDeclaration; + createMethodSignature( + modifiers: readonly Modifier[] | undefined, + name: string | PropertyName, + questionToken: QuestionToken | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + ): MethodSignature; + updateMethodSignature( + node: MethodSignature, + modifiers: readonly Modifier[] | undefined, + name: PropertyName, + questionToken: QuestionToken | undefined, + typeParameters: NodeArray | undefined, + parameters: NodeArray, + type: TypeNode | undefined, + ): MethodSignature; + createMethodDeclaration( + modifiers: readonly ModifierLike[] | undefined, + asteriskToken: AsteriskToken | undefined, + name: string | PropertyName, + questionToken: QuestionToken | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + body: Block | undefined, + ): MethodDeclaration; + updateMethodDeclaration( + node: MethodDeclaration, + modifiers: readonly ModifierLike[] | undefined, + asteriskToken: AsteriskToken | undefined, + name: PropertyName, + questionToken: QuestionToken | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + body: Block | undefined, + ): MethodDeclaration; + createConstructorDeclaration( + modifiers: readonly ModifierLike[] | undefined, + parameters: readonly ParameterDeclaration[], + body: Block | undefined, + ): ConstructorDeclaration; + updateConstructorDeclaration( + node: ConstructorDeclaration, + modifiers: readonly ModifierLike[] | undefined, + parameters: readonly ParameterDeclaration[], + body: Block | undefined, + ): ConstructorDeclaration; + createGetAccessorDeclaration( + modifiers: readonly ModifierLike[] | undefined, + name: string | PropertyName, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + body: Block | undefined, + ): GetAccessorDeclaration; + updateGetAccessorDeclaration( + node: GetAccessorDeclaration, + modifiers: readonly ModifierLike[] | undefined, + name: PropertyName, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + body: Block | undefined, + ): GetAccessorDeclaration; + createSetAccessorDeclaration( + modifiers: readonly ModifierLike[] | undefined, + name: string | PropertyName, + parameters: readonly ParameterDeclaration[], + body: Block | undefined, + ): SetAccessorDeclaration; + updateSetAccessorDeclaration( + node: SetAccessorDeclaration, + modifiers: readonly ModifierLike[] | undefined, + name: PropertyName, + parameters: readonly ParameterDeclaration[], + body: Block | undefined, + ): SetAccessorDeclaration; + createCallSignature( + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + ): CallSignatureDeclaration; + updateCallSignature( + node: CallSignatureDeclaration, + typeParameters: NodeArray | undefined, + parameters: NodeArray, + type: TypeNode | undefined, + ): CallSignatureDeclaration; + createConstructSignature( + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + ): ConstructSignatureDeclaration; + updateConstructSignature( + node: ConstructSignatureDeclaration, + typeParameters: NodeArray | undefined, + parameters: NodeArray, + type: TypeNode | undefined, + ): ConstructSignatureDeclaration; + createIndexSignature( + modifiers: readonly ModifierLike[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode, + ): IndexSignatureDeclaration; + /** @internal */ createIndexSignature( + modifiers: readonly ModifierLike[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + ): IndexSignatureDeclaration; // eslint-disable-line @typescript-eslint/unified-signatures + updateIndexSignature( + node: IndexSignatureDeclaration, + modifiers: readonly ModifierLike[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode, + ): IndexSignatureDeclaration; + createTemplateLiteralTypeSpan( + type: TypeNode, + literal: TemplateMiddle | TemplateTail, + ): TemplateLiteralTypeSpan; + updateTemplateLiteralTypeSpan( + node: TemplateLiteralTypeSpan, + type: TypeNode, + literal: TemplateMiddle | TemplateTail, + ): TemplateLiteralTypeSpan; createClassStaticBlockDeclaration(body: Block): ClassStaticBlockDeclaration; - updateClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration, body: Block): ClassStaticBlockDeclaration; + updateClassStaticBlockDeclaration( + node: ClassStaticBlockDeclaration, + body: Block, + ): ClassStaticBlockDeclaration; // // Types // - createKeywordTypeNode(kind: TKind): KeywordTypeNode; - createTypePredicateNode(assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode | string, type: TypeNode | undefined): TypePredicateNode; - updateTypePredicateNode(node: TypePredicateNode, assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode, type: TypeNode | undefined): TypePredicateNode; - createTypeReferenceNode(typeName: string | EntityName, typeArguments?: readonly TypeNode[]): TypeReferenceNode; - updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray | undefined): TypeReferenceNode; - createFunctionTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): FunctionTypeNode; - updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): FunctionTypeNode; - createConstructorTypeNode(modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode; - updateConstructorTypeNode(node: ConstructorTypeNode, modifiers: readonly Modifier[] | undefined, typeParameters: NodeArray | undefined, parameters: NodeArray, type: TypeNode): ConstructorTypeNode; - createTypeQueryNode(exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode; - updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode; - createTypeLiteralNode(members: readonly TypeElement[] | undefined): TypeLiteralNode; - updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray): TypeLiteralNode; + createKeywordTypeNode( + kind: TKind, + ): KeywordTypeNode; + createTypePredicateNode( + assertsModifier: AssertsKeyword | undefined, + parameterName: Identifier | ThisTypeNode | string, + type: TypeNode | undefined, + ): TypePredicateNode; + updateTypePredicateNode( + node: TypePredicateNode, + assertsModifier: AssertsKeyword | undefined, + parameterName: Identifier | ThisTypeNode, + type: TypeNode | undefined, + ): TypePredicateNode; + createTypeReferenceNode( + typeName: string | EntityName, + typeArguments?: readonly TypeNode[], + ): TypeReferenceNode; + updateTypeReferenceNode( + node: TypeReferenceNode, + typeName: EntityName, + typeArguments: NodeArray | undefined, + ): TypeReferenceNode; + createFunctionTypeNode( + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode, + ): FunctionTypeNode; + updateFunctionTypeNode( + node: FunctionTypeNode, + typeParameters: NodeArray | undefined, + parameters: NodeArray, + type: TypeNode, + ): FunctionTypeNode; + createConstructorTypeNode( + modifiers: readonly Modifier[] | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode, + ): ConstructorTypeNode; + updateConstructorTypeNode( + node: ConstructorTypeNode, + modifiers: readonly Modifier[] | undefined, + typeParameters: NodeArray | undefined, + parameters: NodeArray, + type: TypeNode, + ): ConstructorTypeNode; + createTypeQueryNode( + exprName: EntityName, + typeArguments?: readonly TypeNode[], + ): TypeQueryNode; + updateTypeQueryNode( + node: TypeQueryNode, + exprName: EntityName, + typeArguments?: readonly TypeNode[], + ): TypeQueryNode; + createTypeLiteralNode( + members: readonly TypeElement[] | undefined, + ): TypeLiteralNode; + updateTypeLiteralNode( + node: TypeLiteralNode, + members: NodeArray, + ): TypeLiteralNode; createArrayTypeNode(elementType: TypeNode): ArrayTypeNode; - updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode; - createTupleTypeNode(elements: readonly (TypeNode | NamedTupleMember)[]): TupleTypeNode; - updateTupleTypeNode(node: TupleTypeNode, elements: readonly (TypeNode | NamedTupleMember)[]): TupleTypeNode; - createNamedTupleMember(dotDotDotToken: DotDotDotToken | undefined, name: Identifier, questionToken: QuestionToken | undefined, type: TypeNode): NamedTupleMember; - updateNamedTupleMember(node: NamedTupleMember, dotDotDotToken: DotDotDotToken | undefined, name: Identifier, questionToken: QuestionToken | undefined, type: TypeNode): NamedTupleMember; + updateArrayTypeNode( + node: ArrayTypeNode, + elementType: TypeNode, + ): ArrayTypeNode; + createTupleTypeNode( + elements: readonly (TypeNode | NamedTupleMember)[], + ): TupleTypeNode; + updateTupleTypeNode( + node: TupleTypeNode, + elements: readonly (TypeNode | NamedTupleMember)[], + ): TupleTypeNode; + createNamedTupleMember( + dotDotDotToken: DotDotDotToken | undefined, + name: Identifier, + questionToken: QuestionToken | undefined, + type: TypeNode, + ): NamedTupleMember; + updateNamedTupleMember( + node: NamedTupleMember, + dotDotDotToken: DotDotDotToken | undefined, + name: Identifier, + questionToken: QuestionToken | undefined, + type: TypeNode, + ): NamedTupleMember; createOptionalTypeNode(type: TypeNode): OptionalTypeNode; - updateOptionalTypeNode(node: OptionalTypeNode, type: TypeNode): OptionalTypeNode; + updateOptionalTypeNode( + node: OptionalTypeNode, + type: TypeNode, + ): OptionalTypeNode; createRestTypeNode(type: TypeNode): RestTypeNode; updateRestTypeNode(node: RestTypeNode, type: TypeNode): RestTypeNode; createUnionTypeNode(types: readonly TypeNode[]): UnionTypeNode; - updateUnionTypeNode(node: UnionTypeNode, types: NodeArray): UnionTypeNode; - createIntersectionTypeNode(types: readonly TypeNode[]): IntersectionTypeNode; - updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray): IntersectionTypeNode; - createConditionalTypeNode(checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; - updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode; + updateUnionTypeNode( + node: UnionTypeNode, + types: NodeArray, + ): UnionTypeNode; + createIntersectionTypeNode( + types: readonly TypeNode[], + ): IntersectionTypeNode; + updateIntersectionTypeNode( + node: IntersectionTypeNode, + types: NodeArray, + ): IntersectionTypeNode; + createConditionalTypeNode( + checkType: TypeNode, + extendsType: TypeNode, + trueType: TypeNode, + falseType: TypeNode, + ): ConditionalTypeNode; + updateConditionalTypeNode( + node: ConditionalTypeNode, + checkType: TypeNode, + extendsType: TypeNode, + trueType: TypeNode, + falseType: TypeNode, + ): ConditionalTypeNode; createInferTypeNode(typeParameter: TypeParameterDeclaration): InferTypeNode; - updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode; - createImportTypeNode(argument: TypeNode, attributes?: ImportAttributes, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode; - updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, attributes: ImportAttributes | undefined, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode; + updateInferTypeNode( + node: InferTypeNode, + typeParameter: TypeParameterDeclaration, + ): InferTypeNode; + createImportTypeNode( + argument: TypeNode, + attributes?: ImportAttributes, + qualifier?: EntityName, + typeArguments?: readonly TypeNode[], + isTypeOf?: boolean, + ): ImportTypeNode; + updateImportTypeNode( + node: ImportTypeNode, + argument: TypeNode, + attributes: ImportAttributes | undefined, + qualifier: EntityName | undefined, + typeArguments: readonly TypeNode[] | undefined, + isTypeOf?: boolean, + ): ImportTypeNode; createParenthesizedType(type: TypeNode): ParenthesizedTypeNode; - updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode; + updateParenthesizedType( + node: ParenthesizedTypeNode, + type: TypeNode, + ): ParenthesizedTypeNode; createThisTypeNode(): ThisTypeNode; - createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword, type: TypeNode): TypeOperatorNode; - updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode; - createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode; - createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined): MappedTypeNode; - updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray | undefined): MappedTypeNode; + createTypeOperatorNode( + operator: + | SyntaxKind.KeyOfKeyword + | SyntaxKind.UniqueKeyword + | SyntaxKind.ReadonlyKeyword, + type: TypeNode, + ): TypeOperatorNode; + updateTypeOperatorNode( + node: TypeOperatorNode, + type: TypeNode, + ): TypeOperatorNode; + createIndexedAccessTypeNode( + objectType: TypeNode, + indexType: TypeNode, + ): IndexedAccessTypeNode; + updateIndexedAccessTypeNode( + node: IndexedAccessTypeNode, + objectType: TypeNode, + indexType: TypeNode, + ): IndexedAccessTypeNode; + createMappedTypeNode( + readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, + typeParameter: TypeParameterDeclaration, + nameType: TypeNode | undefined, + questionToken: QuestionToken | PlusToken | MinusToken | undefined, + type: TypeNode | undefined, + members: NodeArray | undefined, + ): MappedTypeNode; + updateMappedTypeNode( + node: MappedTypeNode, + readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, + typeParameter: TypeParameterDeclaration, + nameType: TypeNode | undefined, + questionToken: QuestionToken | PlusToken | MinusToken | undefined, + type: TypeNode | undefined, + members: NodeArray | undefined, + ): MappedTypeNode; createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode; - updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode; - createTemplateLiteralType(head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]): TemplateLiteralTypeNode; - updateTemplateLiteralType(node: TemplateLiteralTypeNode, head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]): TemplateLiteralTypeNode; + updateLiteralTypeNode( + node: LiteralTypeNode, + literal: LiteralTypeNode["literal"], + ): LiteralTypeNode; + createTemplateLiteralType( + head: TemplateHead, + templateSpans: readonly TemplateLiteralTypeSpan[], + ): TemplateLiteralTypeNode; + updateTemplateLiteralType( + node: TemplateLiteralTypeNode, + head: TemplateHead, + templateSpans: readonly TemplateLiteralTypeSpan[], + ): TemplateLiteralTypeNode; // // Binding Patterns // - createObjectBindingPattern(elements: readonly BindingElement[]): ObjectBindingPattern; - updateObjectBindingPattern(node: ObjectBindingPattern, elements: readonly BindingElement[]): ObjectBindingPattern; - createArrayBindingPattern(elements: readonly ArrayBindingElement[]): ArrayBindingPattern; - updateArrayBindingPattern(node: ArrayBindingPattern, elements: readonly ArrayBindingElement[]): ArrayBindingPattern; - createBindingElement(dotDotDotToken: DotDotDotToken | undefined, propertyName: string | PropertyName | undefined, name: string | BindingName, initializer?: Expression): BindingElement; - updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken | undefined, propertyName: PropertyName | undefined, name: BindingName, initializer: Expression | undefined): BindingElement; + createObjectBindingPattern( + elements: readonly BindingElement[], + ): ObjectBindingPattern; + updateObjectBindingPattern( + node: ObjectBindingPattern, + elements: readonly BindingElement[], + ): ObjectBindingPattern; + createArrayBindingPattern( + elements: readonly ArrayBindingElement[], + ): ArrayBindingPattern; + updateArrayBindingPattern( + node: ArrayBindingPattern, + elements: readonly ArrayBindingElement[], + ): ArrayBindingPattern; + createBindingElement( + dotDotDotToken: DotDotDotToken | undefined, + propertyName: string | PropertyName | undefined, + name: string | BindingName, + initializer?: Expression, + ): BindingElement; + updateBindingElement( + node: BindingElement, + dotDotDotToken: DotDotDotToken | undefined, + propertyName: PropertyName | undefined, + name: BindingName, + initializer: Expression | undefined, + ): BindingElement; // // Expression // - createArrayLiteralExpression(elements?: readonly Expression[], multiLine?: boolean): ArrayLiteralExpression; - updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]): ArrayLiteralExpression; - createObjectLiteralExpression(properties?: readonly ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression; - updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]): ObjectLiteralExpression; - createPropertyAccessExpression(expression: Expression, name: string | MemberName): PropertyAccessExpression; - updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: MemberName): PropertyAccessExpression; - createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName): PropertyAccessChain; - updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName): PropertyAccessChain; - createElementAccessExpression(expression: Expression, index: number | Expression): ElementAccessExpression; - updateElementAccessExpression(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression; - createElementAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, index: number | Expression): ElementAccessChain; - updateElementAccessChain(node: ElementAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, argumentExpression: Expression): ElementAccessChain; - createCallExpression(expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): CallExpression; - updateCallExpression(node: CallExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]): CallExpression; - createCallChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): CallChain; - updateCallChain(node: CallChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]): CallChain; - createNewExpression(expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): NewExpression; - updateNewExpression(node: NewExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): NewExpression; - createTaggedTemplateExpression(tag: Expression, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral): TaggedTemplateExpression; - updateTaggedTemplateExpression(node: TaggedTemplateExpression, tag: Expression, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral): TaggedTemplateExpression; + createArrayLiteralExpression( + elements?: readonly Expression[], + multiLine?: boolean, + ): ArrayLiteralExpression; + updateArrayLiteralExpression( + node: ArrayLiteralExpression, + elements: readonly Expression[], + ): ArrayLiteralExpression; + createObjectLiteralExpression( + properties?: readonly ObjectLiteralElementLike[], + multiLine?: boolean, + ): ObjectLiteralExpression; + updateObjectLiteralExpression( + node: ObjectLiteralExpression, + properties: readonly ObjectLiteralElementLike[], + ): ObjectLiteralExpression; + createPropertyAccessExpression( + expression: Expression, + name: string | MemberName, + ): PropertyAccessExpression; + updatePropertyAccessExpression( + node: PropertyAccessExpression, + expression: Expression, + name: MemberName, + ): PropertyAccessExpression; + createPropertyAccessChain( + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + name: string | MemberName, + ): PropertyAccessChain; + updatePropertyAccessChain( + node: PropertyAccessChain, + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + name: MemberName, + ): PropertyAccessChain; + createElementAccessExpression( + expression: Expression, + index: number | Expression, + ): ElementAccessExpression; + updateElementAccessExpression( + node: ElementAccessExpression, + expression: Expression, + argumentExpression: Expression, + ): ElementAccessExpression; + createElementAccessChain( + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + index: number | Expression, + ): ElementAccessChain; + updateElementAccessChain( + node: ElementAccessChain, + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + argumentExpression: Expression, + ): ElementAccessChain; + createCallExpression( + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[] | undefined, + ): CallExpression; + updateCallExpression( + node: CallExpression, + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[], + ): CallExpression; + createCallChain( + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[] | undefined, + ): CallChain; + updateCallChain( + node: CallChain, + expression: Expression, + questionDotToken: QuestionDotToken | undefined, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[], + ): CallChain; + createNewExpression( + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[] | undefined, + ): NewExpression; + updateNewExpression( + node: NewExpression, + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + argumentsArray: readonly Expression[] | undefined, + ): NewExpression; + createTaggedTemplateExpression( + tag: Expression, + typeArguments: readonly TypeNode[] | undefined, + template: TemplateLiteral, + ): TaggedTemplateExpression; + updateTaggedTemplateExpression( + node: TaggedTemplateExpression, + tag: Expression, + typeArguments: readonly TypeNode[] | undefined, + template: TemplateLiteral, + ): TaggedTemplateExpression; createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion; - updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion; - createParenthesizedExpression(expression: Expression): ParenthesizedExpression; - updateParenthesizedExpression(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - createFunctionExpression(modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[] | undefined, type: TypeNode | undefined, body: Block): FunctionExpression; - updateFunctionExpression(node: FunctionExpression, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block): FunctionExpression; - createArrowFunction(modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction; - updateArrowFunction(node: ArrowFunction, modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken, body: ConciseBody): ArrowFunction; + updateTypeAssertion( + node: TypeAssertion, + type: TypeNode, + expression: Expression, + ): TypeAssertion; + createParenthesizedExpression( + expression: Expression, + ): ParenthesizedExpression; + updateParenthesizedExpression( + node: ParenthesizedExpression, + expression: Expression, + ): ParenthesizedExpression; + createFunctionExpression( + modifiers: readonly Modifier[] | undefined, + asteriskToken: AsteriskToken | undefined, + name: string | Identifier | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[] | undefined, + type: TypeNode | undefined, + body: Block, + ): FunctionExpression; + updateFunctionExpression( + node: FunctionExpression, + modifiers: readonly Modifier[] | undefined, + asteriskToken: AsteriskToken | undefined, + name: Identifier | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + body: Block, + ): FunctionExpression; + createArrowFunction( + modifiers: readonly Modifier[] | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + equalsGreaterThanToken: EqualsGreaterThanToken | undefined, + body: ConciseBody, + ): ArrowFunction; + updateArrowFunction( + node: ArrowFunction, + modifiers: readonly Modifier[] | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + equalsGreaterThanToken: EqualsGreaterThanToken, + body: ConciseBody, + ): ArrowFunction; createDeleteExpression(expression: Expression): DeleteExpression; - updateDeleteExpression(node: DeleteExpression, expression: Expression): DeleteExpression; + updateDeleteExpression( + node: DeleteExpression, + expression: Expression, + ): DeleteExpression; createTypeOfExpression(expression: Expression): TypeOfExpression; - updateTypeOfExpression(node: TypeOfExpression, expression: Expression): TypeOfExpression; + updateTypeOfExpression( + node: TypeOfExpression, + expression: Expression, + ): TypeOfExpression; createVoidExpression(expression: Expression): VoidExpression; - updateVoidExpression(node: VoidExpression, expression: Expression): VoidExpression; + updateVoidExpression( + node: VoidExpression, + expression: Expression, + ): VoidExpression; createAwaitExpression(expression: Expression): AwaitExpression; - updateAwaitExpression(node: AwaitExpression, expression: Expression): AwaitExpression; - createPrefixUnaryExpression(operator: PrefixUnaryOperator, operand: Expression): PrefixUnaryExpression; - updatePrefixUnaryExpression(node: PrefixUnaryExpression, operand: Expression): PrefixUnaryExpression; - createPostfixUnaryExpression(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression; - updatePostfixUnaryExpression(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; - createBinaryExpression(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - updateBinaryExpression(node: BinaryExpression, left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression; - createConditionalExpression(condition: Expression, questionToken: QuestionToken | undefined, whenTrue: Expression, colonToken: ColonToken | undefined, whenFalse: Expression): ConditionalExpression; - updateConditionalExpression(node: ConditionalExpression, condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression; - createTemplateExpression(head: TemplateHead, templateSpans: readonly TemplateSpan[]): TemplateExpression; - updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: readonly TemplateSpan[]): TemplateExpression; - createTemplateHead(text: string, rawText?: string, templateFlags?: TokenFlags): TemplateHead; - createTemplateHead(text: string | undefined, rawText: string, templateFlags?: TokenFlags): TemplateHead; - createTemplateMiddle(text: string, rawText?: string, templateFlags?: TokenFlags): TemplateMiddle; - createTemplateMiddle(text: string | undefined, rawText: string, templateFlags?: TokenFlags): TemplateMiddle; - createTemplateTail(text: string, rawText?: string, templateFlags?: TokenFlags): TemplateTail; - createTemplateTail(text: string | undefined, rawText: string, templateFlags?: TokenFlags): TemplateTail; - createNoSubstitutionTemplateLiteral(text: string, rawText?: string): NoSubstitutionTemplateLiteral; - createNoSubstitutionTemplateLiteral(text: string | undefined, rawText: string): NoSubstitutionTemplateLiteral; - /** @internal */ createLiteralLikeNode(kind: LiteralToken["kind"] | SyntaxKind.JsxTextAllWhiteSpaces, text: string): LiteralToken; - /** @internal */ createTemplateLiteralLikeNode(kind: TemplateLiteralToken["kind"], text: string, rawText: string, templateFlags: TokenFlags | undefined): TemplateLiteralLikeNode; - createYieldExpression(asteriskToken: AsteriskToken, expression: Expression): YieldExpression; - createYieldExpression(asteriskToken: undefined, expression: Expression | undefined): YieldExpression; - /** @internal */ createYieldExpression(asteriskToken: AsteriskToken | undefined, expression: Expression | undefined): YieldExpression; // eslint-disable-line @typescript-eslint/unified-signatures - updateYieldExpression(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression | undefined): YieldExpression; + updateAwaitExpression( + node: AwaitExpression, + expression: Expression, + ): AwaitExpression; + createPrefixUnaryExpression( + operator: PrefixUnaryOperator, + operand: Expression, + ): PrefixUnaryExpression; + updatePrefixUnaryExpression( + node: PrefixUnaryExpression, + operand: Expression, + ): PrefixUnaryExpression; + createPostfixUnaryExpression( + operand: Expression, + operator: PostfixUnaryOperator, + ): PostfixUnaryExpression; + updatePostfixUnaryExpression( + node: PostfixUnaryExpression, + operand: Expression, + ): PostfixUnaryExpression; + createBinaryExpression( + left: Expression, + operator: BinaryOperator | BinaryOperatorToken, + right: Expression, + ): BinaryExpression; + updateBinaryExpression( + node: BinaryExpression, + left: Expression, + operator: BinaryOperator | BinaryOperatorToken, + right: Expression, + ): BinaryExpression; + createConditionalExpression( + condition: Expression, + questionToken: QuestionToken | undefined, + whenTrue: Expression, + colonToken: ColonToken | undefined, + whenFalse: Expression, + ): ConditionalExpression; + updateConditionalExpression( + node: ConditionalExpression, + condition: Expression, + questionToken: QuestionToken, + whenTrue: Expression, + colonToken: ColonToken, + whenFalse: Expression, + ): ConditionalExpression; + createTemplateExpression( + head: TemplateHead, + templateSpans: readonly TemplateSpan[], + ): TemplateExpression; + updateTemplateExpression( + node: TemplateExpression, + head: TemplateHead, + templateSpans: readonly TemplateSpan[], + ): TemplateExpression; + createTemplateHead( + text: string, + rawText?: string, + templateFlags?: TokenFlags, + ): TemplateHead; + createTemplateHead( + text: string | undefined, + rawText: string, + templateFlags?: TokenFlags, + ): TemplateHead; + createTemplateMiddle( + text: string, + rawText?: string, + templateFlags?: TokenFlags, + ): TemplateMiddle; + createTemplateMiddle( + text: string | undefined, + rawText: string, + templateFlags?: TokenFlags, + ): TemplateMiddle; + createTemplateTail( + text: string, + rawText?: string, + templateFlags?: TokenFlags, + ): TemplateTail; + createTemplateTail( + text: string | undefined, + rawText: string, + templateFlags?: TokenFlags, + ): TemplateTail; + createNoSubstitutionTemplateLiteral( + text: string, + rawText?: string, + ): NoSubstitutionTemplateLiteral; + createNoSubstitutionTemplateLiteral( + text: string | undefined, + rawText: string, + ): NoSubstitutionTemplateLiteral; + /** @internal */ createLiteralLikeNode( + kind: LiteralToken["kind"] | SyntaxKind.JsxTextAllWhiteSpaces, + text: string, + ): LiteralToken; + /** @internal */ createTemplateLiteralLikeNode( + kind: TemplateLiteralToken["kind"], + text: string, + rawText: string, + templateFlags: TokenFlags | undefined, + ): TemplateLiteralLikeNode; + createYieldExpression( + asteriskToken: AsteriskToken, + expression: Expression, + ): YieldExpression; + createYieldExpression( + asteriskToken: undefined, + expression: Expression | undefined, + ): YieldExpression; + /** @internal */ createYieldExpression( + asteriskToken: AsteriskToken | undefined, + expression: Expression | undefined, + ): YieldExpression; // eslint-disable-line @typescript-eslint/unified-signatures + updateYieldExpression( + node: YieldExpression, + asteriskToken: AsteriskToken | undefined, + expression: Expression | undefined, + ): YieldExpression; createSpreadElement(expression: Expression): SpreadElement; - updateSpreadElement(node: SpreadElement, expression: Expression): SpreadElement; - createClassExpression(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; - updateClassExpression(node: ClassExpression, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression; + updateSpreadElement( + node: SpreadElement, + expression: Expression, + ): SpreadElement; + createClassExpression( + modifiers: readonly ModifierLike[] | undefined, + name: string | Identifier | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly ClassElement[], + ): ClassExpression; + updateClassExpression( + node: ClassExpression, + modifiers: readonly ModifierLike[] | undefined, + name: Identifier | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly ClassElement[], + ): ClassExpression; createOmittedExpression(): OmittedExpression; - createExpressionWithTypeArguments(expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments; - updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments; + createExpressionWithTypeArguments( + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + ): ExpressionWithTypeArguments; + updateExpressionWithTypeArguments( + node: ExpressionWithTypeArguments, + expression: Expression, + typeArguments: readonly TypeNode[] | undefined, + ): ExpressionWithTypeArguments; createAsExpression(expression: Expression, type: TypeNode): AsExpression; - updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression; + updateAsExpression( + node: AsExpression, + expression: Expression, + type: TypeNode, + ): AsExpression; createNonNullExpression(expression: Expression): NonNullExpression; - updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression; + updateNonNullExpression( + node: NonNullExpression, + expression: Expression, + ): NonNullExpression; createNonNullChain(expression: Expression): NonNullChain; - updateNonNullChain(node: NonNullChain, expression: Expression): NonNullChain; - createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty; + updateNonNullChain( + node: NonNullChain, + expression: Expression, + ): NonNullChain; + createMetaProperty( + keywordToken: MetaProperty["keywordToken"], + name: Identifier, + ): MetaProperty; updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty; - createSatisfiesExpression(expression: Expression, type: TypeNode): SatisfiesExpression; - updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode): SatisfiesExpression; + createSatisfiesExpression( + expression: Expression, + type: TypeNode, + ): SatisfiesExpression; + updateSatisfiesExpression( + node: SatisfiesExpression, + expression: Expression, + type: TypeNode, + ): SatisfiesExpression; // // Misc // - createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; - updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; + createTemplateSpan( + expression: Expression, + literal: TemplateMiddle | TemplateTail, + ): TemplateSpan; + updateTemplateSpan( + node: TemplateSpan, + expression: Expression, + literal: TemplateMiddle | TemplateTail, + ): TemplateSpan; createSemicolonClassElement(): SemicolonClassElement; // @@ -8566,103 +11057,438 @@ export interface NodeFactory { createBlock(statements: readonly Statement[], multiLine?: boolean): Block; updateBlock(node: Block, statements: readonly Statement[]): Block; - createVariableStatement(modifiers: readonly ModifierLike[] | undefined, declarationList: VariableDeclarationList | readonly VariableDeclaration[]): VariableStatement; - updateVariableStatement(node: VariableStatement, modifiers: readonly ModifierLike[] | undefined, declarationList: VariableDeclarationList): VariableStatement; + createVariableStatement( + modifiers: readonly ModifierLike[] | undefined, + declarationList: + | VariableDeclarationList + | readonly VariableDeclaration[], + ): VariableStatement; + updateVariableStatement( + node: VariableStatement, + modifiers: readonly ModifierLike[] | undefined, + declarationList: VariableDeclarationList, + ): VariableStatement; createEmptyStatement(): EmptyStatement; createExpressionStatement(expression: Expression): ExpressionStatement; - updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement; - createIfStatement(expression: Expression, thenStatement: Statement, elseStatement?: Statement): IfStatement; - updateIfStatement(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement: Statement | undefined): IfStatement; - createDoStatement(statement: Statement, expression: Expression): DoStatement; - updateDoStatement(node: DoStatement, statement: Statement, expression: Expression): DoStatement; - createWhileStatement(expression: Expression, statement: Statement): WhileStatement; - updateWhileStatement(node: WhileStatement, expression: Expression, statement: Statement): WhileStatement; - createForStatement(initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; - updateForStatement(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement; - createForInStatement(initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; - updateForInStatement(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; - createForOfStatement(awaitModifier: AwaitKeyword | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; - updateForOfStatement(node: ForOfStatement, awaitModifier: AwaitKeyword | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + updateExpressionStatement( + node: ExpressionStatement, + expression: Expression, + ): ExpressionStatement; + createIfStatement( + expression: Expression, + thenStatement: Statement, + elseStatement?: Statement, + ): IfStatement; + updateIfStatement( + node: IfStatement, + expression: Expression, + thenStatement: Statement, + elseStatement: Statement | undefined, + ): IfStatement; + createDoStatement( + statement: Statement, + expression: Expression, + ): DoStatement; + updateDoStatement( + node: DoStatement, + statement: Statement, + expression: Expression, + ): DoStatement; + createWhileStatement( + expression: Expression, + statement: Statement, + ): WhileStatement; + updateWhileStatement( + node: WhileStatement, + expression: Expression, + statement: Statement, + ): WhileStatement; + createForStatement( + initializer: ForInitializer | undefined, + condition: Expression | undefined, + incrementor: Expression | undefined, + statement: Statement, + ): ForStatement; + updateForStatement( + node: ForStatement, + initializer: ForInitializer | undefined, + condition: Expression | undefined, + incrementor: Expression | undefined, + statement: Statement, + ): ForStatement; + createForInStatement( + initializer: ForInitializer, + expression: Expression, + statement: Statement, + ): ForInStatement; + updateForInStatement( + node: ForInStatement, + initializer: ForInitializer, + expression: Expression, + statement: Statement, + ): ForInStatement; + createForOfStatement( + awaitModifier: AwaitKeyword | undefined, + initializer: ForInitializer, + expression: Expression, + statement: Statement, + ): ForOfStatement; + updateForOfStatement( + node: ForOfStatement, + awaitModifier: AwaitKeyword | undefined, + initializer: ForInitializer, + expression: Expression, + statement: Statement, + ): ForOfStatement; createContinueStatement(label?: string | Identifier): ContinueStatement; - updateContinueStatement(node: ContinueStatement, label: Identifier | undefined): ContinueStatement; + updateContinueStatement( + node: ContinueStatement, + label: Identifier | undefined, + ): ContinueStatement; createBreakStatement(label?: string | Identifier): BreakStatement; - updateBreakStatement(node: BreakStatement, label: Identifier | undefined): BreakStatement; + updateBreakStatement( + node: BreakStatement, + label: Identifier | undefined, + ): BreakStatement; createReturnStatement(expression?: Expression): ReturnStatement; - updateReturnStatement(node: ReturnStatement, expression: Expression | undefined): ReturnStatement; - createWithStatement(expression: Expression, statement: Statement): WithStatement; - updateWithStatement(node: WithStatement, expression: Expression, statement: Statement): WithStatement; - createSwitchStatement(expression: Expression, caseBlock: CaseBlock): SwitchStatement; - updateSwitchStatement(node: SwitchStatement, expression: Expression, caseBlock: CaseBlock): SwitchStatement; - createLabeledStatement(label: string | Identifier, statement: Statement): LabeledStatement; - updateLabeledStatement(node: LabeledStatement, label: Identifier, statement: Statement): LabeledStatement; + updateReturnStatement( + node: ReturnStatement, + expression: Expression | undefined, + ): ReturnStatement; + createWithStatement( + expression: Expression, + statement: Statement, + ): WithStatement; + updateWithStatement( + node: WithStatement, + expression: Expression, + statement: Statement, + ): WithStatement; + createSwitchStatement( + expression: Expression, + caseBlock: CaseBlock, + ): SwitchStatement; + updateSwitchStatement( + node: SwitchStatement, + expression: Expression, + caseBlock: CaseBlock, + ): SwitchStatement; + createLabeledStatement( + label: string | Identifier, + statement: Statement, + ): LabeledStatement; + updateLabeledStatement( + node: LabeledStatement, + label: Identifier, + statement: Statement, + ): LabeledStatement; createThrowStatement(expression: Expression): ThrowStatement; - updateThrowStatement(node: ThrowStatement, expression: Expression): ThrowStatement; - createTryStatement(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; - updateTryStatement(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement; + updateThrowStatement( + node: ThrowStatement, + expression: Expression, + ): ThrowStatement; + createTryStatement( + tryBlock: Block, + catchClause: CatchClause | undefined, + finallyBlock: Block | undefined, + ): TryStatement; + updateTryStatement( + node: TryStatement, + tryBlock: Block, + catchClause: CatchClause | undefined, + finallyBlock: Block | undefined, + ): TryStatement; createDebuggerStatement(): DebuggerStatement; - createVariableDeclaration(name: string | BindingName, exclamationToken?: ExclamationToken, type?: TypeNode, initializer?: Expression): VariableDeclaration; - updateVariableDeclaration(node: VariableDeclaration, name: BindingName, exclamationToken: ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration; - createVariableDeclarationList(declarations: readonly VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList; - updateVariableDeclarationList(node: VariableDeclarationList, declarations: readonly VariableDeclaration[]): VariableDeclarationList; - createFunctionDeclaration(modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - updateFunctionDeclaration(node: FunctionDeclaration, modifiers: readonly ModifierLike[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration; - createClassDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; - updateClassDeclaration(node: ClassDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration; - createInterfaceDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; - updateInterfaceDeclaration(node: InterfaceDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration; - createTypeAliasDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; - updateTypeAliasDeclaration(node: TypeAliasDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration; - createEnumDeclaration(modifiers: readonly ModifierLike[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration; - updateEnumDeclaration(node: EnumDeclaration, modifiers: readonly ModifierLike[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration; - createModuleDeclaration(modifiers: readonly ModifierLike[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration; - updateModuleDeclaration(node: ModuleDeclaration, modifiers: readonly ModifierLike[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration; + createVariableDeclaration( + name: string | BindingName, + exclamationToken?: ExclamationToken, + type?: TypeNode, + initializer?: Expression, + ): VariableDeclaration; + updateVariableDeclaration( + node: VariableDeclaration, + name: BindingName, + exclamationToken: ExclamationToken | undefined, + type: TypeNode | undefined, + initializer: Expression | undefined, + ): VariableDeclaration; + createVariableDeclarationList( + declarations: readonly VariableDeclaration[], + flags?: NodeFlags, + ): VariableDeclarationList; + updateVariableDeclarationList( + node: VariableDeclarationList, + declarations: readonly VariableDeclaration[], + ): VariableDeclarationList; + createFunctionDeclaration( + modifiers: readonly ModifierLike[] | undefined, + asteriskToken: AsteriskToken | undefined, + name: string | Identifier | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + body: Block | undefined, + ): FunctionDeclaration; + updateFunctionDeclaration( + node: FunctionDeclaration, + modifiers: readonly ModifierLike[] | undefined, + asteriskToken: AsteriskToken | undefined, + name: Identifier | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + body: Block | undefined, + ): FunctionDeclaration; + createClassDeclaration( + modifiers: readonly ModifierLike[] | undefined, + name: string | Identifier | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly ClassElement[], + ): ClassDeclaration; + updateClassDeclaration( + node: ClassDeclaration, + modifiers: readonly ModifierLike[] | undefined, + name: Identifier | undefined, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly ClassElement[], + ): ClassDeclaration; + createInterfaceDeclaration( + modifiers: readonly ModifierLike[] | undefined, + name: string | Identifier, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly TypeElement[], + ): InterfaceDeclaration; + updateInterfaceDeclaration( + node: InterfaceDeclaration, + modifiers: readonly ModifierLike[] | undefined, + name: Identifier, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + heritageClauses: readonly HeritageClause[] | undefined, + members: readonly TypeElement[], + ): InterfaceDeclaration; + createTypeAliasDeclaration( + modifiers: readonly ModifierLike[] | undefined, + name: string | Identifier, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + type: TypeNode, + ): TypeAliasDeclaration; + updateTypeAliasDeclaration( + node: TypeAliasDeclaration, + modifiers: readonly ModifierLike[] | undefined, + name: Identifier, + typeParameters: readonly TypeParameterDeclaration[] | undefined, + type: TypeNode, + ): TypeAliasDeclaration; + createEnumDeclaration( + modifiers: readonly ModifierLike[] | undefined, + name: string | Identifier, + members: readonly EnumMember[], + ): EnumDeclaration; + updateEnumDeclaration( + node: EnumDeclaration, + modifiers: readonly ModifierLike[] | undefined, + name: Identifier, + members: readonly EnumMember[], + ): EnumDeclaration; + createModuleDeclaration( + modifiers: readonly ModifierLike[] | undefined, + name: ModuleName, + body: ModuleBody | undefined, + flags?: NodeFlags, + ): ModuleDeclaration; + updateModuleDeclaration( + node: ModuleDeclaration, + modifiers: readonly ModifierLike[] | undefined, + name: ModuleName, + body: ModuleBody | undefined, + ): ModuleDeclaration; createModuleBlock(statements: readonly Statement[]): ModuleBlock; - updateModuleBlock(node: ModuleBlock, statements: readonly Statement[]): ModuleBlock; + updateModuleBlock( + node: ModuleBlock, + statements: readonly Statement[], + ): ModuleBlock; createCaseBlock(clauses: readonly CaseOrDefaultClause[]): CaseBlock; - updateCaseBlock(node: CaseBlock, clauses: readonly CaseOrDefaultClause[]): CaseBlock; - createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration; - updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration; - createImportEqualsDeclaration(modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - updateImportEqualsDeclaration(node: ImportEqualsDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration; - createImportDeclaration(modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, attributes?: ImportAttributes): ImportDeclaration; - updateImportDeclaration(node: ImportDeclaration, modifiers: readonly ModifierLike[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, attributes: ImportAttributes | undefined): ImportDeclaration; - createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; - updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause; - /** @deprecated */ createAssertClause(elements: NodeArray, multiLine?: boolean): AssertClause; - /** @deprecated */ updateAssertClause(node: AssertClause, elements: NodeArray, multiLine?: boolean): AssertClause; - /** @deprecated */ createAssertEntry(name: AssertionKey, value: Expression): AssertEntry; - /** @deprecated */ updateAssertEntry(node: AssertEntry, name: AssertionKey, value: Expression): AssertEntry; - /** @deprecated */ createImportTypeAssertionContainer(clause: AssertClause, multiLine?: boolean): ImportTypeAssertionContainer; - /** @deprecated */ updateImportTypeAssertionContainer(node: ImportTypeAssertionContainer, clause: AssertClause, multiLine?: boolean): ImportTypeAssertionContainer; - createImportAttributes(elements: NodeArray, multiLine?: boolean): ImportAttributes; - /** @internal */ createImportAttributes(elements: NodeArray, multiLine?: boolean, token?: ImportAttributes["token"]): ImportAttributes; - updateImportAttributes(node: ImportAttributes, elements: NodeArray, multiLine?: boolean): ImportAttributes; - createImportAttribute(name: ImportAttributeName, value: Expression): ImportAttribute; - updateImportAttribute(node: ImportAttribute, name: ImportAttributeName, value: Expression): ImportAttribute; + updateCaseBlock( + node: CaseBlock, + clauses: readonly CaseOrDefaultClause[], + ): CaseBlock; + createNamespaceExportDeclaration( + name: string | Identifier, + ): NamespaceExportDeclaration; + updateNamespaceExportDeclaration( + node: NamespaceExportDeclaration, + name: Identifier, + ): NamespaceExportDeclaration; + createImportEqualsDeclaration( + modifiers: readonly ModifierLike[] | undefined, + isTypeOnly: boolean, + name: string | Identifier, + moduleReference: ModuleReference, + ): ImportEqualsDeclaration; + updateImportEqualsDeclaration( + node: ImportEqualsDeclaration, + modifiers: readonly ModifierLike[] | undefined, + isTypeOnly: boolean, + name: Identifier, + moduleReference: ModuleReference, + ): ImportEqualsDeclaration; + createImportDeclaration( + modifiers: readonly ModifierLike[] | undefined, + importClause: ImportClause | undefined, + moduleSpecifier: Expression, + attributes?: ImportAttributes, + ): ImportDeclaration; + updateImportDeclaration( + node: ImportDeclaration, + modifiers: readonly ModifierLike[] | undefined, + importClause: ImportClause | undefined, + moduleSpecifier: Expression, + attributes: ImportAttributes | undefined, + ): ImportDeclaration; + createImportClause( + isTypeOnly: boolean, + name: Identifier | undefined, + namedBindings: NamedImportBindings | undefined, + ): ImportClause; + updateImportClause( + node: ImportClause, + isTypeOnly: boolean, + name: Identifier | undefined, + namedBindings: NamedImportBindings | undefined, + ): ImportClause; + /** @deprecated */ createAssertClause( + elements: NodeArray, + multiLine?: boolean, + ): AssertClause; + /** @deprecated */ updateAssertClause( + node: AssertClause, + elements: NodeArray, + multiLine?: boolean, + ): AssertClause; + /** @deprecated */ createAssertEntry( + name: AssertionKey, + value: Expression, + ): AssertEntry; + /** @deprecated */ updateAssertEntry( + node: AssertEntry, + name: AssertionKey, + value: Expression, + ): AssertEntry; + /** @deprecated */ createImportTypeAssertionContainer( + clause: AssertClause, + multiLine?: boolean, + ): ImportTypeAssertionContainer; + /** @deprecated */ updateImportTypeAssertionContainer( + node: ImportTypeAssertionContainer, + clause: AssertClause, + multiLine?: boolean, + ): ImportTypeAssertionContainer; + createImportAttributes( + elements: NodeArray, + multiLine?: boolean, + ): ImportAttributes; + /** @internal */ createImportAttributes( + elements: NodeArray, + multiLine?: boolean, + token?: ImportAttributes["token"], + ): ImportAttributes; + updateImportAttributes( + node: ImportAttributes, + elements: NodeArray, + multiLine?: boolean, + ): ImportAttributes; + createImportAttribute( + name: ImportAttributeName, + value: Expression, + ): ImportAttribute; + updateImportAttribute( + node: ImportAttribute, + name: ImportAttributeName, + value: Expression, + ): ImportAttribute; createNamespaceImport(name: Identifier): NamespaceImport; - updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport; + updateNamespaceImport( + node: NamespaceImport, + name: Identifier, + ): NamespaceImport; createNamespaceExport(name: Identifier): NamespaceExport; - updateNamespaceExport(node: NamespaceExport, name: Identifier): NamespaceExport; + updateNamespaceExport( + node: NamespaceExport, + name: Identifier, + ): NamespaceExport; createNamedImports(elements: readonly ImportSpecifier[]): NamedImports; - updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]): NamedImports; - createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier; - createExportAssignment(modifiers: readonly ModifierLike[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment; - updateExportAssignment(node: ExportAssignment, modifiers: readonly ModifierLike[] | undefined, expression: Expression): ExportAssignment; - createExportDeclaration(modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, attributes?: ImportAttributes): ExportDeclaration; - updateExportDeclaration(node: ExportDeclaration, modifiers: readonly ModifierLike[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, attributes: ImportAttributes | undefined): ExportDeclaration; + updateNamedImports( + node: NamedImports, + elements: readonly ImportSpecifier[], + ): NamedImports; + createImportSpecifier( + isTypeOnly: boolean, + propertyName: Identifier | undefined, + name: Identifier, + ): ImportSpecifier; + updateImportSpecifier( + node: ImportSpecifier, + isTypeOnly: boolean, + propertyName: Identifier | undefined, + name: Identifier, + ): ImportSpecifier; + createExportAssignment( + modifiers: readonly ModifierLike[] | undefined, + isExportEquals: boolean | undefined, + expression: Expression, + ): ExportAssignment; + updateExportAssignment( + node: ExportAssignment, + modifiers: readonly ModifierLike[] | undefined, + expression: Expression, + ): ExportAssignment; + createExportDeclaration( + modifiers: readonly ModifierLike[] | undefined, + isTypeOnly: boolean, + exportClause: NamedExportBindings | undefined, + moduleSpecifier?: Expression, + attributes?: ImportAttributes, + ): ExportDeclaration; + updateExportDeclaration( + node: ExportDeclaration, + modifiers: readonly ModifierLike[] | undefined, + isTypeOnly: boolean, + exportClause: NamedExportBindings | undefined, + moduleSpecifier: Expression | undefined, + attributes: ImportAttributes | undefined, + ): ExportDeclaration; createNamedExports(elements: readonly ExportSpecifier[]): NamedExports; - updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports; - createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier; - updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier; + updateNamedExports( + node: NamedExports, + elements: readonly ExportSpecifier[], + ): NamedExports; + createExportSpecifier( + isTypeOnly: boolean, + propertyName: string | Identifier | undefined, + name: string | Identifier, + ): ExportSpecifier; + updateExportSpecifier( + node: ExportSpecifier, + isTypeOnly: boolean, + propertyName: Identifier | undefined, + name: Identifier, + ): ExportSpecifier; /** @internal */ createMissingDeclaration(): MissingDeclaration; // // Module references // - createExternalModuleReference(expression: Expression): ExternalModuleReference; - updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference; + createExternalModuleReference( + expression: Expression, + ): ExternalModuleReference; + updateExternalModuleReference( + node: ExternalModuleReference, + expression: Expression, + ): ExternalModuleReference; // // JSDoc @@ -8670,167 +11496,625 @@ export interface NodeFactory { createJSDocAllType(): JSDocAllType; createJSDocUnknownType(): JSDocUnknownType; - createJSDocNonNullableType(type: TypeNode, postfix?: boolean): JSDocNonNullableType; - updateJSDocNonNullableType(node: JSDocNonNullableType, type: TypeNode): JSDocNonNullableType; - createJSDocNullableType(type: TypeNode, postfix?: boolean): JSDocNullableType; - updateJSDocNullableType(node: JSDocNullableType, type: TypeNode): JSDocNullableType; + createJSDocNonNullableType( + type: TypeNode, + postfix?: boolean, + ): JSDocNonNullableType; + updateJSDocNonNullableType( + node: JSDocNonNullableType, + type: TypeNode, + ): JSDocNonNullableType; + createJSDocNullableType( + type: TypeNode, + postfix?: boolean, + ): JSDocNullableType; + updateJSDocNullableType( + node: JSDocNullableType, + type: TypeNode, + ): JSDocNullableType; createJSDocOptionalType(type: TypeNode): JSDocOptionalType; - updateJSDocOptionalType(node: JSDocOptionalType, type: TypeNode): JSDocOptionalType; - createJSDocFunctionType(parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): JSDocFunctionType; - updateJSDocFunctionType(node: JSDocFunctionType, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): JSDocFunctionType; + updateJSDocOptionalType( + node: JSDocOptionalType, + type: TypeNode, + ): JSDocOptionalType; + createJSDocFunctionType( + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + ): JSDocFunctionType; + updateJSDocFunctionType( + node: JSDocFunctionType, + parameters: readonly ParameterDeclaration[], + type: TypeNode | undefined, + ): JSDocFunctionType; createJSDocVariadicType(type: TypeNode): JSDocVariadicType; - updateJSDocVariadicType(node: JSDocVariadicType, type: TypeNode): JSDocVariadicType; + updateJSDocVariadicType( + node: JSDocVariadicType, + type: TypeNode, + ): JSDocVariadicType; createJSDocNamepathType(type: TypeNode): JSDocNamepathType; - updateJSDocNamepathType(node: JSDocNamepathType, type: TypeNode): JSDocNamepathType; + updateJSDocNamepathType( + node: JSDocNamepathType, + type: TypeNode, + ): JSDocNamepathType; createJSDocTypeExpression(type: TypeNode): JSDocTypeExpression; - updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression; - createJSDocNameReference(name: EntityName | JSDocMemberName): JSDocNameReference; - updateJSDocNameReference(node: JSDocNameReference, name: EntityName | JSDocMemberName): JSDocNameReference; - createJSDocMemberName(left: EntityName | JSDocMemberName, right: Identifier): JSDocMemberName; - updateJSDocMemberName(node: JSDocMemberName, left: EntityName | JSDocMemberName, right: Identifier): JSDocMemberName; - createJSDocLink(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink; - updateJSDocLink(node: JSDocLink, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLink; - createJSDocLinkCode(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode; - updateJSDocLinkCode(node: JSDocLinkCode, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkCode; - createJSDocLinkPlain(name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain; - updateJSDocLinkPlain(node: JSDocLinkPlain, name: EntityName | JSDocMemberName | undefined, text: string): JSDocLinkPlain; - createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral; - updateJSDocTypeLiteral(node: JSDocTypeLiteral, jsDocPropertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean | undefined): JSDocTypeLiteral; - createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature; - updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature; - createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray): JSDocTemplateTag; - updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray | undefined): JSDocTemplateTag; - createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocTypedefTag; - updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocTypedefTag; - createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocParameterTag; - updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocParameterTag; - createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray): JSDocPropertyTag; - updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray | undefined): JSDocPropertyTag; - createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocTypeTag; - updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocTypeTag; - createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; - updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray): JSDocSeeTag; - createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray): JSDocReturnTag; - updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocReturnTag; - createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocThisTag; - updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray | undefined): JSDocThisTag; - createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocEnumTag; - updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocEnumTag; - createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray): JSDocCallbackTag; - updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray | undefined): JSDocCallbackTag; - createJSDocOverloadTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, comment?: string | NodeArray): JSDocOverloadTag; - updateJSDocOverloadTag(node: JSDocOverloadTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, comment: string | NodeArray | undefined): JSDocOverloadTag; - createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray): JSDocAugmentsTag; - updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | NodeArray | undefined): JSDocAugmentsTag; - createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray): JSDocImplementsTag; - updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | NodeArray | undefined): JSDocImplementsTag; - createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocAuthorTag; - updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocAuthorTag; - createJSDocClassTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocClassTag; - updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocClassTag; - createJSDocPublicTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPublicTag; - updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPublicTag; - createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocPrivateTag; - updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocPrivateTag; - createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocProtectedTag; - updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocProtectedTag; - createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocReadonlyTag; - updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | NodeArray | undefined): JSDocReadonlyTag; - createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray): JSDocUnknownTag; - updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray | undefined): JSDocUnknownTag; - createJSDocDeprecatedTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocDeprecatedTag; - updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier | undefined, comment?: string | NodeArray): JSDocDeprecatedTag; - createJSDocOverrideTag(tagName: Identifier | undefined, comment?: string | NodeArray): JSDocOverrideTag; - updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier | undefined, comment?: string | NodeArray): JSDocOverrideTag; - createJSDocThrowsTag(tagName: Identifier, typeExpression: JSDocTypeExpression | undefined, comment?: string | NodeArray): JSDocThrowsTag; - updateJSDocThrowsTag(node: JSDocThrowsTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment?: string | NodeArray | undefined): JSDocThrowsTag; - createJSDocSatisfiesTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray): JSDocSatisfiesTag; - updateJSDocSatisfiesTag(node: JSDocSatisfiesTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray | undefined): JSDocSatisfiesTag; + updateJSDocTypeExpression( + node: JSDocTypeExpression, + type: TypeNode, + ): JSDocTypeExpression; + createJSDocNameReference( + name: EntityName | JSDocMemberName, + ): JSDocNameReference; + updateJSDocNameReference( + node: JSDocNameReference, + name: EntityName | JSDocMemberName, + ): JSDocNameReference; + createJSDocMemberName( + left: EntityName | JSDocMemberName, + right: Identifier, + ): JSDocMemberName; + updateJSDocMemberName( + node: JSDocMemberName, + left: EntityName | JSDocMemberName, + right: Identifier, + ): JSDocMemberName; + createJSDocLink( + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLink; + updateJSDocLink( + node: JSDocLink, + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLink; + createJSDocLinkCode( + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLinkCode; + updateJSDocLinkCode( + node: JSDocLinkCode, + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLinkCode; + createJSDocLinkPlain( + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLinkPlain; + updateJSDocLinkPlain( + node: JSDocLinkPlain, + name: EntityName | JSDocMemberName | undefined, + text: string, + ): JSDocLinkPlain; + createJSDocTypeLiteral( + jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], + isArrayType?: boolean, + ): JSDocTypeLiteral; + updateJSDocTypeLiteral( + node: JSDocTypeLiteral, + jsDocPropertyTags: readonly JSDocPropertyLikeTag[] | undefined, + isArrayType: boolean | undefined, + ): JSDocTypeLiteral; + createJSDocSignature( + typeParameters: readonly JSDocTemplateTag[] | undefined, + parameters: readonly JSDocParameterTag[], + type?: JSDocReturnTag, + ): JSDocSignature; + updateJSDocSignature( + node: JSDocSignature, + typeParameters: readonly JSDocTemplateTag[] | undefined, + parameters: readonly JSDocParameterTag[], + type: JSDocReturnTag | undefined, + ): JSDocSignature; + createJSDocTemplateTag( + tagName: Identifier | undefined, + constraint: JSDocTypeExpression | undefined, + typeParameters: readonly TypeParameterDeclaration[], + comment?: string | NodeArray, + ): JSDocTemplateTag; + updateJSDocTemplateTag( + node: JSDocTemplateTag, + tagName: Identifier | undefined, + constraint: JSDocTypeExpression | undefined, + typeParameters: readonly TypeParameterDeclaration[], + comment: string | NodeArray | undefined, + ): JSDocTemplateTag; + createJSDocTypedefTag( + tagName: Identifier | undefined, + typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, + fullName?: Identifier | JSDocNamespaceDeclaration, + comment?: string | NodeArray, + ): JSDocTypedefTag; + updateJSDocTypedefTag( + node: JSDocTypedefTag, + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, + fullName: Identifier | JSDocNamespaceDeclaration | undefined, + comment: string | NodeArray | undefined, + ): JSDocTypedefTag; + createJSDocParameterTag( + tagName: Identifier | undefined, + name: EntityName, + isBracketed: boolean, + typeExpression?: JSDocTypeExpression, + isNameFirst?: boolean, + comment?: string | NodeArray, + ): JSDocParameterTag; + updateJSDocParameterTag( + node: JSDocParameterTag, + tagName: Identifier | undefined, + name: EntityName, + isBracketed: boolean, + typeExpression: JSDocTypeExpression | undefined, + isNameFirst: boolean, + comment: string | NodeArray | undefined, + ): JSDocParameterTag; + createJSDocPropertyTag( + tagName: Identifier | undefined, + name: EntityName, + isBracketed: boolean, + typeExpression?: JSDocTypeExpression, + isNameFirst?: boolean, + comment?: string | NodeArray, + ): JSDocPropertyTag; + updateJSDocPropertyTag( + node: JSDocPropertyTag, + tagName: Identifier | undefined, + name: EntityName, + isBracketed: boolean, + typeExpression: JSDocTypeExpression | undefined, + isNameFirst: boolean, + comment: string | NodeArray | undefined, + ): JSDocPropertyTag; + createJSDocTypeTag( + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression, + comment?: string | NodeArray, + ): JSDocTypeTag; + updateJSDocTypeTag( + node: JSDocTypeTag, + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression, + comment: string | NodeArray | undefined, + ): JSDocTypeTag; + createJSDocSeeTag( + tagName: Identifier | undefined, + nameExpression: JSDocNameReference | undefined, + comment?: string | NodeArray, + ): JSDocSeeTag; + updateJSDocSeeTag( + node: JSDocSeeTag, + tagName: Identifier | undefined, + nameExpression: JSDocNameReference | undefined, + comment?: string | NodeArray, + ): JSDocSeeTag; + createJSDocReturnTag( + tagName: Identifier | undefined, + typeExpression?: JSDocTypeExpression, + comment?: string | NodeArray, + ): JSDocReturnTag; + updateJSDocReturnTag( + node: JSDocReturnTag, + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression | undefined, + comment: string | NodeArray | undefined, + ): JSDocReturnTag; + createJSDocThisTag( + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression, + comment?: string | NodeArray, + ): JSDocThisTag; + updateJSDocThisTag( + node: JSDocThisTag, + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression | undefined, + comment: string | NodeArray | undefined, + ): JSDocThisTag; + createJSDocEnumTag( + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression, + comment?: string | NodeArray, + ): JSDocEnumTag; + updateJSDocEnumTag( + node: JSDocEnumTag, + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression, + comment: string | NodeArray | undefined, + ): JSDocEnumTag; + createJSDocCallbackTag( + tagName: Identifier | undefined, + typeExpression: JSDocSignature, + fullName?: Identifier | JSDocNamespaceDeclaration, + comment?: string | NodeArray, + ): JSDocCallbackTag; + updateJSDocCallbackTag( + node: JSDocCallbackTag, + tagName: Identifier | undefined, + typeExpression: JSDocSignature, + fullName: Identifier | JSDocNamespaceDeclaration | undefined, + comment: string | NodeArray | undefined, + ): JSDocCallbackTag; + createJSDocOverloadTag( + tagName: Identifier | undefined, + typeExpression: JSDocSignature, + comment?: string | NodeArray, + ): JSDocOverloadTag; + updateJSDocOverloadTag( + node: JSDocOverloadTag, + tagName: Identifier | undefined, + typeExpression: JSDocSignature, + comment: string | NodeArray | undefined, + ): JSDocOverloadTag; + createJSDocAugmentsTag( + tagName: Identifier | undefined, + className: JSDocAugmentsTag["class"], + comment?: string | NodeArray, + ): JSDocAugmentsTag; + updateJSDocAugmentsTag( + node: JSDocAugmentsTag, + tagName: Identifier | undefined, + className: JSDocAugmentsTag["class"], + comment: string | NodeArray | undefined, + ): JSDocAugmentsTag; + createJSDocImplementsTag( + tagName: Identifier | undefined, + className: JSDocImplementsTag["class"], + comment?: string | NodeArray, + ): JSDocImplementsTag; + updateJSDocImplementsTag( + node: JSDocImplementsTag, + tagName: Identifier | undefined, + className: JSDocImplementsTag["class"], + comment: string | NodeArray | undefined, + ): JSDocImplementsTag; + createJSDocAuthorTag( + tagName: Identifier | undefined, + comment?: string | NodeArray, + ): JSDocAuthorTag; + updateJSDocAuthorTag( + node: JSDocAuthorTag, + tagName: Identifier | undefined, + comment: string | NodeArray | undefined, + ): JSDocAuthorTag; + createJSDocClassTag( + tagName: Identifier | undefined, + comment?: string | NodeArray, + ): JSDocClassTag; + updateJSDocClassTag( + node: JSDocClassTag, + tagName: Identifier | undefined, + comment: string | NodeArray | undefined, + ): JSDocClassTag; + createJSDocPublicTag( + tagName: Identifier | undefined, + comment?: string | NodeArray, + ): JSDocPublicTag; + updateJSDocPublicTag( + node: JSDocPublicTag, + tagName: Identifier | undefined, + comment: string | NodeArray | undefined, + ): JSDocPublicTag; + createJSDocPrivateTag( + tagName: Identifier | undefined, + comment?: string | NodeArray, + ): JSDocPrivateTag; + updateJSDocPrivateTag( + node: JSDocPrivateTag, + tagName: Identifier | undefined, + comment: string | NodeArray | undefined, + ): JSDocPrivateTag; + createJSDocProtectedTag( + tagName: Identifier | undefined, + comment?: string | NodeArray, + ): JSDocProtectedTag; + updateJSDocProtectedTag( + node: JSDocProtectedTag, + tagName: Identifier | undefined, + comment: string | NodeArray | undefined, + ): JSDocProtectedTag; + createJSDocReadonlyTag( + tagName: Identifier | undefined, + comment?: string | NodeArray, + ): JSDocReadonlyTag; + updateJSDocReadonlyTag( + node: JSDocReadonlyTag, + tagName: Identifier | undefined, + comment: string | NodeArray | undefined, + ): JSDocReadonlyTag; + createJSDocUnknownTag( + tagName: Identifier, + comment?: string | NodeArray, + ): JSDocUnknownTag; + updateJSDocUnknownTag( + node: JSDocUnknownTag, + tagName: Identifier, + comment: string | NodeArray | undefined, + ): JSDocUnknownTag; + createJSDocDeprecatedTag( + tagName: Identifier | undefined, + comment?: string | NodeArray, + ): JSDocDeprecatedTag; + updateJSDocDeprecatedTag( + node: JSDocDeprecatedTag, + tagName: Identifier | undefined, + comment?: string | NodeArray, + ): JSDocDeprecatedTag; + createJSDocOverrideTag( + tagName: Identifier | undefined, + comment?: string | NodeArray, + ): JSDocOverrideTag; + updateJSDocOverrideTag( + node: JSDocOverrideTag, + tagName: Identifier | undefined, + comment?: string | NodeArray, + ): JSDocOverrideTag; + createJSDocThrowsTag( + tagName: Identifier, + typeExpression: JSDocTypeExpression | undefined, + comment?: string | NodeArray, + ): JSDocThrowsTag; + updateJSDocThrowsTag( + node: JSDocThrowsTag, + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression | undefined, + comment?: string | NodeArray | undefined, + ): JSDocThrowsTag; + createJSDocSatisfiesTag( + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression, + comment?: string | NodeArray, + ): JSDocSatisfiesTag; + updateJSDocSatisfiesTag( + node: JSDocSatisfiesTag, + tagName: Identifier | undefined, + typeExpression: JSDocTypeExpression, + comment: string | NodeArray | undefined, + ): JSDocSatisfiesTag; createJSDocText(text: string): JSDocText; updateJSDocText(node: JSDocText, text: string): JSDocText; - createJSDocComment(comment?: string | NodeArray | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc; - updateJSDocComment(node: JSDoc, comment: string | NodeArray | undefined, tags: readonly JSDocTag[] | undefined): JSDoc; + createJSDocComment( + comment?: string | NodeArray | undefined, + tags?: readonly JSDocTag[] | undefined, + ): JSDoc; + updateJSDocComment( + node: JSDoc, + comment: string | NodeArray | undefined, + tags: readonly JSDocTag[] | undefined, + ): JSDoc; // // JSX // - createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; - updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement; - createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement; - updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement; - createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxOpeningElement; - updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxOpeningElement; + createJsxElement( + openingElement: JsxOpeningElement, + children: readonly JsxChild[], + closingElement: JsxClosingElement, + ): JsxElement; + updateJsxElement( + node: JsxElement, + openingElement: JsxOpeningElement, + children: readonly JsxChild[], + closingElement: JsxClosingElement, + ): JsxElement; + createJsxSelfClosingElement( + tagName: JsxTagNameExpression, + typeArguments: readonly TypeNode[] | undefined, + attributes: JsxAttributes, + ): JsxSelfClosingElement; + updateJsxSelfClosingElement( + node: JsxSelfClosingElement, + tagName: JsxTagNameExpression, + typeArguments: readonly TypeNode[] | undefined, + attributes: JsxAttributes, + ): JsxSelfClosingElement; + createJsxOpeningElement( + tagName: JsxTagNameExpression, + typeArguments: readonly TypeNode[] | undefined, + attributes: JsxAttributes, + ): JsxOpeningElement; + updateJsxOpeningElement( + node: JsxOpeningElement, + tagName: JsxTagNameExpression, + typeArguments: readonly TypeNode[] | undefined, + attributes: JsxAttributes, + ): JsxOpeningElement; createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement; - updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement; - createJsxFragment(openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment): JsxFragment; - createJsxText(text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText; - updateJsxText(node: JsxText, text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText; + updateJsxClosingElement( + node: JsxClosingElement, + tagName: JsxTagNameExpression, + ): JsxClosingElement; + createJsxFragment( + openingFragment: JsxOpeningFragment, + children: readonly JsxChild[], + closingFragment: JsxClosingFragment, + ): JsxFragment; + createJsxText( + text: string, + containsOnlyTriviaWhiteSpaces?: boolean, + ): JsxText; + updateJsxText( + node: JsxText, + text: string, + containsOnlyTriviaWhiteSpaces?: boolean, + ): JsxText; createJsxOpeningFragment(): JsxOpeningFragment; createJsxJsxClosingFragment(): JsxClosingFragment; - updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment): JsxFragment; - createJsxAttribute(name: JsxAttributeName, initializer: JsxAttributeValue | undefined): JsxAttribute; - updateJsxAttribute(node: JsxAttribute, name: JsxAttributeName, initializer: JsxAttributeValue | undefined): JsxAttribute; + updateJsxFragment( + node: JsxFragment, + openingFragment: JsxOpeningFragment, + children: readonly JsxChild[], + closingFragment: JsxClosingFragment, + ): JsxFragment; + createJsxAttribute( + name: JsxAttributeName, + initializer: JsxAttributeValue | undefined, + ): JsxAttribute; + updateJsxAttribute( + node: JsxAttribute, + name: JsxAttributeName, + initializer: JsxAttributeValue | undefined, + ): JsxAttribute; createJsxAttributes(properties: readonly JsxAttributeLike[]): JsxAttributes; - updateJsxAttributes(node: JsxAttributes, properties: readonly JsxAttributeLike[]): JsxAttributes; + updateJsxAttributes( + node: JsxAttributes, + properties: readonly JsxAttributeLike[], + ): JsxAttributes; createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute; - updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute; - createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression; - updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression; - createJsxNamespacedName(namespace: Identifier, name: Identifier): JsxNamespacedName; - updateJsxNamespacedName(node: JsxNamespacedName, namespace: Identifier, name: Identifier): JsxNamespacedName; + updateJsxSpreadAttribute( + node: JsxSpreadAttribute, + expression: Expression, + ): JsxSpreadAttribute; + createJsxExpression( + dotDotDotToken: DotDotDotToken | undefined, + expression: Expression | undefined, + ): JsxExpression; + updateJsxExpression( + node: JsxExpression, + expression: Expression | undefined, + ): JsxExpression; + createJsxNamespacedName( + namespace: Identifier, + name: Identifier, + ): JsxNamespacedName; + updateJsxNamespacedName( + node: JsxNamespacedName, + namespace: Identifier, + name: Identifier, + ): JsxNamespacedName; // // Clauses // - createCaseClause(expression: Expression, statements: readonly Statement[]): CaseClause; - updateCaseClause(node: CaseClause, expression: Expression, statements: readonly Statement[]): CaseClause; + createCaseClause( + expression: Expression, + statements: readonly Statement[], + ): CaseClause; + updateCaseClause( + node: CaseClause, + expression: Expression, + statements: readonly Statement[], + ): CaseClause; createDefaultClause(statements: readonly Statement[]): DefaultClause; - updateDefaultClause(node: DefaultClause, statements: readonly Statement[]): DefaultClause; - createHeritageClause(token: HeritageClause["token"], types: readonly ExpressionWithTypeArguments[]): HeritageClause; - updateHeritageClause(node: HeritageClause, types: readonly ExpressionWithTypeArguments[]): HeritageClause; - createCatchClause(variableDeclaration: string | BindingName | VariableDeclaration | undefined, block: Block): CatchClause; - updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block): CatchClause; + updateDefaultClause( + node: DefaultClause, + statements: readonly Statement[], + ): DefaultClause; + createHeritageClause( + token: HeritageClause["token"], + types: readonly ExpressionWithTypeArguments[], + ): HeritageClause; + updateHeritageClause( + node: HeritageClause, + types: readonly ExpressionWithTypeArguments[], + ): HeritageClause; + createCatchClause( + variableDeclaration: + | string + | BindingName + | VariableDeclaration + | undefined, + block: Block, + ): CatchClause; + updateCatchClause( + node: CatchClause, + variableDeclaration: VariableDeclaration | undefined, + block: Block, + ): CatchClause; // // Property assignments // - createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment; - updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression): PropertyAssignment; - createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression): ShorthandPropertyAssignment; - updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression | undefined): ShorthandPropertyAssignment; + createPropertyAssignment( + name: string | PropertyName, + initializer: Expression, + ): PropertyAssignment; + updatePropertyAssignment( + node: PropertyAssignment, + name: PropertyName, + initializer: Expression, + ): PropertyAssignment; + createShorthandPropertyAssignment( + name: string | Identifier, + objectAssignmentInitializer?: Expression, + ): ShorthandPropertyAssignment; + updateShorthandPropertyAssignment( + node: ShorthandPropertyAssignment, + name: Identifier, + objectAssignmentInitializer: Expression | undefined, + ): ShorthandPropertyAssignment; createSpreadAssignment(expression: Expression): SpreadAssignment; - updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; + updateSpreadAssignment( + node: SpreadAssignment, + expression: Expression, + ): SpreadAssignment; // // Enum // - createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; - updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; + createEnumMember( + name: string | PropertyName, + initializer?: Expression, + ): EnumMember; + updateEnumMember( + node: EnumMember, + name: PropertyName, + initializer: Expression | undefined, + ): EnumMember; // // Top-level nodes // - createSourceFile(statements: readonly Statement[], endOfFileToken: EndOfFileToken, flags: NodeFlags): SourceFile; - updateSourceFile(node: SourceFile, statements: readonly Statement[], isDeclarationFile?: boolean, referencedFiles?: readonly FileReference[], typeReferences?: readonly FileReference[], hasNoDefaultLib?: boolean, libReferences?: readonly FileReference[]): SourceFile; - - /** @internal */ createRedirectedSourceFile(redirectInfo: RedirectInfo): SourceFile; - - /** @deprecated @internal */ createUnparsedSource(prologues: readonly UnparsedPrologue[], syntheticReferences: readonly UnparsedSyntheticReference[] | undefined, texts: readonly UnparsedSourceText[]): UnparsedSource; - /** @deprecated @internal */ createUnparsedPrologue(data?: string): UnparsedPrologue; - /** @deprecated @internal */ createUnparsedPrepend(data: string | undefined, texts: readonly UnparsedSourceText[]): UnparsedPrepend; - /** @deprecated @internal */ createUnparsedTextLike(data: string | undefined, internal: boolean): UnparsedTextLike; - /** @deprecated @internal */ createUnparsedSyntheticReference(section: BundleFileHasNoDefaultLib | BundleFileReference): UnparsedSyntheticReference; + createSourceFile( + statements: readonly Statement[], + endOfFileToken: EndOfFileToken, + flags: NodeFlags, + ): SourceFile; + updateSourceFile( + node: SourceFile, + statements: readonly Statement[], + isDeclarationFile?: boolean, + referencedFiles?: readonly FileReference[], + typeReferences?: readonly FileReference[], + hasNoDefaultLib?: boolean, + libReferences?: readonly FileReference[], + ): SourceFile; + + /** @internal */ createRedirectedSourceFile( + redirectInfo: RedirectInfo, + ): SourceFile; + + /** @deprecated @internal */ createUnparsedSource( + prologues: readonly UnparsedPrologue[], + syntheticReferences: readonly UnparsedSyntheticReference[] | undefined, + texts: readonly UnparsedSourceText[], + ): UnparsedSource; + /** @deprecated @internal */ createUnparsedPrologue( + data?: string, + ): UnparsedPrologue; + /** @deprecated @internal */ createUnparsedPrepend( + data: string | undefined, + texts: readonly UnparsedSourceText[], + ): UnparsedPrepend; + /** @deprecated @internal */ createUnparsedTextLike( + data: string | undefined, + internal: boolean, + ): UnparsedTextLike; + /** @deprecated @internal */ createUnparsedSyntheticReference( + section: BundleFileHasNoDefaultLib | BundleFileReference, + ): UnparsedSyntheticReference; /** @deprecated @internal */ createInputFiles(): InputFiles; // // Synthetic Nodes // - /** @internal */ createSyntheticExpression(type: Type, isSpread?: boolean, tupleNameSource?: ParameterDeclaration | NamedTupleMember): SyntheticExpression; + /** @internal */ createSyntheticExpression( + type: Type, + isSpread?: boolean, + tupleNameSource?: ParameterDeclaration | NamedTupleMember, + ): SyntheticExpression; /** @internal */ createSyntaxList(children: Node[]): SyntaxList; // @@ -8838,40 +12122,80 @@ export interface NodeFactory { // createNotEmittedStatement(original: Node): NotEmittedStatement; - createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; - updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; - /** @internal */ createSyntheticReferenceExpression(expression: Expression, thisArg: Expression): SyntheticReferenceExpression; - /** @internal */ updateSyntheticReferenceExpression(node: SyntheticReferenceExpression, expression: Expression, thisArg: Expression): SyntheticReferenceExpression; - createCommaListExpression(elements: readonly Expression[]): CommaListExpression; - updateCommaListExpression(node: CommaListExpression, elements: readonly Expression[]): CommaListExpression; + createPartiallyEmittedExpression( + expression: Expression, + original?: Node, + ): PartiallyEmittedExpression; + updatePartiallyEmittedExpression( + node: PartiallyEmittedExpression, + expression: Expression, + ): PartiallyEmittedExpression; + /** @internal */ createSyntheticReferenceExpression( + expression: Expression, + thisArg: Expression, + ): SyntheticReferenceExpression; + /** @internal */ updateSyntheticReferenceExpression( + node: SyntheticReferenceExpression, + expression: Expression, + thisArg: Expression, + ): SyntheticReferenceExpression; + createCommaListExpression( + elements: readonly Expression[], + ): CommaListExpression; + updateCommaListExpression( + node: CommaListExpression, + elements: readonly Expression[], + ): CommaListExpression; createBundle(sourceFiles: readonly SourceFile[]): Bundle; - /** @deprecated*/ createBundle(sourceFiles: readonly SourceFile[], prepends?: readonly (UnparsedSource | InputFiles)[]): Bundle; // eslint-disable-line @typescript-eslint/unified-signatures + /** @deprecated*/ createBundle( + sourceFiles: readonly SourceFile[], + prepends?: readonly (UnparsedSource | InputFiles)[], + ): Bundle; // eslint-disable-line @typescript-eslint/unified-signatures updateBundle(node: Bundle, sourceFiles: readonly SourceFile[]): Bundle; - /** @deprecated*/ updateBundle(node: Bundle, sourceFiles: readonly SourceFile[], prepends?: readonly (UnparsedSource | InputFiles)[]): Bundle; // eslint-disable-line @typescript-eslint/unified-signatures + /** @deprecated*/ updateBundle( + node: Bundle, + sourceFiles: readonly SourceFile[], + prepends?: readonly (UnparsedSource | InputFiles)[], + ): Bundle; // eslint-disable-line @typescript-eslint/unified-signatures // // Common operators // createComma(left: Expression, right: Expression): BinaryExpression; - createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment; - createAssignment(left: Expression, right: Expression): AssignmentExpression; + createAssignment( + left: ObjectLiteralExpression | ArrayLiteralExpression, + right: Expression, + ): DestructuringAssignment; + createAssignment( + left: Expression, + right: Expression, + ): AssignmentExpression; createLogicalOr(left: Expression, right: Expression): BinaryExpression; createLogicalAnd(left: Expression, right: Expression): BinaryExpression; createBitwiseOr(left: Expression, right: Expression): BinaryExpression; createBitwiseXor(left: Expression, right: Expression): BinaryExpression; createBitwiseAnd(left: Expression, right: Expression): BinaryExpression; createStrictEquality(left: Expression, right: Expression): BinaryExpression; - createStrictInequality(left: Expression, right: Expression): BinaryExpression; + createStrictInequality( + left: Expression, + right: Expression, + ): BinaryExpression; createEquality(left: Expression, right: Expression): BinaryExpression; createInequality(left: Expression, right: Expression): BinaryExpression; createLessThan(left: Expression, right: Expression): BinaryExpression; createLessThanEquals(left: Expression, right: Expression): BinaryExpression; createGreaterThan(left: Expression, right: Expression): BinaryExpression; - createGreaterThanEquals(left: Expression, right: Expression): BinaryExpression; + createGreaterThanEquals( + left: Expression, + right: Expression, + ): BinaryExpression; createLeftShift(left: Expression, right: Expression): BinaryExpression; createRightShift(left: Expression, right: Expression): BinaryExpression; - createUnsignedRightShift(left: Expression, right: Expression): BinaryExpression; + createUnsignedRightShift( + left: Expression, + right: Expression, + ): BinaryExpression; createAdd(left: Expression, right: Expression): BinaryExpression; createSubtract(left: Expression, right: Expression): BinaryExpression; createMultiply(left: Expression, right: Expression): BinaryExpression; @@ -8891,30 +12215,98 @@ export interface NodeFactory { // Compound Nodes // - createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): CallExpression; - createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; - createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): ImmediatelyInvokedArrowFunction; - createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedArrowFunction; + createImmediatelyInvokedFunctionExpression( + statements: readonly Statement[], + ): CallExpression; + createImmediatelyInvokedFunctionExpression( + statements: readonly Statement[], + param: ParameterDeclaration, + paramValue: Expression, + ): CallExpression; + createImmediatelyInvokedArrowFunction( + statements: readonly Statement[], + ): ImmediatelyInvokedArrowFunction; + createImmediatelyInvokedArrowFunction( + statements: readonly Statement[], + param: ParameterDeclaration, + paramValue: Expression, + ): ImmediatelyInvokedArrowFunction; createVoidZero(): VoidExpression; createExportDefault(expression: Expression): ExportAssignment; createExternalModuleExport(exportName: Identifier): ExportDeclaration; - /** @internal */ createTypeCheck(value: Expression, tag: TypeOfTag): Expression; - /** @internal */ createIsNotTypeCheck(value: Expression, tag: TypeOfTag): Expression; - /** @internal */ createMethodCall(object: Expression, methodName: string | Identifier, argumentsList: readonly Expression[]): CallExpression; - /** @internal */ createGlobalMethodCall(globalObjectName: string, globalMethodName: string, argumentsList: readonly Expression[]): CallExpression; - /** @internal */ createFunctionBindCall(target: Expression, thisArg: Expression, argumentsList: readonly Expression[]): CallExpression; - /** @internal */ createFunctionCallCall(target: Expression, thisArg: Expression, argumentsList: readonly Expression[]): CallExpression; - /** @internal */ createFunctionApplyCall(target: Expression, thisArg: Expression, argumentsExpression: Expression): CallExpression; - /** @internal */ createObjectDefinePropertyCall(target: Expression, propertyName: string | Expression, attributes: Expression): CallExpression; - /** @internal */ createObjectGetOwnPropertyDescriptorCall(target: Expression, propertyName: string | Expression): CallExpression; - /** @internal */ createReflectGetCall(target: Expression, propertyKey: Expression, receiver?: Expression): CallExpression; - /** @internal */ createReflectSetCall(target: Expression, propertyKey: Expression, value: Expression, receiver?: Expression): CallExpression; - /** @internal */ createPropertyDescriptor(attributes: PropertyDescriptorAttributes, singleLine?: boolean): ObjectLiteralExpression; - /** @internal */ createArraySliceCall(array: Expression, start?: number | Expression): CallExpression; - /** @internal */ createArrayConcatCall(array: Expression, values: readonly Expression[]): CallExpression; - /** @internal */ createCallBinding(expression: Expression, recordTempVariable: (temp: Identifier) => void, languageVersion?: ScriptTarget, cacheIdentifiers?: boolean): CallBinding; + /** @internal */ createTypeCheck( + value: Expression, + tag: TypeOfTag, + ): Expression; + /** @internal */ createIsNotTypeCheck( + value: Expression, + tag: TypeOfTag, + ): Expression; + /** @internal */ createMethodCall( + object: Expression, + methodName: string | Identifier, + argumentsList: readonly Expression[], + ): CallExpression; + /** @internal */ createGlobalMethodCall( + globalObjectName: string, + globalMethodName: string, + argumentsList: readonly Expression[], + ): CallExpression; + /** @internal */ createFunctionBindCall( + target: Expression, + thisArg: Expression, + argumentsList: readonly Expression[], + ): CallExpression; + /** @internal */ createFunctionCallCall( + target: Expression, + thisArg: Expression, + argumentsList: readonly Expression[], + ): CallExpression; + /** @internal */ createFunctionApplyCall( + target: Expression, + thisArg: Expression, + argumentsExpression: Expression, + ): CallExpression; + /** @internal */ createObjectDefinePropertyCall( + target: Expression, + propertyName: string | Expression, + attributes: Expression, + ): CallExpression; + /** @internal */ createObjectGetOwnPropertyDescriptorCall( + target: Expression, + propertyName: string | Expression, + ): CallExpression; + /** @internal */ createReflectGetCall( + target: Expression, + propertyKey: Expression, + receiver?: Expression, + ): CallExpression; + /** @internal */ createReflectSetCall( + target: Expression, + propertyKey: Expression, + value: Expression, + receiver?: Expression, + ): CallExpression; + /** @internal */ createPropertyDescriptor( + attributes: PropertyDescriptorAttributes, + singleLine?: boolean, + ): ObjectLiteralExpression; + /** @internal */ createArraySliceCall( + array: Expression, + start?: number | Expression, + ): CallExpression; + /** @internal */ createArrayConcatCall( + array: Expression, + values: readonly Expression[], + ): CallExpression; + /** @internal */ createCallBinding( + expression: Expression, + recordTempVariable: (temp: Identifier) => void, + languageVersion?: ScriptTarget, + cacheIdentifiers?: boolean, + ): CallBinding; /** * Wraps an expression that cannot be an assignment target in an expression that can be. * @@ -8932,8 +12324,13 @@ export interface NodeFactory { * * @internal */ - createAssignmentTargetWrapper(paramName: Identifier, expression: Expression): PropertyAccessExpression; - /** @internal */ inlineExpressions(expressions: readonly Expression[]): Expression; + createAssignmentTargetWrapper( + paramName: Identifier, + expression: Expression, + ): PropertyAccessExpression; + /** @internal */ inlineExpressions( + expressions: readonly Expression[], + ): Expression; /** * Gets the internal name of a declaration. This is primarily used for declarations that can be * referred to by name in the body of an ES5 class function body. An internal name will *never* @@ -8947,7 +12344,11 @@ export interface NodeFactory { * * @internal */ - getInternalName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; + getInternalName( + node: Declaration, + allowComments?: boolean, + allowSourceMaps?: boolean, + ): Identifier; /** * Gets the local name of a declaration. This is primarily used for declarations that can be * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A @@ -8961,7 +12362,12 @@ export interface NodeFactory { * * @internal */ - getLocalName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean, ignoreAssignedName?: boolean): Identifier; + getLocalName( + node: Declaration, + allowComments?: boolean, + allowSourceMaps?: boolean, + ignoreAssignedName?: boolean, + ): Identifier; /** * Gets the export name of a declaration. This is primarily used for declarations that can be * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An @@ -8974,7 +12380,11 @@ export interface NodeFactory { * * @internal */ - getExportName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; + getExportName( + node: Declaration, + allowComments?: boolean, + allowSourceMaps?: boolean, + ): Identifier; /** * Gets the name of a declaration for use in declarations. * @@ -8984,7 +12394,11 @@ export interface NodeFactory { * * @internal */ - getDeclarationName(node: Declaration | undefined, allowComments?: boolean, allowSourceMaps?: boolean): Identifier; + getDeclarationName( + node: Declaration | undefined, + allowComments?: boolean, + allowSourceMaps?: boolean, + ): Identifier; /** * Gets a namespace-qualified name for use in expressions. * @@ -8995,7 +12409,12 @@ export interface NodeFactory { * * @internal */ - getNamespaceMemberName(ns: Identifier, name: Identifier, allowComments?: boolean, allowSourceMaps?: boolean): PropertyAccessExpression; + getNamespaceMemberName( + ns: Identifier, + name: Identifier, + allowComments?: boolean, + allowSourceMaps?: boolean, + ): PropertyAccessExpression; /** * Gets the exported name of a declaration for use in expressions. * @@ -9009,14 +12428,27 @@ export interface NodeFactory { * * @internal */ - getExternalModuleOrNamespaceExportName(ns: Identifier | undefined, node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier | PropertyAccessExpression; + getExternalModuleOrNamespaceExportName( + ns: Identifier | undefined, + node: Declaration, + allowComments?: boolean, + allowSourceMaps?: boolean, + ): Identifier | PropertyAccessExpression; // // Utilities // - restoreOuterExpressions(outerExpression: Expression | undefined, innerExpression: Expression, kinds?: OuterExpressionKinds): Expression; - /** @internal */ restoreEnclosingLabel(node: Statement, outermostLabeledStatement: LabeledStatement | undefined, afterRestoreLabelCallback?: (node: LabeledStatement) => void): Statement; + restoreOuterExpressions( + outerExpression: Expression | undefined, + innerExpression: Expression, + kinds?: OuterExpressionKinds, + ): Expression; + /** @internal */ restoreEnclosingLabel( + node: Statement, + outermostLabeledStatement: LabeledStatement | undefined, + afterRestoreLabelCallback?: (node: LabeledStatement) => void, + ): Statement; /** @internal */ createUseStrictPrologue(): PrologueDirective; /** * Copies any necessary standard and custom prologue-directives into target array. @@ -9027,7 +12459,12 @@ export interface NodeFactory { * * @internal */ - copyPrologue(source: readonly Statement[], target: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult): number; + copyPrologue( + source: readonly Statement[], + target: Statement[], + ensureUseStrict?: boolean, + visitor?: (node: Node) => VisitResult, + ): number; /** * Copies only the standard (string-expression) prologue-directives into the target statement-array. * @param source origin statements array @@ -9037,7 +12474,12 @@ export interface NodeFactory { * * @internal */ - copyStandardPrologue(source: readonly Statement[], target: Statement[], statementOffset: number | undefined, ensureUseStrict?: boolean): number; + copyStandardPrologue( + source: readonly Statement[], + target: Statement[], + statementOffset: number | undefined, + ensureUseStrict?: boolean, + ): number; /** * Copies only the custom prologue-directives into target statement-array. * @param source origin statements array @@ -9047,22 +12489,42 @@ export interface NodeFactory { * * @internal */ - copyCustomPrologue(source: readonly Statement[], target: Statement[], statementOffset: number, visitor?: (node: Node) => VisitResult, filter?: (node: Statement) => boolean): number; - /** @internal */ copyCustomPrologue(source: readonly Statement[], target: Statement[], statementOffset: number | undefined, visitor?: (node: Node) => VisitResult, filter?: (node: Statement) => boolean): number | undefined; - /** @internal */ ensureUseStrict(statements: NodeArray): NodeArray; + copyCustomPrologue( + source: readonly Statement[], + target: Statement[], + statementOffset: number, + visitor?: (node: Node) => VisitResult, + filter?: (node: Statement) => boolean, + ): number; + /** @internal */ copyCustomPrologue( + source: readonly Statement[], + target: Statement[], + statementOffset: number | undefined, + visitor?: (node: Node) => VisitResult, + filter?: (node: Statement) => boolean, + ): number | undefined; + /** @internal */ ensureUseStrict( + statements: NodeArray, + ): NodeArray; /** @internal */ liftToBlock(nodes: readonly Node[]): Statement; /** * Merges generated lexical declarations into a new statement list. * * @internal */ - mergeLexicalEnvironment(statements: NodeArray, declarations: readonly Statement[] | undefined): NodeArray; + mergeLexicalEnvironment( + statements: NodeArray, + declarations: readonly Statement[] | undefined, + ): NodeArray; /** * Appends generated lexical declarations to an array of statements. * * @internal */ - mergeLexicalEnvironment(statements: Statement[], declarations: readonly Statement[] | undefined): Statement[]; + mergeLexicalEnvironment( + statements: Statement[], + declarations: readonly Statement[] | undefined, + ): Statement[]; /** * Creates a shallow, memberwise clone of a node. * - The result will have its `original` pointer set to `node`. @@ -9075,15 +12537,32 @@ export interface NodeFactory { /** * Updates a node that may contain modifiers, replacing only the modifiers of the node. */ - replaceModifiers(node: T, modifiers: readonly Modifier[] | ModifierFlags | undefined): T; + replaceModifiers( + node: T, + modifiers: readonly Modifier[] | ModifierFlags | undefined, + ): T; /** * Updates a node that may contain decorators or modifiers, replacing only the decorators and modifiers of the node. */ - replaceDecoratorsAndModifiers(node: T, modifiers: readonly ModifierLike[] | undefined): T; + replaceDecoratorsAndModifiers( + node: T, + modifiers: readonly ModifierLike[] | undefined, + ): T; /** * Updates a node that contains a property name, replacing only the name of the node. */ - replacePropertyName(node: T, name: T["name"]): T; + replacePropertyName< + T extends + | AccessorDeclaration + | MethodDeclaration + | MethodSignature + | PropertyDeclaration + | PropertySignature + | PropertyAssignment, + >( + node: T, + name: T["name"], + ): T; } /** @internal */ @@ -9102,7 +12581,10 @@ export interface CoreTransformationContext { /** Starts a new lexical environment. */ startLexicalEnvironment(): void; - /** @internal */ setLexicalEnvironmentFlags(flags: LexicalEnvironmentFlags, value: boolean): void; + /** @internal */ setLexicalEnvironmentFlags( + flags: LexicalEnvironmentFlags, + value: boolean, + ): void; /** @internal */ getLexicalEnvironmentFlags(): LexicalEnvironmentFlags; /** Suspends the current lexical environment, usually after visiting a parameter list. */ @@ -9179,7 +12661,11 @@ export interface TransformationContext extends CoreTransformationContext { * NOTE: Transformation hooks should only be modified during `Transformer` initialization, * before returning the `NodeTransformer` callback. */ - onEmitNode: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void; + onEmitNode: ( + hint: EmitHint, + node: Node, + emitCallback: (hint: EmitHint, node: Node) => void, + ) => void; /** @internal */ addDiagnostic(diag: DiagnosticWithLocation): void; } @@ -9206,7 +12692,11 @@ export interface TransformationResult { * @param node The node to emit. * @param emitCallback A callback used to emit the node. */ - emitNodeWithNotification(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; + emitNodeWithNotification( + hint: EmitHint, + node: Node, + emitCallback: (hint: EmitHint, node: Node) => void, + ): void; /** * Indicates if a given node needs an emit notification @@ -9225,7 +12715,9 @@ export interface TransformationResult { * A function that is used to initialize and return a `Transformer` callback, which in turn * will be used to transform one or more nodes. */ -export type TransformerFactory = (context: TransformationContext) => Transformer; +export type TransformerFactory = ( + context: TransformationContext, +) => Transformer; /** * A function that transforms a node. @@ -9235,7 +12727,10 @@ export type Transformer = (node: T) => T; /** * A function that accepts and possibly transforms a node. */ -export type Visitor = (node: TIn) => VisitResult; +export type Visitor< + TIn extends Node = Node, + TOut extends Node | undefined = TIn | undefined, +> = (node: TIn) => VisitResult; /** * A function that walks a node using the given visitor, lifting node arrays into single nodes, @@ -9250,7 +12745,11 @@ export type Visitor( + < + TIn extends Node | undefined, + TVisited extends Node | undefined, + TOut extends Node, + >( node: TIn, visitor: Visitor, TVisited>, test: (node: Node) => node is TOut, @@ -9276,7 +12775,11 @@ export interface NodeVisitor { * For the canonical implementation of this type, @see {visitNodes}. */ export interface NodesVisitor { - | undefined, TOut extends Node>( + < + TIn extends Node, + TInArray extends NodeArray | undefined, + TOut extends Node, + >( nodes: TInArray, visitor: Visitor, test: (node: Node) => node is TOut, @@ -9292,7 +12795,9 @@ export interface NodesVisitor { ): NodeArray | (TInArray & undefined); } -export type VisitResult = T | readonly Node[]; +export type VisitResult = + | T + | readonly Node[]; export interface Printer { /** @@ -9312,7 +12817,11 @@ export interface Printer { /** * Prints a list of nodes using the given format flags */ - printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string; + printList( + format: ListFormat, + list: NodeArray, + sourceFile: SourceFile, + ): string; /** * Prints a source file as-is, without any emit transformations. */ @@ -9321,10 +12830,28 @@ export interface Printer { * Prints a bundle of source files as-is, without any emit transformations. */ printBundle(bundle: Bundle): string; - /** @internal */ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void; - /** @internal */ writeList(format: ListFormat, list: NodeArray | undefined, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void; - /** @internal */ writeFile(sourceFile: SourceFile, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void; - /** @internal */ writeBundle(bundle: Bundle, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void; + /** @internal */ writeNode( + hint: EmitHint, + node: Node, + sourceFile: SourceFile | undefined, + writer: EmitTextWriter, + ): void; + /** @internal */ writeList( + format: ListFormat, + list: NodeArray | undefined, + sourceFile: SourceFile | undefined, + writer: EmitTextWriter, + ): void; + /** @internal */ writeFile( + sourceFile: SourceFile, + writer: EmitTextWriter, + sourceMapGenerator: SourceMapGenerator | undefined, + ): void; + /** @internal */ writeBundle( + bundle: Bundle, + writer: EmitTextWriter, + sourceMapGenerator: SourceMapGenerator | undefined, + ): void; /** @deprecated @internal */ bundleFileInfo?: BundleFileInfo; } @@ -9369,7 +12896,12 @@ export interface BundleFileHasNoDefaultLib extends BundleFileSectionBase { /** @deprecated @internal */ export interface BundleFileReference extends BundleFileSectionBase { - kind: BundleFileSectionKind.Reference | BundleFileSectionKind.Type | BundleFileSectionKind.Lib | BundleFileSectionKind.TypeResolutionModeImport | BundleFileSectionKind.TypeResolutionModeRequire; + kind: + | BundleFileSectionKind.Reference + | BundleFileSectionKind.Type + | BundleFileSectionKind.Lib + | BundleFileSectionKind.TypeResolutionModeImport + | BundleFileSectionKind.TypeResolutionModeRequire; data: string; } @@ -9381,7 +12913,9 @@ export interface BundleFilePrepend extends BundleFileSectionBase { } /** @deprecated @internal */ -export type BundleFileTextLikeKind = BundleFileSectionKind.Text | BundleFileSectionKind.Internal; +export type BundleFileTextLikeKind = + | BundleFileSectionKind.Text + | BundleFileSectionKind.Internal; /** @deprecated @internal */ export interface BundleFileTextLike extends BundleFileSectionBase { @@ -9469,7 +13003,11 @@ export interface PrintHandlers { * }); * ``` */ - onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void; + onEmitNode?( + hint: EmitHint, + node: Node, + emitCallback: (hint: EmitHint, node: Node) => void, + ): void; /** * A hook used to check if an emit notification is required for a node. @@ -9493,14 +13031,32 @@ export interface PrintHandlers { * ``` */ substituteNode?(hint: EmitHint, node: Node): Node; - /** @internal */ onEmitSourceMapOfNode?: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void; - /** @internal */ onEmitSourceMapOfToken?: (node: Node | undefined, token: SyntaxKind, writer: (s: string) => void, pos: number, emitCallback: (token: SyntaxKind, writer: (s: string) => void, pos: number) => number) => number; + /** @internal */ onEmitSourceMapOfNode?: ( + hint: EmitHint, + node: Node, + emitCallback: (hint: EmitHint, node: Node) => void, + ) => void; + /** @internal */ onEmitSourceMapOfToken?: ( + node: Node | undefined, + token: SyntaxKind, + writer: (s: string) => void, + pos: number, + emitCallback: ( + token: SyntaxKind, + writer: (s: string) => void, + pos: number, + ) => number, + ) => number; /** @internal */ onEmitSourceMapOfPosition?: (pos: number) => void; /** @internal */ onSetSourceFile?: (node: SourceFile) => void; /** @internal */ onBeforeEmitNode?: (node: Node | undefined) => void; /** @internal */ onAfterEmitNode?: (node: Node | undefined) => void; - /** @internal */ onBeforeEmitNodeArray?: (nodes: NodeArray | undefined) => void; - /** @internal */ onAfterEmitNodeArray?: (nodes: NodeArray | undefined) => void; + /** @internal */ onBeforeEmitNodeArray?: ( + nodes: NodeArray | undefined, + ) => void; + /** @internal */ onAfterEmitNodeArray?: ( + nodes: NodeArray | undefined, + ) => void; /** @internal */ onBeforeEmitToken?: (node: Node) => void; /** @internal */ onAfterEmitToken?: (node: Node) => void; } @@ -9564,11 +13120,25 @@ export interface SourceMapGenerator { /** * Adds a mapping with source information. */ - addMapping(generatedLine: number, generatedCharacter: number, sourceIndex: number, sourceLine: number, sourceCharacter: number, nameIndex?: number): void; + addMapping( + generatedLine: number, + generatedCharacter: number, + sourceIndex: number, + sourceLine: number, + sourceCharacter: number, + nameIndex?: number, + ): void; /** * Appends a source map. */ - appendSourceMap(generatedLine: number, generatedCharacter: number, sourceMap: RawSourceMap, sourceMapPath: string, start?: LineAndCharacter, end?: LineAndCharacter): void; + appendSourceMap( + generatedLine: number, + generatedCharacter: number, + sourceMap: RawSourceMap, + sourceMapPath: string, + start?: LineAndCharacter, + end?: LineAndCharacter, + ): void; /** * Gets the source map as a `RawSourceMap` object. */ @@ -9642,7 +13212,10 @@ export interface ModuleSpecifierResolutionHost { getModuleSpecifierCache?(): ModuleSpecifierCache; getPackageJsonInfoCache?(): PackageJsonInfoCache | undefined; getGlobalTypingsCacheLocation?(): string | undefined; - getNearestAncestorDirectoryWithPackageJson?(fileName: string, rootDir?: string): string | undefined; + getNearestAncestorDirectoryWithPackageJson?( + fileName: string, + rootDir?: string, + ): string | undefined; readonly redirectTargetsMap: RedirectTargetsMap; getProjectReferenceRedirect(fileName: string): string | undefined; @@ -9671,10 +13244,34 @@ export interface ModuleSpecifierOptions { /** @internal */ export interface ModuleSpecifierCache { - get(fromFileName: Path, toFileName: Path, preferences: UserPreferences, options: ModuleSpecifierOptions): Readonly | undefined; - set(fromFileName: Path, toFileName: Path, preferences: UserPreferences, options: ModuleSpecifierOptions, modulePaths: readonly ModulePath[], moduleSpecifiers: readonly string[]): void; - setBlockedByPackageJsonDependencies(fromFileName: Path, toFileName: Path, preferences: UserPreferences, options: ModuleSpecifierOptions, isBlockedByPackageJsonDependencies: boolean): void; - setModulePaths(fromFileName: Path, toFileName: Path, preferences: UserPreferences, options: ModuleSpecifierOptions, modulePaths: readonly ModulePath[]): void; + get( + fromFileName: Path, + toFileName: Path, + preferences: UserPreferences, + options: ModuleSpecifierOptions, + ): Readonly | undefined; + set( + fromFileName: Path, + toFileName: Path, + preferences: UserPreferences, + options: ModuleSpecifierOptions, + modulePaths: readonly ModulePath[], + moduleSpecifiers: readonly string[], + ): void; + setBlockedByPackageJsonDependencies( + fromFileName: Path, + toFileName: Path, + preferences: UserPreferences, + options: ModuleSpecifierOptions, + isBlockedByPackageJsonDependencies: boolean, + ): void; + setModulePaths( + fromFileName: Path, + toFileName: Path, + preferences: UserPreferences, + options: ModuleSpecifierOptions, + modulePaths: readonly ModulePath[], + ): void; clear(): void; count(): number; } @@ -9685,17 +13282,30 @@ export interface SymbolTracker { // Called when the symbol writer encounters a symbol to write. Currently only used by the // declaration emitter to help determine if it should patch up the final declaration file // with import statements it previously saw (but chose not to emit). - trackSymbol?(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags): boolean; + trackSymbol?( + symbol: Symbol, + enclosingDeclaration: Node | undefined, + meaning: SymbolFlags, + ): boolean; reportInaccessibleThisError?(): void; reportPrivateInBaseOfClassExpression?(propertyName: string): void; reportInaccessibleUniqueSymbolError?(): void; reportCyclicStructureError?(): void; reportLikelyUnsafeImportRequiredError?(specifier: string): void; reportTruncationError?(): void; - moduleResolverHost?: ModuleSpecifierResolutionHost & { getCommonSourceDirectory(): string; }; - trackReferencedAmbientModule?(decl: ModuleDeclaration, symbol: Symbol): void; + moduleResolverHost?: ModuleSpecifierResolutionHost & { + getCommonSourceDirectory(): string; + }; + trackReferencedAmbientModule?( + decl: ModuleDeclaration, + symbol: Symbol, + ): void; trackExternalModuleSymbolOfImportTypeNode?(symbol: Symbol): void; - reportNonlocalAugmentation?(containingFile: SourceFile, parentSymbol: Symbol, augmentingSymbol: Symbol): void; + reportNonlocalAugmentation?( + containingFile: SourceFile, + parentSymbol: Symbol, + augmentingSymbol: Symbol, + ): void; reportNonSerializableProperty?(propertyName: string): void; } @@ -9727,7 +13337,7 @@ export interface DiagnosticCollection { } // SyntaxKind.SyntaxList -export interface SyntaxList extends Node { +export interface SyntaxList extends NodeBase { kind: SyntaxKind.SyntaxList; _children: Node[]; } @@ -9737,86 +13347,165 @@ export const enum ListFormat { None = 0, // Line separators - SingleLine = 0, // Prints the list on a single line (default). - MultiLine = 1 << 0, // Prints the list on multiple lines. - PreserveLines = 1 << 1, // Prints the list using line preservation if possible. + SingleLine = 0, // Prints the list on a single line (default). + MultiLine = 1 << 0, // Prints the list on multiple lines. + PreserveLines = 1 << 1, // Prints the list using line preservation if possible. LinesMask = SingleLine | MultiLine | PreserveLines, // Delimiters - NotDelimited = 0, // There is no delimiter between list items (default). - BarDelimited = 1 << 2, // Each list item is space-and-bar (" |") delimited. - AmpersandDelimited = 1 << 3, // Each list item is space-and-ampersand (" &") delimited. - CommaDelimited = 1 << 4, // Each list item is comma (",") delimited. - AsteriskDelimited = 1 << 5, // Each list item is asterisk ("\n *") delimited, used with JSDoc. - DelimitersMask = BarDelimited | AmpersandDelimited | CommaDelimited | AsteriskDelimited, - - AllowTrailingComma = 1 << 6, // Write a trailing comma (",") if present. + NotDelimited = 0, // There is no delimiter between list items (default). + BarDelimited = 1 << 2, // Each list item is space-and-bar (" |") delimited. + AmpersandDelimited = 1 << 3, // Each list item is space-and-ampersand (" &") delimited. + CommaDelimited = 1 << 4, // Each list item is comma (",") delimited. + AsteriskDelimited = 1 << 5, // Each list item is asterisk ("\n *") delimited, used with JSDoc. + DelimitersMask = BarDelimited | + AmpersandDelimited | + CommaDelimited | + AsteriskDelimited, + + AllowTrailingComma = 1 << 6, // Write a trailing comma (",") if present. // Whitespace - Indented = 1 << 7, // The list should be indented. - SpaceBetweenBraces = 1 << 8, // Inserts a space after the opening brace and before the closing brace. - SpaceBetweenSiblings = 1 << 9, // Inserts a space between each sibling node. + Indented = 1 << 7, // The list should be indented. + SpaceBetweenBraces = 1 << 8, // Inserts a space after the opening brace and before the closing brace. + SpaceBetweenSiblings = 1 << 9, // Inserts a space between each sibling node. // Brackets/Braces - Braces = 1 << 10, // The list is surrounded by "{" and "}". - Parenthesis = 1 << 11, // The list is surrounded by "(" and ")". - AngleBrackets = 1 << 12, // The list is surrounded by "<" and ">". - SquareBrackets = 1 << 13, // The list is surrounded by "[" and "]". + Braces = 1 << 10, // The list is surrounded by "{" and "}". + Parenthesis = 1 << 11, // The list is surrounded by "(" and ")". + AngleBrackets = 1 << 12, // The list is surrounded by "<" and ">". + SquareBrackets = 1 << 13, // The list is surrounded by "[" and "]". BracketsMask = Braces | Parenthesis | AngleBrackets | SquareBrackets, - OptionalIfUndefined = 1 << 14, // Do not emit brackets if the list is undefined. - OptionalIfEmpty = 1 << 15, // Do not emit brackets if the list is empty. + OptionalIfUndefined = 1 << 14, // Do not emit brackets if the list is undefined. + OptionalIfEmpty = 1 << 15, // Do not emit brackets if the list is empty. Optional = OptionalIfUndefined | OptionalIfEmpty, // Other - PreferNewLine = 1 << 16, // Prefer adding a LineTerminator between synthesized nodes. - NoTrailingNewLine = 1 << 17, // Do not emit a trailing NewLine for a MultiLine list. + PreferNewLine = 1 << 16, // Prefer adding a LineTerminator between synthesized nodes. + NoTrailingNewLine = 1 << 17, // Do not emit a trailing NewLine for a MultiLine list. NoInterveningComments = 1 << 18, // Do not emit comments between each node - NoSpaceIfEmpty = 1 << 19, // If the literal is empty, do not add spaces between braces. + NoSpaceIfEmpty = 1 << 19, // If the literal is empty, do not add spaces between braces. SingleElement = 1 << 20, - SpaceAfterList = 1 << 21, // Add space after list + SpaceAfterList = 1 << 21, // Add space after list // Precomputed Formats - Modifiers = SingleLine | SpaceBetweenSiblings | NoInterveningComments | SpaceAfterList, + Modifiers = SingleLine | + SpaceBetweenSiblings | + NoInterveningComments | + SpaceAfterList, HeritageClauses = SingleLine | SpaceBetweenSiblings, - SingleLineTypeLiteralMembers = SingleLine | SpaceBetweenBraces | SpaceBetweenSiblings, + SingleLineTypeLiteralMembers = SingleLine | + SpaceBetweenBraces | + SpaceBetweenSiblings, MultiLineTypeLiteralMembers = MultiLine | Indented | OptionalIfEmpty, - SingleLineTupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine, - MultiLineTupleTypeElements = CommaDelimited | Indented | SpaceBetweenSiblings | MultiLine, + SingleLineTupleTypeElements = CommaDelimited | + SpaceBetweenSiblings | + SingleLine, + MultiLineTupleTypeElements = CommaDelimited | + Indented | + SpaceBetweenSiblings | + MultiLine, UnionTypeConstituents = BarDelimited | SpaceBetweenSiblings | SingleLine, - IntersectionTypeConstituents = AmpersandDelimited | SpaceBetweenSiblings | SingleLine, - ObjectBindingPatternElements = SingleLine | AllowTrailingComma | SpaceBetweenBraces | CommaDelimited | SpaceBetweenSiblings | NoSpaceIfEmpty, - ArrayBindingPatternElements = SingleLine | AllowTrailingComma | CommaDelimited | SpaceBetweenSiblings | NoSpaceIfEmpty, - ObjectLiteralExpressionProperties = PreserveLines | CommaDelimited | SpaceBetweenSiblings | SpaceBetweenBraces | Indented | Braces | NoSpaceIfEmpty, - ImportAttributes = PreserveLines | CommaDelimited | SpaceBetweenSiblings | SpaceBetweenBraces | Indented | Braces | NoSpaceIfEmpty, + IntersectionTypeConstituents = AmpersandDelimited | + SpaceBetweenSiblings | + SingleLine, + ObjectBindingPatternElements = SingleLine | + AllowTrailingComma | + SpaceBetweenBraces | + CommaDelimited | + SpaceBetweenSiblings | + NoSpaceIfEmpty, + ArrayBindingPatternElements = SingleLine | + AllowTrailingComma | + CommaDelimited | + SpaceBetweenSiblings | + NoSpaceIfEmpty, + ObjectLiteralExpressionProperties = PreserveLines | + CommaDelimited | + SpaceBetweenSiblings | + SpaceBetweenBraces | + Indented | + Braces | + NoSpaceIfEmpty, + ImportAttributes = PreserveLines | + CommaDelimited | + SpaceBetweenSiblings | + SpaceBetweenBraces | + Indented | + Braces | + NoSpaceIfEmpty, /** @deprecated */ ImportClauseEntries = ImportAttributes, - ArrayLiteralExpressionElements = PreserveLines | CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | Indented | SquareBrackets, + ArrayLiteralExpressionElements = PreserveLines | + CommaDelimited | + SpaceBetweenSiblings | + AllowTrailingComma | + Indented | + SquareBrackets, CommaListElements = CommaDelimited | SpaceBetweenSiblings | SingleLine, - CallExpressionArguments = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis, - NewExpressionArguments = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis | OptionalIfUndefined, + CallExpressionArguments = CommaDelimited | + SpaceBetweenSiblings | + SingleLine | + Parenthesis, + NewExpressionArguments = CommaDelimited | + SpaceBetweenSiblings | + SingleLine | + Parenthesis | + OptionalIfUndefined, TemplateExpressionSpans = SingleLine | NoInterveningComments, - SingleLineBlockStatements = SpaceBetweenBraces | SpaceBetweenSiblings | SingleLine, + SingleLineBlockStatements = SpaceBetweenBraces | + SpaceBetweenSiblings | + SingleLine, MultiLineBlockStatements = Indented | MultiLine, - VariableDeclarationList = CommaDelimited | SpaceBetweenSiblings | SingleLine, - SingleLineFunctionBodyStatements = SingleLine | SpaceBetweenSiblings | SpaceBetweenBraces, + VariableDeclarationList = CommaDelimited | + SpaceBetweenSiblings | + SingleLine, + SingleLineFunctionBodyStatements = SingleLine | + SpaceBetweenSiblings | + SpaceBetweenBraces, MultiLineFunctionBodyStatements = MultiLine, ClassHeritageClauses = SingleLine, ClassMembers = Indented | MultiLine, InterfaceMembers = Indented | MultiLine, EnumMembers = CommaDelimited | Indented | MultiLine, CaseBlockClauses = Indented | MultiLine, - NamedImportsOrExportsElements = CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | SingleLine | SpaceBetweenBraces | NoSpaceIfEmpty, + NamedImportsOrExportsElements = CommaDelimited | + SpaceBetweenSiblings | + AllowTrailingComma | + SingleLine | + SpaceBetweenBraces | + NoSpaceIfEmpty, JsxElementOrFragmentChildren = SingleLine | NoInterveningComments, - JsxElementAttributes = SingleLine | SpaceBetweenSiblings | NoInterveningComments, - CaseOrDefaultClauseStatements = Indented | MultiLine | NoTrailingNewLine | OptionalIfEmpty, + JsxElementAttributes = SingleLine | + SpaceBetweenSiblings | + NoInterveningComments, + CaseOrDefaultClauseStatements = Indented | + MultiLine | + NoTrailingNewLine | + OptionalIfEmpty, HeritageClauseTypes = CommaDelimited | SpaceBetweenSiblings | SingleLine, SourceFileStatements = MultiLine | NoTrailingNewLine, Decorators = MultiLine | Optional | SpaceAfterList, - TypeArguments = CommaDelimited | SpaceBetweenSiblings | SingleLine | AngleBrackets | Optional, - TypeParameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | AngleBrackets | Optional, - Parameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis, - IndexSignatureParameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented | SquareBrackets, + TypeArguments = CommaDelimited | + SpaceBetweenSiblings | + SingleLine | + AngleBrackets | + Optional, + TypeParameters = CommaDelimited | + SpaceBetweenSiblings | + SingleLine | + AngleBrackets | + Optional, + Parameters = CommaDelimited | + SpaceBetweenSiblings | + SingleLine | + Parenthesis, + IndexSignatureParameters = CommaDelimited | + SpaceBetweenSiblings | + SingleLine | + Indented | + SquareBrackets, JSDocComment = MultiLine | AsteriskDelimited, } @@ -9852,12 +13541,29 @@ export interface PragmaArgumentSpecification { } /** @internal */ -export interface PragmaDefinition { +export interface PragmaDefinition< + T1 extends string = string, + T2 extends string = string, + T3 extends string = string, + T4 extends string = string, +> { args?: | readonly [PragmaArgumentSpecification] - | readonly [PragmaArgumentSpecification, PragmaArgumentSpecification] - | readonly [PragmaArgumentSpecification, PragmaArgumentSpecification, PragmaArgumentSpecification] - | readonly [PragmaArgumentSpecification, PragmaArgumentSpecification, PragmaArgumentSpecification, PragmaArgumentSpecification]; + | readonly [ + PragmaArgumentSpecification, + PragmaArgumentSpecification, + ] + | readonly [ + PragmaArgumentSpecification, + PragmaArgumentSpecification, + PragmaArgumentSpecification, + ] + | readonly [ + PragmaArgumentSpecification, + PragmaArgumentSpecification, + PragmaArgumentSpecification, + PragmaArgumentSpecification, + ]; // If not present, defaults to PragmaKindFlags.Default kind?: PragmaKindFlags; } @@ -9937,18 +13643,33 @@ export const enum JSDocParsingMode { } /** @internal */ -export type PragmaArgTypeMaybeCapture = TDesc extends { captureSpan: true; } ? { value: string; pos: number; end: number; } : string; +export type PragmaArgTypeMaybeCapture = TDesc extends { + captureSpan: true; +} ? { value: string; pos: number; end: number; } + : string; /** @internal */ -export type PragmaArgTypeOptional = TDesc extends { optional: true; } ? { [K in TName]?: PragmaArgTypeMaybeCapture; } +export type PragmaArgTypeOptional = TDesc extends { + optional: true; +} ? { [K in TName]?: PragmaArgTypeMaybeCapture; } : { [K in TName]: PragmaArgTypeMaybeCapture; }; /** @internal */ -export type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never; +export type UnionToIntersection = ( + U extends any ? (k: U) => void : never +) extends (k: infer I) => void ? I + : never; /** @internal */ -export type ArgumentDefinitionToFieldUnion[]> = { - [K in keyof T]: PragmaArgTypeOptional; +export type ArgumentDefinitionToFieldUnion< + T extends readonly PragmaArgumentSpecification[], +> = { + [K in keyof T]: PragmaArgTypeOptional< + T[K], + T[K] extends { name: infer TName; } ? TName extends string ? TName + : never + : never + >; }[Extract]; // The mapped type maps over only the tuple members, but this reindex gets _all_ members - by extracting only `number` keys, we get only the tuple members /** @@ -9956,22 +13677,47 @@ export type ArgumentDefinitionToFieldUnion = ConcretePragmaSpecs[KPrag] extends { args: readonly PragmaArgumentSpecification[]; } ? UnionToIntersection> +export type PragmaArgumentType = ConcretePragmaSpecs[KPrag] extends { + args: readonly PragmaArgumentSpecification[]; +} ? UnionToIntersection< + ArgumentDefinitionToFieldUnion + > : never; /** @internal */ export type ConcretePragmaSpecs = typeof commentPragmas; /** @internal */ -export type PragmaPseudoMap = { [K in keyof ConcretePragmaSpecs]: { arguments: PragmaArgumentType; range: CommentRange; }; }; +export type PragmaPseudoMap = { + [K in keyof ConcretePragmaSpecs]: { + arguments: PragmaArgumentType; + range: CommentRange; + }; +}; /** @internal */ -export type PragmaPseudoMapEntry = { [K in keyof PragmaPseudoMap]: { name: K; args: PragmaPseudoMap[K]; }; }[keyof PragmaPseudoMap]; +export type PragmaPseudoMapEntry = { + [K in keyof PragmaPseudoMap]: { name: K; args: PragmaPseudoMap[K]; }; +}[keyof PragmaPseudoMap]; /** @internal */ -export interface ReadonlyPragmaMap extends ReadonlyMap { - get(key: TKey): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]; - forEach(action: (value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey, map: ReadonlyPragmaMap) => void): void; +export interface ReadonlyPragmaMap extends + ReadonlyMap< + string, + | PragmaPseudoMap[keyof PragmaPseudoMap] + | PragmaPseudoMap[keyof PragmaPseudoMap][] + > +{ + get( + key: TKey, + ): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]; + forEach( + action: ( + value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], + key: TKey, + map: ReadonlyPragmaMap, + ) => void, + ): void; } /** @@ -9981,10 +13727,28 @@ export interface ReadonlyPragmaMap extends ReadonlyMap, ReadonlyPragmaMap { - set(key: TKey, value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]): this; - get(key: TKey): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]; - forEach(action: (value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey, map: PragmaMap) => void): void; +export interface PragmaMap extends + Map< + string, + | PragmaPseudoMap[keyof PragmaPseudoMap] + | PragmaPseudoMap[keyof PragmaPseudoMap][] + >, + ReadonlyPragmaMap +{ + set( + key: TKey, + value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], + ): this; + get( + key: TKey, + ): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]; + forEach( + action: ( + value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], + key: TKey, + map: PragmaMap, + ) => void, + ): void; } /** @internal */ @@ -10005,7 +13769,11 @@ export interface UserPreferences { readonly includeCompletionsWithObjectLiteralMethodSnippets?: boolean; readonly useLabelDetailsInCompletionEntries?: boolean; readonly allowIncompleteCompletions?: boolean; - readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative"; + readonly importModuleSpecifierPreference?: + | "shortest" + | "project-relative" + | "relative" + | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ readonly importModuleSpecifierEnding?: "auto" | "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 0d1e4a4ac6836..69ba6bf2d124c 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -15,10 +15,7 @@ import { AnyValidImportOrReExport, append, arrayFrom, - ArrayLiteralExpression, - ArrayTypeNode, ArrowFunction, - AsExpression, AssertionExpression, assertType, AssignmentDeclarationKind, @@ -56,7 +53,6 @@ import { ClassLikeDeclaration, ClassStaticBlockDeclaration, combinePaths, - CommaListExpression, CommandLineOption, CommentDirective, CommentDirectivesMap, @@ -72,7 +68,6 @@ import { computeLineOfPosition, computeLineStarts, concatenate, - ConditionalExpression, ConstructorDeclaration, ConstructSignatureDeclaration, ContainerFlags, @@ -85,10 +80,10 @@ import { createTextSpanFromBounds, Debug, Declaration, + DeclarationBase, DeclarationName, DeclarationWithTypeParameterChildren, DeclarationWithTypeParameters, - Decorator, DefaultClause, DestructuringAssignment, Diagnostic, @@ -102,7 +97,7 @@ import { DiagnosticWithLocation, directorySeparator, DoStatement, - DynamicNamedBinaryExpression, + DynamicNamedBinaryExpressionBase, DynamicNamedDeclaration, ElementAccessExpression, EmitFlags, @@ -356,7 +351,6 @@ import { JSDocParameterTag, JSDocPropertyLikeTag, JSDocSatisfiesExpression, - JSDocSatisfiesTag, JSDocSignature, JSDocTag, JSDocTemplateTag, @@ -364,13 +358,9 @@ import { JsonSourceFile, JsxAttributeName, JsxChild, - JsxElement, JsxEmit, - JsxFragment, JsxNamespacedName, - JsxOpeningElement, JsxOpeningLikeElement, - JsxSelfClosingElement, JsxTagNameExpression, KeywordSyntaxKind, LabeledStatement, @@ -404,18 +394,15 @@ import { moduleResolutionOptionDeclarations, MultiMap, NamedDeclaration, - NamedExports, - NamedImports, NamedImportsOrExports, NamespaceExport, NamespaceImport, - NewExpression, NewLineKind, Node, NodeArray, + NodeBase, NodeFlags, nodeModulesPathPart, - NonNullExpression, noop, normalizePath, NoSubstitutionTemplateLiteral, @@ -432,10 +419,8 @@ import { OuterExpressionKinds, PackageId, ParameterDeclaration, - ParenthesizedExpression, ParenthesizedTypeNode, parseConfigFileTextToJson, - PartiallyEmittedExpression, Path, pathIsRelative, Pattern, @@ -454,6 +439,7 @@ import { PropertyNameLiteral, PropertySignature, PseudoBigInt, + PseudoLiteralToken, PunctuationOrKeywordSyntaxKind, PunctuationSyntaxKind, QualifiedName, @@ -507,18 +493,17 @@ import { SymbolFlags, SymbolTable, SyntaxKind, - SyntaxList, TaggedTemplateExpression, TemplateLiteral, TemplateLiteralLikeNode, TemplateLiteralToken, - TemplateLiteralTypeSpan, TemplateSpan, TextRange, TextSpan, ThisTypePredicate, Token, TokenFlags, + TokenSyntaxKind, tokenToString, toPath, tracing, @@ -529,15 +514,12 @@ import { tryRemovePrefix, TryStatement, TsConfigSourceFile, - TupleTypeNode, Type, TypeAliasDeclaration, - TypeAssertion, TypeChecker, TypeCheckerHost, TypeElement, TypeFlags, - TypeLiteralNode, TypeNode, TypeNodeSyntaxKind, TypeParameter, @@ -879,11 +861,11 @@ function aggregateChildData(node: Node): void { } /** @internal */ -export function getSourceFileOfNode(node: Node): SourceFile; +export function getSourceFileOfNode(node: NodeBase): SourceFile; /** @internal */ -export function getSourceFileOfNode(node: Node | undefined): SourceFile | undefined; +export function getSourceFileOfNode(node: NodeBase | undefined): SourceFile | undefined; /** @internal */ -export function getSourceFileOfNode(node: Node | undefined): SourceFile | undefined { +export function getSourceFileOfNode(node: NodeBase | undefined): SourceFile | undefined { while (node && node.kind !== SyntaxKind.SourceFile) { node = node.parent; } @@ -978,7 +960,7 @@ export function isFileLevelUniqueName(sourceFile: SourceFile, name: string, hasG // However, this node will be 'missing' in the sense that no actual source-code/tokens are // contained within it. /** @internal */ -export function nodeIsMissing(node: Node | undefined): boolean { +export function nodeIsMissing(node: NodeBase | undefined): boolean { if (node === undefined) { return true; } @@ -987,7 +969,7 @@ export function nodeIsMissing(node: Node | undefined): boolean { } /** @internal */ -export function nodeIsPresent(node: Node | undefined): boolean { +export function nodeIsPresent(node: NodeBase | undefined): boolean { return !nodeIsMissing(node); } @@ -1156,8 +1138,8 @@ export function getTokenPosOfNode(node: Node, sourceFile?: SourceFileLike, inclu // the syntax list itself considers them as normal trivia. Therefore if we simply skip // trivia for the list, we may have skipped the JSDocComment as well. So we should process its // first child to determine the actual position of its first token. - if (node.kind === SyntaxKind.SyntaxList && (node as SyntaxList)._children.length > 0) { - return getTokenPosOfNode((node as SyntaxList)._children[0], sourceFile, includeJsDoc); + if (node.kind === SyntaxKind.SyntaxList && node._children.length > 0) { + return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc); } return skipTrivia( @@ -1660,7 +1642,7 @@ export const enum GetLiteralTextFlags { } /** @internal */ -export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile | undefined, flags: GetLiteralTextFlags) { +export function getLiteralText(node: PseudoLiteralToken | LiteralLikeNode, sourceFile: SourceFile | undefined, flags: GetLiteralTextFlags) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. if (sourceFile && canUseOriginalText(node, flags)) { @@ -1674,7 +1656,7 @@ export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile | u const escapeText = flags & GetLiteralTextFlags.JsxAttributeEscape ? escapeJsxAttributeString : flags & GetLiteralTextFlags.NeverAsciiEscape || (getEmitFlags(node) & EmitFlags.NoAsciiEscaping) ? escapeString : escapeNonAsciiString; - if ((node as StringLiteral).singleQuote) { + if (node.singleQuote) { return "'" + escapeText(node.text, CharacterCodes.singleQuote) + "'"; } else { @@ -1716,8 +1698,8 @@ export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile | u return Debug.fail(`Literal kind '${node.kind}' not accounted for.`); } -function canUseOriginalText(node: LiteralLikeNode, flags: GetLiteralTextFlags): boolean { - if (nodeIsSynthesized(node) || !node.parent || (flags & GetLiteralTextFlags.TerminateUnterminatedLiterals && node.isUnterminated)) { +function canUseOriginalText(node: PseudoLiteralToken | LiteralLikeNode, flags: GetLiteralTextFlags): boolean { + if (nodeIsSynthesized(node) || !node.parent || (flags & GetLiteralTextFlags.TerminateUnterminatedLiterals && (node as LiteralLikeNode).isUnterminated)) { return false; } @@ -1795,7 +1777,7 @@ export function isShorthandAmbientModuleSymbol(moduleSymbol: Symbol): boolean { function isShorthandAmbientModule(node: Node | undefined): boolean { // The only kind of module that can be missing a body is a shorthand ambient module. - return !!node && node.kind === SyntaxKind.ModuleDeclaration && (!(node as ModuleDeclaration).body); + return !!node && node.kind === SyntaxKind.ModuleDeclaration && (!node.body); } /** @internal */ @@ -2108,7 +2090,7 @@ export function createDiagnosticForNodeArray(sourceFile: SourceFile, nodes: Node } /** @internal */ -export function createDiagnosticForNodeInSourceFile(sourceFile: SourceFile, node: Node, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithLocation { +export function createDiagnosticForNodeInSourceFile(sourceFile: SourceFile, node: Node | NodeBase, message: DiagnosticMessage, ...args: DiagnosticArguments): DiagnosticWithLocation { const span = getErrorSpanForNode(sourceFile, node); return createFileDiagnostic(sourceFile, span.start, span.length, message, ...args); } @@ -2244,7 +2226,7 @@ export function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpa errorNode = (node as NamedDeclaration).name; break; case SyntaxKind.ArrowFunction: - return getErrorSpanForArrowFunction(sourceFile, node as ArrowFunction); + return getErrorSpanForArrowFunction(sourceFile, node); case SyntaxKind.CaseClause: case SyntaxKind.DefaultClause: { const start = skipTrivia(sourceFile.text, (node as CaseOrDefaultClause).pos); @@ -2253,15 +2235,15 @@ export function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpa } case SyntaxKind.ReturnStatement: case SyntaxKind.YieldExpression: { - const pos = skipTrivia(sourceFile.text, (node as ReturnStatement | YieldExpression).pos); + const pos = skipTrivia(sourceFile.text, node.pos); return getSpanOfTokenAtPosition(sourceFile, pos); } case SyntaxKind.SatisfiesExpression: { - const pos = skipTrivia(sourceFile.text, (node as SatisfiesExpression).expression.end); + const pos = skipTrivia(sourceFile.text, node.expression.end); return getSpanOfTokenAtPosition(sourceFile, pos); } case SyntaxKind.JSDocSatisfiesTag: { - const pos = skipTrivia(sourceFile.text, (node as JSDocSatisfiesTag).tagName.pos); + const pos = skipTrivia(sourceFile.text, node.tagName.pos); return getSpanOfTokenAtPosition(sourceFile, pos); } } @@ -2346,12 +2328,12 @@ export function isLet(node: Node): boolean { /** @internal */ export function isSuperCall(n: Node): n is SuperCall { - return n.kind === SyntaxKind.CallExpression && (n as CallExpression).expression.kind === SyntaxKind.SuperKeyword; + return n.kind === SyntaxKind.CallExpression && n.expression.kind === SyntaxKind.SuperKeyword; } /** @internal */ export function isImportCall(n: Node): n is ImportCall { - return n.kind === SyntaxKind.CallExpression && (n as CallExpression).expression.kind === SyntaxKind.ImportKeyword; + return n.kind === SyntaxKind.CallExpression && n.expression.kind === SyntaxKind.ImportKeyword; } /** @internal */ @@ -2369,7 +2351,7 @@ export function isLiteralImportTypeNode(n: Node): n is LiteralImportTypeNode { /** @internal */ export function isPrologueDirective(node: Node): node is PrologueDirective { return node.kind === SyntaxKind.ExpressionStatement - && (node as ExpressionStatement).expression.kind === SyntaxKind.StringLiteral; + && node.expression.kind === SyntaxKind.StringLiteral; } /** @internal */ @@ -2457,10 +2439,10 @@ export function isPartOfTypeNode(node: Node): boolean { // above them to find the lowest container case SyntaxKind.Identifier: // If the identifier is the RHS of a qualified name, then it's a type iff its parent is. - if (node.parent.kind === SyntaxKind.QualifiedName && (node.parent as QualifiedName).right === node) { + if (node.parent.kind === SyntaxKind.QualifiedName && node.parent.right === node) { node = node.parent; } - else if (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent as PropertyAccessExpression).name === node) { + else if (node.parent.kind === SyntaxKind.PropertyAccessExpression && node.parent.name === node) { node = node.parent; } // At this point, node is either a qualified name or an identifier @@ -2475,7 +2457,7 @@ export function isPartOfTypeNode(node: Node): boolean { return false; } if (parent.kind === SyntaxKind.ImportType) { - return !(parent as ImportTypeNode).isTypeOf; + return !parent.isTypeOf; } // Do not recursively call isPartOfTypeNode on the parent. In the example: // @@ -2490,9 +2472,9 @@ export function isPartOfTypeNode(node: Node): boolean { case SyntaxKind.ExpressionWithTypeArguments: return isHeritageClause(parent.parent) && !isExpressionWithTypeArgumentsInClassExtendsClause(parent); case SyntaxKind.TypeParameter: - return node === (parent as TypeParameterDeclaration).constraint; + return node === parent.constraint; case SyntaxKind.JSDocTemplateTag: - return node === (parent as JSDocTemplateTag).constraint; + return node === parent.constraint; case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: case SyntaxKind.Parameter: @@ -2512,7 +2494,7 @@ export function isPartOfTypeNode(node: Node): boolean { case SyntaxKind.IndexSignature: return node === (parent as SignatureDeclaration).type; case SyntaxKind.TypeAssertionExpression: - return node === (parent as TypeAssertion).type; + return node === parent.type; case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: case SyntaxKind.TaggedTemplateExpression: @@ -2544,7 +2526,7 @@ export function forEachReturnStatement(body: Block | Statement, visitor: (stm function traverse(node: Node): T | undefined { switch (node.kind) { case SyntaxKind.ReturnStatement: - return visitor(node as ReturnStatement); + return visitor(node); case SyntaxKind.CaseBlock: case SyntaxKind.Block: case SyntaxKind.IfStatement: @@ -2572,8 +2554,8 @@ export function forEachYieldExpression(body: Block, visitor: (expr: YieldExpress function traverse(node: Node): void { switch (node.kind) { case SyntaxKind.YieldExpression: - visitor(node as YieldExpression); - const operand = (node as YieldExpression).expression; + visitor(node); + const operand = node.expression; if (operand) { traverse(operand); } @@ -2613,10 +2595,10 @@ export function forEachYieldExpression(body: Block, visitor: (expr: YieldExpress */ export function getRestParameterElementType(node: TypeNode | undefined) { if (node && node.kind === SyntaxKind.ArrayType) { - return (node as ArrayTypeNode).elementType; + return node.elementType; } else if (node && node.kind === SyntaxKind.TypeReference) { - return singleOrUndefined((node as TypeReferenceNode).typeArguments); + return singleOrUndefined(node.typeArguments); } else { return undefined; @@ -2630,9 +2612,9 @@ export function getMembersOfDeclaration(node: Declaration): NodeArray nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent!)); + return some(node.members, m => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent!)); case SyntaxKind.ClassExpression: - return !useLegacyDecorators && some((node as ClassExpression).members, m => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent!)); + return !useLegacyDecorators && some(node.members, m => nodeOrChildIsDecorated(useLegacyDecorators, m, node, parent!)); case SyntaxKind.MethodDeclaration: case SyntaxKind.SetAccessor: case SyntaxKind.Constructor: @@ -3429,7 +3411,7 @@ export function isNamespaceReexportDeclaration(node: Node): boolean { /** @internal */ export function isExternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration & { moduleReference: ExternalModuleReference; } { - return node.kind === SyntaxKind.ImportEqualsDeclaration && (node as ImportEqualsDeclaration).moduleReference.kind === SyntaxKind.ExternalModuleReference; + return node.kind === SyntaxKind.ImportEqualsDeclaration && node.moduleReference.kind === SyntaxKind.ExternalModuleReference; } /** @internal */ @@ -3445,7 +3427,7 @@ export function getExternalModuleRequireArgument(node: Node) { /** @internal */ export function isInternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration { - return node.kind === SyntaxKind.ImportEqualsDeclaration && (node as ImportEqualsDeclaration).moduleReference.kind !== SyntaxKind.ExternalModuleReference; + return node.kind === SyntaxKind.ImportEqualsDeclaration && node.moduleReference.kind !== SyntaxKind.ExternalModuleReference; } /** @internal */ @@ -3502,9 +3484,9 @@ export function isRequireCall(callExpression: Node, requireStringLiteralLikeArgu if (callExpression.kind !== SyntaxKind.CallExpression) { return false; } - const { expression, arguments: args } = callExpression as CallExpression; + const { expression, arguments: args } = callExpression; - if (expression.kind !== SyntaxKind.Identifier || (expression as Identifier).escapedText !== "require") { + if (expression.kind !== SyntaxKind.Identifier || expression.escapedText !== "require") { return false; } @@ -4012,7 +3994,7 @@ export function tryGetImportFromModuleSpecifier(node: StringLiteralLike): AnyVal case SyntaxKind.ExportDeclaration: return node.parent as AnyValidImportOrReExport; case SyntaxKind.ExternalModuleReference: - return (node.parent as ExternalModuleReference).parent as AnyValidImportOrReExport; + return node.parent.parent as AnyValidImportOrReExport; case SyntaxKind.CallExpression: return isImportCall(node.parent) || isRequireCall(node.parent, /*requireStringLiteralLikeArgument*/ false) ? node.parent as RequireOrImportCall : undefined; case SyntaxKind.LiteralType: @@ -4135,9 +4117,9 @@ export function getSingleInitializerOfVariableStatementOrPropertyDeclaration(nod const v = getSingleVariableOfVariableStatement(node); return v && v.initializer; case SyntaxKind.PropertyDeclaration: - return (node as PropertyDeclaration).initializer; + return node.initializer; case SyntaxKind.PropertyAssignment: - return (node as PropertyAssignment).initializer; + return node.initializer; } } @@ -4292,11 +4274,11 @@ export function getJSDocCommentsAndTags(hostNode: Node, noCache?: boolean): read } if (node.kind === SyntaxKind.Parameter) { - result = addRange(result, (noCache ? getJSDocParameterTagsNoCache : getJSDocParameterTags)(node as ParameterDeclaration)); + result = addRange(result, (noCache ? getJSDocParameterTagsNoCache : getJSDocParameterTags)(node)); break; } if (node.kind === SyntaxKind.TypeParameter) { - result = addRange(result, (noCache ? getJSDocTypeParameterTagsNoCache : getJSDocTypeParameterTags)(node as TypeParameterDeclaration)); + result = addRange(result, (noCache ? getJSDocTypeParameterTagsNoCache : getJSDocTypeParameterTags)(node)); break; } node = getNextJSDocCommentLocation(node); @@ -4541,7 +4523,7 @@ export function isAssignmentTarget(node: Node): boolean { function isCompoundLikeAssignment(assignment: AssignmentExpression): boolean { const right = skipParentheses(assignment.right); - return right.kind === SyntaxKind.BinaryExpression && isShiftOperatorOrHigher((right as BinaryExpression).operatorToken.kind); + return right.kind === SyntaxKind.BinaryExpression && isShiftOperatorOrHigher(right.operatorToken.kind); } /** @internal */ @@ -4638,7 +4620,7 @@ export function walkUpParenthesizedExpressions(node: Node) { export function walkUpParenthesizedTypesAndGetParentAndChild(node: Node): [ParenthesizedTypeNode | undefined, Node] { let child: ParenthesizedTypeNode | undefined; while (node && node.kind === SyntaxKind.ParenthesizedType) { - child = node as ParenthesizedTypeNode; + child = node; node = node.parent; } return [child, node]; @@ -4746,11 +4728,11 @@ export function isIdentifierName(node: Identifier): boolean { return (parent as NamedDeclaration | PropertyAccessExpression).name === node; case SyntaxKind.QualifiedName: // Name on right hand side of dot in a type query or type reference - return (parent as QualifiedName).right === node; + return parent.right === node; case SyntaxKind.BindingElement: case SyntaxKind.ImportSpecifier: // Property name in binding element or import specifier - return (parent as BindingElement | ImportSpecifier).propertyName === node; + return parent.propertyName === node; case SyntaxKind.ExportSpecifier: case SyntaxKind.JsxAttribute: case SyntaxKind.JsxSelfClosingElement: @@ -4782,12 +4764,12 @@ export function isAliasSymbolDeclaration(node: Node): boolean { if ( node.kind === SyntaxKind.ImportEqualsDeclaration || node.kind === SyntaxKind.NamespaceExportDeclaration || - node.kind === SyntaxKind.ImportClause && !!(node as ImportClause).name || + node.kind === SyntaxKind.ImportClause && !!node.name || node.kind === SyntaxKind.NamespaceImport || node.kind === SyntaxKind.NamespaceExport || node.kind === SyntaxKind.ImportSpecifier || node.kind === SyntaxKind.ExportSpecifier || - node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node as ExportAssignment) + node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) ) { return true; } @@ -4812,10 +4794,10 @@ export function getAliasDeclarationFromName(node: EntityName): Declaration | und case SyntaxKind.ExportAssignment: case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.NamespaceExport: - return node.parent as Declaration; + return node.parent; case SyntaxKind.QualifiedName: do { - node = node.parent as QualifiedName; + node = node.parent; } while (node.parent.kind === SyntaxKind.QualifiedName); return getAliasDeclarationFromName(node); @@ -5042,7 +5024,7 @@ export function isSignedNumericLiteral(node: Node): node is PrefixUnaryExpressio * * @internal */ -export function hasDynamicName(declaration: Declaration): declaration is DynamicNamedDeclaration | DynamicNamedBinaryExpression { +export function hasDynamicName(declaration: Declaration): declaration is DynamicNamedDeclaration | DynamicNamedBinaryExpressionBase { const name = getNameOfDeclaration(declaration); return !!name && isDynamicName(name); } @@ -5134,7 +5116,7 @@ export function isPrivateIdentifierSymbol(symbol: Symbol): boolean { * @internal */ export function isESSymbolIdentifier(node: Node): boolean { - return node.kind === SyntaxKind.Identifier && (node as Identifier).escapedText === "Symbol"; + return node.kind === SyntaxKind.Identifier && node.escapedText === "Symbol"; } /** @@ -5166,12 +5148,12 @@ export function isAnonymousFunctionDefinition(node: Expression, cb?: (node: Anon node = skipOuterExpressions(node); switch (node.kind) { case SyntaxKind.ClassExpression: - if (classHasDeclaredOrExplicitlyAssignedName(node as ClassExpression)) { + if (classHasDeclaredOrExplicitlyAssignedName(node)) { return false; } break; case SyntaxKind.FunctionExpression: - if ((node as FunctionExpression).name) { + if (node.name) { return false; } break; @@ -5202,24 +5184,24 @@ export type NamedEvaluationSource = export function isNamedEvaluationSource(node: Node): node is NamedEvaluationSource { switch (node.kind) { case SyntaxKind.PropertyAssignment: - return !isProtoSetter((node as PropertyAssignment).name); + return !isProtoSetter(node.name); case SyntaxKind.ShorthandPropertyAssignment: - return !!(node as ShorthandPropertyAssignment).objectAssignmentInitializer; + return !!node.objectAssignmentInitializer; case SyntaxKind.VariableDeclaration: - return isIdentifier((node as VariableDeclaration).name) && !!(node as VariableDeclaration).initializer; + return isIdentifier(node.name) && !!node.initializer; case SyntaxKind.Parameter: - return isIdentifier((node as ParameterDeclaration).name) && !!(node as VariableDeclaration).initializer && !(node as BindingElement).dotDotDotToken; + return isIdentifier(node.name) && !!(node as VariableDeclaration).initializer && !(node as BindingElement).dotDotDotToken; case SyntaxKind.BindingElement: - return isIdentifier((node as BindingElement).name) && !!(node as VariableDeclaration).initializer && !(node as BindingElement).dotDotDotToken; + return isIdentifier(node.name) && !!(node as VariableDeclaration).initializer && !node.dotDotDotToken; case SyntaxKind.PropertyDeclaration: - return !!(node as PropertyDeclaration).initializer; + return !!node.initializer; case SyntaxKind.BinaryExpression: - switch ((node as BinaryExpression).operatorToken.kind) { + switch (node.operatorToken.kind) { case SyntaxKind.EqualsToken: case SyntaxKind.AmpersandAmpersandEqualsToken: case SyntaxKind.BarBarEqualsToken: case SyntaxKind.QuestionQuestionEqualsToken: - return isIdentifier((node as BinaryExpression).left); + return isIdentifier(node.left); } break; case SyntaxKind.ExportAssignment: @@ -5325,7 +5307,7 @@ export const enum Associativity { /** @internal */ export function getExpressionAssociativity(expression: Expression) { const operator = getOperator(expression); - const hasArguments = expression.kind === SyntaxKind.NewExpression && (expression as NewExpression).arguments !== undefined; + const hasArguments = expression.kind === SyntaxKind.NewExpression && expression.arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } @@ -5372,17 +5354,17 @@ export function getOperatorAssociativity(kind: SyntaxKind, operator: SyntaxKind, /** @internal */ export function getExpressionPrecedence(expression: Expression) { const operator = getOperator(expression); - const hasArguments = expression.kind === SyntaxKind.NewExpression && (expression as NewExpression).arguments !== undefined; + const hasArguments = expression.kind === SyntaxKind.NewExpression && expression.arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } /** @internal */ export function getOperator(expression: Expression): SyntaxKind { if (expression.kind === SyntaxKind.BinaryExpression) { - return (expression as BinaryExpression).operatorToken.kind; + return expression.operatorToken.kind; } else if (expression.kind === SyntaxKind.PrefixUnaryExpression || expression.kind === SyntaxKind.PostfixUnaryExpression) { - return (expression as PrefixUnaryExpression | PostfixUnaryExpression).operator; + return expression.operator; } else { return expression.kind; @@ -6480,7 +6462,7 @@ export function parameterIsThisKeyword(parameter: ParameterDeclaration): boolean /** @internal */ export function isThisIdentifier(node: Node | undefined): boolean { - return !!node && node.kind === SyntaxKind.Identifier && identifierIsThisKeyword(node as Identifier); + return !!node && node.kind === SyntaxKind.Identifier && identifierIsThisKeyword(node); } /** @internal */ @@ -6513,7 +6495,7 @@ export function identifierIsThisKeyword(id: Identifier): boolean { } /** @internal */ -export function getAllAccessorDeclarations(declarations: readonly Declaration[], accessor: AccessorDeclaration): AllAccessorDeclarations { +export function getAllAccessorDeclarations(declarations: readonly DeclarationBase[], accessor: AccessorDeclaration): AllAccessorDeclarations { // TODO: GH#18217 let firstAccessor!: AccessorDeclaration; let secondAccessor!: AccessorDeclaration; @@ -7185,8 +7167,8 @@ export function isDottedName(node: Expression): boolean { || node.kind === SyntaxKind.ThisKeyword || node.kind === SyntaxKind.SuperKeyword || node.kind === SyntaxKind.MetaProperty - || node.kind === SyntaxKind.PropertyAccessExpression && isDottedName((node as PropertyAccessExpression).expression) - || node.kind === SyntaxKind.ParenthesizedExpression && isDottedName((node as ParenthesizedExpression).expression); + || node.kind === SyntaxKind.PropertyAccessExpression && isDottedName(node.expression) + || node.kind === SyntaxKind.ParenthesizedExpression && isDottedName(node.expression); } /** @internal */ @@ -7254,13 +7236,13 @@ export function isRightSideOfInstanceofExpression(node: Node) { /** @internal */ export function isEmptyObjectLiteral(expression: Node): boolean { return expression.kind === SyntaxKind.ObjectLiteralExpression && - (expression as ObjectLiteralExpression).properties.length === 0; + expression.properties.length === 0; } /** @internal */ export function isEmptyArrayLiteral(expression: Node): boolean { return expression.kind === SyntaxKind.ArrayLiteralExpression && - (expression as ArrayLiteralExpression).elements.length === 0; + expression.elements.length === 0; } /** @internal */ @@ -7744,23 +7726,23 @@ function accessKind(node: Node): AccessKind { return accessKind(parent); case SyntaxKind.PostfixUnaryExpression: case SyntaxKind.PrefixUnaryExpression: - const { operator } = parent as PrefixUnaryExpression | PostfixUnaryExpression; + const { operator } = parent; return operator === SyntaxKind.PlusPlusToken || operator === SyntaxKind.MinusMinusToken ? AccessKind.ReadWrite : AccessKind.Read; case SyntaxKind.BinaryExpression: - const { left, operatorToken } = parent as BinaryExpression; + const { left, operatorToken } = parent; return left === node && isAssignmentOperator(operatorToken.kind) ? operatorToken.kind === SyntaxKind.EqualsToken ? AccessKind.Write : AccessKind.ReadWrite : AccessKind.Read; case SyntaxKind.PropertyAccessExpression: - return (parent as PropertyAccessExpression).name !== node ? AccessKind.Read : accessKind(parent); + return parent.name !== node ? AccessKind.Read : accessKind(parent); case SyntaxKind.PropertyAssignment: { const parentAccess = accessKind(parent.parent); // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write. - return node === (parent as PropertyAssignment).name ? reverseAccessKind(parentAccess) : parentAccess; + return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess; } case SyntaxKind.ShorthandPropertyAssignment: // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals. - return node === (parent as ShorthandPropertyAssignment).objectAssignmentInitializer ? AccessKind.Read : accessKind(parent.parent); + return node === parent.objectAssignmentInitializer ? AccessKind.Read : accessKind(parent.parent); case SyntaxKind.ArrayLiteralExpression: return accessKind(parent); default: @@ -8054,19 +8036,19 @@ export function getLeftmostExpression(node: Expression, stopAtCallExpressions: b while (true) { switch (node.kind) { case SyntaxKind.PostfixUnaryExpression: - node = (node as PostfixUnaryExpression).operand; + node = node.operand; continue; case SyntaxKind.BinaryExpression: - node = (node as BinaryExpression).left; + node = node.left; continue; case SyntaxKind.ConditionalExpression: - node = (node as ConditionalExpression).condition; + node = node.condition; continue; case SyntaxKind.TaggedTemplateExpression: - node = (node as TaggedTemplateExpression).tag; + node = node.tag; continue; case SyntaxKind.CallExpression: @@ -8080,7 +8062,7 @@ export function getLeftmostExpression(node: Expression, stopAtCallExpressions: b case SyntaxKind.NonNullExpression: case SyntaxKind.PartiallyEmittedExpression: case SyntaxKind.SatisfiesExpression: - node = (node as CallExpression | PropertyAccessExpression | ElementAccessExpression | AsExpression | NonNullExpression | PartiallyEmittedExpression | SatisfiesExpression).expression; + node = node.expression; continue; } @@ -8091,7 +8073,7 @@ export function getLeftmostExpression(node: Expression, stopAtCallExpressions: b /** @internal */ export interface ObjectAllocator { getNodeConstructor(): new (kind: SyntaxKind, pos: number, end: number) => Node; - getTokenConstructor(): new (kind: TKind, pos: number, end: number) => Token; + getTokenConstructor(): new (kind: TKind, pos: number, end: number) => Token; getIdentifierConstructor(): new (kind: SyntaxKind.Identifier, pos: number, end: number) => Identifier; getPrivateIdentifierConstructor(): new (kind: SyntaxKind.PrivateIdentifier, pos: number, end: number) => PrivateIdentifier; getSourceFileConstructor(): new (kind: SyntaxKind.SourceFile, pos: number, end: number) => SourceFile; @@ -10075,21 +10057,21 @@ export function getContainingNodeArray(node: Node): NodeArray | undefined if (!node.parent) return undefined; switch (node.kind) { case SyntaxKind.TypeParameter: - const { parent } = node as TypeParameterDeclaration; + const { parent } = node; return parent.kind === SyntaxKind.InferType ? undefined : parent.typeParameters; case SyntaxKind.Parameter: - return (node as ParameterDeclaration).parent.parameters; + return node.parent.parameters; case SyntaxKind.TemplateLiteralTypeSpan: - return (node as TemplateLiteralTypeSpan).parent.templateSpans; + return node.parent.templateSpans; case SyntaxKind.TemplateSpan: - return (node as TemplateSpan).parent.templateSpans; + return node.parent.templateSpans; case SyntaxKind.Decorator: { - const { parent } = node as Decorator; + const { parent } = node; return canHaveDecorators(parent) ? parent.modifiers : undefined; } case SyntaxKind.HeritageClause: - return (node as HeritageClause).parent.heritageClauses; + return node.parent.heritageClauses; } const { parent } = node; @@ -10100,7 +10082,7 @@ export function getContainingNodeArray(node: Node): NodeArray | undefined switch (parent.kind) { case SyntaxKind.TypeLiteral: case SyntaxKind.InterfaceDeclaration: - return isTypeElement(node) ? (parent as TypeLiteralNode | InterfaceDeclaration).members : undefined; + return isTypeElement(node) ? parent.members : undefined; case SyntaxKind.UnionType: case SyntaxKind.IntersectionType: return (parent as UnionOrIntersectionTypeNode).types; @@ -10109,35 +10091,35 @@ export function getContainingNodeArray(node: Node): NodeArray | undefined case SyntaxKind.CommaListExpression: case SyntaxKind.NamedImports: case SyntaxKind.NamedExports: - return (parent as TupleTypeNode | ArrayLiteralExpression | CommaListExpression | NamedImports | NamedExports).elements; + return parent.elements; case SyntaxKind.ObjectLiteralExpression: case SyntaxKind.JsxAttributes: return (parent as ObjectLiteralExpressionBase).properties; case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: - return isTypeNode(node) ? (parent as CallExpression | NewExpression).typeArguments : - (parent as CallExpression | NewExpression).expression === node ? undefined : - (parent as CallExpression | NewExpression).arguments; + return isTypeNode(node) ? parent.typeArguments : + parent.expression === node ? undefined : + parent.arguments; case SyntaxKind.JsxElement: case SyntaxKind.JsxFragment: - return isJsxChild(node) ? (parent as JsxElement | JsxFragment).children : undefined; + return isJsxChild(node) ? parent.children : undefined; case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxSelfClosingElement: - return isTypeNode(node) ? (parent as JsxOpeningElement | JsxSelfClosingElement).typeArguments : undefined; + return isTypeNode(node) ? parent.typeArguments : undefined; case SyntaxKind.Block: case SyntaxKind.CaseClause: case SyntaxKind.DefaultClause: case SyntaxKind.ModuleBlock: return (parent as Block | CaseOrDefaultClause | ModuleBlock).statements; case SyntaxKind.CaseBlock: - return (parent as CaseBlock).clauses; + return parent.clauses; case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: return isClassElement(node) ? (parent as ClassLikeDeclaration).members : undefined; case SyntaxKind.EnumDeclaration: - return isEnumMember(node) ? (parent as EnumDeclaration).members : undefined; + return isEnumMember(node) ? parent.members : undefined; case SyntaxKind.SourceFile: - return (parent as SourceFile).statements; + return parent.statements; } } @@ -10310,10 +10292,10 @@ export function isTypeDeclaration(node: Node): node is TypeParameterDeclaration case SyntaxKind.JSDocEnumTag: return true; case SyntaxKind.ImportClause: - return (node as ImportClause).isTypeOnly; + return node.isTypeOnly; case SyntaxKind.ImportSpecifier: case SyntaxKind.ExportSpecifier: - return (node as ImportSpecifier | ExportSpecifier).parent.parent.isTypeOnly; + return node.parent.parent.isTypeOnly; default: return false; } @@ -10364,9 +10346,9 @@ export function isOptionalDeclaration(declaration: Declaration): boolean { switch (declaration.kind) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - return !!(declaration as PropertyDeclaration | PropertySignature).questionToken; + return !!declaration.questionToken; case SyntaxKind.Parameter: - return !!(declaration as ParameterDeclaration).questionToken || isJSDocOptionalParameter(declaration as ParameterDeclaration); + return !!declaration.questionToken || isJSDocOptionalParameter(declaration); case SyntaxKind.JSDocPropertyTag: case SyntaxKind.JSDocParameterTag: return isOptionalJSDocPropertyLikeTag(declaration); diff --git a/src/compiler/utilitiesPublic.ts b/src/compiler/utilitiesPublic.ts index 98830e1a73961..fc278c222f8ed 100644 --- a/src/compiler/utilitiesPublic.ts +++ b/src/compiler/utilitiesPublic.ts @@ -47,14 +47,11 @@ import { Diagnostic, Diagnostics, ElementAccessChain, - ElementAccessExpression, emptyArray, EntityName, entityNameToString, EnumDeclaration, every, - ExportAssignment, - ExportDeclaration, ExportSpecifier, Expression, FileReference, @@ -92,8 +89,6 @@ import { HasType, Identifier, ImportAttributeName, - ImportClause, - ImportEqualsDeclaration, ImportSpecifier, ImportTypeNode, isAccessExpression, @@ -219,11 +214,10 @@ import { NamedExportBindings, NamedImportBindings, NamespaceBody, - NamespaceExport, - NamespaceImport, NewExpression, Node, NodeArray, + NodeBase, NodeFlags, NonNullChain, normalizePath, @@ -292,7 +286,9 @@ export function isExternalModuleNameRelative(moduleName: string): boolean { return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } -export function sortAndDeduplicateDiagnostics(diagnostics: readonly T[]): SortedReadonlyArray { +export function sortAndDeduplicateDiagnostics( + diagnostics: readonly T[], +): SortedReadonlyArray { return sortAndDeduplicate(diagnostics, compareDiagnostics); } @@ -334,7 +330,10 @@ export function textSpanContainsPosition(span: TextSpan, position: number) { } /** @internal */ -export function textRangeContainsPositionInclusive(span: TextRange, position: number): boolean { +export function textRangeContainsPositionInclusive( + span: TextRange, + position: number, +): boolean { return position >= span.pos && position <= span.end; } @@ -347,30 +346,61 @@ export function textSpanOverlapsWith(span: TextSpan, other: TextSpan) { return textSpanOverlap(span, other) !== undefined; } -export function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan | undefined { +export function textSpanOverlap( + span1: TextSpan, + span2: TextSpan, +): TextSpan | undefined { const overlap = textSpanIntersection(span1, span2); return overlap && overlap.length === 0 ? undefined : overlap; } -export function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan) { - return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length); -} - -export function textSpanIntersectsWith(span: TextSpan, start: number, length: number) { - return decodedTextSpanIntersectsWith(span.start, span.length, start, length); -} - -export function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number) { +export function textSpanIntersectsWithTextSpan( + span: TextSpan, + other: TextSpan, +) { + return decodedTextSpanIntersectsWith( + span.start, + span.length, + other.start, + other.length, + ); +} + +export function textSpanIntersectsWith( + span: TextSpan, + start: number, + length: number, +) { + return decodedTextSpanIntersectsWith( + span.start, + span.length, + start, + length, + ); +} + +export function decodedTextSpanIntersectsWith( + start1: number, + length1: number, + start2: number, + length2: number, +) { const end1 = start1 + length1; const end2 = start2 + length2; return start2 <= end1 && end2 >= start1; } -export function textSpanIntersectsWithPosition(span: TextSpan, position: number) { +export function textSpanIntersectsWithPosition( + span: TextSpan, + position: number, +) { return position <= textSpanEnd(span) && position >= span.start; } -export function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan | undefined { +export function textSpanIntersection( + span1: TextSpan, + span2: TextSpan, +): TextSpan | undefined { const start = Math.max(span1.start, span2.start); const end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); return start <= end ? createTextSpanFromBounds(start, end) : undefined; @@ -399,7 +429,10 @@ export function textChangeRangeIsUnchanged(range: TextChangeRange) { return textSpanIsEmpty(range.span) && range.newLength === 0; } -export function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange { +export function createTextChangeRange( + span: TextSpan, + newLength: number, +): TextChangeRange { if (newLength < 0) { throw new Error("newLength < 0"); } @@ -407,7 +440,10 @@ export function createTextChangeRange(span: TextSpan, newLength: number): TextCh return { span, newLength }; } -export const unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); +export const unchangedTextChangeRange = createTextChangeRange( + createTextSpan(0, 0), + 0, +); /** * Called to merge all the changes that occurred across several versions of a script snapshot @@ -417,7 +453,9 @@ export const unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, * This function will then merge those changes into a single change range valid between V1 and * Vn. */ -export function collapseTextChangeRangesAcrossMultipleVersions(changes: readonly TextChangeRange[]): TextChangeRange { +export function collapseTextChangeRangesAcrossMultipleVersions( + changes: readonly TextChangeRange[], +): TextChangeRange { if (changes.length === 0) { return unchangedTextChangeRange; } @@ -530,26 +568,45 @@ export function collapseTextChangeRangesAcrossMultipleVersions(changes: readonly newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); } - return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN); + return createTextChangeRange( + createTextSpanFromBounds(oldStartN, oldEndN), + /*newLength*/ newEndN - oldStartN, + ); } export function getTypeParameterOwner(d: Declaration): Declaration | undefined { if (d && d.kind === SyntaxKind.TypeParameter) { for (let current: Node = d; current; current = current.parent) { - if (isFunctionLike(current) || isClassLike(current) || current.kind === SyntaxKind.InterfaceDeclaration) { + if ( + isFunctionLike(current) || + isClassLike(current) || + current.kind === SyntaxKind.InterfaceDeclaration + ) { return current as Declaration; } } } } -export type ParameterPropertyDeclaration = ParameterDeclaration & { parent: ConstructorDeclaration; name: Identifier; }; +export type ParameterPropertyDeclaration = ParameterDeclaration & { + parent: ConstructorDeclaration; + name: Identifier; +}; -export function isParameterPropertyDeclaration(node: Node, parent: Node): node is ParameterPropertyDeclaration { - return isParameter(node) && hasSyntacticModifier(node, ModifierFlags.ParameterPropertyModifier) && parent.kind === SyntaxKind.Constructor; +export function isParameterPropertyDeclaration( + node: Node, + parent: Node, +): node is ParameterPropertyDeclaration { + return ( + isParameter(node) && + hasSyntacticModifier(node, ModifierFlags.ParameterPropertyModifier) && + parent.kind === SyntaxKind.Constructor + ); } -export function isEmptyBindingPattern(node: BindingName): node is BindingPattern { +export function isEmptyBindingPattern( + node: BindingName, +): node is BindingPattern { if (isBindingPattern(node)) { return every(node.elements, isEmptyBindingElement); } @@ -559,14 +616,18 @@ export function isEmptyBindingPattern(node: BindingName): node is BindingPattern // TODO(jakebailey): It is very weird that we have BindingElement and ArrayBindingElement; // we should have ObjectBindingElement and ArrayBindingElement, which are both BindingElement, // just like BindingPattern is a ObjectBindingPattern or a ArrayBindingPattern. -export function isEmptyBindingElement(node: BindingElement | ArrayBindingElement): boolean { +export function isEmptyBindingElement( + node: BindingElement | ArrayBindingElement, +): boolean { if (isOmittedExpression(node)) { return true; } return isEmptyBindingPattern(node.name); } -export function walkUpBindingElementsAndPatterns(binding: BindingElement): VariableDeclaration | ParameterDeclaration { +export function walkUpBindingElementsAndPatterns( + binding: BindingElement, +): VariableDeclaration | ParameterDeclaration { let node = binding.parent; while (isBindingElement(node.parent)) { node = node.parent.parent; @@ -597,7 +658,9 @@ export function getCombinedModifierFlags(node: Declaration): ModifierFlags { } /** @internal */ -export function getCombinedNodeFlagsAlwaysIncludeJSDoc(node: Declaration): ModifierFlags { +export function getCombinedNodeFlagsAlwaysIncludeJSDoc( + node: Declaration, +): ModifierFlags { return getCombinedFlags(node, getEffectiveModifierFlagsAlwaysIncludeJSDoc); } @@ -617,7 +680,21 @@ function getNodeFlags(node: Node) { } /** @internal */ -export const supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; +export const supportedLocaleDirectories = [ + "cs", + "de", + "es", + "fr", + "it", + "ja", + "ko", + "pl", + "pt-br", + "ru", + "tr", + "zh-cn", + "zh-tw", +]; /** * Checks to see if the locale is in the appropriate format, @@ -625,7 +702,12 @@ export const supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", " */ export function validateLocaleAndSetLanguage( locale: string, - sys: { getExecutingFilePath(): string; resolvePath(path: string): string; fileExists(fileName: string): boolean; readFile(fileName: string): string | undefined; }, + sys: { + getExecutingFilePath(): string; + resolvePath(path: string): string; + fileExists(fileName: string): boolean; + readFile(fileName: string): string | undefined; + }, errors?: Diagnostic[], ) { const lowerCaseLocale = locale.toLowerCase(); @@ -633,7 +715,13 @@ export function validateLocaleAndSetLanguage( if (!matchResult) { if (errors) { - errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); + errors.push( + createCompilerDiagnostic( + Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, + "en", + "ja-jp", + ), + ); } return; } @@ -643,14 +731,21 @@ export function validateLocaleAndSetLanguage( // First try the entire locale, then fall back to just language if that's all we have. // Either ways do not fail, and fallback to the English diagnostic strings. - if (contains(supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { + if ( + contains(supportedLocaleDirectories, lowerCaseLocale) && + !trySetLanguageAndTerritory(language, territory, errors) + ) { trySetLanguageAndTerritory(language, /*territory*/ undefined, errors); } // Set the UI locale for string collation setUILocale(locale); - function trySetLanguageAndTerritory(language: string, territory: string | undefined, errors?: Diagnostic[]): boolean { + function trySetLanguageAndTerritory( + language: string, + territory: string | undefined, + errors?: Diagnostic[], + ): boolean { const compilerFilePath = normalizePath(sys.getExecutingFilePath()); const containingDirectoryPath = getDirectoryPath(compilerFilePath); @@ -660,7 +755,9 @@ export function validateLocaleAndSetLanguage( filePath = filePath + "-" + territory; } - filePath = sys.resolvePath(combinePaths(filePath, "diagnosticMessages.generated.json")); + filePath = sys.resolvePath( + combinePaths(filePath, "diagnosticMessages.generated.json"), + ); if (!sys.fileExists(filePath)) { return false; @@ -673,7 +770,12 @@ export function validateLocaleAndSetLanguage( } catch (e) { if (errors) { - errors.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath)); + errors.push( + createCompilerDiagnostic( + Diagnostics.Unable_to_open_file_0, + filePath, + ), + ); } return false; } @@ -683,7 +785,12 @@ export function validateLocaleAndSetLanguage( } catch { if (errors) { - errors.push(createCompilerDiagnostic(Diagnostics.Corrupted_locale_file_0, filePath)); + errors.push( + createCompilerDiagnostic( + Diagnostics.Corrupted_locale_file_0, + filePath, + ), + ); } return false; } @@ -693,10 +800,19 @@ export function validateLocaleAndSetLanguage( } export function getOriginalNode(node: Node): Node; -export function getOriginalNode(node: Node, nodeTest: (node: Node) => node is T): T; +export function getOriginalNode( + node: Node, + nodeTest: (node: Node) => node is T, +): T; export function getOriginalNode(node: Node | undefined): Node | undefined; -export function getOriginalNode(node: Node | undefined, nodeTest: (node: Node) => node is T): T | undefined; -export function getOriginalNode(node: Node | undefined, nodeTest?: (node: Node) => node is T): T | undefined { +export function getOriginalNode( + node: Node | undefined, + nodeTest: (node: Node) => node is T, +): T | undefined; +export function getOriginalNode( + node: Node | undefined, + nodeTest?: (node: Node) => node is T, +): T | undefined { if (node) { while (node.original !== undefined) { node = node.original; @@ -716,9 +832,18 @@ export function getOriginalNode(node: Node | undefined, nodeTest * If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit" * At that point findAncestor returns undefined. */ -export function findAncestor(node: Node | undefined, callback: (element: Node) => element is T): T | undefined; -export function findAncestor(node: Node | undefined, callback: (element: Node) => boolean | "quit"): Node | undefined; -export function findAncestor(node: Node | undefined, callback: (element: Node) => boolean | "quit"): Node | undefined { +export function findAncestor( + node: Node | undefined, + callback: (element: Node) => element is T, +): T | undefined; +export function findAncestor( + node: Node | undefined, + callback: (element: Node) => boolean | "quit", +): Node | undefined; +export function findAncestor( + node: Node | undefined, + callback: (element: Node) => boolean | "quit", +): Node | undefined { while (node) { const result = callback(node); if (result === "quit") { @@ -756,8 +881,14 @@ export function getParseTreeNode(node: Node | undefined): Node | undefined; * @param nodeTest A callback used to ensure the correct type of parse tree node is returned. * @returns The original parse tree node if found; otherwise, undefined. */ -export function getParseTreeNode(node: T | undefined, nodeTest?: (node: Node) => node is T): T | undefined; -export function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) => boolean): Node | undefined { +export function getParseTreeNode( + node: T | undefined, + nodeTest?: (node: Node) => node is T, +): T | undefined; +export function getParseTreeNode( + node: Node | undefined, + nodeTest?: (node: Node) => boolean, +): Node | undefined { if (node === undefined || isParseTreeNode(node)) { return node; } @@ -773,7 +904,13 @@ export function getParseTreeNode(node: Node | undefined, nodeTest?: (node: Node) /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */ export function escapeLeadingUnderscores(identifier: string): __String { - return (identifier.length >= 2 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ ? "_" + identifier : identifier) as __String; + return ( + identifier.length >= 2 && + identifier.charCodeAt(0) === CharacterCodes._ && + identifier.charCodeAt(1) === CharacterCodes._ + ? "_" + identifier + : identifier + ) as __String; } /** @@ -784,10 +921,17 @@ export function escapeLeadingUnderscores(identifier: string): __String { */ 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.substr(1) : id; + return id.length >= 3 && + id.charCodeAt(0) === CharacterCodes._ && + id.charCodeAt(1) === CharacterCodes._ && + id.charCodeAt(2) === CharacterCodes._ + ? id.substr(1) + : id; } -export function idText(identifierOrPrivateName: Identifier | PrivateIdentifier): string { +export function idText( + identifierOrPrivateName: Identifier | PrivateIdentifier, +): string { return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText); } @@ -795,13 +939,18 @@ export function idText(identifierOrPrivateName: Identifier | PrivateIdentifier): * If the text of an Identifier matches a keyword (including contextual and TypeScript-specific keywords), returns the * SyntaxKind for the matching keyword. */ -export function identifierToKeywordKind(node: Identifier): KeywordSyntaxKind | undefined { +export function identifierToKeywordKind( + node: Identifier, +): KeywordSyntaxKind | undefined { const token = stringToToken(node.escapedText as string); return token ? tryCast(token, isKeyword) : undefined; } export function symbolName(symbol: Symbol): string { - if (symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { + if ( + symbol.valueDeclaration && + isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration) + ) { return idText(symbol.valueDeclaration.name); } return unescapeLeadingUnderscores(symbol.escapedName); @@ -812,7 +961,9 @@ export function symbolName(symbol: Symbol): string { * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol * will be merged with) */ -function nameForNamelessJSDocTypedef(declaration: JSDocTypedefTag | JSDocEnumTag): Identifier | PrivateIdentifier | undefined { +function nameForNamelessJSDocTypedef( + declaration: JSDocTypedefTag | JSDocEnumTag, +): Identifier | PrivateIdentifier | undefined { const hostNode = declaration.parent.parent; if (!hostNode) { return undefined; @@ -824,20 +975,30 @@ function nameForNamelessJSDocTypedef(declaration: JSDocTypedefTag | JSDocEnumTag // Covers remaining cases (returning undefined if none match). switch (hostNode.kind) { case SyntaxKind.VariableStatement: - if (hostNode.declarationList && hostNode.declarationList.declarations[0]) { - return getDeclarationIdentifier(hostNode.declarationList.declarations[0]); + if ( + hostNode.declarationList && + hostNode.declarationList.declarations[0] + ) { + return getDeclarationIdentifier( + hostNode.declarationList.declarations[0], + ); } break; case SyntaxKind.ExpressionStatement: let expr = hostNode.expression; - if (expr.kind === SyntaxKind.BinaryExpression && (expr as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) { - expr = (expr as BinaryExpression).left; + if ( + expr.kind === SyntaxKind.BinaryExpression && + expr.operatorToken.kind === + SyntaxKind.EqualsToken + ) { + expr = expr.left; } switch (expr.kind) { case SyntaxKind.PropertyAccessExpression: - return (expr as PropertyAccessExpression).name; + return expr.name; case SyntaxKind.ElementAccessExpression: - const arg = (expr as ElementAccessExpression).argumentExpression; + const arg = expr + .argumentExpression; if (isIdentifier(arg)) { return arg; } @@ -847,7 +1008,10 @@ function nameForNamelessJSDocTypedef(declaration: JSDocTypedefTag | JSDocEnumTag return getDeclarationIdentifier(hostNode.expression); } case SyntaxKind.LabeledStatement: { - if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) { + if ( + isDeclaration(hostNode.statement) || + isExpression(hostNode.statement) + ) { return getDeclarationIdentifier(hostNode.statement); } break; @@ -855,39 +1019,54 @@ function nameForNamelessJSDocTypedef(declaration: JSDocTypedefTag | JSDocEnumTag } } -function getDeclarationIdentifier(node: Declaration | Expression): Identifier | undefined { +function getDeclarationIdentifier( + node: Declaration | Expression, +): Identifier | undefined { const name = getNameOfDeclaration(node); return name && isIdentifier(name) ? name : undefined; } /** @internal */ export function nodeHasName(statement: Node, name: Identifier) { - if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name as Identifier) === idText(name)) { + if ( + isNamedDeclaration(statement) && + isIdentifier(statement.name) && + idText(statement.name as Identifier) === idText(name) + ) { return true; } - if (isVariableStatement(statement) && some(statement.declarationList.declarations, d => nodeHasName(d, name))) { + if ( + isVariableStatement(statement) && + some(statement.declarationList.declarations, d => nodeHasName(d, name)) + ) { return true; } return false; } -export function getNameOfJSDocTypedef(declaration: JSDocTypedefTag): Identifier | PrivateIdentifier | undefined { +export function getNameOfJSDocTypedef( + declaration: JSDocTypedefTag, +): Identifier | PrivateIdentifier | undefined { return declaration.name || nameForNamelessJSDocTypedef(declaration); } /** @internal */ -export function isNamedDeclaration(node: Node): node is NamedDeclaration & { name: DeclarationName; } { +export function isNamedDeclaration( + node: Node, +): node is NamedDeclaration & { name: DeclarationName; } { return !!(node as NamedDeclaration).name; // A 'name' property should always be a DeclarationName. } /** @internal */ -export function getNonAssignedNameOfDeclaration(declaration: Declaration | Expression): DeclarationName | undefined { +export function getNonAssignedNameOfDeclaration( + declaration: Declaration | Expression, +): DeclarationName | undefined { switch (declaration.kind) { case SyntaxKind.Identifier: - return declaration as Identifier; + return declaration; case SyntaxKind.JSDocPropertyTag: case SyntaxKind.JSDocParameterTag: { - const { name } = declaration as JSDocPropertyLikeTag; + const { name } = declaration; if (name.kind === SyntaxKind.QualifiedName) { return name.right; } @@ -895,31 +1074,34 @@ export function getNonAssignedNameOfDeclaration(declaration: Declaration | Expre } case SyntaxKind.CallExpression: case SyntaxKind.BinaryExpression: { - const expr = declaration as BinaryExpression | CallExpression; + const expr = declaration; switch (getAssignmentDeclarationKind(expr)) { case AssignmentDeclarationKind.ExportsProperty: case AssignmentDeclarationKind.ThisProperty: case AssignmentDeclarationKind.Property: case AssignmentDeclarationKind.PrototypeProperty: - return getElementOrPropertyAccessArgumentExpressionOrName((expr as BinaryExpression).left as AccessExpression); + return getElementOrPropertyAccessArgumentExpressionOrName( + (expr as BinaryExpression).left as AccessExpression, + ); case AssignmentDeclarationKind.ObjectDefinePropertyValue: case AssignmentDeclarationKind.ObjectDefinePropertyExports: case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: - return (expr as BindableObjectDefinePropertyCall).arguments[1]; + return (expr as BindableObjectDefinePropertyCall) + .arguments[1]; default: return undefined; } } case SyntaxKind.JSDocTypedefTag: - return getNameOfJSDocTypedef(declaration as JSDocTypedefTag); + return getNameOfJSDocTypedef(declaration); case SyntaxKind.JSDocEnumTag: - return nameForNamelessJSDocTypedef(declaration as JSDocEnumTag); + return nameForNamelessJSDocTypedef(declaration); case SyntaxKind.ExportAssignment: { - const { expression } = declaration as ExportAssignment; + const { expression } = declaration; return isIdentifier(expression) ? expression : undefined; } case SyntaxKind.ElementAccessExpression: - const expr = declaration as ElementAccessExpression; + const expr = declaration; if (isBindableStaticElementAccessExpression(expr)) { return expr.argumentExpression; } @@ -927,10 +1109,18 @@ export function getNonAssignedNameOfDeclaration(declaration: Declaration | Expre return (declaration as NamedDeclaration).name; } -export function getNameOfDeclaration(declaration: Declaration | Expression | undefined): DeclarationName | undefined { +export function getNameOfDeclaration( + declaration: Declaration | Expression | undefined, +): DeclarationName | undefined { if (declaration === undefined) return undefined; - return getNonAssignedNameOfDeclaration(declaration) || - (isFunctionExpression(declaration) || isArrowFunction(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined); + return ( + getNonAssignedNameOfDeclaration(declaration) || + (isFunctionExpression(declaration) || + isArrowFunction(declaration) || + isClassExpression(declaration) + ? getAssignedName(declaration) + : undefined) + ); } /** @internal */ @@ -938,7 +1128,10 @@ export function getAssignedName(node: Node): DeclarationName | undefined { if (!node.parent) { return undefined; } - else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) { + else if ( + isPropertyAssignment(node.parent) || + isBindingElement(node.parent) + ) { return node.parent.name; } else if (isBinaryExpression(node.parent) && node === node.parent.right) { @@ -946,36 +1139,58 @@ export function getAssignedName(node: Node): DeclarationName | undefined { return node.parent.left; } else if (isAccessExpression(node.parent.left)) { - return getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left); + return getElementOrPropertyAccessArgumentExpressionOrName( + node.parent.left, + ); } } - else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) { + else if ( + isVariableDeclaration(node.parent) && + isIdentifier(node.parent.name) + ) { return node.parent.name; } } -export function getDecorators(node: HasDecorators): readonly Decorator[] | undefined { +export function getDecorators( + node: HasDecorators, +): readonly Decorator[] | undefined { if (hasDecorators(node)) { return filter(node.modifiers, isDecorator); } } -export function getModifiers(node: HasModifiers): readonly Modifier[] | undefined { +export function getModifiers( + node: HasModifiers, +): readonly Modifier[] | undefined { if (hasSyntacticModifier(node, ModifierFlags.Modifier)) { return filter(node.modifiers, isModifier); } } -function getJSDocParameterTagsWorker(param: ParameterDeclaration, noCache?: boolean): readonly JSDocParameterTag[] { +function getJSDocParameterTagsWorker( + param: ParameterDeclaration, + noCache?: boolean, +): readonly JSDocParameterTag[] { if (param.name) { if (isIdentifier(param.name)) { const name = param.name.escapedText; - return getJSDocTagsWorker(param.parent, noCache).filter((tag): tag is JSDocParameterTag => isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name); + return getJSDocTagsWorker(param.parent, noCache).filter( + (tag): tag is JSDocParameterTag => + isJSDocParameterTag(tag) && + isIdentifier(tag.name) && + tag.name.escapedText === name, + ); } else { const i = param.parent.parameters.indexOf(param); - Debug.assert(i > -1, "Parameters should always be in their parents' parameter list"); - const paramTags = getJSDocTagsWorker(param.parent, noCache).filter(isJSDocParameterTag); + Debug.assert( + i > -1, + "Parameters should always be in their parents' parameter list", + ); + const paramTags = getJSDocTagsWorker(param.parent, noCache).filter( + isJSDocParameterTag, + ); if (i < paramTags.length) { return [paramTags[i]]; } @@ -997,18 +1212,29 @@ function getJSDocParameterTagsWorker(param: ParameterDeclaration, noCache?: bool * * For binding patterns, parameter tags are matched by position. */ -export function getJSDocParameterTags(param: ParameterDeclaration): readonly JSDocParameterTag[] { +export function getJSDocParameterTags( + param: ParameterDeclaration, +): readonly JSDocParameterTag[] { return getJSDocParameterTagsWorker(param, /*noCache*/ false); } /** @internal */ -export function getJSDocParameterTagsNoCache(param: ParameterDeclaration): readonly JSDocParameterTag[] { +export function getJSDocParameterTagsNoCache( + param: ParameterDeclaration, +): readonly JSDocParameterTag[] { return getJSDocParameterTagsWorker(param, /*noCache*/ true); } -function getJSDocTypeParameterTagsWorker(param: TypeParameterDeclaration, noCache?: boolean): readonly JSDocTemplateTag[] { +function getJSDocTypeParameterTagsWorker( + param: TypeParameterDeclaration, + noCache?: boolean, +): readonly JSDocTemplateTag[] { const name = param.name.escapedText; - return getJSDocTagsWorker(param.parent, noCache).filter((tag): tag is JSDocTemplateTag => isJSDocTemplateTag(tag) && tag.typeParameters.some(tp => tp.name.escapedText === name)); + return getJSDocTagsWorker(param.parent, noCache).filter( + (tag): tag is JSDocTemplateTag => + isJSDocTemplateTag(tag) && + tag.typeParameters.some(tp => tp.name.escapedText === name), + ); } /** @@ -1021,12 +1247,16 @@ function getJSDocTypeParameterTagsWorker(param: TypeParameterDeclaration, noCach * node are returned first, so in the previous example, the template * tag on the containing function expression would be first. */ -export function getJSDocTypeParameterTags(param: TypeParameterDeclaration): readonly JSDocTemplateTag[] { +export function getJSDocTypeParameterTags( + param: TypeParameterDeclaration, +): readonly JSDocTemplateTag[] { return getJSDocTypeParameterTagsWorker(param, /*noCache*/ false); } /** @internal */ -export function getJSDocTypeParameterTagsNoCache(param: TypeParameterDeclaration): readonly JSDocTemplateTag[] { +export function getJSDocTypeParameterTagsNoCache( + param: TypeParameterDeclaration, +): readonly JSDocTemplateTag[] { return getJSDocTypeParameterTagsWorker(param, /*noCache*/ true); } @@ -1036,7 +1266,9 @@ export function getJSDocTypeParameterTagsNoCache(param: TypeParameterDeclaration * @remarks Includes parameter tags that are not directly on the node, * for example on a variable declaration whose initializer is a function expression. */ -export function hasJSDocParameterTags(node: FunctionLikeDeclaration | SignatureDeclaration): boolean { +export function hasJSDocParameterTags( + node: FunctionLikeDeclaration | SignatureDeclaration, +): boolean { return !!getFirstJSDocTag(node, isJSDocParameterTag); } @@ -1046,7 +1278,9 @@ export function getJSDocAugmentsTag(node: Node): JSDocAugmentsTag | undefined { } /** Gets the JSDoc implements tags for the node if present */ -export function getJSDocImplementsTags(node: Node): readonly JSDocImplementsTag[] { +export function getJSDocImplementsTags( + node: Node, +): readonly JSDocImplementsTag[] { return getAllJSDocTags(node, isJSDocImplementsTag); } @@ -1061,7 +1295,9 @@ export function getJSDocPublicTag(node: Node): JSDocPublicTag | undefined { } /** @internal */ -export function getJSDocPublicTagNoCache(node: Node): JSDocPublicTag | undefined { +export function getJSDocPublicTagNoCache( + node: Node, +): JSDocPublicTag | undefined { return getFirstJSDocTag(node, isJSDocPublicTag, /*noCache*/ true); } @@ -1071,17 +1307,23 @@ export function getJSDocPrivateTag(node: Node): JSDocPrivateTag | undefined { } /** @internal */ -export function getJSDocPrivateTagNoCache(node: Node): JSDocPrivateTag | undefined { +export function getJSDocPrivateTagNoCache( + node: Node, +): JSDocPrivateTag | undefined { return getFirstJSDocTag(node, isJSDocPrivateTag, /*noCache*/ true); } /** Gets the JSDoc protected tag for the node if present */ -export function getJSDocProtectedTag(node: Node): JSDocProtectedTag | undefined { +export function getJSDocProtectedTag( + node: Node, +): JSDocProtectedTag | undefined { return getFirstJSDocTag(node, isJSDocProtectedTag); } /** @internal */ -export function getJSDocProtectedTagNoCache(node: Node): JSDocProtectedTag | undefined { +export function getJSDocProtectedTagNoCache( + node: Node, +): JSDocProtectedTag | undefined { return getFirstJSDocTag(node, isJSDocProtectedTag, /*noCache*/ true); } @@ -1091,21 +1333,29 @@ export function getJSDocReadonlyTag(node: Node): JSDocReadonlyTag | undefined { } /** @internal */ -export function getJSDocReadonlyTagNoCache(node: Node): JSDocReadonlyTag | undefined { +export function getJSDocReadonlyTagNoCache( + node: Node, +): JSDocReadonlyTag | undefined { return getFirstJSDocTag(node, isJSDocReadonlyTag, /*noCache*/ true); } -export function getJSDocOverrideTagNoCache(node: Node): JSDocOverrideTag | undefined { +export function getJSDocOverrideTagNoCache( + node: Node, +): JSDocOverrideTag | undefined { return getFirstJSDocTag(node, isJSDocOverrideTag, /*noCache*/ true); } /** Gets the JSDoc deprecated tag for the node if present */ -export function getJSDocDeprecatedTag(node: Node): JSDocDeprecatedTag | undefined { +export function getJSDocDeprecatedTag( + node: Node, +): JSDocDeprecatedTag | undefined { return getFirstJSDocTag(node, isJSDocDeprecatedTag); } /** @internal */ -export function getJSDocDeprecatedTagNoCache(node: Node): JSDocDeprecatedTag | undefined { +export function getJSDocDeprecatedTagNoCache( + node: Node, +): JSDocDeprecatedTag | undefined { return getFirstJSDocTag(node, isJSDocDeprecatedTag, /*noCache*/ true); } @@ -1129,7 +1379,9 @@ export function getJSDocTemplateTag(node: Node): JSDocTemplateTag | undefined { return getFirstJSDocTag(node, isJSDocTemplateTag); } -export function getJSDocSatisfiesTag(node: Node): JSDocSatisfiesTag | undefined { +export function getJSDocSatisfiesTag( + node: Node, +): JSDocSatisfiesTag | undefined { return getFirstJSDocTag(node, isJSDocSatisfiesTag); } @@ -1155,7 +1407,10 @@ export function getJSDocTypeTag(node: Node): JSDocTypeTag | undefined { * tag directly on the node would be returned. */ export function getJSDocType(node: Node): TypeNode | undefined { - let tag: JSDocTypeTag | JSDocParameterTag | undefined = getFirstJSDocTag(node, isJSDocTypeTag); + let tag: JSDocTypeTag | JSDocParameterTag | undefined = getFirstJSDocTag( + node, + isJSDocTypeTag, + ); if (!tag && isParameter(node)) { tag = find(getJSDocParameterTags(node), tag => !!tag.typeExpression); } @@ -1187,14 +1442,17 @@ export function getJSDocReturnType(node: Node): TypeNode | undefined { } } -function getJSDocTagsWorker(node: Node, noCache?: boolean): readonly JSDocTag[] { +function getJSDocTagsWorker( + node: Node, + noCache?: boolean, +): readonly JSDocTag[] { if (!canHaveJSDoc(node)) return emptyArray; let tags = node.jsDoc?.jsDocCache; // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing. if (tags === undefined || noCache) { const comments = getJSDocCommentsAndTags(node, noCache); Debug.assert(comments.length < 2 || comments[0] !== comments[1]); - tags = flatMap(comments, j => isJSDoc(j) ? j.tags : j); + tags = flatMap(comments, j => (isJSDoc(j) ? j.tags : j)); if (!noCache) { node.jsDoc ??= []; node.jsDoc.jsDocCache = tags; @@ -1214,29 +1472,46 @@ export function getJSDocTagsNoCache(node: Node): readonly JSDocTag[] { } /** Get the first JSDoc tag of a specified kind, or undefined if not present. */ -function getFirstJSDocTag(node: Node, predicate: (tag: JSDocTag) => tag is T, noCache?: boolean): T | undefined { +function getFirstJSDocTag( + node: Node, + predicate: (tag: JSDocTag) => tag is T, + noCache?: boolean, +): T | undefined { return find(getJSDocTagsWorker(node, noCache), predicate); } /** Gets all JSDoc tags that match a specified predicate */ -export function getAllJSDocTags(node: Node, predicate: (tag: JSDocTag) => tag is T): readonly T[] { +export function getAllJSDocTags( + node: Node, + predicate: (tag: JSDocTag) => tag is T, +): readonly T[] { return getJSDocTags(node).filter(predicate); } /** Gets all JSDoc tags of a specified kind */ -export function getAllJSDocTagsOfKind(node: Node, kind: SyntaxKind): readonly JSDocTag[] { +export function getAllJSDocTagsOfKind( + node: Node, + kind: SyntaxKind, +): readonly JSDocTag[] { return getJSDocTags(node).filter(doc => doc.kind === kind); } /** Gets the text of a jsdoc comment, flattening links to their text. */ -export function getTextOfJSDocComment(comment?: string | NodeArray) { - return typeof comment === "string" ? comment - : comment?.map(c => c.kind === SyntaxKind.JSDocText ? c.text : formatJSDocLink(c)).join(""); +export function getTextOfJSDocComment( + comment?: string | NodeArray, +) { + return typeof comment === "string" + ? comment + : comment + ?.map(c => c.kind === SyntaxKind.JSDocText ? c.text : formatJSDocLink(c)) + .join(""); } function formatJSDocLink(link: JSDocLink | JSDocLinkCode | JSDocLinkPlain) { - const kind = link.kind === SyntaxKind.JSDocLink ? "link" - : link.kind === SyntaxKind.JSDocLinkCode ? "linkcode" + const kind = link.kind === SyntaxKind.JSDocLink + ? "link" + : link.kind === SyntaxKind.JSDocLinkCode + ? "linkcode" : "linkplain"; const name = link.name ? entityNameToString(link.name) : ""; const space = link.name && link.text.startsWith("://") ? "" : " "; @@ -1253,7 +1528,9 @@ function formatJSDocLink(link: JSDocLink | JSDocLinkCode | JSDocLinkPlain) { * /** @type {Id} / * function id(x) { return x } */ -export function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeParameters): readonly TypeParameterDeclaration[] { +export function getEffectiveTypeParameterDeclarations( + node: DeclarationWithTypeParameters, +): readonly TypeParameterDeclaration[] { if (isJSDocSignature(node)) { if (isJSDocOverloadTag(node.parent)) { const jsDoc = getJSDocRoot(node.parent); @@ -1286,47 +1563,78 @@ export function getEffectiveTypeParameterDeclarations(node: DeclarationWithTypeP return emptyArray; } -export function getEffectiveConstraintOfTypeParameter(node: TypeParameterDeclaration): TypeNode | undefined { - return node.constraint ? node.constraint : - isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint : - undefined; +export function getEffectiveConstraintOfTypeParameter( + node: TypeParameterDeclaration, +): TypeNode | undefined { + return node.constraint + ? node.constraint + : isJSDocTemplateTag(node.parent) && + node === node.parent.typeParameters[0] + ? node.parent.constraint + : undefined; } // #region export function isMemberName(node: Node): node is MemberName { - return node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.PrivateIdentifier; + return ( + node.kind === SyntaxKind.Identifier || + node.kind === SyntaxKind.PrivateIdentifier + ); } /** @internal */ -export function isGetOrSetAccessorDeclaration(node: Node): node is AccessorDeclaration { - return node.kind === SyntaxKind.SetAccessor || node.kind === SyntaxKind.GetAccessor; +export function isGetOrSetAccessorDeclaration( + node: Node, +): node is AccessorDeclaration { + return ( + node.kind === SyntaxKind.SetAccessor || + node.kind === SyntaxKind.GetAccessor + ); } -export function isPropertyAccessChain(node: Node): node is PropertyAccessChain { - return isPropertyAccessExpression(node) && !!(node.flags & NodeFlags.OptionalChain); +export function isPropertyAccessChain( + node: Node, +): node is PropertyAccessChain { + return ( + isPropertyAccessExpression(node) && + !!(node.flags & NodeFlags.OptionalChain) + ); } -export function isElementAccessChain(node: Node): node is ElementAccessChain { - return isElementAccessExpression(node) && !!(node.flags & NodeFlags.OptionalChain); +export function isElementAccessChain( + node: Node, +): node is ElementAccessChain { + return ( + isElementAccessExpression(node) && + !!(node.flags & NodeFlags.OptionalChain) + ); } export function isCallChain(node: Node): node is CallChain { return isCallExpression(node) && !!(node.flags & NodeFlags.OptionalChain); } -export function isOptionalChain(node: Node): node is PropertyAccessChain | ElementAccessChain | CallChain | NonNullChain { +export function isOptionalChain( + node: Node, +): node is PropertyAccessChain | ElementAccessChain | CallChain | NonNullChain { const kind = node.kind; - return !!(node.flags & NodeFlags.OptionalChain) && - (kind === SyntaxKind.PropertyAccessExpression - || kind === SyntaxKind.ElementAccessExpression - || kind === SyntaxKind.CallExpression - || kind === SyntaxKind.NonNullExpression); + return ( + !!(node.flags & NodeFlags.OptionalChain) && + (kind === SyntaxKind.PropertyAccessExpression || + kind === SyntaxKind.ElementAccessExpression || + kind === SyntaxKind.CallExpression || + kind === SyntaxKind.NonNullExpression) + ); } /** @internal */ export function isOptionalChainRoot(node: Node): node is OptionalChainRoot { - return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken; + return ( + isOptionalChain(node) && + !isNonNullExpression(node) && + !!node.questionDotToken + ); } /** @@ -1334,7 +1642,9 @@ export function isOptionalChainRoot(node: Node): node is OptionalChainRoot { * * @internal */ -export function isExpressionOfOptionalChainRoot(node: Node): node is Expression & { parent: OptionalChainRoot; } { +export function isExpressionOfOptionalChainRoot( + node: Node, +): node is Expression & { parent: OptionalChainRoot; } { return isOptionalChainRoot(node.parent) && node.parent.expression === node; } @@ -1352,36 +1662,61 @@ export function isExpressionOfOptionalChainRoot(node: Node): node is Expression * @internal */ export function isOutermostOptionalChain(node: OptionalChain) { - return !isOptionalChain(node.parent) // cases 1, 2, and 3 - || isOptionalChainRoot(node.parent) // case 4 - || node !== node.parent.expression; // case 5 + return ( + !isOptionalChain(node.parent) || // cases 1, 2, and 3 + isOptionalChainRoot(node.parent) || // case 4 + node !== node.parent.expression + ); // case 5 } export function isNullishCoalesce(node: Node) { - return node.kind === SyntaxKind.BinaryExpression && (node as BinaryExpression).operatorToken.kind === SyntaxKind.QuestionQuestionToken; + return ( + node.kind === SyntaxKind.BinaryExpression && + node.operatorToken.kind === + SyntaxKind.QuestionQuestionToken + ); } export function isConstTypeReference(node: Node) { - return isTypeReferenceNode(node) && isIdentifier(node.typeName) && - node.typeName.escapedText === "const" && !node.typeArguments; + return ( + isTypeReferenceNode(node) && + isIdentifier(node.typeName) && + node.typeName.escapedText === "const" && + !node.typeArguments + ); } export function skipPartiallyEmittedExpressions(node: Expression): Expression; export function skipPartiallyEmittedExpressions(node: Node): Node; export function skipPartiallyEmittedExpressions(node: Node) { - return skipOuterExpressions(node, OuterExpressionKinds.PartiallyEmittedExpressions); + return skipOuterExpressions( + node, + OuterExpressionKinds.PartiallyEmittedExpressions, + ); } export function isNonNullChain(node: Node): node is NonNullChain { - return isNonNullExpression(node) && !!(node.flags & NodeFlags.OptionalChain); + return ( + isNonNullExpression(node) && !!(node.flags & NodeFlags.OptionalChain) + ); } -export function isBreakOrContinueStatement(node: Node): node is BreakOrContinueStatement { - return node.kind === SyntaxKind.BreakStatement || node.kind === SyntaxKind.ContinueStatement; +export function isBreakOrContinueStatement( + node: Node, +): node is BreakOrContinueStatement { + return ( + node.kind === SyntaxKind.BreakStatement || + node.kind === SyntaxKind.ContinueStatement + ); } -export function isNamedExportBindings(node: Node): node is NamedExportBindings { - return node.kind === SyntaxKind.NamespaceExport || node.kind === SyntaxKind.NamedExports; +export function isNamedExportBindings( + node: Node, +): node is NamedExportBindings { + return ( + node.kind === SyntaxKind.NamespaceExport || + node.kind === SyntaxKind.NamedExports + ); } /** @deprecated */ @@ -1397,13 +1732,20 @@ export function isUnparsedTextLike(node: Node): node is UnparsedTextLike { /** @deprecated */ export function isUnparsedNode(node: Node): node is UnparsedNode { - return isUnparsedTextLike(node) || + return ( + isUnparsedTextLike(node) || node.kind === SyntaxKind.UnparsedPrologue || - node.kind === SyntaxKind.UnparsedSyntheticReference; + node.kind === SyntaxKind.UnparsedSyntheticReference + ); } -export function isJSDocPropertyLikeTag(node: Node): node is JSDocPropertyLikeTag { - return node.kind === SyntaxKind.JSDocPropertyTag || node.kind === SyntaxKind.JSDocParameterTag; +export function isJSDocPropertyLikeTag( + node: Node, +): node is JSDocPropertyLikeTag { + return ( + node.kind === SyntaxKind.JSDocPropertyTag || + node.kind === SyntaxKind.JSDocParameterTag + ); } // #endregion @@ -1444,7 +1786,9 @@ export function isToken(n: Node): boolean { // Node Arrays /** @internal */ -export function isNodeArray(array: readonly T[]): array is NodeArray { +export function isNodeArray( + array: readonly T[], +): array is NodeArray { return hasProperty(array, "pos") && hasProperty(array, "end"); } @@ -1452,7 +1796,10 @@ export function isNodeArray(array: readonly T[]): array is NodeA /** @internal */ export function isLiteralKind(kind: SyntaxKind): kind is LiteralToken["kind"] { - return SyntaxKind.FirstLiteralToken <= kind && kind <= SyntaxKind.LastLiteralToken; + return ( + SyntaxKind.FirstLiteralToken <= kind && + kind <= SyntaxKind.LastLiteralToken + ); } export function isLiteralExpression(node: Node): node is LiteralExpression { @@ -1475,89 +1822,143 @@ export function isLiteralExpressionOfObject(node: Node) { // Pseudo-literals /** @internal */ -export function isTemplateLiteralKind(kind: SyntaxKind): kind is TemplateLiteralToken["kind"] { - return SyntaxKind.FirstTemplateToken <= kind && kind <= SyntaxKind.LastTemplateToken; +export function isTemplateLiteralKind( + kind: SyntaxKind, +): kind is TemplateLiteralToken["kind"] { + return ( + SyntaxKind.FirstTemplateToken <= kind && + kind <= SyntaxKind.LastTemplateToken + ); } -export function isTemplateLiteralToken(node: Node): node is TemplateLiteralToken { +export function isTemplateLiteralToken( + node: Node, +): node is TemplateLiteralToken { return isTemplateLiteralKind(node.kind); } -export function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail { +export function isTemplateMiddleOrTemplateTail( + node: Node, +): node is TemplateMiddle | TemplateTail { const kind = node.kind; - return kind === SyntaxKind.TemplateMiddle - || kind === SyntaxKind.TemplateTail; + return ( + kind === SyntaxKind.TemplateMiddle || kind === SyntaxKind.TemplateTail + ); } -export function isImportOrExportSpecifier(node: Node): node is ImportSpecifier | ExportSpecifier { +export function isImportOrExportSpecifier( + node: Node, +): node is ImportSpecifier | ExportSpecifier { return isImportSpecifier(node) || isExportSpecifier(node); } -export function isTypeOnlyImportDeclaration(node: Node): node is TypeOnlyImportDeclaration { +export function isTypeOnlyImportDeclaration( + node: Node, +): node is TypeOnlyImportDeclaration { switch (node.kind) { case SyntaxKind.ImportSpecifier: - return (node as ImportSpecifier).isTypeOnly || (node as ImportSpecifier).parent.parent.isTypeOnly; + return ( + node.isTypeOnly || + node.parent.parent.isTypeOnly + ); case SyntaxKind.NamespaceImport: - return (node as NamespaceImport).parent.isTypeOnly; + return node.parent.isTypeOnly; case SyntaxKind.ImportClause: case SyntaxKind.ImportEqualsDeclaration: - return (node as ImportClause | ImportEqualsDeclaration).isTypeOnly; + return node.isTypeOnly; } return false; } -export function isTypeOnlyExportDeclaration(node: Node): node is TypeOnlyExportDeclaration { +export function isTypeOnlyExportDeclaration( + node: Node, +): node is TypeOnlyExportDeclaration { switch (node.kind) { case SyntaxKind.ExportSpecifier: - return (node as ExportSpecifier).isTypeOnly || (node as ExportSpecifier).parent.parent.isTypeOnly; + return ( + node.isTypeOnly || + node.parent.parent.isTypeOnly + ); case SyntaxKind.ExportDeclaration: - return (node as ExportDeclaration).isTypeOnly && !!(node as ExportDeclaration).moduleSpecifier && !(node as ExportDeclaration).exportClause; + return ( + node.isTypeOnly && + !!node.moduleSpecifier && + !node.exportClause + ); case SyntaxKind.NamespaceExport: - return (node as NamespaceExport).parent.isTypeOnly; + return node.parent.isTypeOnly; } return false; } -export function isTypeOnlyImportOrExportDeclaration(node: Node): node is TypeOnlyAliasDeclaration { - return isTypeOnlyImportDeclaration(node) || isTypeOnlyExportDeclaration(node); +export function isTypeOnlyImportOrExportDeclaration( + node: Node, +): node is TypeOnlyAliasDeclaration { + return ( + isTypeOnlyImportDeclaration(node) || isTypeOnlyExportDeclaration(node) + ); } -export function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken { - return node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind); +export function isStringTextContainingNode( + node: Node, +): node is StringLiteral | TemplateLiteralToken { + return ( + node.kind === SyntaxKind.StringLiteral || + isTemplateLiteralKind(node.kind) + ); } -export function isImportAttributeName(node: Node): node is ImportAttributeName { +export function isImportAttributeName( + node: Node, +): node is ImportAttributeName { return isStringLiteral(node) || isIdentifier(node); } // Identifiers /** @internal */ -export function isGeneratedIdentifier(node: Node): node is GeneratedIdentifier { +export function isGeneratedIdentifier( + node: NodeBase, +): node is GeneratedIdentifier { return isIdentifier(node) && node.emitNode?.autoGenerate !== undefined; } /** @internal */ -export function isGeneratedPrivateIdentifier(node: Node): node is GeneratedPrivateIdentifier { - return isPrivateIdentifier(node) && node.emitNode?.autoGenerate !== undefined; +export function isGeneratedPrivateIdentifier( + node: NodeBase, +): node is GeneratedPrivateIdentifier { + return ( + isPrivateIdentifier(node) && node.emitNode?.autoGenerate !== undefined + ); } /** @internal */ -export function isFileLevelReservedGeneratedIdentifier(node: GeneratedIdentifier) { +export function isFileLevelReservedGeneratedIdentifier( + node: GeneratedIdentifier, +) { const flags = node.emitNode.autoGenerate.flags; - return !!(flags & GeneratedIdentifierFlags.FileLevel) - && !!(flags & GeneratedIdentifierFlags.Optimistic) - && !!(flags & GeneratedIdentifierFlags.ReservedInNestedScopes); + return ( + !!(flags & GeneratedIdentifierFlags.FileLevel) && + !!(flags & GeneratedIdentifierFlags.Optimistic) && + !!(flags & GeneratedIdentifierFlags.ReservedInNestedScopes) + ); } // Private Identifiers /** @internal */ -export function isPrivateIdentifierClassElementDeclaration(node: Node): node is PrivateClassElementDeclaration { - return (isPropertyDeclaration(node) || isMethodOrAccessor(node)) && isPrivateIdentifier(node.name); +export function isPrivateIdentifierClassElementDeclaration( + node: Node, +): node is PrivateClassElementDeclaration { + return ( + (isPropertyDeclaration(node) || isMethodOrAccessor(node)) && + isPrivateIdentifier(node.name) + ); } /** @internal */ -export function isPrivateIdentifierPropertyAccessExpression(node: Node): node is PrivateIdentifierPropertyAccessExpression { +export function isPrivateIdentifierPropertyAccessExpression( + node: Node, +): node is PrivateIdentifierPropertyAccessExpression { return isPropertyAccessExpression(node) && isPrivateIdentifier(node.name); } @@ -1593,10 +1994,12 @@ export function isParameterPropertyModifier(kind: SyntaxKind): boolean { /** @internal */ export function isClassMemberModifier(idToken: SyntaxKind): boolean { - return isParameterPropertyModifier(idToken) || + return ( + isParameterPropertyModifier(idToken) || idToken === SyntaxKind.StaticKeyword || idToken === SyntaxKind.OverrideKeyword || - idToken === SyntaxKind.AccessorKeyword; + idToken === SyntaxKind.AccessorKeyword + ); } export function isModifier(node: Node): node is Modifier { @@ -1605,45 +2008,60 @@ export function isModifier(node: Node): node is Modifier { export function isEntityName(node: Node): node is EntityName { const kind = node.kind; - return kind === SyntaxKind.QualifiedName - || kind === SyntaxKind.Identifier; + return kind === SyntaxKind.QualifiedName || kind === SyntaxKind.Identifier; } export function isPropertyName(node: Node): node is PropertyName { const kind = node.kind; - return kind === SyntaxKind.Identifier - || kind === SyntaxKind.PrivateIdentifier - || kind === SyntaxKind.StringLiteral - || kind === SyntaxKind.NumericLiteral - || kind === SyntaxKind.ComputedPropertyName; + return ( + kind === SyntaxKind.Identifier || + kind === SyntaxKind.PrivateIdentifier || + kind === SyntaxKind.StringLiteral || + kind === SyntaxKind.NumericLiteral || + kind === SyntaxKind.ComputedPropertyName + ); } export function isBindingName(node: Node): node is BindingName { const kind = node.kind; - return kind === SyntaxKind.Identifier - || kind === SyntaxKind.ObjectBindingPattern - || kind === SyntaxKind.ArrayBindingPattern; + return ( + kind === SyntaxKind.Identifier || + kind === SyntaxKind.ObjectBindingPattern || + kind === SyntaxKind.ArrayBindingPattern + ); } // Functions -export function isFunctionLike(node: Node | undefined): node is SignatureDeclaration { +export function isFunctionLike( + node: Node | undefined, +): node is SignatureDeclaration { return !!node && isFunctionLikeKind(node.kind); } /** @internal */ -export function isFunctionLikeOrClassStaticBlockDeclaration(node: Node | undefined): node is SignatureDeclaration | ClassStaticBlockDeclaration { - return !!node && (isFunctionLikeKind(node.kind) || isClassStaticBlockDeclaration(node)); +export function isFunctionLikeOrClassStaticBlockDeclaration( + node: Node | undefined, +): node is SignatureDeclaration | ClassStaticBlockDeclaration { + return ( + !!node && + (isFunctionLikeKind(node.kind) || isClassStaticBlockDeclaration(node)) + ); } /** @internal */ -export function isFunctionLikeDeclaration(node: Node): node is FunctionLikeDeclaration { +export function isFunctionLikeDeclaration( + node: Node, +): node is FunctionLikeDeclaration { return node && isFunctionLikeDeclarationKind(node.kind); } /** @internal */ export function isBooleanLiteral(node: Node): node is BooleanLiteral { - return node.kind === SyntaxKind.TrueKeyword || node.kind === SyntaxKind.FalseKeyword; + return ( + node.kind === SyntaxKind.TrueKeyword || + node.kind === SyntaxKind.FalseKeyword + ); } function isFunctionLikeDeclarationKind(kind: SyntaxKind): boolean { @@ -1680,44 +2098,71 @@ export function isFunctionLikeKind(kind: SyntaxKind): boolean { /** @internal */ export function isFunctionOrModuleBlock(node: Node): boolean { - return isSourceFile(node) || isModuleBlock(node) || isBlock(node) && isFunctionLike(node.parent); + return ( + isSourceFile(node) || + isModuleBlock(node) || + (isBlock(node) && isFunctionLike(node.parent)) + ); } // Classes export function isClassElement(node: Node): node is ClassElement { const kind = node.kind; - return kind === SyntaxKind.Constructor - || kind === SyntaxKind.PropertyDeclaration - || kind === SyntaxKind.MethodDeclaration - || kind === SyntaxKind.GetAccessor - || kind === SyntaxKind.SetAccessor - || kind === SyntaxKind.IndexSignature - || kind === SyntaxKind.ClassStaticBlockDeclaration - || kind === SyntaxKind.SemicolonClassElement; + return ( + kind === SyntaxKind.Constructor || + kind === SyntaxKind.PropertyDeclaration || + kind === SyntaxKind.MethodDeclaration || + kind === SyntaxKind.GetAccessor || + kind === SyntaxKind.SetAccessor || + kind === SyntaxKind.IndexSignature || + kind === SyntaxKind.ClassStaticBlockDeclaration || + kind === SyntaxKind.SemicolonClassElement + ); } export function isClassLike(node: Node): node is ClassLikeDeclaration { - return node && (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression); + return ( + node && + (node.kind === SyntaxKind.ClassDeclaration || + node.kind === SyntaxKind.ClassExpression) + ); } export function isAccessor(node: Node): node is AccessorDeclaration { - return node && (node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor); + return ( + node && + (node.kind === SyntaxKind.GetAccessor || + node.kind === SyntaxKind.SetAccessor) + ); } -export function isAutoAccessorPropertyDeclaration(node: Node): node is AutoAccessorPropertyDeclaration { +export function isAutoAccessorPropertyDeclaration( + node: Node, +): node is AutoAccessorPropertyDeclaration { return isPropertyDeclaration(node) && hasAccessorModifier(node); } /** @internal */ export function isClassInstanceProperty(node: Declaration): boolean { if (isInJSFile(node) && isExpandoPropertyDeclaration(node)) { - return (!isBindableStaticAccessExpression(node) || !isPrototypeAccess(node.expression)) && !isBindableStaticNameExpression(node, /*excludeThisKeyword*/ true); + return ( + (!isBindableStaticAccessExpression(node) || + !isPrototypeAccess(node.expression)) && + !isBindableStaticNameExpression(node, /*excludeThisKeyword*/ true) + ); } - return node.parent && isClassLike(node.parent) && isPropertyDeclaration(node) && !hasAccessorModifier(node); + return ( + node.parent && + isClassLike(node.parent) && + isPropertyDeclaration(node) && + !hasAccessorModifier(node) + ); } /** @internal */ -export function isMethodOrAccessor(node: Node): node is MethodDeclaration | AccessorDeclaration { +export function isMethodOrAccessor( + node: Node, +): node is MethodDeclaration | AccessorDeclaration { switch (node.kind) { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: @@ -1729,7 +2174,9 @@ export function isMethodOrAccessor(node: Node): node is MethodDeclaration | Acce } /** @internal */ -export function isNamedClassElement(node: Node): node is MethodDeclaration | AccessorDeclaration | PropertyDeclaration { +export function isNamedClassElement( + node: Node, +): node is MethodDeclaration | AccessorDeclaration | PropertyDeclaration { switch (node.kind) { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: @@ -1749,27 +2196,35 @@ export function isModifierLike(node: Node): node is ModifierLike { export function isTypeElement(node: Node): node is TypeElement { const kind = node.kind; - return kind === SyntaxKind.ConstructSignature - || kind === SyntaxKind.CallSignature - || kind === SyntaxKind.PropertySignature - || kind === SyntaxKind.MethodSignature - || kind === SyntaxKind.IndexSignature - || kind === SyntaxKind.GetAccessor - || kind === SyntaxKind.SetAccessor; -} - -export function isClassOrTypeElement(node: Node): node is ClassElement | TypeElement { + return ( + kind === SyntaxKind.ConstructSignature || + kind === SyntaxKind.CallSignature || + kind === SyntaxKind.PropertySignature || + kind === SyntaxKind.MethodSignature || + kind === SyntaxKind.IndexSignature || + kind === SyntaxKind.GetAccessor || + kind === SyntaxKind.SetAccessor + ); +} + +export function isClassOrTypeElement( + node: Node, +): node is ClassElement | TypeElement { return isTypeElement(node) || isClassElement(node); } -export function isObjectLiteralElementLike(node: Node): node is ObjectLiteralElementLike { +export function isObjectLiteralElementLike( + node: Node, +): node is ObjectLiteralElementLike { const kind = node.kind; - return kind === SyntaxKind.PropertyAssignment - || kind === SyntaxKind.ShorthandPropertyAssignment - || kind === SyntaxKind.SpreadAssignment - || kind === SyntaxKind.MethodDeclaration - || kind === SyntaxKind.GetAccessor - || kind === SyntaxKind.SetAccessor; + return ( + kind === SyntaxKind.PropertyAssignment || + kind === SyntaxKind.ShorthandPropertyAssignment || + kind === SyntaxKind.SpreadAssignment || + kind === SyntaxKind.MethodDeclaration || + kind === SyntaxKind.GetAccessor || + kind === SyntaxKind.SetAccessor + ); } // Type @@ -1783,7 +2238,9 @@ export function isTypeNode(node: Node): node is TypeNode { return isTypeNodeKind(node.kind); } -export function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTypeNode | ConstructorTypeNode { +export function isFunctionOrConstructorTypeNode( + node: Node, +): node is FunctionTypeNode | ConstructorTypeNode { switch (node.kind) { case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: @@ -1796,11 +2253,15 @@ export function isFunctionOrConstructorTypeNode(node: Node): node is FunctionTyp // Binding patterns /** @internal */ -export function isBindingPattern(node: Node | undefined): node is BindingPattern { +export function isBindingPattern( + node: Node | undefined, +): node is BindingPattern { if (node) { const kind = node.kind; - return kind === SyntaxKind.ArrayBindingPattern - || kind === SyntaxKind.ObjectBindingPattern; + return ( + kind === SyntaxKind.ArrayBindingPattern || + kind === SyntaxKind.ObjectBindingPattern + ); } return false; @@ -1809,14 +2270,20 @@ export function isBindingPattern(node: Node | undefined): node is BindingPattern /** @internal */ export function isAssignmentPattern(node: Node): node is AssignmentPattern { const kind = node.kind; - return kind === SyntaxKind.ArrayLiteralExpression - || kind === SyntaxKind.ObjectLiteralExpression; + return ( + kind === SyntaxKind.ArrayLiteralExpression || + kind === SyntaxKind.ObjectLiteralExpression + ); } -export function isArrayBindingElement(node: Node): node is ArrayBindingElement { +export function isArrayBindingElement( + node: Node, +): node is ArrayBindingElement { const kind = node.kind; - return kind === SyntaxKind.BindingElement - || kind === SyntaxKind.OmittedExpression; + return ( + kind === SyntaxKind.BindingElement || + kind === SyntaxKind.OmittedExpression + ); } /** @@ -1824,7 +2291,13 @@ export function isArrayBindingElement(node: Node): node is ArrayBindingElement { * * @internal */ -export function isDeclarationBindingElement(bindingElement: BindingOrAssignmentElement): bindingElement is VariableDeclaration | ParameterDeclaration | BindingElement { +export function isDeclarationBindingElement( + bindingElement: BindingOrAssignmentElement, +): bindingElement is + | VariableDeclaration + | ParameterDeclaration + | BindingElement +{ switch (bindingElement.kind) { case SyntaxKind.VariableDeclaration: case SyntaxKind.Parameter: @@ -1836,11 +2309,15 @@ export function isDeclarationBindingElement(bindingElement: BindingOrAssignmentE } /** @internal */ -export function isBindingOrAssignmentElement(node: Node): node is BindingOrAssignmentElement { - return isVariableDeclaration(node) - || isParameter(node) - || isObjectBindingOrAssignmentElement(node) - || isArrayBindingOrAssignmentElement(node); +export function isBindingOrAssignmentElement( + node: Node, +): node is BindingOrAssignmentElement { + return ( + isVariableDeclaration(node) || + isParameter(node) || + isObjectBindingOrAssignmentElement(node) || + isArrayBindingOrAssignmentElement(node) + ); } /** @@ -1848,9 +2325,13 @@ export function isBindingOrAssignmentElement(node: Node): node is BindingOrAssig * * @internal */ -export function isBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is BindingOrAssignmentPattern { - return isObjectBindingOrAssignmentPattern(node) - || isArrayBindingOrAssignmentPattern(node); +export function isBindingOrAssignmentPattern( + node: BindingOrAssignmentElementTarget, +): node is BindingOrAssignmentPattern { + return ( + isObjectBindingOrAssignmentPattern(node) || + isArrayBindingOrAssignmentPattern(node) + ); } /** @@ -1858,7 +2339,9 @@ export function isBindingOrAssignmentPattern(node: BindingOrAssignmentElementTar * * @internal */ -export function isObjectBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is ObjectBindingOrAssignmentPattern { +export function isObjectBindingOrAssignmentPattern( + node: BindingOrAssignmentElementTarget, +): node is ObjectBindingOrAssignmentPattern { switch (node.kind) { case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ObjectLiteralExpression: @@ -1869,7 +2352,9 @@ export function isObjectBindingOrAssignmentPattern(node: BindingOrAssignmentElem } /** @internal */ -export function isObjectBindingOrAssignmentElement(node: Node): node is ObjectBindingOrAssignmentElement { +export function isObjectBindingOrAssignmentElement( + node: Node, +): node is ObjectBindingOrAssignmentElement { switch (node.kind) { case SyntaxKind.BindingElement: case SyntaxKind.PropertyAssignment: // AssignmentProperty @@ -1885,7 +2370,9 @@ export function isObjectBindingOrAssignmentElement(node: Node): node is ObjectBi * * @internal */ -export function isArrayBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is ArrayBindingOrAssignmentPattern { +export function isArrayBindingOrAssignmentPattern( + node: BindingOrAssignmentElementTarget, +): node is ArrayBindingOrAssignmentPattern { switch (node.kind) { case SyntaxKind.ArrayBindingPattern: case SyntaxKind.ArrayLiteralExpression: @@ -1896,7 +2383,9 @@ export function isArrayBindingOrAssignmentPattern(node: BindingOrAssignmentEleme } /** @internal */ -export function isArrayBindingOrAssignmentElement(node: Node): node is ArrayBindingOrAssignmentElement { +export function isArrayBindingOrAssignmentElement( + node: Node, +): node is ArrayBindingOrAssignmentElement { switch (node.kind) { case SyntaxKind.BindingElement: case SyntaxKind.OmittedExpression: // Elision @@ -1912,27 +2401,39 @@ export function isArrayBindingOrAssignmentElement(node: Node): node is ArrayBind } /** @internal */ -export function isPropertyAccessOrQualifiedNameOrImportTypeNode(node: Node): node is PropertyAccessExpression | QualifiedName | ImportTypeNode { +export function isPropertyAccessOrQualifiedNameOrImportTypeNode( + node: Node, +): node is PropertyAccessExpression | QualifiedName | ImportTypeNode { const kind = node.kind; - return kind === SyntaxKind.PropertyAccessExpression - || kind === SyntaxKind.QualifiedName - || kind === SyntaxKind.ImportType; + return ( + kind === SyntaxKind.PropertyAccessExpression || + kind === SyntaxKind.QualifiedName || + kind === SyntaxKind.ImportType + ); } // Expression -export function isPropertyAccessOrQualifiedName(node: Node): node is PropertyAccessExpression | QualifiedName { +export function isPropertyAccessOrQualifiedName( + node: Node, +): node is PropertyAccessExpression | QualifiedName { const kind = node.kind; - return kind === SyntaxKind.PropertyAccessExpression - || kind === SyntaxKind.QualifiedName; + return ( + kind === SyntaxKind.PropertyAccessExpression || + kind === SyntaxKind.QualifiedName + ); } /** @internal */ -export function isCallLikeOrFunctionLikeExpression(node: Node): node is CallLikeExpression | SignatureDeclaration { +export function isCallLikeOrFunctionLikeExpression( + node: Node, +): node is CallLikeExpression | SignatureDeclaration { return isCallLikeExpression(node) || isFunctionLike(node); } -export function isCallLikeExpression(node: Node): node is CallLikeExpression { +export function isCallLikeExpression( + node: Node, +): node is CallLikeExpression { switch (node.kind) { case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxSelfClosingElement: @@ -1946,18 +2447,29 @@ export function isCallLikeExpression(node: Node): node is CallLikeExpression { } } -export function isCallOrNewExpression(node: Node): node is CallExpression | NewExpression { - return node.kind === SyntaxKind.CallExpression || node.kind === SyntaxKind.NewExpression; +export function isCallOrNewExpression( + node: Node, +): node is CallExpression | NewExpression { + return ( + node.kind === SyntaxKind.CallExpression || + node.kind === SyntaxKind.NewExpression + ); } export function isTemplateLiteral(node: Node): node is TemplateLiteral { const kind = node.kind; - return kind === SyntaxKind.TemplateExpression - || kind === SyntaxKind.NoSubstitutionTemplateLiteral; + return ( + kind === SyntaxKind.TemplateExpression || + kind === SyntaxKind.NoSubstitutionTemplateLiteral + ); } -export function isLeftHandSideExpression(node: Node): node is LeftHandSideExpression { - return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind); +export function isLeftHandSideExpression( + node: Node, +): node is LeftHandSideExpression { + return isLeftHandSideExpressionKind( + skipPartiallyEmittedExpressions(node).kind, + ); } function isLeftHandSideExpressionKind(kind: SyntaxKind): boolean { @@ -2020,19 +2532,32 @@ function isUnaryExpressionKind(kind: SyntaxKind): boolean { } /** @internal */ -export function isUnaryExpressionWithWrite(expr: Node): expr is PrefixUnaryExpression | PostfixUnaryExpression { +export function isUnaryExpressionWithWrite( + expr: Node, +): expr is PrefixUnaryExpression | PostfixUnaryExpression { switch (expr.kind) { case SyntaxKind.PostfixUnaryExpression: return true; case SyntaxKind.PrefixUnaryExpression: - return (expr as PrefixUnaryExpression).operator === SyntaxKind.PlusPlusToken || - (expr as PrefixUnaryExpression).operator === SyntaxKind.MinusMinusToken; + return ( + expr.operator === + SyntaxKind.PlusPlusToken || + expr.operator === + SyntaxKind.MinusMinusToken + ); default: return false; } } -export function isLiteralTypeLiteral(node: Node): node is NullLiteral | BooleanLiteral | LiteralExpression | PrefixUnaryExpression { +export function isLiteralTypeLiteral( + node: Node, +): node is + | NullLiteral + | BooleanLiteral + | LiteralExpression + | PrefixUnaryExpression +{ switch (node.kind) { case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: @@ -2069,23 +2594,37 @@ function isExpressionKind(kind: SyntaxKind): boolean { } } -export function isAssertionExpression(node: Node): node is AssertionExpression { +export function isAssertionExpression( + node: Node, +): node is AssertionExpression { const kind = node.kind; - return kind === SyntaxKind.TypeAssertionExpression - || kind === SyntaxKind.AsExpression; + return ( + kind === SyntaxKind.TypeAssertionExpression || + kind === SyntaxKind.AsExpression + ); } /** @internal */ -export function isNotEmittedOrPartiallyEmittedNode(node: Node): node is NotEmittedStatement | PartiallyEmittedExpression { - return isNotEmittedStatement(node) - || isPartiallyEmittedExpression(node); +export function isNotEmittedOrPartiallyEmittedNode( + node: Node, +): node is NotEmittedStatement | PartiallyEmittedExpression { + return isNotEmittedStatement(node) || isPartiallyEmittedExpression(node); } // Statement -export function isIterationStatement(node: Node, lookInLabeledStatements: false): node is IterationStatement; -export function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement | LabeledStatement; -export function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement { +export function isIterationStatement( + node: Node, + lookInLabeledStatements: false, +): node is IterationStatement; +export function isIterationStatement( + node: Node, + lookInLabeledStatements: boolean, +): node is IterationStatement | LabeledStatement; +export function isIterationStatement( + node: Node, + lookInLabeledStatements: boolean, +): node is IterationStatement { switch (node.kind) { case SyntaxKind.ForStatement: case SyntaxKind.ForInStatement: @@ -2094,7 +2633,13 @@ export function isIterationStatement(node: Node, lookInLabeledStatements: boolea case SyntaxKind.WhileStatement: return true; case SyntaxKind.LabeledStatement: - return lookInLabeledStatements && isIterationStatement((node as LabeledStatement).statement, lookInLabeledStatements); + return ( + lookInLabeledStatements && + isIterationStatement( + node.statement, + lookInLabeledStatements, + ) + ); } return false; @@ -2112,25 +2657,38 @@ export function hasScopeMarker(statements: readonly Statement[]) { /** @internal */ export function needsScopeMarker(result: Statement) { - return !isAnyImportOrReExport(result) && !isExportAssignment(result) && !hasSyntacticModifier(result, ModifierFlags.Export) && !isAmbientModule(result); + return ( + !isAnyImportOrReExport(result) && + !isExportAssignment(result) && + !hasSyntacticModifier(result, ModifierFlags.Export) && + !isAmbientModule(result) + ); } /** @internal */ export function isExternalModuleIndicator(result: Statement) { // Exported top-level member indicates moduleness - return isAnyImportOrReExport(result) || isExportAssignment(result) || hasSyntacticModifier(result, ModifierFlags.Export); + return ( + isAnyImportOrReExport(result) || + isExportAssignment(result) || + hasSyntacticModifier(result, ModifierFlags.Export) + ); } /** @internal */ -export function isForInOrOfStatement(node: Node): node is ForInOrOfStatement { - return node.kind === SyntaxKind.ForInStatement || node.kind === SyntaxKind.ForOfStatement; +export function isForInOrOfStatement( + node: Node, +): node is ForInOrOfStatement { + return ( + node.kind === SyntaxKind.ForInStatement || + node.kind === SyntaxKind.ForOfStatement + ); } // Element export function isConciseBody(node: Node): node is ConciseBody { - return isBlock(node) - || isExpression(node); + return isBlock(node) || isExpression(node); } /** @internal */ @@ -2139,40 +2697,53 @@ export function isFunctionBody(node: Node): node is FunctionBody { } export function isForInitializer(node: Node): node is ForInitializer { - return isVariableDeclarationList(node) - || isExpression(node); + return isVariableDeclarationList(node) || isExpression(node); } export function isModuleBody(node: Node): node is ModuleBody { const kind = node.kind; - return kind === SyntaxKind.ModuleBlock - || kind === SyntaxKind.ModuleDeclaration - || kind === SyntaxKind.Identifier; + return ( + kind === SyntaxKind.ModuleBlock || + kind === SyntaxKind.ModuleDeclaration || + kind === SyntaxKind.Identifier + ); } /** @internal */ export function isNamespaceBody(node: Node): node is NamespaceBody { const kind = node.kind; - return kind === SyntaxKind.ModuleBlock - || kind === SyntaxKind.ModuleDeclaration; + return ( + kind === SyntaxKind.ModuleBlock || kind === SyntaxKind.ModuleDeclaration + ); } /** @internal */ -export function isJSDocNamespaceBody(node: Node): node is JSDocNamespaceBody { +export function isJSDocNamespaceBody( + node: Node, +): node is JSDocNamespaceBody { const kind = node.kind; - return kind === SyntaxKind.Identifier - || kind === SyntaxKind.ModuleDeclaration; + return ( + kind === SyntaxKind.Identifier || kind === SyntaxKind.ModuleDeclaration + ); } -export function isNamedImportBindings(node: Node): node is NamedImportBindings { +export function isNamedImportBindings( + node: Node, +): node is NamedImportBindings { const kind = node.kind; - return kind === SyntaxKind.NamedImports - || kind === SyntaxKind.NamespaceImport; + return ( + kind === SyntaxKind.NamedImports || kind === SyntaxKind.NamespaceImport + ); } /** @internal */ -export function isModuleOrEnumDeclaration(node: Node): node is ModuleDeclaration | EnumDeclaration { - return node.kind === SyntaxKind.ModuleDeclaration || node.kind === SyntaxKind.EnumDeclaration; +export function isModuleOrEnumDeclaration( + node: Node, +): node is ModuleDeclaration | EnumDeclaration { + return ( + node.kind === SyntaxKind.ModuleDeclaration || + node.kind === SyntaxKind.EnumDeclaration + ); } /** @internal */ @@ -2290,91 +2861,102 @@ export function canHaveLocals(node: Node): node is HasLocals { } function isDeclarationKind(kind: SyntaxKind) { - return kind === SyntaxKind.ArrowFunction - || kind === SyntaxKind.BindingElement - || kind === SyntaxKind.ClassDeclaration - || kind === SyntaxKind.ClassExpression - || kind === SyntaxKind.ClassStaticBlockDeclaration - || kind === SyntaxKind.Constructor - || kind === SyntaxKind.EnumDeclaration - || kind === SyntaxKind.EnumMember - || kind === SyntaxKind.ExportSpecifier - || kind === SyntaxKind.FunctionDeclaration - || kind === SyntaxKind.FunctionExpression - || kind === SyntaxKind.GetAccessor - || kind === SyntaxKind.ImportClause - || kind === SyntaxKind.ImportEqualsDeclaration - || kind === SyntaxKind.ImportSpecifier - || kind === SyntaxKind.InterfaceDeclaration - || kind === SyntaxKind.JsxAttribute - || kind === SyntaxKind.MethodDeclaration - || kind === SyntaxKind.MethodSignature - || kind === SyntaxKind.ModuleDeclaration - || kind === SyntaxKind.NamespaceExportDeclaration - || kind === SyntaxKind.NamespaceImport - || kind === SyntaxKind.NamespaceExport - || kind === SyntaxKind.Parameter - || kind === SyntaxKind.PropertyAssignment - || kind === SyntaxKind.PropertyDeclaration - || kind === SyntaxKind.PropertySignature - || kind === SyntaxKind.SetAccessor - || kind === SyntaxKind.ShorthandPropertyAssignment - || kind === SyntaxKind.TypeAliasDeclaration - || kind === SyntaxKind.TypeParameter - || kind === SyntaxKind.VariableDeclaration - || kind === SyntaxKind.JSDocTypedefTag - || kind === SyntaxKind.JSDocCallbackTag - || kind === SyntaxKind.JSDocPropertyTag; + return ( + kind === SyntaxKind.ArrowFunction || + kind === SyntaxKind.BindingElement || + kind === SyntaxKind.ClassDeclaration || + kind === SyntaxKind.ClassExpression || + kind === SyntaxKind.ClassStaticBlockDeclaration || + kind === SyntaxKind.Constructor || + kind === SyntaxKind.EnumDeclaration || + kind === SyntaxKind.EnumMember || + kind === SyntaxKind.ExportSpecifier || + kind === SyntaxKind.FunctionDeclaration || + kind === SyntaxKind.FunctionExpression || + kind === SyntaxKind.GetAccessor || + kind === SyntaxKind.ImportClause || + kind === SyntaxKind.ImportEqualsDeclaration || + kind === SyntaxKind.ImportSpecifier || + kind === SyntaxKind.InterfaceDeclaration || + kind === SyntaxKind.JsxAttribute || + kind === SyntaxKind.MethodDeclaration || + kind === SyntaxKind.MethodSignature || + kind === SyntaxKind.ModuleDeclaration || + kind === SyntaxKind.NamespaceExportDeclaration || + kind === SyntaxKind.NamespaceImport || + kind === SyntaxKind.NamespaceExport || + kind === SyntaxKind.Parameter || + kind === SyntaxKind.PropertyAssignment || + kind === SyntaxKind.PropertyDeclaration || + kind === SyntaxKind.PropertySignature || + kind === SyntaxKind.SetAccessor || + kind === SyntaxKind.ShorthandPropertyAssignment || + kind === SyntaxKind.TypeAliasDeclaration || + kind === SyntaxKind.TypeParameter || + kind === SyntaxKind.VariableDeclaration || + kind === SyntaxKind.JSDocTypedefTag || + kind === SyntaxKind.JSDocCallbackTag || + kind === SyntaxKind.JSDocPropertyTag + ); } function isDeclarationStatementKind(kind: SyntaxKind) { - return kind === SyntaxKind.FunctionDeclaration - || kind === SyntaxKind.MissingDeclaration - || kind === SyntaxKind.ClassDeclaration - || kind === SyntaxKind.InterfaceDeclaration - || kind === SyntaxKind.TypeAliasDeclaration - || kind === SyntaxKind.EnumDeclaration - || kind === SyntaxKind.ModuleDeclaration - || kind === SyntaxKind.ImportDeclaration - || kind === SyntaxKind.ImportEqualsDeclaration - || kind === SyntaxKind.ExportDeclaration - || kind === SyntaxKind.ExportAssignment - || kind === SyntaxKind.NamespaceExportDeclaration; + return ( + kind === SyntaxKind.FunctionDeclaration || + kind === SyntaxKind.MissingDeclaration || + kind === SyntaxKind.ClassDeclaration || + kind === SyntaxKind.InterfaceDeclaration || + kind === SyntaxKind.TypeAliasDeclaration || + kind === SyntaxKind.EnumDeclaration || + kind === SyntaxKind.ModuleDeclaration || + kind === SyntaxKind.ImportDeclaration || + kind === SyntaxKind.ImportEqualsDeclaration || + kind === SyntaxKind.ExportDeclaration || + kind === SyntaxKind.ExportAssignment || + kind === SyntaxKind.NamespaceExportDeclaration + ); } function isStatementKindButNotDeclarationKind(kind: SyntaxKind) { - return kind === SyntaxKind.BreakStatement - || kind === SyntaxKind.ContinueStatement - || kind === SyntaxKind.DebuggerStatement - || kind === SyntaxKind.DoStatement - || kind === SyntaxKind.ExpressionStatement - || kind === SyntaxKind.EmptyStatement - || kind === SyntaxKind.ForInStatement - || kind === SyntaxKind.ForOfStatement - || kind === SyntaxKind.ForStatement - || kind === SyntaxKind.IfStatement - || kind === SyntaxKind.LabeledStatement - || kind === SyntaxKind.ReturnStatement - || kind === SyntaxKind.SwitchStatement - || kind === SyntaxKind.ThrowStatement - || kind === SyntaxKind.TryStatement - || kind === SyntaxKind.VariableStatement - || kind === SyntaxKind.WhileStatement - || kind === SyntaxKind.WithStatement - || kind === SyntaxKind.NotEmittedStatement; -} - -/** @internal */ -export function isDeclaration(node: Node): node is NamedDeclaration { + return ( + kind === SyntaxKind.BreakStatement || + kind === SyntaxKind.ContinueStatement || + kind === SyntaxKind.DebuggerStatement || + kind === SyntaxKind.DoStatement || + kind === SyntaxKind.ExpressionStatement || + kind === SyntaxKind.EmptyStatement || + kind === SyntaxKind.ForInStatement || + kind === SyntaxKind.ForOfStatement || + kind === SyntaxKind.ForStatement || + kind === SyntaxKind.IfStatement || + kind === SyntaxKind.LabeledStatement || + kind === SyntaxKind.ReturnStatement || + kind === SyntaxKind.SwitchStatement || + kind === SyntaxKind.ThrowStatement || + kind === SyntaxKind.TryStatement || + kind === SyntaxKind.VariableStatement || + kind === SyntaxKind.WhileStatement || + kind === SyntaxKind.WithStatement || + kind === SyntaxKind.NotEmittedStatement + ); +} + +/** @internal */ +export function isDeclaration(node: Node): node is Declaration { if (node.kind === SyntaxKind.TypeParameter) { - return (node.parent && node.parent.kind !== SyntaxKind.JSDocTemplateTag) || isInJSFile(node); + return ( + (node.parent && node.parent.kind !== SyntaxKind.JSDocTemplateTag) || + isInJSFile(node) + ); } return isDeclarationKind(node.kind); } /** @internal */ -export function isDeclarationStatement(node: Node): node is DeclarationStatement { +export function isDeclarationStatement( + node: Node, +): node is DeclarationStatement { return isDeclarationStatementKind(node.kind); } @@ -2383,21 +2965,28 @@ export function isDeclarationStatement(node: Node): node is DeclarationStatement * * @internal */ -export function isStatementButNotDeclaration(node: Node): node is Statement { +export function isStatementButNotDeclaration( + node: Node, +): boolean { return isStatementKindButNotDeclarationKind(node.kind); } export function isStatement(node: Node): node is Statement { const kind = node.kind; - return isStatementKindButNotDeclarationKind(kind) - || isDeclarationStatementKind(kind) - || isBlockStatement(node); + return ( + isStatementKindButNotDeclarationKind(kind) || + isDeclarationStatementKind(kind) || + isBlockStatement(node) + ); } function isBlockStatement(node: Node): node is Block { if (node.kind !== SyntaxKind.Block) return false; if (node.parent !== undefined) { - if (node.parent.kind === SyntaxKind.TryStatement || node.parent.kind === SyntaxKind.CatchClause) { + if ( + node.parent.kind === SyntaxKind.TryStatement || + node.parent.kind === SyntaxKind.CatchClause + ) { return false; } } @@ -2412,63 +3001,83 @@ function isBlockStatement(node: Node): node is Block { */ export function isStatementOrBlock(node: Node): node is Statement | Block { const kind = node.kind; - return isStatementKindButNotDeclarationKind(kind) - || isDeclarationStatementKind(kind) - || kind === SyntaxKind.Block; + return ( + isStatementKindButNotDeclarationKind(kind) || + isDeclarationStatementKind(kind) || + kind === SyntaxKind.Block + ); } // Module references export function isModuleReference(node: Node): node is ModuleReference { const kind = node.kind; - return kind === SyntaxKind.ExternalModuleReference - || kind === SyntaxKind.QualifiedName - || kind === SyntaxKind.Identifier; + return ( + kind === SyntaxKind.ExternalModuleReference || + kind === SyntaxKind.QualifiedName || + kind === SyntaxKind.Identifier + ); } // JSX -export function isJsxTagNameExpression(node: Node): node is JsxTagNameExpression { +export function isJsxTagNameExpression( + node: Node, +): node is JsxTagNameExpression { const kind = node.kind; - return kind === SyntaxKind.ThisKeyword - || kind === SyntaxKind.Identifier - || kind === SyntaxKind.PropertyAccessExpression - || kind === SyntaxKind.JsxNamespacedName; + return ( + kind === SyntaxKind.ThisKeyword || + kind === SyntaxKind.Identifier || + kind === SyntaxKind.PropertyAccessExpression || + kind === SyntaxKind.JsxNamespacedName + ); } export function isJsxChild(node: Node): node is JsxChild { const kind = node.kind; - return kind === SyntaxKind.JsxElement - || kind === SyntaxKind.JsxExpression - || kind === SyntaxKind.JsxSelfClosingElement - || kind === SyntaxKind.JsxText - || kind === SyntaxKind.JsxFragment; + return ( + kind === SyntaxKind.JsxElement || + kind === SyntaxKind.JsxExpression || + kind === SyntaxKind.JsxSelfClosingElement || + kind === SyntaxKind.JsxText || + kind === SyntaxKind.JsxFragment + ); } export function isJsxAttributeLike(node: Node): node is JsxAttributeLike { const kind = node.kind; - return kind === SyntaxKind.JsxAttribute - || kind === SyntaxKind.JsxSpreadAttribute; + return ( + kind === SyntaxKind.JsxAttribute || + kind === SyntaxKind.JsxSpreadAttribute + ); } -export function isStringLiteralOrJsxExpression(node: Node): node is StringLiteral | JsxExpression { +export function isStringLiteralOrJsxExpression( + node: Node, +): node is StringLiteral | JsxExpression { const kind = node.kind; - return kind === SyntaxKind.StringLiteral - || kind === SyntaxKind.JsxExpression; + return ( + kind === SyntaxKind.StringLiteral || kind === SyntaxKind.JsxExpression + ); } -export function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement { +export function isJsxOpeningLikeElement( + node: Node, +): node is JsxOpeningLikeElement { const kind = node.kind; - return kind === SyntaxKind.JsxOpeningElement - || kind === SyntaxKind.JsxSelfClosingElement; + return ( + kind === SyntaxKind.JsxOpeningElement || + kind === SyntaxKind.JsxSelfClosingElement + ); } // Clauses -export function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause { +export function isCaseOrDefaultClause( + node: Node, +): node is CaseOrDefaultClause { const kind = node.kind; - return kind === SyntaxKind.CaseClause - || kind === SyntaxKind.DefaultClause; + return kind === SyntaxKind.CaseClause || kind === SyntaxKind.DefaultClause; } // JSDoc @@ -2479,24 +3088,32 @@ export function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause { * @internal */ export function isJSDocNode(node: Node): boolean { - return node.kind >= SyntaxKind.FirstJSDocNode && node.kind <= SyntaxKind.LastJSDocNode; + return ( + node.kind >= SyntaxKind.FirstJSDocNode && + node.kind <= SyntaxKind.LastJSDocNode + ); } /** True if node is of a kind that may contain comment text. */ export function isJSDocCommentContainingNode(node: Node): boolean { - return node.kind === SyntaxKind.JSDoc - || node.kind === SyntaxKind.JSDocNamepathType - || node.kind === SyntaxKind.JSDocText - || isJSDocLinkLike(node) - || isJSDocTag(node) - || isJSDocTypeLiteral(node) - || isJSDocSignature(node); + return ( + node.kind === SyntaxKind.JSDoc || + node.kind === SyntaxKind.JSDocNamepathType || + node.kind === SyntaxKind.JSDocText || + isJSDocLinkLike(node) || + isJSDocTag(node) || + isJSDocTypeLiteral(node) || + isJSDocSignature(node) + ); } // TODO: determine what this does before making it public. /** @internal */ export function isJSDocTag(node: Node): node is JSDocTag { - return node.kind >= SyntaxKind.FirstJSDocTagNode && node.kind <= SyntaxKind.LastJSDocTagNode; + return ( + node.kind >= SyntaxKind.FirstJSDocTagNode && + node.kind <= SyntaxKind.LastJSDocTagNode + ); } export function isSetAccessor(node: Node): node is SetAccessorDeclaration { @@ -2539,7 +3156,9 @@ export function hasInitializer(node: Node): node is HasInitializer { } /** True if has initializer node attached to it. */ -export function hasOnlyExpressionInitializer(node: Node): node is HasExpressionInitializer { +export function hasOnlyExpressionInitializer( + node: Node, +): node is HasExpressionInitializer { switch (node.kind) { case SyntaxKind.VariableDeclaration: case SyntaxKind.Parameter: @@ -2553,13 +3172,22 @@ export function hasOnlyExpressionInitializer(node: Node): node is HasExpressionI } } -export function isObjectLiteralElement(node: Node): node is ObjectLiteralElement { - return node.kind === SyntaxKind.JsxAttribute || node.kind === SyntaxKind.JsxSpreadAttribute || isObjectLiteralElementLike(node); +export function isObjectLiteralElement( + node: Node, +): node is ObjectLiteralElement { + return ( + node.kind === SyntaxKind.JsxAttribute || + node.kind === SyntaxKind.JsxSpreadAttribute || + isObjectLiteralElementLike(node) + ); } /** @internal */ export function isTypeReferenceType(node: Node): node is TypeReferenceType { - return node.kind === SyntaxKind.TypeReference || node.kind === SyntaxKind.ExpressionWithTypeArguments; + return ( + node.kind === SyntaxKind.TypeReference || + node.kind === SyntaxKind.ExpressionWithTypeArguments + ); } const MAX_SMI_X86 = 0x3fff_ffff; @@ -2586,20 +3214,42 @@ export function guessIndentation(lines: string[]) { return indentation === MAX_SMI_X86 ? undefined : indentation; } -export function isStringLiteralLike(node: Node | FileReference): node is StringLiteralLike { - return (node as Node).kind === SyntaxKind.StringLiteral || (node as Node).kind === SyntaxKind.NoSubstitutionTemplateLiteral; +export function isStringLiteralLike( + node: NodeBase | FileReference, +): node is StringLiteralLike { + return ( + (node as Node).kind === SyntaxKind.StringLiteral || + (node as Node).kind === SyntaxKind.NoSubstitutionTemplateLiteral + ); } -export function isJSDocLinkLike(node: Node): node is JSDocLink | JSDocLinkCode | JSDocLinkPlain { - return node.kind === SyntaxKind.JSDocLink || node.kind === SyntaxKind.JSDocLinkCode || node.kind === SyntaxKind.JSDocLinkPlain; +export function isJSDocLinkLike( + node: Node, +): node is JSDocLink | JSDocLinkCode | JSDocLinkPlain { + return ( + node.kind === SyntaxKind.JSDocLink || + node.kind === SyntaxKind.JSDocLinkCode || + node.kind === SyntaxKind.JSDocLinkPlain + ); } -export function hasRestParameter(s: SignatureDeclaration | JSDocSignature): boolean { - const last = lastOrUndefined(s.parameters); +export function hasRestParameter( + s: SignatureDeclaration | JSDocSignature, +): boolean { + const last = lastOrUndefined( + s.parameters, + ); return !!last && isRestParameter(last); } -export function isRestParameter(node: ParameterDeclaration | JSDocParameterTag): boolean { - const type = isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; - return (node as ParameterDeclaration).dotDotDotToken !== undefined || !!type && type.kind === SyntaxKind.JSDocVariadicType; +export function isRestParameter( + node: ParameterDeclaration | JSDocParameterTag, +): boolean { + const type = isJSDocParameterTag(node) + ? node.typeExpression && node.typeExpression.type + : node.type; + return ( + (node as ParameterDeclaration).dotDotDotToken !== undefined || + (!!type && type.kind === SyntaxKind.JSDocVariadicType) + ); } diff --git a/src/compiler/visitorPublic.ts b/src/compiler/visitorPublic.ts index c5e99d170911c..be19e95166447 100644 --- a/src/compiler/visitorPublic.ts +++ b/src/compiler/visitorPublic.ts @@ -86,8 +86,8 @@ import { isVariableDeclaration, isVariableDeclarationList, LexicalEnvironmentFlags, - Node, NodeArray, + Node, NodesVisitor, NodeVisitor, ParameterDeclaration, diff --git a/src/services/classifier2020.ts b/src/services/classifier2020.ts index 1fa90584974f5..7d8984b6ba6d0 100644 --- a/src/services/classifier2020.ts +++ b/src/services/classifier2020.ts @@ -5,7 +5,7 @@ import { ClassifiedSpan2020, createTextSpan, Debug, - Declaration, + DeclarationBase, EndOfLineState, forEachChild, getCombinedModifierFlags, @@ -28,7 +28,7 @@ import { isSourceFile, isVariableDeclaration, ModifierFlags, - NamedDeclaration, + NamedDeclarationBase, Node, NodeFlags, ParameterDeclaration, @@ -158,7 +158,7 @@ function collectTokens(program: Program, sourceFile: SourceFile, span: TextSpan, let modifierSet = 0; if (node.parent) { const parentIsDeclaration = isBindingElement(node.parent) || tokenFromDeclarationMapping.get(node.parent.kind) === typeIdx; - if (parentIsDeclaration && (node.parent as NamedDeclaration).name === node) { + if (parentIsDeclaration && (node.parent as NamedDeclarationBase).name === node) { modifierSet = 1 << TokenModifier.declaration; } } @@ -252,7 +252,7 @@ function reclassifyByType(typeChecker: TypeChecker, node: Node, typeIdx: TokenTy return typeIdx; } -function isLocalDeclaration(decl: Declaration, sourceFile: SourceFile): boolean { +function isLocalDeclaration(decl: DeclarationBase, sourceFile: SourceFile): boolean { if (isBindingElement(decl)) { decl = getDeclarationForBindingElement(decl); } diff --git a/src/services/codefixes/fixImportNonExportedMember.ts b/src/services/codefixes/fixImportNonExportedMember.ts index 376a74663e114..72c2066fbdfe2 100644 --- a/src/services/codefixes/fixImportNonExportedMember.ts +++ b/src/services/codefixes/fixImportNonExportedMember.ts @@ -1,7 +1,7 @@ import { canHaveExportModifier, canHaveLocals, - Declaration, + DeclarationBase, Diagnostics, ExportDeclaration, factory, @@ -105,7 +105,7 @@ interface ExportName { interface Info { exportName: ExportName; - node: Declaration | VariableStatement; + node: DeclarationBase | VariableStatement; moduleSourceFile: SourceFile; moduleSpecifier: string; } diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 804e87040f48b..e3dca9efca336 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -11,7 +11,7 @@ import { CodeFixContextBase, combine, Debug, - Declaration, + DeclarationBase, Diagnostics, emptyArray, EntityName, @@ -357,7 +357,7 @@ export function addNewNodeForMemberSymbol( return getSynthesizedDeepClone(typeNode, /*includeTrivia*/ false); } - function createDeclarationName(symbol: Symbol, declaration: Declaration | undefined): PropertyName { + function createDeclarationName(symbol: Symbol, declaration: DeclarationBase | undefined): PropertyName { if (getCheckFlags(symbol) & CheckFlags.Mapped) { const nameType = (symbol as TransientSymbol).links.nameType; if (nameType && isTypeUsableAsPropertyName(nameType)) { diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 95a19e1d39638..fac7d50df9174 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -9,7 +9,7 @@ import { createMultiMap, createSymbolTable, Debug, - Declaration, + DeclarationBase, DiagnosticMessage, Diagnostics, ElementAccessExpression, @@ -163,7 +163,7 @@ registerCodeFix({ const { sourceFile, program, span: { start }, errorCode, cancellationToken, host, preferences } = context; const token = getTokenAtPosition(sourceFile, start); - let declaration: Declaration | undefined; + let declaration: DeclarationBase | undefined; const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host, preferences); }); @@ -219,7 +219,7 @@ function mapSuggestionDiagnostic(errorCode: number) { return errorCode; } -function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost, preferences: UserPreferences): Declaration | undefined { +function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost, preferences: UserPreferences): DeclarationBase | undefined { if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken && token.kind !== SyntaxKind.ThisKeyword) { return undefined; } @@ -265,7 +265,7 @@ function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, to return undefined; } - let declaration: Declaration | undefined; + let declaration: DeclarationBase | undefined; switch (errorCode) { // Parameter declarations case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: diff --git a/src/services/completions.ts b/src/services/completions.ts index 11fbce92c6b41..f8187a0dcca0d 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -44,7 +44,7 @@ import { createTextSpanFromNode, createTextSpanFromRange, Debug, - Declaration, + DeclarationBase, Decorator, Diagnostics, diagnosticToString, @@ -4321,7 +4321,7 @@ function getCompletionData( completionKind = CompletionKind.ObjectPropertyDeclaration; let typeMembers: Symbol[] | undefined; - let existingMembers: readonly Declaration[] | undefined; + let existingMembers: readonly DeclarationBase[] | undefined; if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) { const instantiatedType = tryGetObjectLiteralContextualType(objectLikeContainer, typeChecker); @@ -4862,7 +4862,7 @@ function getCompletionData( * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations * do not occur at the current position and have not otherwise been typed. */ - function filterObjectMembersList(contextualMemberSymbols: Symbol[], existingMembers: readonly Declaration[]): Symbol[] { + function filterObjectMembersList(contextualMemberSymbols: Symbol[], existingMembers: readonly DeclarationBase[]): Symbol[] { if (existingMembers.length === 0) { return contextualMemberSymbols; } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 9dc0f88bf85a1..383e4df12e0e2 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -21,7 +21,7 @@ import { createTextSpanFromBounds, createTextSpanFromRange, Debug, - Declaration, + DeclarationBase, displayPart, DocumentSpan, emptyArray, @@ -192,7 +192,7 @@ import { ModifierFlags, ModuleDeclaration, MultiMap, - NamedDeclaration, + NamedDeclarationBase, Node, NodeFlags, nodeSeenTracker, @@ -320,7 +320,7 @@ export interface SpanEntry { export function nodeEntry(node: Node, kind: NodeEntryKind = EntryKind.Node): NodeEntry { return { kind, - node: (node as NamedDeclaration).name || node, + node: (node as NamedDeclarationBase).name || node, context: getContextNodeForNodeEntry(node), }; } @@ -369,7 +369,7 @@ function getContextNodeForNodeEntry(node: Node): ContextNode | undefined { const declOrStatement = findAncestor(validImport, node => isDeclaration(node) || isStatement(node) || - isJSDocTag(node))! as NamedDeclaration | Statement | JSDocTag; + isJSDocTag(node))! as NamedDeclarationBase | Statement | JSDocTag; return isDeclaration(declOrStatement) ? getContextNode(declOrStatement) : declOrStatement; @@ -400,7 +400,7 @@ function getContextNodeForNodeEntry(node: Node): ContextNode | undefined { } /** @internal */ -export function getContextNode(node: NamedDeclaration | BinaryExpression | ForInOrOfStatement | undefined): ContextNode | undefined { +export function getContextNode(node: NamedDeclarationBase | BinaryExpression | ForInOrOfStatement | undefined): ContextNode | undefined { if (!node) return undefined; switch (node.kind) { case SyntaxKind.VariableDeclaration: @@ -413,7 +413,7 @@ export function getContextNode(node: NamedDeclaration | BinaryExpression | ForIn node.parent; case SyntaxKind.BindingElement: - return getContextNode(node.parent.parent as NamedDeclaration); + return getContextNode(node.parent.parent as NamedDeclarationBase); case SyntaxKind.ImportSpecifier: return node.parent.parent.parent; @@ -899,7 +899,7 @@ export function isDeclarationOfSymbol(node: Node, target: Symbol | undefined): b : isLiteralComputedPropertyDeclarationName(node) ? node.parent.parent : node.kind === SyntaxKind.ConstructorKeyword && isConstructorDeclaration(node.parent) ? node.parent.parent : undefined); - const commonjsSource = source && isBinaryExpression(source) ? source.left as unknown as Declaration : undefined; + const commonjsSource = source && isBinaryExpression(source) ? source.left as unknown as DeclarationBase : undefined; return !!(source && target.declarations?.some(d => d === source || d === commonjsSource)); } @@ -907,7 +907,7 @@ export function isDeclarationOfSymbol(node: Node, target: Symbol | undefined): b * True if 'decl' provides a value, as in `function f() {}`; * false if 'decl' is just a location for a future write, as in 'let x;' */ -function declarationIsWriteAccess(decl: Declaration): boolean { +function declarationIsWriteAccess(decl: DeclarationBase): boolean { // Consider anything in an ambient declaration to be a write access since it may be coming from JS. if (!!(decl.flags & NodeFlags.Ambient)) return true; diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 474af54946f32..754a3a5fee578 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -9,7 +9,7 @@ import { concatenate, createTextChangeFromStartLength, Debug, - Declaration, + DeclarationBase, Diagnostic, EditorSettings, find, @@ -681,7 +681,7 @@ function formatSpanWorker( case SyntaxKind.PropertyDeclaration: case SyntaxKind.Parameter: - const name = getNameOfDeclaration(node as Declaration); + const name = getNameOfDeclaration(node as DeclarationBase); if (name) { return name.kind; } diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index c603c6c7bab3d..af7b102aced54 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -10,7 +10,7 @@ import { createTextSpanFromNode, createTextSpanFromRange, Debug, - Declaration, + DeclarationBase, DefinitionInfo, DefinitionInfoAndBoundSpan, emptyArray, @@ -549,11 +549,11 @@ function shouldSkipAlias(node: Node, declaration: Node): boolean { * calling) covers our tests but feels like a hack, and it would be great if someone could come * up with a more precise definition of what counts as a definition. */ -function isExpandoDeclaration(node: Declaration): boolean { +function isExpandoDeclaration(node: DeclarationBase): boolean { if (!isAssignmentDeclaration(node)) return false; const containingAssignment = findAncestor(node, p => { if (isAssignmentExpression(p)) return true; - if (!isAssignmentDeclaration(p as Declaration)) return "quit"; + if (!isAssignmentDeclaration(p as DeclarationBase)) return "quit"; return false; }) as AssignmentExpression | undefined; return !!containingAssignment && getAssignmentDeclarationKind(containingAssignment) === AssignmentDeclarationKind.Property; @@ -580,7 +580,7 @@ function getDefinitionFromSymbol(typeChecker: TypeChecker, symbol: Symbol, node: : undefined; } - function getSignatureDefinition(signatureDeclarations: readonly Declaration[] | undefined, selectConstructors: boolean): DefinitionInfo[] | undefined { + function getSignatureDefinition(signatureDeclarations: readonly DeclarationBase[] | undefined, selectConstructors: boolean): DefinitionInfo[] | undefined { if (!signatureDeclarations) { return undefined; } @@ -601,7 +601,7 @@ function getDefinitionFromSymbol(typeChecker: TypeChecker, symbol: Symbol, node: * * @internal */ -export function createDefinitionInfo(declaration: Declaration, checker: TypeChecker, symbol: Symbol, node: Node, unverified?: boolean, failedAliasResolution?: boolean): DefinitionInfo { +export function createDefinitionInfo(declaration: DeclarationBase, checker: TypeChecker, symbol: Symbol, node: Node, unverified?: boolean, failedAliasResolution?: boolean): DefinitionInfo { const symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol const symbolKind = SymbolDisplay.getSymbolKind(checker, symbol, node); const containerName = symbol.parent ? checker.symbolToString(symbol.parent, node) : ""; @@ -609,7 +609,7 @@ export function createDefinitionInfo(declaration: Declaration, checker: TypeChec } /** Creates a DefinitionInfo directly from the name of a declaration. */ -function createDefinitionInfoFromName(checker: TypeChecker, declaration: Declaration, symbolKind: ScriptElementKind, symbolName: string, containerName: string, unverified?: boolean, failedAliasResolution?: boolean, textSpan?: TextSpan): DefinitionInfo { +function createDefinitionInfoFromName(checker: TypeChecker, declaration: DeclarationBase, symbolKind: ScriptElementKind, symbolName: string, containerName: string, unverified?: boolean, failedAliasResolution?: boolean, textSpan?: TextSpan): DefinitionInfo { const sourceFile = declaration.getSourceFile(); if (!textSpan) { const name = getNameOfDeclaration(declaration) || declaration; @@ -634,12 +634,12 @@ function createDefinitionInfoFromName(checker: TypeChecker, declaration: Declara }; } -function isDefinitionVisible(checker: TypeChecker, declaration: Declaration): boolean { +function isDefinitionVisible(checker: TypeChecker, declaration: DeclarationBase): boolean { if (checker.isDeclarationVisible(declaration)) return true; if (!declaration.parent) return false; // Variable initializers are visible if variable is visible - if (hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) return isDefinitionVisible(checker, declaration.parent as Declaration); + if (hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) return isDefinitionVisible(checker, declaration.parent as DeclarationBase); // Handle some exceptions here like arrow function, members of class and object literal expression which are technically not visible but we want the definition to be determined by its parent switch (declaration.kind) { @@ -659,7 +659,7 @@ function isDefinitionVisible(checker: TypeChecker, declaration: Declaration): bo case SyntaxKind.ClassExpression: case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionExpression: - return isDefinitionVisible(checker, declaration.parent as Declaration); + return isDefinitionVisible(checker, declaration.parent as DeclarationBase); default: return false; } diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 27d57464b5abe..f6602b3e04be7 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -10,7 +10,7 @@ import { Completions, ConstructorDeclaration, contains, - Declaration, + DeclarationBase, DocCommentTemplateOptions, emptyArray, Expression, @@ -181,7 +181,7 @@ let jsDocTagNameCompletionEntries: CompletionEntry[]; let jsDocTagCompletionEntries: CompletionEntry[]; /** @internal */ -export function getJsDocCommentsFromDeclarations(declarations: readonly Declaration[], checker?: TypeChecker): SymbolDisplayPart[] { +export function getJsDocCommentsFromDeclarations(declarations: readonly DeclarationBase[], checker?: TypeChecker): SymbolDisplayPart[] { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times // which only varies in type parameter @@ -222,7 +222,7 @@ function isIdenticalListOfDisplayParts(parts1: SymbolDisplayPart[], parts2: Symb return arraysEqual(parts1, parts2, (p1, p2) => p1.kind === p2.kind && p1.text === p2.text); } -function getCommentHavingNodes(declaration: Declaration): readonly (JSDoc | JSDocTag)[] { +function getCommentHavingNodes(declaration: DeclarationBase): readonly (JSDoc | JSDocTag)[] { switch (declaration.kind) { case SyntaxKind.JSDocParameterTag: case SyntaxKind.JSDocPropertyTag: @@ -236,7 +236,7 @@ function getCommentHavingNodes(declaration: Declaration): readonly (JSDoc | JSDo } /** @internal */ -export function getJsDocTagsFromDeclarations(declarations?: Declaration[], checker?: TypeChecker): JSDocTagInfo[] { +export function getJsDocTagsFromDeclarations(declarations?: DeclarationBase[], checker?: TypeChecker): JSDocTagInfo[] { // Only collect doc comments from duplicate declarations once. const infos: JSDocTagInfo[] = []; forEachUnique(declarations, declaration => { diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 5beb279698d2e..486d404c485e0 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -4,7 +4,7 @@ import { compareValues, createPatternMatcher, createTextSpanFromNode, - Declaration, + DeclarationBase, emptyArray, Expression, getContainerNode, @@ -34,7 +34,7 @@ interface RawNavigateToItem { readonly fileName: string; readonly matchKind: PatternMatchKind; readonly isCaseSensitive: boolean; - readonly declaration: Declaration; + readonly declaration: DeclarationBase; } /** @internal */ @@ -75,7 +75,7 @@ function shouldExcludeFile(file: SourceFile, excludeLibFiles: boolean, singleCur function getItemsFromNamedDeclaration( patternMatcher: PatternMatcher, name: string, - declarations: readonly Declaration[], + declarations: readonly DeclarationBase[], checker: TypeChecker, fileName: string, excludeLibFiles: boolean, @@ -106,7 +106,7 @@ function getItemsFromNamedDeclaration( } function shouldKeepItem( - declaration: Declaration, + declaration: DeclarationBase, checker: TypeChecker, excludeLibFiles: boolean, singleCurrentFile: SourceFile | undefined, @@ -124,7 +124,7 @@ function shouldKeepItem( } } -function tryAddSingleDeclarationName(declaration: Declaration, containers: string[]): boolean { +function tryAddSingleDeclarationName(declaration: DeclarationBase, containers: string[]): boolean { const name = getNameOfDeclaration(declaration); return !!name && (pushLiteral(name, containers) || name.kind === SyntaxKind.ComputedPropertyName && tryAddComputedPropertyName(name.expression, containers)); } @@ -141,7 +141,7 @@ function pushLiteral(node: Node, containers: string[]): boolean { return isPropertyNameLiteral(node) && (containers.push(getTextOfIdentifierOrLiteral(node)), true); } -function getContainers(declaration: Declaration): readonly string[] { +function getContainers(declaration: DeclarationBase): readonly string[] { const containers: string[] = []; // First, if we started with a computed property name, then add all but the last diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 26a5f098967e1..7e48ce983e86a 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -19,7 +19,7 @@ import { createTextSpanFromNode, createTextSpanFromRange, Debug, - Declaration, + DeclarationBase, DeclarationName, declarationNameToString, EntityNameExpression, @@ -308,7 +308,7 @@ function addNodeWithRecursiveInitializer(node: VariableDeclaration | PropertyAss } } -function hasNavigationBarName(node: Declaration) { +function hasNavigationBarName(node: DeclarationBase) { const name = getNameOfDeclaration(node); if (name === undefined) return false; @@ -579,7 +579,7 @@ function addChildrenRecursively(node: Node | undefined): void { function mergeChildren(children: NavigationBarNode[], node: NavigationBarNode): void { const nameToItems = new Map(); filterMutate(children, (child, index) => { - const declName = child.name || getNameOfDeclaration(child.node as Declaration); + const declName = child.name || getNameOfDeclaration(child.node as DeclarationBase); const name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. @@ -807,7 +807,7 @@ function tryGetName(node: Node): string | undefined { return getModuleName(node as ModuleDeclaration); } - const declName = getNameOfDeclaration(node as Declaration); + const declName = getNameOfDeclaration(node as DeclarationBase); if (declName && isPropertyName(declName)) { const propertyName = getPropertyNameForPropertyNameNode(declName); return propertyName && unescapeLeadingUnderscores(propertyName); diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index f25098e2c060a..6c9c75db14d1d 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -22,7 +22,7 @@ import { createDiagnosticForNode, createFileDiagnostic, Debug, - Declaration, + DeclarationBase, Diagnostic, DiagnosticCategory, DiagnosticMessage, @@ -116,7 +116,7 @@ import { Modifier, ModifierFlags, ModuleBlock, - NamedDeclaration, + NamedDeclarationBase, Node, NodeBuilderFlags, NodeFlags, @@ -1561,7 +1561,7 @@ function getContainingVariableDeclarationIfInList(node: Node, scope: Scope) { } } -function getFirstDeclarationBeforePosition(type: Type, position: number): Declaration | undefined { +function getFirstDeclarationBeforePosition(type: Type, position: number): DeclarationBase | undefined { let firstDeclaration; const symbol = type.symbol; @@ -1577,8 +1577,8 @@ function getFirstDeclarationBeforePosition(type: Type, position: number): Declar } function compareTypesByDeclarationOrder( - { type: type1, declaration: declaration1 }: { type: Type; declaration?: Declaration; }, - { type: type2, declaration: declaration2 }: { type: Type; declaration?: Declaration; }, + { type: type1, declaration: declaration1 }: { type: Type; declaration?: DeclarationBase; }, + { type: type2, declaration: declaration2 }: { type: Type; declaration?: DeclarationBase; }, ) { return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive( @@ -1827,10 +1827,10 @@ function collectReadsAndWrites( const substitutionsPerScope: Map[] = []; const functionErrorsPerScope: Diagnostic[][] = []; const constantErrorsPerScope: Diagnostic[][] = []; - const visibleDeclarationsInExtractedRange: NamedDeclaration[] = []; + const visibleDeclarationsInExtractedRange: NamedDeclarationBase[] = []; const exposedVariableSymbolSet = new Map(); // Key is symbol ID const exposedVariableDeclarations: VariableDeclaration[] = []; - let firstExposedNonVariableDeclaration: NamedDeclaration | undefined; + let firstExposedNonVariableDeclaration: NamedDeclarationBase | undefined; const expression = !isReadonlyArray(targetRange.range) ? targetRange.range @@ -1941,7 +1941,7 @@ function collectReadsAndWrites( } let hasWrite = false; - let readonlyClassPropertyWrite: Declaration | undefined; + let readonlyClassPropertyWrite: DeclarationBase | undefined; usagesPerScope[i].usages.forEach(value => { if (value.usage === Usage.Write) { hasWrite = true; diff --git a/src/services/refactors/moveToFile.ts b/src/services/refactors/moveToFile.ts index 29aa22de80216..554835315545d 100644 --- a/src/services/refactors/moveToFile.ts +++ b/src/services/refactors/moveToFile.ts @@ -24,8 +24,8 @@ import { createModuleSpecifierResolutionHost, createTextRangeFromSpan, Debug, - Declaration, - DeclarationStatement, + DeclarationBase, + DeclarationStatementBase, Diagnostics, emptyArray, EnumDeclaration, @@ -724,7 +724,7 @@ function addEs6Export(d: TopLevelDeclarationStatement): TopLevelDeclarationState // Shouldn't try to add 'export' keyword to `exports.x = ...` return Debug.fail(); default: - return Debug.assertNever(d, `Unexpected declaration kind ${(d as DeclarationStatement).kind}`); + return Debug.assertNever(d, `Unexpected declaration kind ${(d as DeclarationStatementBase).kind}`); } } function addCommonjsExport(decl: TopLevelDeclarationStatement): readonly Statement[] | undefined { @@ -1109,7 +1109,7 @@ function forEachTopLevelDeclaration(statement: Statement, cb: (node: TopLevel } } -function isInImport(decl: Declaration) { +function isInImport(decl: DeclarationBase) { switch (decl.kind) { case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.ImportSpecifier: diff --git a/src/services/services.ts b/src/services/services.ts index 56af0f72d70f3..4dc0fd54bc9d4 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -44,7 +44,7 @@ import { createTextSpanFromNode, createTextSpanFromRange, Debug, - Declaration, + DeclarationBase, deduplicate, DefinitionInfo, DefinitionInfoAndBoundSpan, @@ -620,8 +620,8 @@ class TokenOrIdentifierObject implements Node { class SymbolObject implements Symbol { flags: SymbolFlags; escapedName: __String; - declarations!: Declaration[]; - valueDeclaration!: Declaration; + declarations!: DeclarationBase[]; + valueDeclaration!: DeclarationBase; id = 0; mergeId = 0; constEnumOnlyModule: boolean | undefined; @@ -658,7 +658,7 @@ class SymbolObject implements Symbol { return this.name; } - getDeclarations(): Declaration[] | undefined { + getDeclarations(): DeclarationBase[] | undefined { return this.declarations; } @@ -940,7 +940,7 @@ function hasJSDocInheritDocTag(node: Node) { return getJSDocTags(node).some(tag => tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc"); } -function getJsDocTagsOfDeclarations(declarations: Declaration[] | undefined, checker: TypeChecker | undefined): JSDocTagInfo[] { +function getJsDocTagsOfDeclarations(declarations: DeclarationBase[] | undefined, checker: TypeChecker | undefined): JSDocTagInfo[] { if (!declarations) return emptyArray; let tags = JsDoc.getJsDocTagsFromDeclarations(declarations, checker); @@ -964,7 +964,7 @@ function getJsDocTagsOfDeclarations(declarations: Declaration[] | undefined, che return tags; } -function getDocumentationComment(declarations: readonly Declaration[] | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[] { +function getDocumentationComment(declarations: readonly DeclarationBase[] | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[] { if (!declarations) return emptyArray; let doc = JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); @@ -987,7 +987,7 @@ function getDocumentationComment(declarations: readonly Declaration[] | undefine return doc; } -function findBaseOfDeclaration(checker: TypeChecker, declaration: Declaration, cb: (symbol: Symbol) => T[] | undefined): T[] | undefined { +function findBaseOfDeclaration(checker: TypeChecker, declaration: DeclarationBase, cb: (symbol: Symbol) => T[] | undefined): T[] | undefined { const classOrInterfaceDeclaration = declaration.parent?.kind === SyntaxKind.Constructor ? declaration.parent.parent : declaration.parent; if (!classOrInterfaceDeclaration) return; @@ -1042,7 +1042,7 @@ class SourceFileObject extends NodeObject implements SourceFile { public nameTable: Map<__String, number> | undefined; public imports!: readonly StringLiteralLike[]; public moduleAugmentations!: StringLiteral[]; - private namedDeclarations: Map | undefined; + private namedDeclarations: Map | undefined; public ambientModuleNames!: string[]; public checkJsDirective: CheckJsDirective | undefined; public errorExpectations: TextRange[] | undefined; @@ -1088,7 +1088,7 @@ class SourceFileObject extends NodeObject implements SourceFile { return fullText[lastCharPos] === "\n" && fullText[lastCharPos - 1] === "\r" ? lastCharPos - 1 : lastCharPos; } - public getNamedDeclarations(): Map { + public getNamedDeclarations(): Map { if (!this.namedDeclarations) { this.namedDeclarations = this.computeNamedDeclarations(); } @@ -1096,14 +1096,14 @@ class SourceFileObject extends NodeObject implements SourceFile { return this.namedDeclarations; } - private computeNamedDeclarations(): Map { - const result = createMultiMap(); + private computeNamedDeclarations(): Map { + const result = createMultiMap(); this.forEachChild(visit); return result; - function addDeclaration(declaration: Declaration) { + function addDeclaration(declaration: DeclarationBase) { const name = getDeclarationName(declaration); if (name) { result.add(name, declaration); @@ -1118,7 +1118,7 @@ class SourceFileObject extends NodeObject implements SourceFile { return declarations; } - function getDeclarationName(declaration: Declaration) { + function getDeclarationName(declaration: DeclarationBase) { const name = getNonAssignedNameOfDeclaration(declaration); return name && (isComputedPropertyName(name) && isPropertyAccessExpression(name.expression) ? name.expression.name.text : isPropertyName(name) ? getNameFromPropertyName(name) : undefined); @@ -1166,7 +1166,7 @@ class SourceFileObject extends NodeObject implements SourceFile { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.TypeLiteral: - addDeclaration(node as Declaration); + addDeclaration(node as DeclarationBase); forEachChild(node, visit); break; @@ -1192,7 +1192,7 @@ class SourceFileObject extends NodeObject implements SourceFile { case SyntaxKind.EnumMember: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - addDeclaration(node as Declaration); + addDeclaration(node as DeclarationBase); break; case SyntaxKind.ExportDeclaration: diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 177e25b18d0e5..cbbaddfd424df 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -21,7 +21,7 @@ import { createTextSpanFromRange, createTextWriter, Debug, - DeclarationStatement, + DeclarationStatementBase, EmitHint, EmitTextWriter, endsWith, @@ -1005,7 +1005,7 @@ export class ChangeTracker { } } - public insertExportModifier(sourceFile: SourceFile, node: DeclarationStatement | VariableStatement): void { + public insertExportModifier(sourceFile: SourceFile, node: DeclarationStatementBase | VariableStatement): void { this.insertText(sourceFile, node.getStart(sourceFile), "export "); } diff --git a/src/services/types.ts b/src/services/types.ts index c1d92f808dccf..c2d083fd3a37d 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -45,7 +45,7 @@ import { declare module "../compiler/types" { // Module transform: converted from interface augmentation - export interface Node { + export interface NodeBase { getSourceFile(): SourceFile; getChildCount(sourceFile?: SourceFile): number; getChildAt(index: number, sourceFile?: SourceFile): Node; @@ -94,7 +94,7 @@ declare module "../compiler/types" { getFlags(): SymbolFlags; getEscapedName(): __String; getName(): string; - getDeclarations(): Declaration[] | undefined; + getDeclarations(): DeclarationBase[] | undefined; getDocumentationComment(typeChecker: TypeChecker | undefined): SymbolDisplayPart[]; /** @internal */ getContextualDocumentationComment(context: Node | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[]; @@ -163,7 +163,7 @@ declare module "../compiler/types" { /** @internal */ scriptSnapshot: IScriptSnapshot | undefined; /** @internal */ nameTable: Map<__String, number> | undefined; - /** @internal */ getNamedDeclarations(): Map; + /** @internal */ getNamedDeclarations(): Map; getLineAndCharacterOfPosition(pos: number): LineAndCharacter; getLineEndOfPosition(pos: number): number; diff --git a/src/services/utilities.ts b/src/services/utilities.ts index b14d16bd671c2..7f3fc1d0fb7fc 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -36,7 +36,7 @@ import { createTextSpan, createTextSpanFromBounds, Debug, - Declaration, + DeclarationBase, Decorator, DefaultClause, defaultMaximumTruncationLength, @@ -715,7 +715,7 @@ export function isLiteralNameOfPropertyDeclarationOrIndexAccess(node: StringLite case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.ModuleDeclaration: - return getNameOfDeclaration(node.parent as Declaration) === node; + return getNameOfDeclaration(node.parent as DeclarationBase) === node; case SyntaxKind.ElementAccessExpression: return (node.parent as ElementAccessExpression).argumentExpression === node; case SyntaxKind.ComputedPropertyName: @@ -734,7 +734,7 @@ export function isExpressionOfExternalModuleImportEqualsDeclaration(node: Node) } /** @internal */ -export function getContainerNode(node: Node): Declaration | undefined { +export function getContainerNode(node: Node): DeclarationBase | undefined { if (isJSDocTypeAlias(node)) { // This doesn't just apply to the node immediately under the comment, but to everything in its parent's scope. // node.parent = the JSDoc comment, node.parent.parent = the node having the comment. @@ -759,7 +759,7 @@ export function getContainerNode(node: Node): Declaration | undefined { case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.ModuleDeclaration: - return node as Declaration; + return node as DeclarationBase; } } } @@ -2939,7 +2939,7 @@ export function linkTextPart(text: string) { } /** @internal */ -export function linkNamePart(text: string, target: Declaration): JSDocLinkDisplayPart { +export function linkNamePart(text: string, target: DeclarationBase): JSDocLinkDisplayPart { return { text, kind: SymbolDisplayPartKind[SymbolDisplayPartKind.linkName], @@ -4091,12 +4091,12 @@ export function startsWithUnderscore(name: string): boolean { } /** @internal */ -export function isGlobalDeclaration(declaration: Declaration) { +export function isGlobalDeclaration(declaration: DeclarationBase) { return !isNonGlobalDeclaration(declaration); } /** @internal */ -export function isNonGlobalDeclaration(declaration: Declaration) { +export function isNonGlobalDeclaration(declaration: DeclarationBase) { const sourceFile = declaration.getSourceFile(); // If the file is not a module, the declaration is global if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { @@ -4107,7 +4107,7 @@ export function isNonGlobalDeclaration(declaration: Declaration) { } /** @internal */ -export function isDeprecatedDeclaration(decl: Declaration) { +export function isDeprecatedDeclaration(decl: DeclarationBase) { return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & ModifierFlags.Deprecated); }