From ec4785962422d309b613b46e29bbc4eda094b3b3 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 1 Mar 2019 15:47:17 -0800 Subject: [PATCH 1/7] Make watch use sourceFileHash so it can be used with --incremental as well --- src/compiler/tsbuild.ts | 10 +----- src/compiler/watch.ts | 69 +++++++++++++++++++++++------------------ 2 files changed, 39 insertions(+), 40 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 1ab990355b8..59edd85d716 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -451,15 +451,7 @@ namespace ts { let readFileWithCache = (f: string) => host.readFile(f); let projectCompilerOptions = baseCompilerOptions; const compilerHost = createCompilerHostFromProgramHost(host, () => projectCompilerOptions); - const originalGetSourceFile = compilerHost.getSourceFile; - const computeHash = host.createHash || generateDjb2Hash; - compilerHost.getSourceFile = (...args) => { - const result = originalGetSourceFile.call(compilerHost, ...args); - if (result) { - result.version = computeHash.call(host, result.text); - } - return result; - }; + setCreateSourceFileAsHashVersioned(compilerHost, host); const buildInfoChecked = createFileMap(toPath); diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 41ef7876d76..02b40720783 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -280,6 +280,18 @@ namespace ts { } } + export function setCreateSourceFileAsHashVersioned(compilerHost: CompilerHost, host: ProgramHost) { + const originalGetSourceFile = compilerHost.getSourceFile; + const computeHash = host.createHash || generateDjb2Hash; + compilerHost.getSourceFile = (...args) => { + const result = originalGetSourceFile.call(compilerHost, ...args); + if (result) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -524,8 +536,6 @@ namespace ts { } } - const initialVersion = 1; - /** * Creates the watch from the host for root files and compiler options */ @@ -536,13 +546,14 @@ namespace ts { export function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; export function createWatchProgram(host: WatchCompilerHostOfFilesAndCompilerOptions & WatchCompilerHostOfConfigFile): WatchOfFilesAndCompilerOptions | WatchOfConfigFile { interface FilePresentOnHost { - version: number; + version: string; sourceFile: SourceFile; fileWatcher: FileWatcher; } - type FileMissingOnHost = number; + type FileMissingOnHost = false; interface FilePresenceUnknownOnHost { - version: number; + version: false; + fileWatcher?: FileWatcher; } type FileMayBePresentOnHost = FilePresentOnHost | FilePresenceUnknownOnHost; type HostFileInfo = FilePresentOnHost | FileMissingOnHost | FilePresenceUnknownOnHost; @@ -597,6 +608,7 @@ namespace ts { } const compilerHost = createCompilerHostFromProgramHost(host, () => compilerOptions, directoryStructureHost) as CompilerHost & ResolutionCacheHost; + setCreateSourceFileAsHashVersioned(compilerHost, host); // Members for CompilerHost const getNewSourceFile = compilerHost.getSourceFile; compilerHost.getSourceFile = (fileName, ...args) => getVersionedSourceFileByPath(fileName, toPath(fileName), ...args); @@ -731,19 +743,19 @@ namespace ts { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } - function isFileMissingOnHost(hostSourceFile: HostFileInfo): hostSourceFile is FileMissingOnHost { - return typeof hostSourceFile === "number"; + function isFileMissingOnHost(hostSourceFile: HostFileInfo | undefined): hostSourceFile is FileMissingOnHost { + return typeof hostSourceFile === "boolean"; } - function isFilePresentOnHost(hostSourceFile: FileMayBePresentOnHost): hostSourceFile is FilePresentOnHost { - return !!(hostSourceFile as FilePresentOnHost).sourceFile; + function isFilePresenceUnknownOnHost(hostSourceFile: FileMayBePresentOnHost): hostSourceFile is FilePresenceUnknownOnHost { + return typeof (hostSourceFile as FilePresenceUnknownOnHost).version === "boolean"; } function fileExists(fileName: string) { const path = toPath(fileName); // If file is missing on host from cache, we can definitely say file doesnt exist // otherwise we need to ensure from the disk - if (isFileMissingOnHost(sourceFilesCache.get(path)!)) { + if (isFileMissingOnHost(sourceFilesCache.get(path))) { return true; } @@ -751,44 +763,39 @@ namespace ts { } function getVersionedSourceFileByPath(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined { - const hostSourceFile = sourceFilesCache.get(path)!; + const hostSourceFile = sourceFilesCache.get(path); // No source file on the host if (isFileMissingOnHost(hostSourceFile)) { return undefined; } // Create new source file if requested or the versions dont match - if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) { const sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { - if (shouldCreateNewSourceFile) { - hostSourceFile.version++; - } - if (sourceFile) { // Set the source file and create file watcher now that file was present on the disk (hostSourceFile as FilePresentOnHost).sourceFile = sourceFile; - sourceFile.version = hostSourceFile.version.toString(); - if (!(hostSourceFile as FilePresentOnHost).fileWatcher) { - (hostSourceFile as FilePresentOnHost).fileWatcher = watchFilePath(host, fileName, onSourceFileChange, PollingInterval.Low, path, WatchType.SourceFile); + hostSourceFile.version = sourceFile.version; + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, PollingInterval.Low, path, WatchType.SourceFile); } } else { // There is no source file on host any more, close the watch, missing file paths will track it - if (isFilePresentOnHost(hostSourceFile)) { + if (hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher.close(); } - sourceFilesCache.set(path, hostSourceFile.version); + sourceFilesCache.set(path, false); } } else { if (sourceFile) { - sourceFile.version = initialVersion.toString(); const fileWatcher = watchFilePath(host, fileName, onSourceFileChange, PollingInterval.Low, path, WatchType.SourceFile); - sourceFilesCache.set(path, { sourceFile, version: initialVersion, fileWatcher }); + sourceFilesCache.set(path, { sourceFile, version: sourceFile.version, fileWatcher }); } else { - sourceFilesCache.set(path, initialVersion); + sourceFilesCache.set(path, false); } } return sourceFile; @@ -801,17 +808,17 @@ namespace ts { if (hostSourceFile !== undefined) { if (isFileMissingOnHost(hostSourceFile)) { // The next version, lets set it as presence unknown file - sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + sourceFilesCache.set(path, { version: false }); } else { - hostSourceFile.version++; + (hostSourceFile as FilePresenceUnknownOnHost).version = false; } } } function getSourceVersion(path: Path): string | undefined { const hostSourceFile = sourceFilesCache.get(path); - return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version; } function onReleaseOldSourceFile(oldSourceFile: SourceFile, _oldOptions: CompilerOptions, hasSourceFileByPath: boolean) { @@ -820,14 +827,14 @@ namespace ts { // remove the cached entry. // Note we arent deleting entry if file became missing in new program or // there was version update and new source file was created. - if (hostSourceFileInfo) { + if (hostSourceFileInfo !== undefined) { // record the missing file paths so they can be removed later if watchers arent tracking them if (isFileMissingOnHost(hostSourceFileInfo)) { (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); } else if ((hostSourceFileInfo as FilePresentOnHost).sourceFile === oldSourceFile) { - if ((hostSourceFileInfo as FilePresentOnHost).fileWatcher) { - (hostSourceFileInfo as FilePresentOnHost).fileWatcher.close(); + if (hostSourceFileInfo.fileWatcher) { + hostSourceFileInfo.fileWatcher.close(); } sourceFilesCache.delete(oldSourceFile.resolvedPath); if (!hasSourceFileByPath) { @@ -924,7 +931,7 @@ namespace ts { updateCachedSystemWithFile(fileName, path, eventKind); // Update the source file cache - if (eventKind === FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + if (eventKind === FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); From 8527be9ea89b4125c9494a8672db505722ff71cc Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 4 Mar 2019 11:02:44 -0800 Subject: [PATCH 2/7] Read program from buildInfo --- src/compiler/watch.ts | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 02b40720783..39161d78948 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -646,6 +646,7 @@ namespace ts { ((typeDirectiveNames, containingFile, redirectedReference) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference)); const userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + readBuilderProgram(); synchronizeProgram(); // Update the wild card directory watch @@ -655,18 +656,30 @@ namespace ts { { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames }; + function readBuilderProgram() { + if (compilerOptions.out || compilerOptions.outFile) return; + if (!isIncrementalCompilation(compilerOptions)) return; + const buildInfoPath = getOutputPathForBuildInfo(compilerOptions); + if (!buildInfoPath) return; + const content = directoryStructureHost.readFile(buildInfoPath); + if (!content) return; + const buildInfo = JSON.parse(content) as BuildInfo; + if (!buildInfo.program) return; + builderProgram = createBuildProgramUsingProgramBuildInfo(buildInfo.program) as any as T; + } + function getCurrentBuilderProgram() { return builderProgram; } function getCurrentProgram() { - return builderProgram && builderProgram.getProgram(); + return builderProgram && builderProgram.getProgramOrUndefined(); } function synchronizeProgram() { writeLog(`Synchronizing program`); - const program = getCurrentProgram(); + const program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { @@ -683,7 +696,7 @@ namespace ts { } } else { - createNewProgram(program, hasInvalidatedResolution); + createNewProgram(hasInvalidatedResolution); } if (host.afterProgramCreate) { @@ -693,13 +706,13 @@ namespace ts { return builderProgram; } - function createNewProgram(program: Program, hasInvalidatedResolution: HasInvalidatedResolution) { + function createNewProgram(hasInvalidatedResolution: HasInvalidatedResolution) { // Compile the program writeLog("CreatingProgramWith::"); writeLog(` roots: ${JSON.stringify(rootFileNames)}`); writeLog(` options: ${JSON.stringify(compilerOptions)}`); - const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); From 6c0b4568a0d8765a459815713018c1b888730e79 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 4 Mar 2019 14:34:20 -0800 Subject: [PATCH 3/7] Enable incremental program updates through tsbuildinfo in tsc --watch mode --- src/compiler/watch.ts | 39 +- src/testRunner/tsconfig.json | 1 + src/testRunner/unittests/tscWatch/helpers.ts | 2 + .../unittests/tscWatch/incremental.ts | 447 ++++++++++++++++++ 4 files changed, 480 insertions(+), 9 deletions(-) create mode 100644 src/testRunner/unittests/tscWatch/incremental.ts diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 39161d78948..18d9e7807a3 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -129,7 +129,6 @@ namespace ts { const diagnostics = program.getConfigFileParsingDiagnostics().slice(); const configFileParsingDiagnosticsLength = diagnostics.length; addRange(diagnostics, program.getSyntacticDiagnostics()); - let reportSemanticDiagnostics = false; // If we didn't have any syntactic errors, then also try getting the global and // semantic errors. @@ -138,7 +137,7 @@ namespace ts { addRange(diagnostics, program.getGlobalDiagnostics()); if (diagnostics.length === configFileParsingDiagnosticsLength) { - reportSemanticDiagnostics = true; + addRange(diagnostics, program.getSemanticDiagnostics()); } } @@ -146,10 +145,6 @@ namespace ts { const { emittedFiles, emitSkipped, diagnostics: emitDiagnostics } = program.emit(/*targetSourceFile*/ undefined, writeFile); addRange(diagnostics, emitDiagnostics); - if (reportSemanticDiagnostics) { - addRange(diagnostics, program.getSemanticDiagnostics()); - } - sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); if (writeFileName) { const currentDir = program.getCurrentDirectory(); @@ -506,6 +501,9 @@ namespace ts { /** Gets the existing program without synchronizing with changes on host */ /*@internal*/ getCurrentProgram(): T; + /** Closes the watch */ + /*@internal*/ + close(): void; } /** @@ -603,8 +601,9 @@ namespace ts { const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog(`Current directory: ${currentDirectory} CaseSensitiveFileNames: ${useCaseSensitiveFileNames}`); + let configFileWatcher: FileWatcher | undefined; if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, PollingInterval.High, WatchType.ConfigFile); + configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, PollingInterval.High, WatchType.ConfigFile); } const compilerHost = createCompilerHostFromProgramHost(host, () => compilerOptions, directoryStructureHost) as CompilerHost & ResolutionCacheHost; @@ -653,8 +652,30 @@ namespace ts { watchConfigFileWildCardDirectories(); return configFileName ? - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames }; + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames, close }; + + function close() { + resolutionCache.clear(); + clearMap(sourceFilesCache, value => { + if (value && value.fileWatcher) { + value.fileWatcher.close(); + value.fileWatcher = undefined; + } + }); + if (configFileWatcher) { + configFileWatcher.close(); + configFileWatcher = undefined; + } + if (watchedWildcardDirectories) { + clearMap(watchedWildcardDirectories, closeFileWatcherOf); + watchedWildcardDirectories = undefined!; + } + if (missingFilesMap) { + clearMap(missingFilesMap, closeFileWatcher); + missingFilesMap = undefined!; + } + } function readBuilderProgram() { if (compilerOptions.out || compilerOptions.outFile) return; diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index d912e229b4b..d3ea4744e8a 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -101,6 +101,7 @@ "unittests/tscWatch/consoleClearing.ts", "unittests/tscWatch/emit.ts", "unittests/tscWatch/emitAndErrorUpdates.ts", + "unittests/tscWatch/incremental.ts", "unittests/tscWatch/programUpdates.ts", "unittests/tscWatch/resolutionCache.ts", "unittests/tscWatch/watchEnvironment.ts", diff --git a/src/testRunner/unittests/tscWatch/helpers.ts b/src/testRunner/unittests/tscWatch/helpers.ts index b593cabbec6..a499e361fb5 100644 --- a/src/testRunner/unittests/tscWatch/helpers.ts +++ b/src/testRunner/unittests/tscWatch/helpers.ts @@ -32,6 +32,7 @@ namespace ts.tscWatch { export interface Watch { (): Program; getBuilderProgram(): EmitAndSemanticDiagnosticsBuilderProgram; + close(): void; } export function createWatchOfConfigFile(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) { @@ -40,6 +41,7 @@ namespace ts.tscWatch { const watch = createWatchProgram(compilerHost); const result = (() => watch.getCurrentProgram().getProgram()) as Watch; result.getBuilderProgram = () => watch.getCurrentProgram(); + result.close = () => watch.close(); return result; } diff --git a/src/testRunner/unittests/tscWatch/incremental.ts b/src/testRunner/unittests/tscWatch/incremental.ts new file mode 100644 index 00000000000..bd923c620fe --- /dev/null +++ b/src/testRunner/unittests/tscWatch/incremental.ts @@ -0,0 +1,447 @@ +namespace ts.tscWatch { + describe("unittests:: tsc-watch:: emit file --incremental", () => { + const project = "/users/username/projects/project"; + + const configFile: File = { + path: `${project}/tsconfig.json`, + content: JSON.stringify({ compilerOptions: { incremental: true } }) + }; + + interface VerifyIncrementalWatchEmitInput { + files: ReadonlyArray; + expectedInitialEmit: ReadonlyArray; + expectedInitialErrors: ReadonlyArray; + modifyFs?: (host: WatchedSystem) => void; + expectedIncrementalEmit?: ReadonlyArray; + expectedIncrementalErrors?: ReadonlyArray; + } + function verifyIncrementalWatchEmit({ + files, expectedInitialEmit, expectedInitialErrors, modifyFs, expectedIncrementalEmit, expectedIncrementalErrors + }: VerifyIncrementalWatchEmitInput) { + const host = createWatchedSystem(files, { currentDirectory: project }); + const originalWriteFile = host.writeFile; + const writtenFiles = createMap(); + host.writeFile = (path, content) => { + assert.isFalse(writtenFiles.has(path)); + writtenFiles.set(path, content); + originalWriteFile.call(host, path, content); + }; + verifyWatch(host, writtenFiles, expectedInitialEmit, expectedInitialErrors); + if (modifyFs) { + modifyFs(host); + verifyWatch(host, writtenFiles, Debug.assertDefined(expectedIncrementalEmit), Debug.assertDefined(expectedIncrementalErrors)); + } + } + + function verifyWatch(host: WatchedSystem, writtenFiles: Map, expectedEmit: ReadonlyArray, expectedErrors: ReadonlyArray) { + writtenFiles.clear(); + const watch = createWatchOfConfigFile("tsconfig.json", host); + checkFileEmit(writtenFiles, expectedEmit); + checkOutputErrorsInitial(host, expectedErrors); + watch.close(); + } + + function checkFileEmit(actual: Map, expected: ReadonlyArray) { + assert.equal(actual.size, expected.length, `Actual: ${JSON.stringify(arrayFrom(actual.entries()))}\nExpected: ${JSON.stringify(expected)}`); + expected.forEach(file => assert.equal(actual.get(file.path), file.content, `Emit for ${file.path}`)); + } + + const libFileInfo: BuilderState.FileInfo = { + version: Harness.mockHash(libFile.content), + signature: Harness.mockHash(libFile.content) + }; + + describe("non module compilation", () => { + function getFileInfo(content: string): BuilderState.FileInfo { + return { version: Harness.mockHash(content), signature: Harness.mockHash(`declare ${content}\n`) }; + } + + const file1: File = { + path: `${project}/file1.ts`, + content: "const x = 10;" + }; + const file2: File = { + path: `${project}/file2.ts`, + content: "const y = 20;" + }; + const file1Js: File = { + path: `${project}/file1.js`, + content: "var x = 10;\n" + }; + const file2Js: File = { + path: `${project}/file2.js`, + content: "var y = 20;\n" + }; + + it("own file emit without errors", () => { + const modifiedFile2Content = file2.content.replace("y", "z").replace("20", "10"); + verifyIncrementalWatchEmit({ + files: [libFile, file1, file2, configFile], + expectedInitialEmit: [ + file1Js, + file2Js, + { + path: `${project}/tsconfig.tsbuildinfo`, + content: getBuildInfoText({ + program: { + fileInfos: { + [libFile.path]: libFileInfo, + [file1.path]: getFileInfo(file1.content), + [file2.path]: getFileInfo(file2.content) + }, + options: { incremental: true, configFilePath: configFile.path }, + referencedMap: {}, + exportedModulesMap: {}, + semanticDiagnosticsPerFile: [libFile.path, file1.path, file2.path] + } + }) + } + ], + expectedInitialErrors: emptyArray, + modifyFs: host => host.writeFile(file2.path, modifiedFile2Content), + expectedIncrementalEmit: [ + file1Js, + { path: file2Js.path, content: file2Js.content.replace("y", "z").replace("20", "10") }, + { + path: `${project}/tsconfig.tsbuildinfo`, + content: getBuildInfoText({ + program: { + fileInfos: { + [libFile.path]: libFileInfo, + [file1.path]: getFileInfo(file1.content), + [file2.path]: getFileInfo(modifiedFile2Content) + }, + options: { incremental: true, configFilePath: configFile.path }, + referencedMap: {}, + exportedModulesMap: {}, + semanticDiagnosticsPerFile: [libFile.path, file1.path, file2.path] + } + }) + } + ], + expectedIncrementalErrors: emptyArray, + }); + }); + + it("own file emit with errors", () => { + const fileModified: File = { + path: file2.path, + content: `const y: string = 20;` + }; + const file2FileInfo: BuilderState.FileInfo = { + version: Harness.mockHash(fileModified.content), + signature: Harness.mockHash("declare const y: string;\n") + }; + const file2ReuasableError: ProgramBuildInfoDiagnostic = [ + file2.path, [ + { + file: file2.path, + start: 6, + length: 1, + code: Diagnostics.Type_0_is_not_assignable_to_type_1.code, + category: Diagnostics.Type_0_is_not_assignable_to_type_1.category, + messageText: "Type '20' is not assignable to type 'string'." + } + ] as ReusableDiagnostic[] + ]; + const file2Errors = [ + "file2.ts(1,7): error TS2322: Type '20' is not assignable to type 'string'.\n" + ]; + const modifiedFile1Content = file1.content.replace("x", "z"); + verifyIncrementalWatchEmit({ + files: [libFile, file1, fileModified, configFile], + expectedInitialEmit: [ + file1Js, + file2Js, + { + path: `${project}/tsconfig.tsbuildinfo`, + content: getBuildInfoText({ + program: { + fileInfos: { + [libFile.path]: libFileInfo, + [file1.path]: getFileInfo(file1.content), + [file2.path]: file2FileInfo + }, + options: { incremental: true, configFilePath: configFile.path }, + referencedMap: {}, + exportedModulesMap: {}, + semanticDiagnosticsPerFile: [ + libFile.path, + file1.path, + file2ReuasableError + ] + } + }) + } + ], + expectedInitialErrors: file2Errors, + modifyFs: host => host.writeFile(file1.path, modifiedFile1Content), + expectedIncrementalEmit: [ + { path: file1Js.path, content: file1Js.content.replace("x", "z") }, + file2Js, + { + path: `${project}/tsconfig.tsbuildinfo`, + content: getBuildInfoText({ + program: { + fileInfos: { + [libFile.path]: libFileInfo, + [file1.path]: getFileInfo(modifiedFile1Content), + [file2.path]: file2FileInfo + }, + options: { incremental: true, configFilePath: configFile.path }, + referencedMap: {}, + exportedModulesMap: {}, + semanticDiagnosticsPerFile: [ + libFile.path, + file1.path, + file2ReuasableError + ] + } + }) + } + ], + expectedIncrementalErrors: file2Errors, + }); + }); + + it("with --out", () => { + const config: File = { + path: configFile.path, + content: JSON.stringify({ compilerOptions: { incremental: true, outFile: "out.js" } }) + }; + const outFile: File = { + path: `${project}/out.js`, + content: "var x = 10;\nvar y = 20;\n" + }; + verifyIncrementalWatchEmit({ + files: [libFile, file1, file2, config], + expectedInitialEmit: [ + outFile, + { + path: `${project}/out.tsbuildinfo`, + content: getBuildInfoText({ + bundle: { + commonSourceDirectory: `${project}/`, + sourceFiles: [file1.path, file2.path], + js: { + sections: [ + { pos: 0, end: outFile.content.length, kind: BundleFileSectionKind.Text } + ] + }, + } + }) + } + ], + expectedInitialErrors: emptyArray + }); + }); + }); + + describe("module compilation", () => { + function getFileInfo(content: string): BuilderState.FileInfo { + return { + version: Harness.mockHash(content), + signature: Harness.mockHash(`${content.replace("export ", "export declare ")}\n`) + }; + } + + function getEmitContent(varName: string, value: string) { + return `define(["require", "exports"], function (require, exports) { + "use strict"; + exports.__esModule = true; + exports.${varName} = ${value}; +}); +`; + } + const file1: File = { + path: `${project}/file1.ts`, + content: "export const x = 10;" + }; + const file2: File = { + path: `${project}/file2.ts`, + content: "export const y = 20;" + }; + const file1Js: File = { + path: `${project}/file1.js`, + content: getEmitContent("x", "10") + }; + const file2Js: File = { + path: `${project}/file2.js`, + content: getEmitContent("y", "20") + }; + const config: File = { + path: configFile.path, + content: JSON.stringify({ compilerOptions: { incremental: true, module: "amd" } }) + }; + + it("own file emit without errors", () => { + const modifiedFile2Content = file2.content.replace("y", "z").replace("20", "10"); + verifyIncrementalWatchEmit({ + files: [libFile, file1, file2, config], + expectedInitialEmit: [ + file1Js, + file2Js, + { + path: `${project}/tsconfig.tsbuildinfo`, + content: getBuildInfoText({ + program: { + fileInfos: { + [libFile.path]: libFileInfo, + [file1.path]: getFileInfo(file1.content), + [file2.path]: getFileInfo(file2.content) + }, + options: { incremental: true, module: ModuleKind.AMD, configFilePath: configFile.path }, + referencedMap: {}, + exportedModulesMap: {}, + semanticDiagnosticsPerFile: [libFile.path, file1.path, file2.path] + } + }) + } + ], + expectedInitialErrors: emptyArray, + modifyFs: host => host.writeFile(file2.path, modifiedFile2Content), + expectedIncrementalEmit: [ + { path: `${project}/file2.js`, content: getEmitContent("z", "10") }, + { + path: `${project}/tsconfig.tsbuildinfo`, + content: getBuildInfoText({ + program: { + fileInfos: { + [libFile.path]: libFileInfo, + [file1.path]: getFileInfo(file1.content), + [file2.path]: getFileInfo(modifiedFile2Content) + }, + options: { incremental: true, module: ModuleKind.AMD, configFilePath: configFile.path }, + referencedMap: {}, + exportedModulesMap: {}, + semanticDiagnosticsPerFile: [libFile.path, file1.path, file2.path] + } + }) + } + ], + expectedIncrementalErrors: emptyArray, + }); + }); + + it("own file emit with errors", () => { + const fileModified: File = { + path: file2.path, + content: `export const y: string = 20;` + }; + const file2FileInfo: BuilderState.FileInfo = { + version: Harness.mockHash(fileModified.content), + signature: Harness.mockHash("export declare const y: string;\n") + }; + const file2ReuasableError: ProgramBuildInfoDiagnostic = [ + file2.path, [ + { + file: file2.path, + start: 13, + length: 1, + code: Diagnostics.Type_0_is_not_assignable_to_type_1.code, + category: Diagnostics.Type_0_is_not_assignable_to_type_1.category, + messageText: "Type '20' is not assignable to type 'string'." + } + ] as ReusableDiagnostic[] + ]; + const file2Errors = [ + "file2.ts(1,14): error TS2322: Type '20' is not assignable to type 'string'.\n" + ]; + const modifiedFile1Content = file1.content.replace("x = 10", "z = 10"); + verifyIncrementalWatchEmit({ + files: [libFile, file1, fileModified, config], + expectedInitialEmit: [ + file1Js, + file2Js, + { + path: `${project}/tsconfig.tsbuildinfo`, + content: getBuildInfoText({ + program: { + fileInfos: { + [libFile.path]: libFileInfo, + [file1.path]: getFileInfo(file1.content), + [file2.path]: file2FileInfo + }, + options: { incremental: true, module: ModuleKind.AMD, configFilePath: configFile.path }, + referencedMap: {}, + exportedModulesMap: {}, + semanticDiagnosticsPerFile: [ + libFile.path, + file1.path, + file2ReuasableError + ] + } + }) + } + ], + expectedInitialErrors: file2Errors, + modifyFs: host => host.writeFile(file1.path, modifiedFile1Content), + expectedIncrementalEmit: [ + { path: file1Js.path, content: file1Js.content.replace("x = 10", "z = 10") }, + { + path: `${project}/tsconfig.tsbuildinfo`, + content: getBuildInfoText({ + program: { + fileInfos: { + [libFile.path]: libFileInfo, + [file1.path]: getFileInfo(modifiedFile1Content), + [file2.path]: file2FileInfo + }, + options: { incremental: true, module: ModuleKind.AMD, configFilePath: configFile.path }, + referencedMap: {}, + exportedModulesMap: {}, + semanticDiagnosticsPerFile: [ + libFile.path, + file2ReuasableError, + file1.path + ] + } + }) + } + ], + expectedIncrementalErrors: file2Errors, + }); + }); + + it("with --out", () => { + const config: File = { + path: configFile.path, + content: JSON.stringify({ compilerOptions: { incremental: true, module: "amd", outFile: "out.js" } }) + }; + const outFile: File = { + path: `${project}/out.js`, + content: `${getEmitContent("file1", "x", "10")}${getEmitContent("file2", "y", "20")}` + }; + function getEmitContent(file: string, varName: string, value: string) { + return `define("${file}", ["require", "exports"], function (require, exports) { + "use strict"; + exports.__esModule = true; + exports.${varName} = ${value}; +}); +`; + } + verifyIncrementalWatchEmit({ + files: [libFile, file1, file2, config], + expectedInitialEmit: [ + outFile, + { + path: `${project}/out.tsbuildinfo`, + content: getBuildInfoText({ + bundle: { + commonSourceDirectory: `${project}/`, + sourceFiles: [file1.path, file2.path], + js: { + sections: [ + { pos: 0, end: outFile.content.length, kind: BundleFileSectionKind.Text } + ] + }, + } + }) + } + ], + expectedInitialErrors: emptyArray + }); + }); + }); + }); +} From e41cbb6316f9f973f2a25ab578a956e697b20472 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 4 Mar 2019 15:24:55 -0800 Subject: [PATCH 4/7] Add incremental to normal tsc --- src/compiler/tsbuild.ts | 8 +------- src/compiler/watch.ts | 27 ++++++++++++++------------- src/tsc/tsc.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 20 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 59edd85d716..20e7101fcd8 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -1233,13 +1233,7 @@ namespace ts { function getOldProgram(proj: ResolvedConfigFileName, parsed: ParsedCommandLine) { const value = builderPrograms.getValue(proj); if (value) return value; - const buildInfoPath = getOutputPathForBuildInfo(parsed.options); - if (!buildInfoPath) return undefined; - const content = readFileWithCache(buildInfoPath); - if (!content) return undefined; - const buildInfo = getBuildInfo(content); - if (buildInfo.version !== version) return undefined; - return buildInfo.program && createBuildProgramUsingProgramBuildInfo(buildInfo.program) as any as T; + return readBuilderProgram(parsed.options, readFileWithCache) as any as T; } function updateBundle(proj: ResolvedConfigFileName): BuildResultFlags { diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 18d9e7807a3..e4660130be5 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -371,6 +371,19 @@ namespace ts { host.projectReferences = projectReferences; return host; } + + export function readBuilderProgram(compilerOptions: CompilerOptions, readFile: (path: string) => string | undefined) { + if (compilerOptions.out || compilerOptions.outFile) return undefined; + if (!isIncrementalCompilation(compilerOptions)) return undefined; + const buildInfoPath = getOutputPathForBuildInfo(compilerOptions); + if (!buildInfoPath) return undefined; + const content = readFile(buildInfoPath); + if (!content) return undefined; + const buildInfo = getBuildInfo(content); + if (buildInfo.version !== version) return undefined; + if (!buildInfo.program) return undefined; + return createBuildProgramUsingProgramBuildInfo(buildInfo.program); + } } namespace ts { @@ -645,7 +658,7 @@ namespace ts { ((typeDirectiveNames, containingFile, redirectedReference) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference)); const userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; - readBuilderProgram(); + readBuilderProgram(compilerOptions, path => compilerHost.readFile(path)); synchronizeProgram(); // Update the wild card directory watch @@ -677,18 +690,6 @@ namespace ts { } } - function readBuilderProgram() { - if (compilerOptions.out || compilerOptions.outFile) return; - if (!isIncrementalCompilation(compilerOptions)) return; - const buildInfoPath = getOutputPathForBuildInfo(compilerOptions); - if (!buildInfoPath) return; - const content = directoryStructureHost.readFile(buildInfoPath); - if (!content) return; - const buildInfo = JSON.parse(content) as BuildInfo; - if (!buildInfo.program) return; - builderProgram = createBuildProgramUsingProgramBuildInfo(buildInfo.program) as any as T; - } - function getCurrentBuilderProgram() { return builderProgram; } diff --git a/src/tsc/tsc.ts b/src/tsc/tsc.ts index 88c3cdedfd9..d53d5bd3bd6 100644 --- a/src/tsc/tsc.ts +++ b/src/tsc/tsc.ts @@ -147,6 +147,9 @@ namespace ts { reportWatchModeWithoutSysSupport(); createWatchOfConfigFile(configParseResult, commandLineOptions); } + else if (isIncrementalCompilation(configParseResult.options)) { + performIncrementalCompilation(configParseResult); + } else { performCompilation(configParseResult.fileNames, configParseResult.projectReferences, configParseResult.options, getConfigFileParsingDiagnostics(configParseResult)); } @@ -254,6 +257,44 @@ namespace ts { return sys.exit(exitStatus); } + function performIncrementalCompilation(config: ParsedCommandLine) { + const { options, fileNames, projectReferences } = config; + const host = createCompilerHost(options); + const currentDirectory = host.getCurrentDirectory(); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + changeCompilerHostLikeToUseCache(host, fileName => toPath(fileName, currentDirectory, getCanonicalFileName)); + enableStatistics(options); + const oldProgram = readBuilderProgram(options, path => host.readFile(path)); + const configFileParsingDiagnostics = getConfigFileParsingDiagnostics(config); + const programOptions: CreateProgramOptions = { + rootNames: fileNames, + options, + projectReferences, + host, + configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config), + }; + const program = createProgram(programOptions); + const builderProgram = createEmitAndSemanticDiagnosticsBuilderProgram( + program, + { + useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames, + createHash: maybeBind(sys, sys.createHash), + writeFile: (path, data, writeByteOrderMark) => sys.writeFile(path, data, writeByteOrderMark) + }, + oldProgram, + configFileParsingDiagnostics + ); + + const exitStatus = emitFilesAndReportErrors( + builderProgram, + reportDiagnostic, + s => sys.write(s + sys.newLine), + createReportErrorSummary(options) + ); + reportStatistics(program); + return sys.exit(exitStatus); + } + function updateCreateProgram(host: { createProgram: CreateProgram; }) { const compileUsingBuilder = host.createProgram; host.createProgram = (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) => { From 0b202b20954ca91a71c1723ef8ead36460c0e798 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 8 Mar 2019 16:03:23 -0800 Subject: [PATCH 5/7] Fix tests after rebase --- src/compiler/watch.ts | 3 +- src/testRunner/unittests/tsbuild/outFile.ts | 16 ++-------- .../unittests/tscWatch/incremental.ts | 32 ++++++++++++------- 3 files changed, 24 insertions(+), 27 deletions(-) diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index e4660130be5..c01174f685b 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -374,7 +374,6 @@ namespace ts { export function readBuilderProgram(compilerOptions: CompilerOptions, readFile: (path: string) => string | undefined) { if (compilerOptions.out || compilerOptions.outFile) return undefined; - if (!isIncrementalCompilation(compilerOptions)) return undefined; const buildInfoPath = getOutputPathForBuildInfo(compilerOptions); if (!buildInfoPath) return undefined; const content = readFile(buildInfoPath); @@ -658,7 +657,7 @@ namespace ts { ((typeDirectiveNames, containingFile, redirectedReference) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference)); const userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; - readBuilderProgram(compilerOptions, path => compilerHost.readFile(path)); + builderProgram = readBuilderProgram(compilerOptions, path => compilerHost.readFile(path)) as any as T; synchronizeProgram(); // Update the wild card directory watch diff --git a/src/testRunner/unittests/tsbuild/outFile.ts b/src/testRunner/unittests/tsbuild/outFile.ts index e9b7cdae326..c488efac4e3 100644 --- a/src/testRunner/unittests/tsbuild/outFile.ts +++ b/src/testRunner/unittests/tsbuild/outFile.ts @@ -99,13 +99,7 @@ namespace ts { // outputs ...outputFiles[project.first], ...outputFiles[project.second], - - // build info - outputFiles[project.third][ext.buildinfo], - ], - // These are first not present and later read new contents to generate third output - outputFiles[project.first][ext.buildinfo], - outputFiles[project.second][ext.buildinfo] + ] ); let dtsChangedExpectedDiagnostics: ReadonlyArray = [ @@ -131,12 +125,8 @@ namespace ts { ...outputFiles[project.first], ...outputFiles[project.second], outputFiles[project.third][ext.dts], - - // build info - outputFiles[project.third][ext.buildinfo], ], outputFiles[project.first][ext.dts], // dts changes so once read old content, and once new (to emit third) - outputFiles[project.first][ext.buildinfo], // since first build info changes ); let dtsChangedExpectedDiagnosticsDependOrdered: ReadonlyArray = [ @@ -173,8 +163,7 @@ namespace ts { ...outputFiles[project.first], ...outputFiles[project.second], ...outputFiles[project.third], - ], - outputFiles[project.first][ext.buildinfo], // since first build info changes + ] ); let dtsUnchangedExpectedDiagnosticsDependOrdered: ReadonlyArray = [ @@ -227,7 +216,6 @@ namespace ts { value.set(path, 1); } value.set(outputFiles[project.second][ext.dts], 2); // dts changes so once read old content, and once new (to emit third) - value.set(outputFiles[project.second][ext.buildinfo], 2); // since first build info changes return value; } diff --git a/src/testRunner/unittests/tscWatch/incremental.ts b/src/testRunner/unittests/tscWatch/incremental.ts index bd923c620fe..f21f994914c 100644 --- a/src/testRunner/unittests/tscWatch/incremental.ts +++ b/src/testRunner/unittests/tscWatch/incremental.ts @@ -42,7 +42,7 @@ namespace ts.tscWatch { } function checkFileEmit(actual: Map, expected: ReadonlyArray) { - assert.equal(actual.size, expected.length, `Actual: ${JSON.stringify(arrayFrom(actual.entries()))}\nExpected: ${JSON.stringify(expected)}`); + assert.equal(actual.size, expected.length, `Actual: ${JSON.stringify(arrayFrom(actual.entries()), /*replacer*/ undefined, " ")}\nExpected: ${JSON.stringify(expected, /*replacer*/ undefined, " ")}`); expected.forEach(file => assert.equal(actual.get(file.path), file.content, `Emit for ${file.path}`)); } @@ -93,7 +93,8 @@ namespace ts.tscWatch { referencedMap: {}, exportedModulesMap: {}, semanticDiagnosticsPerFile: [libFile.path, file1.path, file2.path] - } + }, + version }) } ], @@ -115,7 +116,8 @@ namespace ts.tscWatch { referencedMap: {}, exportedModulesMap: {}, semanticDiagnosticsPerFile: [libFile.path, file1.path, file2.path] - } + }, + version }) } ], @@ -170,7 +172,8 @@ namespace ts.tscWatch { file1.path, file2ReuasableError ] - } + }, + version }) } ], @@ -196,7 +199,8 @@ namespace ts.tscWatch { file1.path, file2ReuasableError ] - } + }, + version }) } ], @@ -228,7 +232,8 @@ namespace ts.tscWatch { { pos: 0, end: outFile.content.length, kind: BundleFileSectionKind.Text } ] }, - } + }, + version }) } ], @@ -294,7 +299,8 @@ namespace ts.tscWatch { referencedMap: {}, exportedModulesMap: {}, semanticDiagnosticsPerFile: [libFile.path, file1.path, file2.path] - } + }, + version }) } ], @@ -315,7 +321,8 @@ namespace ts.tscWatch { referencedMap: {}, exportedModulesMap: {}, semanticDiagnosticsPerFile: [libFile.path, file1.path, file2.path] - } + }, + version }) } ], @@ -370,7 +377,8 @@ namespace ts.tscWatch { file1.path, file2ReuasableError ] - } + }, + version }) } ], @@ -395,7 +403,8 @@ namespace ts.tscWatch { file2ReuasableError, file1.path ] - } + }, + version }) } ], @@ -435,7 +444,8 @@ namespace ts.tscWatch { { pos: 0, end: outFile.content.length, kind: BundleFileSectionKind.Text } ] }, - } + }, + version }) } ], From f82cb2370fd2838cdd93b3a3ce1a4d6b18aec72a Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 8 Mar 2019 16:35:58 -0800 Subject: [PATCH 6/7] Udpate LKG --- lib/tsc.js | 1172 ++++++++++++++------------ lib/tsserver.js | 1625 ++++++++++++++++++------------------- lib/tsserverlibrary.js | 1625 ++++++++++++++++++------------------- lib/typescript.js | 1625 ++++++++++++++++++------------------- lib/typescriptServices.js | 1625 ++++++++++++++++++------------------- lib/typingsInstaller.js | 1619 ++++++++++++++++++------------------ 6 files changed, 4593 insertions(+), 4698 deletions(-) diff --git a/lib/tsc.js b/lib/tsc.js index a32addec337..63a7accb5a3 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -6391,7 +6391,7 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - function addStatementsAfterPrologue(to, from) { + function insertStatementsAfterPrologue(to, from, isPrologueDirective) { if (from === undefined || from.length === 0) return to; var statementIndex = 0; @@ -6403,7 +6403,37 @@ var ts; to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + function insertStatementAfterPrologue(to, statement, isPrologueDirective) { + if (statement === undefined) + return to; + var statementIndex = 0; + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice(statementIndex, 0, statement); + return to; + } + function isAnyPrologueDirective(node) { + return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576); + } + function insertStatementsAfterStandardPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isPrologueDirective); + } + ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue; + function insertStatementsAfterCustomPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective); + } + ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue; + function insertStatementAfterStandardPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isPrologueDirective); + } + ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue; + function insertStatementAfterCustomPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective); + } + ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue; function isRecognizedTripleSlashComment(text, commentPos, commentEnd) { if (text.charCodeAt(commentPos + 1) === 47 && commentPos + 2 < commentEnd && @@ -7281,6 +7311,11 @@ var ts; } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + function isSuperOrSuperProperty(node) { + return node.kind === 98 + || isSuperProperty(node); + } + ts.isSuperOrSuperProperty = isSuperOrSuperProperty; function isSuperProperty(node) { var kind = node.kind; return (kind === 189 || kind === 190) @@ -24597,53 +24632,50 @@ var ts; ts.computeTransformFlagsForNode = computeTransformFlagsForNode; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; + var callee = ts.skipOuterExpressions(node.expression); var expression = node.expression; if (node.typeArguments) { - transformFlags |= 3; + transformFlags |= 1; } - if (subtreeFlags & 131072 - || (expression.transformFlags & (33554432 | 67108864))) { - transformFlags |= 192; - if (expression.transformFlags & 67108864) { - transformFlags |= 8192; + if (subtreeFlags & 4096 || ts.isSuperOrSuperProperty(callee)) { + transformFlags |= 128; + if (ts.isSuperProperty(callee)) { + transformFlags |= 2048; } } if (expression.kind === 92) { - transformFlags |= 16777216; - if (subtreeFlags & 8192) { - transformFlags |= 16384; - } + transformFlags |= 524288; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637666625; + return transformFlags & ~536875008; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { - transformFlags |= 3; + transformFlags |= 1; } - if (subtreeFlags & 131072) { - transformFlags |= 192; + if (subtreeFlags & 4096) { + transformFlags |= 128; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637666625; + return transformFlags & ~536875008; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var operatorTokenKind = node.operatorToken.kind; var leftKind = node.left.kind; if (operatorTokenKind === 59 && leftKind === 188) { - transformFlags |= 134217728 | 192 | 3072; + transformFlags |= 16 | 128 | 512; } else if (operatorTokenKind === 59 && leftKind === 187) { - transformFlags |= 192 | 3072; + transformFlags |= 128 | 512; } else if (operatorTokenKind === 41 || operatorTokenKind === 63) { - transformFlags |= 32; + transformFlags |= 64; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637535553; + return transformFlags & ~536870912; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -24652,135 +24684,125 @@ var ts; var dotDotDotToken = node.dotDotDotToken; if (node.questionToken || node.type - || (subtreeFlags & 4096 && ts.some(node.decorators)) + || (subtreeFlags & 1024 && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { - transformFlags |= 3; + transformFlags |= 1; } if (ts.hasModifier(node, 92)) { - transformFlags |= 3 | 4096; + transformFlags |= 1 | 1024; } - if (subtreeFlags & 262144) { - transformFlags |= 134217728; + if (subtreeFlags & 8192) { + transformFlags |= 16; } - if (subtreeFlags & 2097152 || initializer || dotDotDotToken) { - transformFlags |= 192 | 65536; + if (subtreeFlags & 65536 || initializer || dotDotDotToken) { + transformFlags |= 128; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637535553; + return transformFlags & ~536870912; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; if (expressionKind === 212 || expressionKind === 194) { - transformFlags |= 3; - } - if (expressionTransformFlags & 1024) { - transformFlags |= 1024; + transformFlags |= 1; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~536870912; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; if (ts.hasModifier(node, 2)) { - transformFlags = 3; + transformFlags = 1; } else { - transformFlags = subtreeFlags | 192; - if ((subtreeFlags & 4096) + transformFlags = subtreeFlags | 128; + if ((subtreeFlags & 1024) || node.typeParameters) { - transformFlags |= 3; - } - if (subtreeFlags & 32768) { - transformFlags |= 8192; + transformFlags |= 1; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~638121281; + return transformFlags & ~536888320; } function computeClassExpression(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; - if (subtreeFlags & 4096 + var transformFlags = subtreeFlags | 128; + if (subtreeFlags & 1024 || node.typeParameters) { - transformFlags |= 3; - } - if (subtreeFlags & 32768) { - transformFlags |= 8192; + transformFlags |= 1; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~638121281; + return transformFlags & ~536888320; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { case 86: - transformFlags |= 192; + transformFlags |= 128; break; case 109: - transformFlags |= 3; + transformFlags |= 1; break; default: ts.Debug.fail("Unexpected token for heritage clause"); break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637535553; + return transformFlags & ~536870912; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; if (!node.variableDeclaration) { - transformFlags |= 268435456; + transformFlags |= 8; } else if (ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192; + transformFlags |= 128; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637797697; + return transformFlags & ~536879104; } function computeExpressionWithTypeArguments(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; + var transformFlags = subtreeFlags | 128; if (node.typeArguments) { - transformFlags |= 3; + transformFlags |= 1; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637535553; + return transformFlags & ~536870912; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; if (ts.hasModifier(node, 2270) || !node.body) { - transformFlags |= 3; + transformFlags |= 1; } - if (subtreeFlags & 262144) { - transformFlags |= 134217728; + if (subtreeFlags & 8192) { + transformFlags |= 16; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~653616449; + return transformFlags & ~537372672; } function computeMethod(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; + var transformFlags = subtreeFlags | 128; if (node.decorators || ts.hasModifier(node, 2270) || node.typeParameters || node.type || (node.name && ts.isComputedPropertyName(node.name)) || !node.body) { - transformFlags |= 3; + transformFlags |= 1; } - if (subtreeFlags & 262144) { - transformFlags |= 134217728; + if (subtreeFlags & 8192) { + transformFlags |= 16; } if (ts.hasModifier(node, 256)) { - transformFlags |= node.asteriskToken ? 134217728 : 16; + transformFlags |= node.asteriskToken ? 16 : 32; } if (node.asteriskToken) { - transformFlags |= 768; + transformFlags |= 256; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~653616449; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672); } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -24789,198 +24811,182 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) || !node.body) { - transformFlags |= 3; + transformFlags |= 1; } - if (subtreeFlags & 262144) { - transformFlags |= 134217728; + if (subtreeFlags & 8192) { + transformFlags |= 16; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~653616449; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672); } function computePropertyDeclaration(node, subtreeFlags) { - var transformFlags = subtreeFlags | 3; + var transformFlags = subtreeFlags | 1; if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 4096; + transformFlags |= 1024; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637535553; + return propagatePropertyNameFlags(node.name, transformFlags & ~536872960); } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; var modifierFlags = ts.getModifierFlags(node); var body = node.body; if (!body || (modifierFlags & 2)) { - transformFlags = 3; + transformFlags = 1; } else { - transformFlags = subtreeFlags | 8388608; + transformFlags = subtreeFlags | 262144; if (modifierFlags & 2270 || node.typeParameters || node.type) { - transformFlags |= 3; + transformFlags |= 1; } if (modifierFlags & 256) { - transformFlags |= node.asteriskToken ? 134217728 : 16; + transformFlags |= node.asteriskToken ? 16 : 32; } - if (subtreeFlags & 262144) { - transformFlags |= 134217728; - } - if (subtreeFlags & 81920) { - transformFlags |= 192; + if (subtreeFlags & 8192) { + transformFlags |= 16; } if (node.asteriskToken) { - transformFlags |= 768; + transformFlags |= 256; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~653620545; + return transformFlags & ~537373696; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (ts.hasModifier(node, 2270) || node.typeParameters || node.type) { - transformFlags |= 3; + transformFlags |= 1; } if (ts.hasModifier(node, 256)) { - transformFlags |= node.asteriskToken ? 134217728 : 16; + transformFlags |= node.asteriskToken ? 16 : 32; } - if (subtreeFlags & 262144) { - transformFlags |= 134217728; - } - if (subtreeFlags & 81920) { - transformFlags |= 192; + if (subtreeFlags & 8192) { + transformFlags |= 16; } if (node.asteriskToken) { - transformFlags |= 768; + transformFlags |= 256; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~653620545; + return transformFlags & ~537373696; } function computeArrowFunction(node, subtreeFlags) { - var transformFlags = subtreeFlags | 192; + var transformFlags = subtreeFlags | 128; if (ts.hasModifier(node, 2270) || node.typeParameters || node.type) { - transformFlags |= 3; + transformFlags |= 1; } if (ts.hasModifier(node, 256)) { - transformFlags |= 16; - } - if (subtreeFlags & 262144) { - transformFlags |= 134217728; + transformFlags |= 32; } if (subtreeFlags & 8192) { - transformFlags |= 16384; + transformFlags |= 16; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~653604161; + return transformFlags & ~537371648; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (transformFlags & 33554432) { - transformFlags ^= 33554432; - transformFlags |= 67108864 | 16 | 134217728; + if (node.expression.kind === 98) { + transformFlags |= 32 | 16; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~570426689; + return transformFlags & ~536870912; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionFlags = expression.transformFlags; - if (expressionFlags & 33554432) { - transformFlags &= ~33554432; - transformFlags |= 67108864 | 16 | 134217728; + if (node.expression.kind === 98) { + transformFlags |= 32 | 16; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~570426689; + return transformFlags & ~536870912; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 | 2097152; - if (subtreeFlags & 262144) { - transformFlags |= 134217728; + transformFlags |= 128 | 65536; + if (subtreeFlags & 8192) { + transformFlags |= 16; } if (node.type) { - transformFlags |= 3; + transformFlags |= 1; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637535553; + return transformFlags & ~536870912; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; var declarationListTransformFlags = node.declarationList.transformFlags; if (ts.hasModifier(node, 2)) { - transformFlags = 3; + transformFlags = 1; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 2097152) { - transformFlags |= 192; + if (declarationListTransformFlags & 65536) { + transformFlags |= 128; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637535553; + return transformFlags & ~536870912; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (subtreeFlags & 1048576 + if (subtreeFlags & 32768 && ts.isIterationStatement(node, true)) { - transformFlags |= 192; + transformFlags |= 128; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637535553; + return transformFlags & ~536870912; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3; + transformFlags |= 1; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637535553; + return transformFlags & ~536870912; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - if (node.expression.transformFlags & 1024) { - transformFlags |= 192; - } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~637535553; + return transformFlags & ~536870912; } function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3; + var transformFlags = 1; var modifierFlags = ts.getModifierFlags(node); if ((modifierFlags & 2) === 0) { transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~647001409; + return transformFlags & ~537168896; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608; - if (subtreeFlags & 2097152) { - transformFlags |= 192; + var transformFlags = subtreeFlags | 262144; + if (subtreeFlags & 65536) { + transformFlags |= 128; } if (node.flags & 3) { - transformFlags |= 192 | 1048576; + transformFlags |= 128 | 32768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~639894849; + return transformFlags & ~536944640; } function computeOther(node, kind, subtreeFlags) { var transformFlags = subtreeFlags; - var excludeFlags = 637535553; + var excludeFlags = 536870912; switch (kind) { case 121: case 201: - transformFlags |= 134217728 | 16; + transformFlags |= 16 | 32; break; case 194: case 212: case 313: - transformFlags |= 3; - excludeFlags = 536872257; + transformFlags |= 1; + excludeFlags = 536870912; break; case 115: case 113: @@ -24992,7 +24998,7 @@ var ts; case 278: case 213: case 133: - transformFlags |= 3; + transformFlags |= 1; break; case 260: case 261: @@ -25006,7 +25012,7 @@ var ts; case 268: case 269: case 270: - transformFlags |= 4; + transformFlags |= 2; break; case 14: case 15: @@ -25017,29 +25023,29 @@ var ts; case 276: case 116: case 214: - transformFlags |= 192; + transformFlags |= 128; break; case 10: if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192; + transformFlags |= 128; } break; case 8: if (node.numericLiteralFlags & 384) { - transformFlags |= 192; + transformFlags |= 128; } break; case 9: - transformFlags |= 8; + transformFlags |= 4; break; case 227: if (node.awaitModifier) { - transformFlags |= 134217728; + transformFlags |= 16; } - transformFlags |= 192; + transformFlags |= 128; break; case 207: - transformFlags |= 134217728 | 192 | 4194304; + transformFlags |= 16 | 128 | 131072; break; case 120: case 135: @@ -25079,120 +25085,110 @@ var ts; case 181: case 182: case 247: - transformFlags = 3; - excludeFlags = -3; + transformFlags = 1; + excludeFlags = -2; break; case 149: - transformFlags |= 524288; - if (subtreeFlags & 8192) { - transformFlags |= 32768; - } + transformFlags |= 16384; break; case 208: - transformFlags |= 192 | 131072; + transformFlags |= 128 | 4096; break; case 277: - transformFlags |= 134217728 | 262144; + transformFlags |= 16 | 8192; break; case 98: - transformFlags |= 192 | 33554432; - excludeFlags = 536872257; + transformFlags |= 128; + excludeFlags = 536870912; break; case 100: - transformFlags |= 8192; + transformFlags |= 2048; break; case 184: - transformFlags |= 192 | 2097152; - if (subtreeFlags & 131072) { - transformFlags |= 134217728 | 262144; + transformFlags |= 128 | 65536; + if (subtreeFlags & 4096) { + transformFlags |= 16 | 8192; } - excludeFlags = 637666625; + excludeFlags = 536875008; break; case 185: - transformFlags |= 192 | 2097152; - excludeFlags = 637666625; + transformFlags |= 128 | 65536; + excludeFlags = 536875008; break; case 186: - transformFlags |= 192; + transformFlags |= 128; if (node.dotDotDotToken) { - transformFlags |= 131072; + transformFlags |= 4096; } break; case 152: - transformFlags |= 3 | 4096; + transformFlags |= 1 | 1024; break; case 188: - excludeFlags = 638358849; - if (subtreeFlags & 524288) { - transformFlags |= 192; + excludeFlags = 536896512; + if (subtreeFlags & 16384) { + transformFlags |= 128; } - if (subtreeFlags & 32768) { - transformFlags |= 8192; - } - if (subtreeFlags & 262144) { - transformFlags |= 134217728; + if (subtreeFlags & 8192) { + transformFlags |= 16; } break; case 187: - case 192: - excludeFlags = 637666625; - if (subtreeFlags & 131072) { - transformFlags |= 192; - } + excludeFlags = 536875008; break; case 223: case 224: case 225: case 226: - if (subtreeFlags & 1048576) { - transformFlags |= 192; + if (subtreeFlags & 32768) { + transformFlags |= 128; } break; case 284: - if (subtreeFlags & 16384) { - transformFlags |= 192; - } break; case 230: - transformFlags |= 8388608 | 134217728; + transformFlags |= 262144 | 16; break; case 228: case 229: - transformFlags |= 8388608; + transformFlags |= 262144; break; } node.transformFlags = transformFlags | 536870912; return transformFlags & ~excludeFlags; } + function propagatePropertyNameFlags(node, transformFlags) { + return transformFlags | (node.transformFlags & 2048); + } function getTransformFlagsSubtreeExclusions(kind) { if (kind >= 163 && kind <= 183) { - return -3; + return -2; } switch (kind) { case 191: case 192: case 187: - return 637666625; + return 536875008; case 244: - return 647001409; + return 537168896; case 151: - return 637535553; + return 536870912; case 197: - return 653604161; + return 537371648; case 196: case 239: - return 653620545; + return 537373696; case 238: - return 639894849; + return 536944640; case 240: case 209: - return 638121281; + return 536888320; case 157: - return 653616449; + return 537372672; case 156: case 158: case 159: - return 653616449; + return 537372672; case 120: case 135: case 146: @@ -25210,25 +25206,25 @@ var ts; case 162: case 241: case 242: - return -3; + return -2; case 188: - return 638358849; + return 536896512; case 274: - return 637797697; + return 536879104; case 184: case 185: - return 637666625; + return 536875008; case 194: case 212: case 313: case 195: case 98: - return 536872257; + return 536870912; case 189: case 190: - return 570426689; + return 536870912; default: - return 637535553; + return 536870912; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -25736,6 +25732,7 @@ var ts; var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); + var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4, "unknown"); @@ -31377,20 +31374,25 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } + function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { + var rootTrueType = root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432) + ? rootTrueType + : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + return instantiateType(rootTrueConstraint, combinedMapper || mapper); + } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { - var rootTrueType = type.root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432) - ? rootTrueType - : (rootTrueType.substitute).flags & 3 - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); + var falseConstraint = getFalseTypeFromConditionalType(type); + type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; } function getConstraintOfDistributiveConditionalType(type) { - if (type.root.isDistributive) { + if (type.root.isDistributive && type.restrictiveInstantiation !== type) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint && constraint !== type.checkType) { @@ -33519,12 +33521,43 @@ var ts; function getActualTypeVariable(type) { return type.flags & 33554432 ? type.typeVariable : type; } + function isIntersectionEmpty(type1, type2) { + return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072); + } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); var extendsType = instantiateType(root.extendsType, mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } + var trueType = instantiateType(root.trueType, mapper); + var falseType = instantiateType(root.falseType, mapper); + var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; + } + var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); + conditionalTypes.set(instantiationId, newResult); + return newResult; + } + function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) { + if (falseType.flags & 131072 && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { + if (checkType.flags & 1 || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { + return getDefaultConstraintOfTrueBranchOfConditionalType(root, undefined, mapper); + } + else if (isIntersectionEmpty(checkType, extendsType)) { + return neverType; + } + } + else if (trueType.flags & 131072 && isTypeIdenticalTo(getActualTypeVariable(falseType), getActualTypeVariable(checkType))) { + if (!(checkType.flags & 1) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { + return neverType; + } + else if (checkType.flags & 1 || isIntersectionEmpty(checkType, extendsType)) { + return falseType; + } + } var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 | 131072); var combinedMapper; if (root.inferTypeParameters) { @@ -33537,13 +33570,13 @@ var ts; var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 | 131072)) { if (inferredExtendsType.flags & 3) { - return instantiateType(root.trueType, mapper); + return trueType; } if (checkType.flags & 1) { - return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]); } if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { - return instantiateType(root.falseType, mapper); + return falseType; } if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { return instantiateType(root.trueType, combinedMapper || mapper); @@ -33556,6 +33589,10 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; + if (!combinedMapper) { + result.resolvedTrueType = trueType; + result.resolvedFalseType = falseType; + } result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); return result; @@ -34389,8 +34426,15 @@ var ts; type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); } function getRestrictiveInstantiation(type) { - return type.flags & (131068 | 3 | 131072) ? type : - type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); + if (type.flags & (131068 | 3 | 131072)) { + return type; + } + if (type.restrictiveInstantiation) { + return type.restrictiveInstantiation; + } + type.restrictiveInstantiation = instantiateType(type, restrictiveMapper); + type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation; + return type.restrictiveInstantiation; } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -35745,15 +35789,24 @@ var ts; template.indexType === getTypeParameterFromMappedType(target)) { return -1; } - if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - return result; + if (!isGenericMappedType(source)) { + var targetConstraint = getConstraintTypeFromMappedType(target); + var sourceKeys_1 = getIndexType(source); + var hasOptionalUnionKeys = modifiers & 4 && targetConstraint.flags & 1048576; + var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined; + if (hasOptionalUnionKeys + ? !(filteredByApplicability.flags & 131072) + : isRelatedTo(targetConstraint, sourceKeys_1)) { + var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target); + var indexedAccessType = getIndexedAccessType(source, indexingType); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } - originalErrorInfo = errorInfo; - errorInfo = saveErrorInfo; } } if (source.flags & 8650752) { @@ -37202,6 +37255,7 @@ var ts; if (inference.priority === undefined || priority < inference.priority) { inference.candidates = undefined; inference.contraCandidates = undefined; + inference.topLevel = true; inference.priority = priority; } if (priority === inference.priority) { @@ -55314,8 +55368,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) - : ts.addStatementsAfterPrologue(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) + : ts.insertStatementsAfterStandardPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; function liftToBlock(nodes) { @@ -56416,8 +56470,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 - && !(element.transformFlags & (131072 | 262144)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 | 262144)) + && !(element.transformFlags & (4096 | 8192)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 | 8192)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -56464,7 +56518,7 @@ var ts; for (var i = 0; i < numElements; i++) { var element = elements[i]; if (flattenContext.level >= 1) { - if (element.transformFlags & 262144) { + if (element.transformFlags & 8192) { var temp = ts.createTempVariable(undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -56679,9 +56733,6 @@ var ts; if (node.transformFlags & 1) { return visitTypeScript(node); } - else if (node.transformFlags & 2) { - return ts.visitEachChild(node, visitor, context); - } return node; } function sourceElementVisitor(node) { @@ -56701,7 +56752,7 @@ var ts; function visitEllidableStatement(node) { var parsed = ts.getParseTreeNode(node); if (parsed !== node) { - if (node.transformFlags & 2) { + if (node.transformFlags & 1) { return ts.visitEachChild(node, visitor, context); } return node; @@ -56733,9 +56784,6 @@ var ts; else if (node.transformFlags & 1 || ts.hasModifier(node, 1)) { return visitTypeScript(node); } - else if (node.transformFlags & 2) { - return ts.visitEachChild(node, visitor, context); - } return node; } function classElementVisitor(node) { @@ -56767,7 +56815,7 @@ var ts; return node; } function visitTypeScript(node) { - if (ts.hasModifier(node, 2) && ts.isStatement(node)) { + if (ts.isStatement(node) && ts.hasModifier(node, 2)) { return ts.createNotEmittedStatement(node); } switch (node.kind) { @@ -56867,7 +56915,7 @@ var ts; case 248: return visitImportEqualsDeclaration(node); default: - return ts.Debug.failBadSyntaxKind(node); + return ts.visitEachChild(node, visitor, context); } } function visitSourceFile(node) { @@ -56910,7 +56958,19 @@ var ts; facts |= 128; return facts; } + function hasTypeScriptClassSyntax(node) { + return !!(node.transformFlags & 1024); + } + function isClassLikeDeclarationWithTypeScriptSyntax(node) { + return ts.some(node.decorators) + || ts.some(node.typeParameters) + || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) + || ts.some(node.members, hasTypeScriptClassSyntax); + } function visitClassDeclaration(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1))) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, true); @@ -56943,7 +57003,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432); var varStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ @@ -57004,6 +57064,9 @@ var ts; return statement; } function visitClassExpression(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, true); @@ -57046,7 +57109,7 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); var hasParameterPropertyAssignments = constructor && - constructor.transformFlags & 4096 && + constructor.transformFlags & 1024 && ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); if (!hasInstancePropertyWithInitializer && !hasParameterPropertyAssignments) { return ts.visitEachChild(constructor, visitor, context); @@ -57676,11 +57739,10 @@ var ts; } } function visitHeritageClause(node) { - if (node.token === 86) { - var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(86, types), node); + if (node.token === 109) { + return undefined; } - return undefined; + return ts.visitEachChild(node, visitor, context); } function visitExpressionWithTypeArguments(node) { return ts.updateExpressionWithTypeArguments(node, undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)); @@ -57764,13 +57826,14 @@ var ts; if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameter(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); - ts.setOriginalNode(parameter, node); - ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); - ts.setCommentRange(parameter, node); - ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - ts.setEmitFlags(parameter.name, 32); - return parameter; + var updated = ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); + if (updated !== node) { + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32); + } + return updated; } function visitVariableStatement(node) { if (isExportOfNamespace(node)) { @@ -57869,7 +57932,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); @@ -58019,7 +58082,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -58384,7 +58447,7 @@ var ts; return visited; } function visitor(node) { - if ((node.transformFlags & 16) === 0) { + if ((node.transformFlags & 32) === 0) { return node; } switch (node.kind) { @@ -58603,13 +58666,13 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); @@ -58841,7 +58904,7 @@ var ts; return node; } function visitorWorker(node, noDestructuringValue) { - if ((node.transformFlags & 134217728) === 0) { + if ((node.transformFlags & 16) === 0) { return node; } switch (node.kind) { @@ -58958,7 +59021,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 262144) { + if (node.transformFlags & 8192) { var objects = chunkObjectLiteralElements(node.properties); if (objects.length && objects[0].kind !== 188) { objects.unshift(ts.createObjectLiteral()); @@ -58974,7 +59037,7 @@ var ts; return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192) { return ts.flattenDestructuringAssignment(node, visitor, context, 1, !noDestructuringValue); } else if (node.operatorToken.kind === 27) { @@ -58983,7 +59046,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192) { return ts.flattenDestructuringBinding(node, visitor, context, 1); } return ts.visitEachChild(node, visitor, context); @@ -58995,7 +59058,7 @@ var ts; return ts.visitEachChild(node, visitorNoDestructuringValue, context); } function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 262144) { + if (node.initializer.transformFlags & 8192) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -59082,7 +59145,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 262144) { + if (node.transformFlags & 8192) { return ts.updateParameter(node, undefined, undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } return ts.visitEachChild(node, visitor, context); @@ -59169,10 +59232,10 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } statements.push(returnStatement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096) { @@ -59198,7 +59261,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, true); - ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.insertStatementsAfterStandardPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -59207,7 +59270,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 262144) { + if (parameter.transformFlags & 8192) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); if (ts.some(declarations)) { @@ -59382,7 +59445,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 268435456) === 0) { + if ((node.transformFlags & 8) === 0) { return node; } switch (node.kind) { @@ -59412,7 +59475,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8) === 0) { + if ((node.transformFlags & 4) === 0) { return node; } switch (node.kind) { @@ -59439,7 +59502,7 @@ var ts; return visited; } function visitor(node) { - if (node.transformFlags & 4) { + if (node.transformFlags & 2) { return visitorWorker(node); } else { @@ -59890,7 +59953,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 32) === 0) { + if ((node.transformFlags & 64) === 0) { return node; } switch (node.kind) { @@ -59976,11 +60039,11 @@ var ts; } function enterSubtree(excludeFacts, includeFacts) { var ancestorFacts = hierarchyFacts; - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191; return ancestorFacts; } function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 | ancestorFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096) !== 0 @@ -60002,12 +60065,6 @@ var ts; return node; } } - function functionBodyVisitor(node) { - if (shouldVisitNode(node)) { - return visitBlock(node, true); - } - return node; - } function callExpressionVisitor(node) { if (node.kind === 98) { return visitSuperKeyword(true); @@ -60114,18 +60171,19 @@ var ts; } function visitSourceFile(node) { var ancestorFacts = enterSubtree(3968, 64); + var prologue = []; var statements = []; startLexicalEnvironment(); - var statementOffset = ts.addStandardPrologue(statements, node.statements, false); - addCaptureThisForNodeIfNeeded(statements, node); - statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + var statementOffset = ts.addStandardPrologue(prologue, node.statements, false); + statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureThisForNodeIfNeeded(prologue, node); exitSubtree(ancestorFacts, 0, 0); - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements)); } function visitSwitchStatement(node) { if (convertedLoopState !== undefined) { @@ -60164,6 +60222,9 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitThisKeyword(node) { + if (hierarchyFacts & 2) { + hierarchyFacts |= 16384; + } if (convertedLoopState) { if (hierarchyFacts & 2) { convertedLoopState.containsLexicalThis = true; @@ -60293,7 +60354,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 | 384); statements.push(statement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), node.members), true); ts.setEmitFlags(block, 1536); return block; @@ -60306,7 +60367,7 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16278, 73); + var ancestorFacts = enterSubtree(8086, 73); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getInternalName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); @@ -60315,56 +60376,78 @@ var ts; ts.setEmitFlags(constructorFunction, 8); } statements.push(constructorFunction); - exitSubtree(ancestorFacts, 49152, 0); + exitSubtree(ancestorFacts, 24576, 0); convertedLoopState = savedConvertedLoopState; } function transformConstructorParameters(constructor, hasSynthesizedSuper) { return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } - function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { + function createDefaultConstructorBody(node, isDerivedClass) { var statements = []; resumeLexicalEnvironment(); - var statementOffset = -1; - if (hasSynthesizedSuper) { - statementOffset = 0; - } - else if (constructor) { - statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, false); - } - if (constructor) { - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); - if (!hasSynthesizedSuper) { - statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); - } - ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + if (isDerivedClass) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); } + var statementsArray = ts.createNodeArray(statements); + ts.setTextRange(statementsArray, node.members); + var block = ts.createBlock(statementsArray, true); + ts.setTextRange(block, node); + ts.setEmitFlags(block, 1536); + return block; + } + function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96; - var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); - if (superCaptureStatus === 1 || superCaptureStatus === 2) { + if (!constructor) + return createDefaultConstructorBody(node, isDerivedClass); + var prologue = []; + var statements = []; + resumeLexicalEnvironment(); + var statementOffset = 0; + if (!hasSynthesizedSuper) + statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, false); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + var superCallExpression; + if (hasSynthesizedSuper) { + superCallExpression = createDefaultSuperCallOrThis(); + } + else if (isDerivedClass && statementOffset < constructor.body.statements.length) { + var firstStatement = constructor.body.statements[statementOffset]; + if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); + } + } + if (superCallExpression) { + hierarchyFacts |= 4096; statementOffset++; } - if (constructor) { - if (superCaptureStatus === 1) { - hierarchyFacts |= 4096; + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset)); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, constructor, false); + if (isDerivedClass) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048)) { + var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); + var returnStatement = ts.createReturn(superCallExpression); + ts.setCommentRange(returnStatement, ts.getCommentRange(superCall)); + ts.setEmitFlags(superCall, 1536); + statements.push(returnStatement); + } + else { + insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); + if (!isSufficientlyCoveredByReturnStatements(constructor.body)) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } } - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset)); } - if (isDerivedClass - && superCaptureStatus !== 2 - && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { - statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); - } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - if (constructor) { - prependCaptureNewTargetIfNeeded(statements, constructor, false); - } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), constructor ? constructor.body.statements : node.members), true); - ts.setTextRange(block, constructor ? constructor.body : node); - if (!constructor) { - ts.setEmitFlags(block, 1536); + else { + insertCaptureThisForNodeIfNeeded(prologue, constructor); } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), constructor.body.statements), true); + ts.setTextRange(block, constructor.body); return block; } function isSufficientlyCoveredByReturnStatements(statement) { @@ -60386,49 +60469,6 @@ var ts; } return false; } - function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { - if (!isDerivedClass) { - if (ctor) { - addCaptureThisForNodeIfNeeded(statements, ctor); - } - return 0; - } - if (!ctor) { - statements.push(ts.createReturn(createDefaultSuperCallOrThis())); - return 2; - } - if (hasSynthesizedSuper) { - captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); - enableSubstitutionsForCapturedThis(); - return 1; - } - var firstStatement; - var superCallExpression; - var ctorStatements = ctor.body.statements; - if (statementOffset < ctorStatements.length) { - firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 221 && ts.isSuperCall(firstStatement.expression)) { - superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); - } - } - if (superCallExpression - && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (8192 | 16384))) { - var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 204 - || superCallExpression.left.kind !== 191) { - ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); - } - ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536))); - statements.push(returnStatement); - return 2; - } - captureThisForNode(statements, ctor, superCallExpression || createActualThis()); - if (superCallExpression) { - return 1; - } - return 0; - } function createActualThis() { return ts.setEmitFlags(ts.createThis(), 4); } @@ -60449,13 +60489,15 @@ var ts; return node; } } - function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536) !== 0; + function hasDefaultValueOrBindingPattern(node) { + return node.initializer !== undefined + || ts.isBindingPattern(node.name); } function addDefaultValueAssignmentsIfNeeded(statements, node) { - if (!shouldAddDefaultValueAssignments(node)) { - return; + if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) { + return false; } + var added = false; for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; @@ -60463,23 +60505,27 @@ var ts; continue; } if (ts.isBindingPattern(name)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added; } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + added = true; } } + return added; } - function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { - var temp = ts.getGeneratedNameForNode(parameter); + function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { if (name.elements.length > 0) { - statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 1048576)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, ts.getGeneratedNameForNode(parameter)))), 1048576)); + return true; } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576)); + return true; } + return false; } - function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48), ts.setEmitFlags(initializer, 48 | ts.getEmitFlags(initializer) | 1536)), parameter), 1536)) @@ -60487,22 +60533,23 @@ var ts; ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); ts.setEmitFlags(statement, 384 | 32 | 1048576 | 1536); - statements.push(statement); + ts.insertStatementAfterCustomPrologue(statements, statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper); } function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var prologueStatements = []; var parameter = ts.lastOrUndefined(node.parameters); if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { - return; + return false; } var declarationName = parameter.name.kind === 72 ? ts.getMutableClone(parameter.name) : ts.createTempVariable(undefined); ts.setEmitFlags(declarationName, 48); var expressionName = parameter.name.kind === 72 ? ts.getSynthesizedClone(parameter.name) : declarationName; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) ])), parameter), 1048576)); var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ @@ -60514,27 +60561,31 @@ var ts; ])); ts.setEmitFlags(forStatement, 1048576); ts.startOnNewLine(forStatement); - statements.push(forStatement); + prologueStatements.push(forStatement); if (parameter.name.kind !== 72) { - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, expressionName))), parameter), 1048576)); + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, expressionName))), parameter), 1048576)); } + ts.insertStatementsAfterCustomPrologue(statements, prologueStatements); + return true; } - function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 && node.kind !== 197) { - captureThisForNode(statements, node, ts.createThis()); + function insertCaptureThisForNodeIfNeeded(statements, node) { + if (hierarchyFacts & 16384 && node.kind !== 197) { + insertCaptureThisForNode(statements, node, ts.createThis()); + return true; } + return false; } - function captureThisForNode(statements, node, initializer) { + function insertCaptureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), undefined, initializer) ])); ts.setEmitFlags(captureThisStatement, 1536 | 1048576); ts.setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + ts.insertStatementAfterCustomPrologue(statements, captureThisStatement); } - function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { - if (hierarchyFacts & 16384) { + function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 8192) { var newTarget = void 0; switch (node.kind) { case 197: @@ -60557,10 +60608,11 @@ var ts; var captureNewTargetStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), undefined, newTarget) ])); + ts.setEmitFlags(captureNewTargetStatement, 1536 | 1048576); if (copyOnWrite) { - return [captureNewTargetStatement].concat(statements); + statements = statements.slice(); } - statements.unshift(captureNewTargetStatement); + ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); } return statements; } @@ -60593,7 +60645,6 @@ var ts; return ts.setTextRange(ts.createEmptyStatement(), member); } function transformClassMethodDeclarationToStatement(receiver, member, container) { - var ancestorFacts = enterSubtree(0, 0); var commentRange = ts.getCommentRange(member); var sourceMapRange = ts.getSourceMapRange(member); var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name); @@ -60604,7 +60655,6 @@ var ts; ts.setOriginalNode(statement, member); ts.setCommentRange(statement, commentRange); ts.setEmitFlags(statement, 48); - exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); return statement; } function transformAccessorsToStatement(receiver, accessors, container) { @@ -60615,7 +60665,6 @@ var ts; } function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; - var ancestorFacts = enterSubtree(0, 0); var target = ts.getMutableClone(receiver); ts.setEmitFlags(target, 1536 | 32); ts.setSourceMapRange(target, firstAccessor.name); @@ -60648,53 +60697,51 @@ var ts; if (startsOnNewLine) { ts.startOnNewLine(call); } - exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); return call; } function visitArrowFunction(node) { - if (node.transformFlags & 8192) { - enableSubstitutionsForCapturedThis(); + if (node.transformFlags & 2048) { + hierarchyFacts |= 16384; } var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16256, 66); + var ancestorFacts = enterSubtree(8064, 66); var func = ts.createFunctionExpression(undefined, undefined, undefined, undefined, ts.visitParameterList(node.parameters, visitor, context), undefined, transformFunctionBody(node)); ts.setTextRange(func, node); ts.setOriginalNode(func, node); ts.setEmitFlags(func, 8); + if (hierarchyFacts & 16384) { + enableSubstitutionsForCapturedThis(); + } exitSubtree(ancestorFacts, 0, 0); convertedLoopState = savedConvertedLoopState; return func; } function visitFunctionExpression(node) { var ancestorFacts = ts.getEmitFlags(node) & 262144 - ? enterSubtree(16278, 69) - : enterSubtree(16286, 65); + ? enterSubtree(8086, 69) + : enterSubtree(8094, 65); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152, 0); + exitSubtree(ancestorFacts, 24576, 0); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionExpression(node, undefined, node.asteriskToken, name, undefined, parameters, undefined, body); } function visitFunctionDeclaration(node) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286, 65); + var ancestorFacts = enterSubtree(8094, 65); var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152, 0); + exitSubtree(ancestorFacts, 24576, 0); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionDeclaration(node, undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, undefined, parameters, undefined, body); } @@ -60702,14 +60749,14 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32) - ? enterSubtree(16286, 65 | 8) - : enterSubtree(16286, 65); + ? enterSubtree(8094, 65 | 8) + : enterSubtree(8094, 65); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 && !name && (node.kind === 239 || node.kind === 196)) { + if (hierarchyFacts & 8192 && !name && (node.kind === 239 || node.kind === 196)) { name = ts.getGeneratedNameForNode(node); } - exitSubtree(ancestorFacts, 49152, 0); + exitSubtree(ancestorFacts, 24576, 0); convertedLoopState = savedConvertedLoopState; return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(undefined, node.asteriskToken, name, undefined, parameters, undefined, body), location), node); } @@ -60718,19 +60765,18 @@ var ts; var singleLine = false; var statementsLocation; var closeBraceLocation; - var leadingStatements = []; + var prologue = []; var statements = []; var body = node.body; var statementOffset; resumeLexicalEnvironment(); if (ts.isBlock(body)) { - statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, false); + statementOffset = ts.addStandardPrologue(prologue, body.statements, false); } - addCaptureThisForNodeIfNeeded(leadingStatements, node); - addDefaultValueAssignmentsIfNeeded(leadingStatements, node); - addRestParameterIfNeeded(leadingStatements, node, false); + multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; + multiLine = addRestParameterIfNeeded(statements, node, false) || multiLine; if (ts.isBlock(body)) { - statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); if (!multiLine && body.multiLine) { @@ -60757,13 +60803,17 @@ var ts; statements.push(returnStatement); closeBraceLocation = body; } - var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); - prependCaptureNewTargetIfNeeded(statements, node, false); - if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, node, false); + insertCaptureThisForNodeIfNeeded(prologue, node); + if (ts.some(prologue)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + statements.unshift.apply(statements, prologue); + if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) { + return body; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1); @@ -60774,10 +60824,6 @@ var ts; ts.setOriginalNode(block, node.body); return block; } - function visitFunctionBodyDownLevel(node) { - var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); - return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, true)), updated.statements)); - } function visitBlock(node, isFunctionBody) { if (isFunctionBody) { return ts.visitEachChild(node, visitor, context); @@ -60849,7 +60895,7 @@ var ts; return updated; } function visitVariableDeclarationList(node) { - if (node.transformFlags & 64) { + if (node.flags & 3 || node.transformFlags & 65536) { if (node.flags & 3) { enableSubstitutionsForBlockScopedBindings(); } @@ -60860,7 +60906,7 @@ var ts; ts.setOriginalNode(declarationList, node); ts.setTextRange(declarationList, node); ts.setCommentRange(declarationList, node); - if (node.transformFlags & 2097152 + if (node.transformFlags & 65536 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -61061,7 +61107,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 4194304 && hierarchyFacts & 4) + if ((property.transformFlags & 131072 && hierarchyFacts & 4) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -61292,7 +61338,7 @@ var ts; } function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = ts.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 4194304) !== 0; + var containsYield = (node.initializer.transformFlags & 131072) !== 0; var emitFlags = 0; if (currentState.containsLexicalThis) emitFlags |= 8; @@ -61327,11 +61373,11 @@ var ts; statements.push(statement); } copyOutParameters(currentState.loopOutParameters, 1, 1, statements); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment); var loopBody = ts.createBlock(statements, true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 4194304) !== 0; + var containsYield = (node.statement.transformFlags & 131072) !== 0; var emitFlags = 0; if (currentState.containsLexicalThis) emitFlags |= 8; @@ -61506,13 +61552,11 @@ var ts; return expression; } function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { - var ancestorFacts = enterSubtree(0, 0); var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, method, undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { ts.startOnNewLine(expression); } - exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 16384 : 0); return expression; } function visitCatchClause(node) { @@ -61549,19 +61593,17 @@ var ts; ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286, 65); + var ancestorFacts = enterSubtree(8094, 65); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (16384 | 128) - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); + var body = transformFunctionBody(node); if (node.kind === 158) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } - exitSubtree(ancestorFacts, 49152, 0); + exitSubtree(ancestorFacts, 24576, 0); convertedLoopState = savedConvertedLoopState; return updated; } @@ -61569,16 +61611,13 @@ var ts; return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), node); } function visitComputedPropertyName(node) { - var ancestorFacts = enterSubtree(0, 8192); - var updated = ts.visitEachChild(node, visitor, context); - exitSubtree(ancestorFacts, 49152, hierarchyFacts & 49152 ? 32768 : 0); - return updated; + return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { return ts.visitEachChild(node, visitor, context); } function visitArrayLiteralExpression(node) { - if (node.transformFlags & 64) { + if (ts.some(node.elements, ts.isSpreadElement)) { return transformAndSpreadElements(node.elements, true, !!node.multiLine, !!node.elements.hasTrailingComma); } return ts.visitEachChild(node, visitor, context); @@ -61587,7 +61626,10 @@ var ts; if (ts.getEmitFlags(node) & 33554432) { return visitTypeScriptClassWrapper(node); } - if (node.transformFlags & 64) { + var expression = ts.skipOuterExpressions(node.expression); + if (expression.kind === 98 || + ts.isSuperProperty(expression) || + ts.some(node.arguments, ts.isSpreadElement)) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression)); @@ -61633,7 +61675,7 @@ var ts; return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { - if (node.transformFlags & 131072 || + if (node.transformFlags & 4096 || node.expression.kind === 98 || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -61641,16 +61683,14 @@ var ts; ts.setEmitFlags(thisArg, 4); } var resultingCall = void 0; - if (node.transformFlags & 131072) { - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + if (node.transformFlags & 4096) { + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); } if (node.expression.kind === 98) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4); - var initializer = ts.createLogicalOr(resultingCall, actualThis); + var initializer = ts.createLogicalOr(resultingCall, createActualThis()); resultingCall = assignToCapturedThis ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) : initializer; @@ -61660,7 +61700,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitNewExpression(node) { - if (node.transformFlags & 131072) { + if (ts.some(node.arguments, ts.isSpreadElement)) { var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray([ts.createVoidZero()].concat(node.arguments)), false, false, false)), undefined, []); } @@ -61801,19 +61841,14 @@ var ts; } function visitMetaProperty(node) { if (node.keywordToken === 95 && node.name.escapedText === "target") { - if (hierarchyFacts & 8192) { - hierarchyFacts |= 32768; - } - else { - hierarchyFacts |= 16384; - } + hierarchyFacts |= 8192; return ts.createFileLevelUniqueName("_newTarget"); } return node; } function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { - var ancestorFacts = enterSubtree(16286, ts.getEmitFlags(node) & 8 + var ancestorFacts = enterSubtree(8094, ts.getEmitFlags(node) & 8 ? 65 | 16 : 65); previousOnEmitNode(hint, node, emitCallback); @@ -62089,7 +62124,7 @@ var ts; var withBlockStack; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 256) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -62104,10 +62139,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 256) { + else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512) { + else if (transformFlags & 256) { return ts.visitEachChild(node, visitor, context); } else { @@ -62150,10 +62185,10 @@ var ts; case 230: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304) { + if (node.transformFlags & 131072) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 | 8388608)) { + else if (node.transformFlags & (256 | 262144)) { return ts.visitEachChild(node, visitor, context); } else { @@ -62271,7 +62306,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); inGeneratorFunctionBody = savedInGeneratorFunctionBody; inStatementContainingYield = savedInStatementContainingYield; @@ -62289,7 +62324,7 @@ var ts; return ts.setTextRange(ts.createBlock(statements, body.multiLine), body); } function visitVariableStatement(node) { - if (node.transformFlags & 4194304) { + if (node.transformFlags & 131072) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -62970,7 +63005,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 4194304) !== 0; + return !!node && (node.transformFlags & 131072) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -63711,7 +63746,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 16777216 || + node.transformFlags & 524288 || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } @@ -63742,7 +63777,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, false); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(updated, exportStarHelper); @@ -63860,7 +63895,7 @@ var ts; } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { ts.addEmitHelper(body, exportStarHelper); @@ -63914,13 +63949,13 @@ var ts; } } function moduleExpressionElementVisitor(node) { - if (!(node.transformFlags & 16777216) && !(node.transformFlags & 2048)) { + if (!(node.transformFlags & 524288) && !(node.transformFlags & 512)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if (node.transformFlags & 1024 && ts.isBinaryExpression(node)) { + else if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else { @@ -63981,7 +64016,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 8192); + var containsLexicalThis = !!(node.transformFlags & 2048); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -64592,7 +64627,7 @@ var ts; var noSubstitution; return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288)) { return node; } var id = ts.getOriginalNodeId(node); @@ -64664,7 +64699,7 @@ var ts; ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement); var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset); ts.addRange(statements, hoistedStatements); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -65206,14 +65241,13 @@ var ts; return node; } function destructuringAndImportCallVisitor(node) { - if (node.transformFlags & 1024 - && node.kind === 204) { + if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048) || (node.transformFlags & 16777216)) { + else if ((node.transformFlags & 512) || (node.transformFlags & 524288)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -75942,19 +75976,15 @@ var ts; var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics()); - var reportSemanticDiagnostics = false; if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics()); ts.addRange(diagnostics, program.getGlobalDiagnostics()); if (diagnostics.length === configFileParsingDiagnosticsLength) { - reportSemanticDiagnostics = true; + ts.addRange(diagnostics, program.getSemanticDiagnostics()); } } var _a = program.emit(undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); - if (reportSemanticDiagnostics) { - ts.addRange(diagnostics, program.getSemanticDiagnostics()); - } ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); if (writeFileName) { var currentDir_1 = program.getCurrentDirectory(); @@ -76063,6 +76093,22 @@ var ts; } } ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; + function setCreateSourceFileAsHashVersioned(compilerHost, host) { + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + ts.setCreateSourceFileAsHashVersioned = setCreateSourceFileAsHashVersioned; function createProgramHost(system, createProgram) { var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); }); var host = system; @@ -76122,6 +76168,23 @@ var ts; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; + function readBuilderProgram(compilerOptions, readFile) { + if (compilerOptions.out || compilerOptions.outFile) + return undefined; + var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions); + if (!buildInfoPath) + return undefined; + var content = readFile(buildInfoPath); + if (!content) + return undefined; + var buildInfo = ts.getBuildInfo(content); + if (buildInfo.version !== ts.version) + return undefined; + if (!buildInfo.program) + return undefined; + return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + } + ts.readBuilderProgram = readBuilderProgram; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -76133,7 +76196,6 @@ var ts; } } ts.createWatchCompilerHost = createWatchCompilerHost; - var initialVersion = 1; function createWatchProgram(host) { var builderProgram; var reloadLevel; @@ -76173,10 +76235,12 @@ var ts; var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + var configFileWatcher; if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); } var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); var getNewSourceFile = compilerHost.getSourceFile; compilerHost.getSourceFile = function (fileName) { var args = []; @@ -76212,20 +76276,42 @@ var ts; (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); }); synchronizeProgram(); watchConfigFileWildCardDirectories(); return configFileName ? - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close }; + function close() { + resolutionCache.clear(); + ts.clearMap(sourceFilesCache, function (value) { + if (value && value.fileWatcher) { + value.fileWatcher.close(); + value.fileWatcher = undefined; + } + }); + if (configFileWatcher) { + configFileWatcher.close(); + configFileWatcher = undefined; + } + if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + watchedWildcardDirectories = undefined; + } + if (missingFilesMap) { + ts.clearMap(missingFilesMap, ts.closeFileWatcher); + missingFilesMap = undefined; + } + } function getCurrentBuilderProgram() { return builderProgram; } function getCurrentProgram() { - return builderProgram && builderProgram.getProgram(); + return builderProgram && builderProgram.getProgramOrUndefined(); } function synchronizeProgram() { writeLog("Synchronizing program"); - var program = getCurrentProgram(); + var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { @@ -76240,18 +76326,18 @@ var ts; } } else { - createNewProgram(program, hasInvalidatedResolution); + createNewProgram(hasInvalidatedResolution); } if (host.afterProgramCreate) { host.afterProgramCreate(builderProgram); } return builderProgram; } - function createNewProgram(program, hasInvalidatedResolution) { + function createNewProgram(hasInvalidatedResolution) { writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); - var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); @@ -76285,10 +76371,10 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function isFileMissingOnHost(hostSourceFile) { - return typeof hostSourceFile === "number"; + return typeof hostSourceFile === "boolean"; } - function isFilePresentOnHost(hostSourceFile) { - return !!hostSourceFile.sourceFile; + function isFilePresenceUnknownOnHost(hostSourceFile) { + return typeof hostSourceFile.version === "boolean"; } function fileExists(fileName) { var path = toPath(fileName); @@ -76302,34 +76388,30 @@ var ts; if (isFileMissingOnHost(hostSourceFile)) { return undefined; } - if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) { var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { - if (shouldCreateNewSourceFile) { - hostSourceFile.version++; - } if (sourceFile) { hostSourceFile.sourceFile = sourceFile; - sourceFile.version = hostSourceFile.version.toString(); + hostSourceFile.version = sourceFile.version; if (!hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); } } else { - if (isFilePresentOnHost(hostSourceFile)) { + if (hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher.close(); } - sourceFilesCache.set(path, hostSourceFile.version); + sourceFilesCache.set(path, false); } } else { if (sourceFile) { - sourceFile.version = initialVersion.toString(); var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); - sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher }); } else { - sourceFilesCache.set(path, initialVersion); + sourceFilesCache.set(path, false); } } return sourceFile; @@ -76340,20 +76422,20 @@ var ts; var hostSourceFile = sourceFilesCache.get(path); if (hostSourceFile !== undefined) { if (isFileMissingOnHost(hostSourceFile)) { - sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + sourceFilesCache.set(path, { version: false }); } else { - hostSourceFile.version++; + hostSourceFile.version = false; } } } function getSourceVersion(path) { var hostSourceFile = sourceFilesCache.get(path); - return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version; } function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); - if (hostSourceFileInfo) { + if (hostSourceFileInfo !== undefined) { if (isFileMissingOnHost(hostSourceFileInfo)) { (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); } @@ -76435,7 +76517,7 @@ var ts; } function onSourceFileChange(fileName, eventKind, path) { updateCachedSystemWithFile(fileName, path, eventKind); - if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); @@ -76675,19 +76757,7 @@ var ts; var readFileWithCache = function (f) { return host.readFile(f); }; var projectCompilerOptions = baseCompilerOptions; var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); - var originalGetSourceFile = compilerHost.getSourceFile; - var computeHash = host.createHash || ts.generateDjb2Hash; - compilerHost.getSourceFile = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); - if (result) { - result.version = computeHash.call(host, result.text); - } - return result; - }; + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); var buildInfoChecked = createFileMap(toPath); var builderPrograms = createFileMap(toPath); var diagnostics = createFileMap(toPath); @@ -77300,16 +77370,7 @@ var ts; var value = builderPrograms.getValue(proj); if (value) return value; - var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options); - if (!buildInfoPath) - return undefined; - var content = readFileWithCache(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); - if (buildInfo.version !== ts.version) - return undefined; - return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + return ts.readBuilderProgram(parsed.options, readFileWithCache); } function updateBundle(proj) { if (options.dry) { @@ -77836,6 +77897,9 @@ var ts; reportWatchModeWithoutSysSupport(); createWatchOfConfigFile(configParseResult, commandLineOptions); } + else if (ts.isIncrementalCompilation(configParseResult.options)) { + performIncrementalCompilation(configParseResult); + } else { performCompilation(configParseResult.fileNames, configParseResult.projectReferences, configParseResult.options, ts.getConfigFileParsingDiagnostics(configParseResult)); } @@ -77926,6 +77990,32 @@ var ts; reportStatistics(program); return ts.sys.exit(exitStatus); } + function performIncrementalCompilation(config) { + var options = config.options, fileNames = config.fileNames, projectReferences = config.projectReferences; + var host = ts.createCompilerHost(options); + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }); + enableStatistics(options); + var oldProgram = ts.readBuilderProgram(options, function (path) { return host.readFile(path); }); + var configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(config); + var programOptions = { + rootNames: fileNames, + options: options, + projectReferences: projectReferences, + host: host, + configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(config), + }; + var program = ts.createProgram(programOptions); + var builderProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram(program, { + useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + createHash: ts.maybeBind(ts.sys, ts.sys.createHash), + writeFile: function (path, data, writeByteOrderMark) { return ts.sys.writeFile(path, data, writeByteOrderMark); } + }, oldProgram, configFileParsingDiagnostics); + var exitStatus = ts.emitFilesAndReportErrors(builderProgram, reportDiagnostic, function (s) { return ts.sys.write(s + ts.sys.newLine); }, createReportErrorSummary(options)); + reportStatistics(program); + return ts.sys.exit(exitStatus); + } function updateCreateProgram(host) { var compileUsingBuilder = host.createProgram; host.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) { diff --git a/lib/tsserver.js b/lib/tsserver.js index ed05481b9ab..6489fac56cc 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -3854,75 +3854,69 @@ var ts; TransformFlags[TransformFlags["None"] = 0] = "None"; // Facts // - Flags used to indicate that a node or subtree contains syntax that requires transformation. - TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; - TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; - TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; - TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; - TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016"; TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; - TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; - TransformFlags[TransformFlags["ContainsES2018"] = 134217728] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2019"] = 268435456] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. - TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; - TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; - TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2019"] = 268435456] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 134217728] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; - TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes"; + // Propagating flags + // - Bitmasks for flags that should propagate from a child + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -8686,10 +8680,7 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - /** - * Prepends statements to an array while taking care of prologue directives. - */ - function addStatementsAfterPrologue(to, from) { + function insertStatementsAfterPrologue(to, from, isPrologueDirective) { if (from === undefined || from.length === 0) return to; var statementIndex = 0; @@ -8702,7 +8693,44 @@ var ts; to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + function insertStatementAfterPrologue(to, statement, isPrologueDirective) { + if (statement === undefined) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice(statementIndex, 0, statement); + return to; + } + function isAnyPrologueDirective(node) { + return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementsAfterStandardPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isPrologueDirective); + } + ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue; + function insertStatementsAfterCustomPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective); + } + ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementAfterStandardPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isPrologueDirective); + } + ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue; + function insertStatementAfterCustomPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective); + } + ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue; /** * Determine if the given comment is a triple-slash * @@ -9692,6 +9720,11 @@ var ts; } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + function isSuperOrSuperProperty(node) { + return node.kind === 98 /* SuperKeyword */ + || isSuperProperty(node); + } + ts.isSuperOrSuperProperty = isSuperOrSuperProperty; /** * Determines whether a node is a property or element access expression for `super`. */ @@ -30134,44 +30167,37 @@ var ts; ts.computeTransformFlagsForNode = computeTransformFlagsForNode; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; + var callee = ts.skipOuterExpressions(node.expression); var expression = node.expression; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */ - || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; - // super property or element accesses could be inside lambdas, etc, and need a captured `this`, - // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 67108864 /* ContainsSuper */) { - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 128 /* AssertES2015 */; + if (ts.isSuperProperty(callee)) { + transformFlags |= 2048 /* ContainsLexicalThis */; } } if (expression.kind === 92 /* ImportKeyword */) { - transformFlags |= 16777216 /* ContainsDynamicImport */; - // A dynamic 'import()' call that contains a lexical 'this' will - // require a captured 'this' when emitting down-level. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; - } + transformFlags |= 524288 /* ContainsDynamicImport */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30180,19 +30206,19 @@ var ts; if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ES2018 if they contain rest - transformFlags |= 134217728 /* AssertES2018 */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. - transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { // Exponentiation is ES2016 syntax. - transformFlags |= 32 /* AssertES2016 */; + transformFlags |= 64 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30203,147 +30229,131 @@ var ts; // syntax. if (node.questionToken || node.type - || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) + || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* ParameterExcludes */; + return transformFlags & ~536870912 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. if (expressionKind === 212 /* AsExpression */ || expressionKind === 194 /* TypeAssertionExpression */) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the expression of a ParenthesizedExpression is a destructuring assignment, - // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 1024 /* DestructuringAssignment */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* OuterExpressionExcludes */; + return transformFlags & ~536870912 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; if (ts.hasModifier(node, 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES2015 */; + transformFlags = subtreeFlags | 128 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, computed property name, or decorator is // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) + if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ + if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { case 86 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 109 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; default: ts.Debug.fail("Unexpected token for heritage clause"); break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; if (!node.variableDeclaration) { - transformFlags |= 268435456 /* AssertES2019 */; + transformFlags |= 8 /* AssertES2019 */; } else if (ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637797697 /* CatchClauseExcludes */; + return transformFlags & ~536879104 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; // TypeScript-specific modifiers and overloads are TypeScript syntax if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* ConstructorExcludes */; + return transformFlags & ~537372672 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and // overloads are TypeScript syntax. if (node.decorators @@ -30352,21 +30362,21 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // An async method declaration is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30377,25 +30387,25 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. - var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + var transformFlags = subtreeFlags | 1 /* AssertTypeScript */; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */); } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -30404,30 +30414,24 @@ var ts; if (!body || (modifierFlags & 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. // A FunctionDeclaration without a body is an overload and is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function declaration is ES2017 syntax. if (modifierFlags & 256 /* Async */) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If a FunctionDeclaration's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionDeclaration is generator function and is the body of a // transformed async function, then this node can be transformed to a @@ -30435,11 +30439,11 @@ var ts; // Currently we do not support transforming any other generator functions // down level. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30448,181 +30452,161 @@ var ts; if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function expression is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } // function expressions with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If a FunctionExpression's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionExpression is generator function and is the body of a // transformed async function, then this node can be transformed to a // down-level generator. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async arrow function is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= 16 /* AssertES2017 */; + transformFlags |= 32 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653604161 /* ArrowFunctionExcludes */; + return transformFlags & ~537371648 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 33554432 /* Super */) { - transformFlags ^= 33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). // same for super inside of an async generator, which is ES2018. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 134217728 /* ContainsES2018 */; + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 33554432 /* Super */) { - transformFlags &= ~33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). // same for super inside of an async generator, which is ES2018. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 134217728 /* ContainsES2018 */; + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally? // A VariableDeclaration containing ObjectRest is ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // Type annotations are TypeScript syntax. if (node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; var declarationListTransformFlags = node.declarationList.transformFlags; // An ambient declaration is TypeScript syntax. if (ts.hasModifier(node, 2 /* Ambient */)) { - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; // An ImportEqualsDeclaration with a namespace reference is TypeScript. if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - // If the expression of an expression statement is a destructuring assignment, - // then we treat the statement as ES6 so that we can indicate that we do not - // need to hold on to the right-hand side. - if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES2015 */; - } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3 /* AssertTypeScript */; + var transformFlags = 1 /* AssertTypeScript */; var modifierFlags = ts.getModifierFlags(node); if ((modifierFlags & 2 /* Ambient */) === 0) { transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~647001409 /* ModuleExcludes */; + return transformFlags & ~537168896 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; + transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; + return transformFlags & ~536944640 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 637535553 /* NodeExcludes */; + var excludeFlags = 536870912 /* NodeExcludes */; switch (kind) { case 121 /* AsyncKeyword */: case 201 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators) - transformFlags |= 134217728 /* AssertES2018 */ | 16 /* AssertES2017 */; + transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */; break; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: case 313 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; + transformFlags |= 1 /* AssertTypeScript */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; break; case 115 /* PublicKeyword */: case 113 /* PrivateKeyword */: @@ -30635,7 +30619,7 @@ var ts; case 213 /* NonNullExpression */: case 133 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; case 260 /* JsxElement */: case 261 /* JsxSelfClosingElement */: @@ -30650,7 +30634,7 @@ var ts; case 269 /* JsxSpreadAttribute */: case 270 /* JsxExpression */: // These nodes are Jsx syntax. - transformFlags |= 4 /* AssertJsx */; + transformFlags |= 2 /* AssertJsx */; break; case 14 /* NoSubstitutionTemplateLiteral */: case 15 /* TemplateHead */: @@ -30662,32 +30646,32 @@ var ts; case 116 /* StaticKeyword */: case 214 /* MetaProperty */: // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 10 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 8 /* NumericLiteral */: if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 9 /* BigIntLiteral */: - transformFlags |= 8 /* AssertESNext */; + transformFlags |= 4 /* AssertESNext */; break; case 227 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { - transformFlags |= 134217728 /* AssertES2018 */; + transformFlags |= 16 /* AssertES2018 */; } - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 207 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 134217728 /* AssertES2018 */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */; break; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: @@ -30728,115 +30712,93 @@ var ts; case 182 /* LiteralType */: case 247 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. - transformFlags = 3 /* AssertTypeScript */; - excludeFlags = -3 /* TypeExcludes */; + transformFlags = 1 /* AssertTypeScript */; + excludeFlags = -2 /* TypeExcludes */; break; case 149 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 524288 /* ContainsComputedPropertyName */; - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - // A computed method name like `[this.getName()](x: string) { ... }` needs to - // distinguish itself from the normal case of a method body containing `this`: - // `this` inside a method doesn't need to be rewritten (the method provides `this`), - // whereas `this` inside a computed name *might* need to be rewritten if the class/object - // is inside an arrow function: - // `_this = this; () => class K { [_this.getName()]() { ... } }` - // To make this distinction, use ContainsLexicalThisInComputedPropertyName - // instead of ContainsLexicalThis for computed property names - transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; - } + transformFlags |= 16384 /* ContainsComputedPropertyName */; break; case 208 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */; break; case 277 /* SpreadAssignment */: - transformFlags |= 134217728 /* AssertES2018 */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; break; case 98 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + transformFlags |= 128 /* AssertES2015 */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 100 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 2048 /* ContainsLexicalThis */; break; case 184 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; } - excludeFlags = 637666625 /* BindingPatternExcludes */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 185 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - excludeFlags = 637666625 /* BindingPatternExcludes */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 186 /* BindingElement */: - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 131072 /* ContainsRestOrSpread */; + transformFlags |= 4096 /* ContainsRestOrSpread */; } break; case 152 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; break; case 188 /* ObjectLiteralExpression */: - excludeFlags = 638358849 /* ObjectLiteralExcludes */; - if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + excludeFlags = 536896512 /* ObjectLiteralExcludes */; + if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; - } - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES2018 node. - transformFlags |= 134217728 /* AssertES2018 */; + transformFlags |= 16 /* AssertES2018 */; } break; case 187 /* ArrayLiteralExpression */: - case 192 /* NewExpression */: - excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - // If the this node contains a SpreadExpression, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } + excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */; break; case 223 /* DoStatement */: case 224 /* WhileStatement */: case 225 /* ForStatement */: case 226 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) { + transformFlags |= 128 /* AssertES2015 */; } break; case 284 /* SourceFile */: - if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES2015 */; - } break; case 230 /* ReturnStatement */: // Return statements may require an `await` in ES2018. - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 134217728 /* AssertES2018 */; + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */; break; case 228 /* ContinueStatement */: case 229 /* BreakStatement */: - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~excludeFlags; } + function propagatePropertyNameFlags(node, transformFlags) { + return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */); + } /** * Gets the transform flags to exclude when unioning the transform flags of a subtree. * @@ -30846,33 +30808,33 @@ var ts; */ function getTransformFlagsSubtreeExclusions(kind) { if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; } switch (kind) { case 191 /* CallExpression */: case 192 /* NewExpression */: case 187 /* ArrayLiteralExpression */: - return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return 536875008 /* ArrayLiteralOrCallOrNewExcludes */; case 244 /* ModuleDeclaration */: - return 647001409 /* ModuleExcludes */; + return 537168896 /* ModuleExcludes */; case 151 /* Parameter */: - return 637535553 /* ParameterExcludes */; + return 536870912 /* ParameterExcludes */; case 197 /* ArrowFunction */: - return 653604161 /* ArrowFunctionExcludes */; + return 537371648 /* ArrowFunctionExcludes */; case 196 /* FunctionExpression */: case 239 /* FunctionDeclaration */: - return 653620545 /* FunctionExcludes */; + return 537373696 /* FunctionExcludes */; case 238 /* VariableDeclarationList */: - return 639894849 /* VariableDeclarationListExcludes */; + return 536944640 /* VariableDeclarationListExcludes */; case 240 /* ClassDeclaration */: case 209 /* ClassExpression */: - return 638121281 /* ClassExcludes */; + return 536888320 /* ClassExcludes */; case 157 /* Constructor */: - return 653616449 /* ConstructorExcludes */; + return 537372672 /* ConstructorExcludes */; case 156 /* MethodDeclaration */: case 158 /* GetAccessor */: case 159 /* SetAccessor */: - return 653616449 /* MethodOrAccessorExcludes */; + return 537372672 /* MethodOrAccessorExcludes */; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: case 146 /* BigIntKeyword */: @@ -30890,25 +30852,25 @@ var ts; case 162 /* IndexSignature */: case 241 /* InterfaceDeclaration */: case 242 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; case 188 /* ObjectLiteralExpression */: - return 638358849 /* ObjectLiteralExcludes */; + return 536896512 /* ObjectLiteralExcludes */; case 274 /* CatchClause */: - return 637797697 /* CatchClauseExcludes */; + return 536879104 /* CatchClauseExcludes */; case 184 /* ObjectBindingPattern */: case 185 /* ArrayBindingPattern */: - return 637666625 /* BindingPatternExcludes */; + return 536875008 /* BindingPatternExcludes */; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: case 313 /* PartiallyEmittedExpression */: case 195 /* ParenthesizedExpression */: case 98 /* SuperKeyword */: - return 536872257 /* OuterExpressionExcludes */; + return 536870912 /* OuterExpressionExcludes */; case 189 /* PropertyAccessExpression */: case 190 /* ElementAccessExpression */: - return 570426689 /* PropertyAccessExcludes */; + return 536870912 /* PropertyAccessExcludes */; default: - return 637535553 /* NodeExcludes */; + return 536870912 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -31453,6 +31415,7 @@ var ts; var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); + var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -37981,15 +37944,24 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } + function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { + var rootTrueType = root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + return instantiateType(rootTrueConstraint, combinedMapper || mapper); + } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { - var rootTrueType = type.root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) - ? rootTrueType - : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + // An `any` branch of a conditional type would normally be viral - specifically, without special handling here, + // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to + // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type, + // in effect treating `any` like `never` rather than `unknown` in this location. + var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); + var falseConstraint = getFalseTypeFromConditionalType(type); + type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; } @@ -37999,7 +37971,13 @@ var ts; // with its constraint. We do this because if the constraint is a union type it will be distributed // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. - if (type.root.isDistributive) { + // We skip returning a distributive constraint for a restrictive instantiation of a conditional type + // as the constraint for all type params (check type included) have been replace with `unknown`, which + // is going to produce even more false positive/negative results than the distribute constraint already does. + // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter + // a union - once negated types exist and are applied to the conditional false branch, this "constraint" + // likely doesn't need to exist. + if (type.root.isDistributive && type.restrictiveInstantiation !== type) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint && constraint !== type.checkType) { @@ -40392,12 +40370,47 @@ var ts; function getActualTypeVariable(type) { return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; } + /** + * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent + */ + function isIntersectionEmpty(type1, type2) { + return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */); + } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); var extendsType = instantiateType(root.extendsType, mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } + var trueType = instantiateType(root.trueType, mapper); + var falseType = instantiateType(root.falseType, mapper); + var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; + } + var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); + conditionalTypes.set(instantiationId, newResult); + return newResult; + } + function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) { + // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`. + if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { + if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return getDefaultConstraintOfTrueBranchOfConditionalType(root, /*combinedMapper*/ undefined, mapper); + } + else if (isIntersectionEmpty(checkType, extendsType)) { // Always false + return neverType; + } + } + else if (trueType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(falseType), getActualTypeVariable(checkType))) { + if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return neverType; + } + else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false + return falseType; // TODO: Intersect negated `extends` type here + } + } var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); var combinedMapper; if (root.inferTypeParameters) { @@ -40415,18 +40428,18 @@ var ts; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) { if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { - return instantiateType(root.trueType, mapper); + return trueType; } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { - return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]); } // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { - return instantiateType(root.falseType, mapper); + return falseType; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -40445,6 +40458,10 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; + if (!combinedMapper) { + result.resolvedTrueType = trueType; + result.resolvedFalseType = falseType; + } result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; @@ -41349,8 +41366,20 @@ var ts; type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); } function getRestrictiveInstantiation(type) { - return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : - type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); + if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) { + return type; + } + if (type.restrictiveInstantiation) { + return type.restrictiveInstantiation; + } + type.restrictiveInstantiation = instantiateType(type, restrictiveMapper); + // We set the following so we don't attempt to set the restrictive instance of a restrictive instance + // which is redundant - we'll produce new type identities, but all type params have already been mapped. + // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint" + // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters + // are constrained to `unknown` and produce tons of false positives/negatives! + type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation; + return type.restrictiveInstantiation; } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -42895,16 +42924,26 @@ var ts; template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } - // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. - if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - return result; + if (!isGenericMappedType(source)) { + var targetConstraint = getConstraintTypeFromMappedType(target); + var sourceKeys_1 = getIndexType(source); + var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */; + var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined; + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X. + if (hasOptionalUnionKeys + ? !(filteredByApplicability.flags & 131072 /* Never */) + : isRelatedTo(targetConstraint, sourceKeys_1)) { + var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target); + var indexedAccessType = getIndexedAccessType(source, indexingType); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } - originalErrorInfo = errorInfo; - errorInfo = saveErrorInfo; } } if (source.flags & 8650752 /* TypeVariable */) { @@ -44580,6 +44619,7 @@ var ts; if (inference.priority === undefined || priority < inference.priority) { inference.candidates = undefined; inference.contraCandidates = undefined; + inference.topLevel = true; inference.priority = priority; } if (priority === inference.priority) { @@ -65601,8 +65641,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) - : ts.addStatementsAfterPrologue(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) + : ts.insertStatementsAfterStandardPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -66876,8 +66916,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -66943,7 +66983,7 @@ var ts; if (flattenContext.level >= 1 /* 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 & 262144 /* ContainsObjectRestOrSpread */) { + if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -67271,14 +67311,9 @@ var ts; * @param node The node to visit. */ function visitorWorker(node) { - if (node.transformFlags & 1 /* TypeScript */) { - // This node is explicitly marked as TypeScript, so we should transform the node. + if (node.transformFlags & 1 /* ContainsTypeScript */) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -67312,7 +67347,7 @@ var ts; // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, // and will trigger debug failures when debug verbosity is turned up - if (node.transformFlags & 2 /* ContainsTypeScript */) { + if (node.transformFlags & 1 /* ContainsTypeScript */) { // This node contains TypeScript, so we should visit its children. return ts.visitEachChild(node, visitor, context); } @@ -67354,15 +67389,9 @@ var ts; // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } - else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { - // This node is explicitly marked as TypeScript, or is exported at the namespace - // level, so we should transform the node. + else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -67413,7 +67442,7 @@ var ts; * @param node The node to visit. */ function visitTypeScript(node) { - if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) { // TypeScript ambient declarations are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); @@ -67480,7 +67509,7 @@ var ts; // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); case 240 /* ClassDeclaration */: - // This is a class declaration with TypeScript syntax extensions. + // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -67491,7 +67520,7 @@ var ts; // - method overload signatures return visitClassDeclaration(node); case 209 /* ClassExpression */: - // This is a class expression with TypeScript syntax extensions. + // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -67502,7 +67531,7 @@ var ts; // - method overload signatures return visitClassExpression(node); case 273 /* HeritageClause */: - // This is a heritage clause with TypeScript syntax extensions. + // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause @@ -67530,7 +67559,7 @@ var ts; // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); case 151 /* Parameter */: - // This is a parameter declaration with TypeScript syntax extensions. + // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: // - decorators @@ -67571,7 +67600,8 @@ var ts; // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: - return ts.Debug.failBadSyntaxKind(node); + // node contains some other TypeScript syntax + return ts.visitEachChild(node, visitor, context); } } function visitSourceFile(node) { @@ -67620,18 +67650,19 @@ var ts; facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; return facts; } - /** - * Transforms a class declaration with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has decorators. - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - The class is an export in a TypeScript namespace. - * - * @param node The node to transform. - */ + function hasTypeScriptClassSyntax(node) { + return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */); + } + function isClassLikeDeclarationWithTypeScriptSyntax(node) { + return ts.some(node.decorators) + || ts.some(node.typeParameters) + || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) + || ts.some(node.members, hasTypeScriptClassSyntax); + } function visitClassDeclaration(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -67684,7 +67715,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -67861,16 +67892,10 @@ var ts; ts.setCommentRange(statement, node); return statement; } - /** - * Transforms a class expression with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - * @param node The node to transform. - */ function visitClassExpression(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -67934,7 +67959,7 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); var hasParameterPropertyAssignments = constructor && - constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. @@ -68979,11 +69004,11 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 86 /* ExtendsKeyword */) { - var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); + if (node.token === 109 /* ImplementsKeyword */) { + // implements clauses are elided + return undefined; } - return undefined; + return ts.visitEachChild(node, visitor, context); } /** * Transforms an ExpressionWithTypeArguments with TypeScript syntax. @@ -69019,16 +69044,6 @@ var ts; } return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); } - /** - * Visits a method declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is marked as abstract, public, private, protected, or readonly - * - The node has a computed property name - * - * @param node The method node. - */ function visitMethodDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; @@ -69055,15 +69070,6 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); } - /** - * Visits a get accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The get accessor node. - */ function visitGetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -69079,15 +69085,6 @@ var ts; } return updated; } - /** - * Visits a set accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The set accessor node. - */ function visitSetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -69102,16 +69099,6 @@ var ts; } return updated; } - /** - * Visits a function declaration. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is exported from a TypeScript namespace - * - The node has decorators - * - * @param node The function node. - */ function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); @@ -69127,14 +69114,6 @@ var ts; } return updated; } - /** - * Visits a function expression node. - * - * This function will be called when one of the following conditions are met: - * - The node has type annotations - * - * @param node The function expression node. - */ function visitFunctionExpression(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createOmittedExpression(); @@ -69144,51 +69123,31 @@ var ts; /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); return updated; } - /** - * @remarks - * This function will be called when one of the following conditions are met: - * - The node has type annotations - */ function visitArrowFunction(node) { var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } - /** - * Visits a parameter declaration node. - * - * This function will be called when one of the following conditions are met: - * - The node has an accessibility modifier. - * - The node has a questionToken. - * - The node's kind is ThisKeyword. - * - * @param node The parameter declaration node. - */ function visitParameter(node) { if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameter( + var updated = ts.updateParameter(node, /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setOriginalNode(parameter, node); - ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); - ts.setCommentRange(parameter, node); - ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); - return parameter; + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */); + } + return updated; } - /** - * Visits a variable statement in a namespace. - * - * This function will be called when one of the following conditions are met: - * - The node is exported from a TypeScript namespace. - */ function visitVariableStatement(node) { if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); @@ -69217,12 +69176,6 @@ var ts; return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } - /** - * Visits a parenthesized expression that contains either a type assertion or an `as` - * expression. - * - * @param node The parenthesized expression node. - */ function visitParenthesizedExpression(node) { var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); if (ts.isAssertionExpression(innerExpression)) { @@ -69359,7 +69312,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -69606,7 +69559,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -70161,7 +70114,7 @@ var ts; return visited; } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { @@ -70438,7 +70391,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.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. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); @@ -70446,7 +70399,7 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -70740,7 +70693,7 @@ var ts; return node; } function visitorWorker(node, noDestructuringValue) { - if ((node.transformFlags & 134217728 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { @@ -70858,7 +70811,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -70884,7 +70837,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 27 /* CommaToken */) { @@ -70899,7 +70852,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -70916,7 +70869,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -71013,7 +70966,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -71126,10 +71079,10 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } statements.push(returnStatement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { @@ -71155,7 +71108,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.insertStatementsAfterStandardPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -71164,7 +71117,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -71372,7 +71325,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 268435456 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { @@ -71403,7 +71356,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { return node; } switch (node.kind) { @@ -71436,7 +71389,7 @@ var ts; return visited; } function visitor(node) { - if (node.transformFlags & 4 /* ContainsJsx */) { + if (node.transformFlags & 2 /* ContainsJsx */) { return visitorWorker(node); } else { @@ -71938,7 +71891,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { @@ -72018,30 +71971,6 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); - var SuperCaptureResult; - (function (SuperCaptureResult) { - /** - * A capture may have been added for calls to 'super', but - * the caller should emit subsequent statements normally. - */ - SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * var _this = _super.call(...) || this; - * - * Callers should skip the current statement. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * return _super.call(...) || this; - * - * Callers should skip the current statement and avoid any returns of '_this'. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; - })(SuperCaptureResult || (SuperCaptureResult = {})); // Facts we track as we traverse the tree var HierarchyFacts; (function (HierarchyFacts) { @@ -72062,12 +71991,12 @@ var ts; HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; - HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below. // // Ancestor masks // - HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask"; // We are always in *some* kind of block scope, but only specific block-scope containers are // top-level or Blocks. HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; @@ -72077,16 +72006,16 @@ var ts; HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; // Functions, methods, and accessors are both new lexical scopes and new block scopes. HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; - HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes"; HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes"; // Arrow functions are lexically scoped to their container, but are new block scopes. HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; - HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes"; // Constructors are both new lexical scopes and new block scopes. Constructors are also // always considered non-static members of a class. HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; - HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes"; // 'do' and 'while' statements are not block scopes. We track that the subtree is contained // within an IterationStatement to indicate whether the embedded statement is an // IterationStatementBlock. @@ -72104,19 +72033,17 @@ var ts; HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; - // Computed property names track subtree flags differently than their containing members. - HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; - HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; // // Subtree facts // - HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; - HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget"; + HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis"; // // Subtree masks // - HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; - HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes"; + HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes"; })(HierarchyFacts || (HierarchyFacts = {})); function transformES2015(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; @@ -72165,7 +72092,7 @@ var ts; */ function enterSubtree(excludeFacts, includeFacts) { var ancestorFacts = hierarchyFacts; - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */; return ancestorFacts; } /** @@ -72176,7 +72103,7 @@ var ts; * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. */ function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 @@ -72198,12 +72125,6 @@ var ts; return node; } } - function functionBodyVisitor(node) { - if (shouldVisitNode(node)) { - return visitBlock(node, /*isFunctionBody*/ true); - } - return node; - } function callExpressionVisitor(node) { if (node.kind === 98 /* SuperKeyword */) { return visitSuperKeyword(/*isExpressionOfCall*/ true); @@ -72310,18 +72231,19 @@ var ts; } function visitSourceFile(node) { var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + var prologue = []; var statements = []; startLexicalEnvironment(); - var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); - addCaptureThisForNodeIfNeeded(statements, node); - statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureThisForNodeIfNeeded(prologue, node); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements)); } function visitSwitchStatement(node) { if (convertedLoopState !== undefined) { @@ -72361,6 +72283,9 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitThisKeyword(node) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; + } if (convertedLoopState) { if (hierarchyFacts & 2 /* ArrowFunction */) { // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. @@ -72574,7 +72499,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -72602,7 +72527,7 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = ts.createFunctionDeclaration( @@ -72616,7 +72541,7 @@ var ts; ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); } statements.push(constructorFunction); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; } /** @@ -72635,6 +72560,24 @@ var ts; return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } + function createDefaultConstructorBody(node, isDerivedClass) { + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + var statements = []; + resumeLexicalEnvironment(); + ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + if (isDerivedClass) { + // return _super !== null && _super.apply(this, arguments) || this; + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + } + var statementsArray = ts.createNodeArray(statements); + ts.setTextRange(statementsArray, node.members); + var block = ts.createBlock(statementsArray, /*multiLine*/ true); + ts.setTextRange(block, node); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } /** * Transforms the body of a constructor declaration of a class. * @@ -72645,59 +72588,137 @@ var ts; * synthesized `super` call. */ function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { - var statements = []; - resumeLexicalEnvironment(); - var statementOffset = -1; - if (hasSynthesizedSuper) { - // If a super call has already been synthesized, - // we're going to assume that we should just transform everything after that. - // The assumption is that no prior step in the pipeline has added any prologue directives. - statementOffset = 0; - } - else if (constructor) { - statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); - } - if (constructor) { - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); - if (!hasSynthesizedSuper) { - // If no super call has been synthesized, emit custom prologue directives. - statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); - } - ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); - } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; - var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); - // The last statement expression was replaced. Skip it. - if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { - statementOffset++; + // When the subclass does not have a constructor, we synthesize a *default* constructor using the following + // representation: + // + // ``` + // // es2015 (source) + // class C extends Base { } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.apply(this, arguments) || this; + // } + // return C; + // })(Base); + // ``` + if (!constructor) + return createDefaultConstructorBody(node, isDerivedClass); + // The prologue will contain all leading standard and custom prologue statements added by this transform + var prologue = []; + var statements = []; + resumeLexicalEnvironment(); + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + var statementOffset = 0; + if (!hasSynthesizedSuper) + statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + // If the first statement is a call to `super()`, visit the statement directly + var superCallExpression; + if (hasSynthesizedSuper) { + superCallExpression = createDefaultSuperCallOrThis(); } - if (constructor) { - if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { - hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + else if (isDerivedClass && statementOffset < constructor.body.statements.length) { + var firstStatement = constructor.body.statements[statementOffset]; + if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); } - // Return `_this` unless we're sure enough that it would be pointless to add a return statement. - // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. - if (isDerivedClass - && superCaptureStatus !== 2 /* ReplaceWithReturn */ - && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { - statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + if (superCallExpression) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + statementOffset++; // skip this statement, we will add it after visiting the rest of the body. } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - if (constructor) { - prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); + // visit the remaining statements + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); + if (isDerivedClass) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) { + // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the + // following representation: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.call(this, "foo") || this; + // } + // return C; + // })(Base); + // ``` + var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); + var returnStatement = ts.createReturn(superCallExpression); + ts.setCommentRange(returnStatement, ts.getCommentRange(superCall)); + ts.setEmitFlags(superCall, 1536 /* NoComments */); + statements.push(returnStatement); + } + else { + // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // this.x = 1; + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // var _this = _super.call(this, "foo") || this; + // _this.x = 1; + // return _this; + // } + // return C; + // })(Base); + // ``` + // Since the `super()` call was the first statement, we insert the `this` capturing call to + // `super()` at the top of the list of `statements` (after any pre-existing custom prologues). + insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); + if (!isSufficientlyCoveredByReturnStatements(constructor.body)) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } + } } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), - /*location*/ constructor ? constructor.body.statements : node.members), + else { + // If a class is not derived from a base class or does not have a call to `super()`, `this` is only + // captured when necessitated by an arrow function capturing the lexical `this`: + // + // ``` + // // es2015 + // class C {} + // + // // es5 + // var C = (function () { + // function C() { + // } + // return C; + // })(); + // ``` + insertCaptureThisForNodeIfNeeded(prologue, constructor); + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), + /*location*/ constructor.body.statements), /*multiLine*/ true); - ts.setTextRange(block, constructor ? constructor.body : node); - if (!constructor) { - ts.setEmitFlags(block, 1536 /* NoComments */); - } + ts.setTextRange(block, constructor.body); return block; } /** @@ -72727,83 +72748,6 @@ var ts; } return false; } - /** - * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. - * - * @returns The new statement offset into the `statements` array. - */ - function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { - // If this isn't a derived class, just capture 'this' for arrow functions if necessary. - if (!isDerivedClass) { - if (ctor) { - addCaptureThisForNodeIfNeeded(statements, ctor); - } - return 0 /* NoReplacement */; - } - // We must be here because the user didn't write a constructor - // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. - // If that's the case we can just immediately return the result of a 'super()' call. - if (!ctor) { - statements.push(ts.createReturn(createDefaultSuperCallOrThis())); - return 2 /* ReplaceWithReturn */; - } - // The constructor exists, but it and the 'super()' call it contains were generated - // for something like property initializers. - // Create a captured '_this' variable and assume it will subsequently be used. - if (hasSynthesizedSuper) { - captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); - enableSubstitutionsForCapturedThis(); - return 1 /* ReplaceSuperCapture */; - } - // Most of the time, a 'super' call will be the first real statement in a constructor body. - // In these cases, we'd like to transform these into a *single* statement instead of a declaration - // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, - // we'd get: - // - // var _this; - // _this = _super.call(...) || this; - // - // instead of - // - // var _this = _super.call(...) || this; - // - // Additionally, if the 'super()' call is the last statement, we should just avoid capturing - // entirely and immediately return the result like so: - // - // return _super.call(...) || this; - // - var firstStatement; - var superCallExpression; - var ctorStatements = ctor.body.statements; - if (statementOffset < ctorStatements.length) { - firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { - superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); - } - } - // Return the result if we have an immediate super() call on the last statement, - // but only if the constructor itself doesn't use 'this' elsewhere. - if (superCallExpression - && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { - var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 204 /* BinaryExpression */ - || superCallExpression.left.kind !== 191 /* CallExpression */) { - ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); - } - // Shift comments from the original super call to the return statement. - ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); - statements.push(returnStatement); - return 2 /* ReplaceWithReturn */; - } - // Perform the capture. - captureThisForNode(statements, ctor, superCallExpression || createActualThis()); - // If we're actually replacing the original statement, we need to signal this to the caller. - if (superCallExpression) { - return 1 /* ReplaceSuperCapture */; - } - return 0 /* NoReplacement */; - } function createActualThis() { return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); } @@ -72849,14 +72793,9 @@ var ts; return node; } } - /** - * Gets a value indicating whether we need to add default value assignments for a - * function-like node. - * - * @param node A function-like node. - */ - function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + function hasDefaultValueOrBindingPattern(node) { + return node.initializer !== undefined + || ts.isBindingPattern(node.name); } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -72866,9 +72805,10 @@ var ts; * @param node A function-like node. */ function addDefaultValueAssignmentsIfNeeded(statements, node) { - if (!shouldAddDefaultValueAssignments(node)) { - return; + if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) { + return false; } + var added = false; for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; @@ -72878,12 +72818,14 @@ var ts; continue; } if (ts.isBindingPattern(name)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added; } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + added = true; } } + return added; } /** * Adds statements to the body of a function-like node for parameters with binding patterns @@ -72893,18 +72835,20 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { - var temp = ts.getGeneratedNameForNode(parameter); + function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { // In cases where a binding pattern is simply '[]' or '{}', // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { - statements.push(ts.setEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */)); + return true; } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + return true; } + return false; } /** * Adds statements to the body of a function-like node for parameters with initializers. @@ -72914,7 +72858,7 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) @@ -72922,7 +72866,7 @@ var ts; ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); - statements.push(statement); + ts.insertStatementAfterCustomPrologue(statements, statement); } /** * Gets a value indicating whether we need to add statements to handle a rest parameter. @@ -72945,9 +72889,10 @@ var ts; * synthesized call to `super` */ function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var prologueStatements = []; var parameter = ts.lastOrUndefined(node.parameters); if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { - return; + return false; } // `declarationName` is the name of the local declaration for the parameter. var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -72957,7 +72902,7 @@ var ts; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) @@ -72976,25 +72921,30 @@ var ts; ])); ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); - statements.push(forStatement); + prologueStatements.push(forStatement); if (parameter.name.kind !== 72 /* Identifier */) { // do the actual destructuring of the rest parameter if necessary - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */)); } + ts.insertStatementsAfterCustomPrologue(statements, prologueStatements); + return true; } /** * Adds a statement to capture the `this` of a function declaration if it is needed. + * NOTE: This must be executed *after* the subtree has been visited. * * @param statements The statements for the new function body. * @param node A node. */ - function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { - captureThisForNode(statements, node, ts.createThis()); + function insertCaptureThisForNodeIfNeeded(statements, node) { + if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { + insertCaptureThisForNode(statements, node, ts.createThis()); + return true; } + return false; } - function captureThisForNode(statements, node, initializer) { + function insertCaptureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -73003,10 +72953,10 @@ var ts; ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); ts.setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + ts.insertStatementAfterCustomPrologue(statements, captureThisStatement); } - function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { - if (hierarchyFacts & 16384 /* NewTarget */) { + function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 8192 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { case 197 /* ArrowFunction */: @@ -73037,10 +72987,11 @@ var ts; ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), /*type*/ undefined, newTarget) ])); + ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); if (copyOnWrite) { - return [captureNewTargetStatement].concat(statements); + statements = statements.slice(); } - statements.unshift(captureNewTargetStatement); + ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); } return statements; } @@ -73092,7 +73043,6 @@ var ts; * @param member The MethodDeclaration node. */ function transformClassMethodDeclarationToStatement(receiver, member, container) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var commentRange = ts.getCommentRange(member); var sourceMapRange = ts.getSourceMapRange(member); var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); @@ -73107,7 +73057,6 @@ var ts; // No source map should be emitted for this statement to align with the // old emitter. ts.setEmitFlags(statement, 48 /* NoSourceMap */); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return statement; } /** @@ -73133,7 +73082,6 @@ var ts; */ function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); // To align with source maps in the old emitter, the receiver and property name // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); @@ -73169,7 +73117,6 @@ var ts; if (startsOnNewLine) { ts.startOnNewLine(call); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return call; } /** @@ -73178,12 +73125,12 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* ContainsLexicalThis */) { - enableSubstitutionsForCapturedThis(); + if (node.transformFlags & 2048 /* ContainsLexicalThis */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); var func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -73193,7 +73140,11 @@ var ts; ts.setTextRange(func, node); ts.setOriginalNode(func, node); ts.setEmitFlags(func, 8 /* CapturesThis */); - exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + if (hierarchyFacts & 16384 /* CapturedLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + // If an arrow function contains + exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return func; } @@ -73204,18 +73155,16 @@ var ts; */ function visitFunctionExpression(node) { var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ - ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionExpression(node, /*modifiers*/ undefined, node.asteriskToken, name, @@ -73230,15 +73179,13 @@ var ts; function visitFunctionDeclaration(node) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionDeclaration(node, /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, @@ -73256,14 +73203,14 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) - ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { + if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( /*modifiers*/ undefined, node.asteriskToken, name, @@ -73281,7 +73228,7 @@ var ts; var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; - var leadingStatements = []; + var prologue = []; var statements = []; var body = node.body; var statementOffset; @@ -73289,14 +73236,13 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false); } - addCaptureThisForNodeIfNeeded(leadingStatements, node); - addDefaultValueAssignmentsIfNeeded(leadingStatements, node); - addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); + multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; + multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; if (ts.isBlock(body)) { // addCustomPrologue puts already-existing directives at the beginning of the target statement-array - statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); // If the original body was a multi-line block, this must be a multi-line block. @@ -73330,14 +73276,19 @@ var ts; // source map location for the close brace. closeBraceLocation = body; } - var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); - prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false); + insertCaptureThisForNodeIfNeeded(prologue, node); // If we added any final generated statements, this must be a multi-line block - if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + if (ts.some(prologue)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + statements.unshift.apply(statements, prologue); + if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) { + // no changes were made, preserve the tree + return body; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1 /* SingleLine */); @@ -73348,11 +73299,6 @@ var ts; ts.setOriginalNode(block, node.body); return block; } - function visitFunctionBodyDownLevel(node) { - var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); - return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), - /*location*/ updated.statements)); - } function visitBlock(node, isFunctionBody) { if (isFunctionBody) { // A function body is not a block scope. @@ -73457,7 +73403,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) { if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -73470,7 +73416,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + if (node.transformFlags & 65536 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -73792,7 +73738,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -74068,7 +74014,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = ts.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0 /* None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -74173,11 +74119,11 @@ var ts; statements.push(statement); } copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment); var loopBody = ts.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -74409,13 +74355,11 @@ var ts; * @param receiver The receiver for the assignment. */ function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { ts.startOnNewLine(expression); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return expression; } function visitCatchClause(node) { @@ -74467,19 +74411,17 @@ var ts; ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); + var body = transformFunctionBody(node); if (node.kind === 158 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return updated; } @@ -74493,10 +74435,7 @@ var ts; /*location*/ node); } function visitComputedPropertyName(node) { - var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); - var updated = ts.visitEachChild(node, visitor, context); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); - return updated; + return ts.visitEachChild(node, visitor, context); } /** * Visits a YieldExpression node. @@ -74513,7 +74452,7 @@ var ts; * @param node An ArrayLiteralExpression node. */ function visitArrayLiteralExpression(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (ts.some(node.elements, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); } @@ -74528,7 +74467,10 @@ var ts; if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { return visitTypeScriptClassWrapper(node); } - if (node.transformFlags & 64 /* ES2015 */) { + var expression = ts.skipOuterExpressions(node.expression); + if (expression.kind === 98 /* SuperKeyword */ || + ts.isSuperProperty(expression) || + ts.some(node.arguments, ts.isSpreadElement)) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), @@ -74649,7 +74591,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + if (node.transformFlags & 4096 /* ContainsRestOrSpread */ || node.expression.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -74657,7 +74599,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (node.transformFlags & 4096 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -74671,7 +74613,7 @@ var ts; // _super.apply(this, a.concat([b])) // _super.m.apply(this, a.concat([b])) // _super.prototype.m.apply(this, a.concat([b])) - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); } else { // [source] @@ -74683,13 +74625,11 @@ var ts; // _super.call(this, a) // _super.m.call(this, a) // _super.prototype.m.call(this, a) - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } if (node.expression.kind === 98 /* SuperKeyword */) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); - var initializer = ts.createLogicalOr(resultingCall, actualThis); + var initializer = ts.createLogicalOr(resultingCall, createActualThis()); resultingCall = assignToCapturedThis ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) : initializer; @@ -74704,7 +74644,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (ts.some(node.arguments, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -74967,12 +74907,7 @@ var ts; } function visitMetaProperty(node) { if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { - if (hierarchyFacts & 8192 /* ComputedPropertyName */) { - hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; - } - else { - hierarchyFacts |= 16384 /* NewTarget */; - } + hierarchyFacts |= 8192 /* NewTarget */; return ts.createFileLevelUniqueName("_newTarget"); } return node; @@ -74987,7 +74922,7 @@ var ts; function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ : 65 /* FunctionIncludes */); previousOnEmitNode(hint, node, emitCallback); @@ -75535,7 +75470,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -75555,10 +75490,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 256 /* Generator */) { + else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512 /* ContainsGenerator */) { + else if (transformFlags & 256 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -75611,10 +75546,10 @@ var ts; case 230 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -75790,7 +75725,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -75817,7 +75752,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -76875,7 +76810,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -77994,7 +77929,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 16777216 /* ContainsDynamicImport */ || + node.transformFlags & 524288 /* ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } @@ -78031,7 +77966,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -78257,7 +78192,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -78331,13 +78266,13 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + else if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else { @@ -78398,7 +78333,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -79363,7 +79298,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -79529,7 +79464,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -80441,14 +80376,13 @@ var ts; * @param node The node to visit. */ function destructuringAndImportCallVisitor(node) { - if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 204 /* BinaryExpression */) { + if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -92691,22 +92625,18 @@ var ts; var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics()); - var reportSemanticDiagnostics = false; // If we didn't have any syntactic errors, then also try getting the global and // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics()); ts.addRange(diagnostics, program.getGlobalDiagnostics()); if (diagnostics.length === configFileParsingDiagnosticsLength) { - reportSemanticDiagnostics = true; + ts.addRange(diagnostics, program.getSemanticDiagnostics()); } } // Emit and report any errors we ran into. var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); - if (reportSemanticDiagnostics) { - ts.addRange(diagnostics, program.getSemanticDiagnostics()); - } ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); if (writeFileName) { var currentDir_1 = program.getCurrentDirectory(); @@ -92827,6 +92757,22 @@ var ts; } } ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; + function setCreateSourceFileAsHashVersioned(compilerHost, host) { + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + ts.setCreateSourceFileAsHashVersioned = setCreateSourceFileAsHashVersioned; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -92901,6 +92847,23 @@ var ts; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; + function readBuilderProgram(compilerOptions, readFile) { + if (compilerOptions.out || compilerOptions.outFile) + return undefined; + var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions); + if (!buildInfoPath) + return undefined; + var content = readFile(buildInfoPath); + if (!content) + return undefined; + var buildInfo = ts.getBuildInfo(content); + if (buildInfo.version !== ts.version) + return undefined; + if (!buildInfo.program) + return undefined; + return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + } + ts.readBuilderProgram = readBuilderProgram; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -92912,7 +92875,6 @@ var ts; } } ts.createWatchCompilerHost = createWatchCompilerHost; - var initialVersion = 1; function createWatchProgram(host) { var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc @@ -92953,10 +92915,12 @@ var ts; var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + var configFileWatcher; if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); + configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); } var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); // Members for CompilerHost var getNewSourceFile = compilerHost.getSourceFile; compilerHost.getSourceFile = function (fileName) { @@ -92997,21 +92961,43 @@ var ts; (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); }); synchronizeProgram(); // Update the wild card directory watch watchConfigFileWildCardDirectories(); return configFileName ? - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close }; + function close() { + resolutionCache.clear(); + ts.clearMap(sourceFilesCache, function (value) { + if (value && value.fileWatcher) { + value.fileWatcher.close(); + value.fileWatcher = undefined; + } + }); + if (configFileWatcher) { + configFileWatcher.close(); + configFileWatcher = undefined; + } + if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + watchedWildcardDirectories = undefined; + } + if (missingFilesMap) { + ts.clearMap(missingFilesMap, ts.closeFileWatcher); + missingFilesMap = undefined; + } + } function getCurrentBuilderProgram() { return builderProgram; } function getCurrentProgram() { - return builderProgram && builderProgram.getProgram(); + return builderProgram && builderProgram.getProgramOrUndefined(); } function synchronizeProgram() { writeLog("Synchronizing program"); - var program = getCurrentProgram(); + var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { @@ -93027,19 +93013,19 @@ var ts; } } else { - createNewProgram(program, hasInvalidatedResolution); + createNewProgram(hasInvalidatedResolution); } if (host.afterProgramCreate) { host.afterProgramCreate(builderProgram); } return builderProgram; } - function createNewProgram(program, hasInvalidatedResolution) { + function createNewProgram(hasInvalidatedResolution) { // Compile the program writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); - var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); @@ -93079,10 +93065,10 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function isFileMissingOnHost(hostSourceFile) { - return typeof hostSourceFile === "number"; + return typeof hostSourceFile === "boolean"; } - function isFilePresentOnHost(hostSourceFile) { - return !!hostSourceFile.sourceFile; + function isFilePresenceUnknownOnHost(hostSourceFile) { + return typeof hostSourceFile.version === "boolean"; } function fileExists(fileName) { var path = toPath(fileName); @@ -93100,36 +93086,32 @@ var ts; return undefined; } // Create new source file if requested or the versions dont match - if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) { var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { - if (shouldCreateNewSourceFile) { - hostSourceFile.version++; - } if (sourceFile) { // Set the source file and create file watcher now that file was present on the disk hostSourceFile.sourceFile = sourceFile; - sourceFile.version = hostSourceFile.version.toString(); + hostSourceFile.version = sourceFile.version; if (!hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); } } else { // There is no source file on host any more, close the watch, missing file paths will track it - if (isFilePresentOnHost(hostSourceFile)) { + if (hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher.close(); } - sourceFilesCache.set(path, hostSourceFile.version); + sourceFilesCache.set(path, false); } } else { if (sourceFile) { - sourceFile.version = initialVersion.toString(); var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); - sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher }); } else { - sourceFilesCache.set(path, initialVersion); + sourceFilesCache.set(path, false); } } return sourceFile; @@ -93141,16 +93123,16 @@ var ts; if (hostSourceFile !== undefined) { if (isFileMissingOnHost(hostSourceFile)) { // The next version, lets set it as presence unknown file - sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + sourceFilesCache.set(path, { version: false }); } else { - hostSourceFile.version++; + hostSourceFile.version = false; } } } function getSourceVersion(path) { var hostSourceFile = sourceFilesCache.get(path); - return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version; } function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); @@ -93158,7 +93140,7 @@ var ts; // remove the cached entry. // Note we arent deleting entry if file became missing in new program or // there was version update and new source file was created. - if (hostSourceFileInfo) { + if (hostSourceFileInfo !== undefined) { // record the missing file paths so they can be removed later if watchers arent tracking them if (isFileMissingOnHost(hostSourceFileInfo)) { (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); @@ -93247,7 +93229,7 @@ var ts; function onSourceFileChange(fileName, eventKind, path) { updateCachedSystemWithFile(fileName, path, eventKind); // Update the source file cache - if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); @@ -93525,19 +93507,7 @@ var ts; var readFileWithCache = function (f) { return host.readFile(f); }; var projectCompilerOptions = baseCompilerOptions; var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); - var originalGetSourceFile = compilerHost.getSourceFile; - var computeHash = host.createHash || ts.generateDjb2Hash; - compilerHost.getSourceFile = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); - if (result) { - result.version = computeHash.call(host, result.text); - } - return result; - }; + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); var buildInfoChecked = createFileMap(toPath); // Watch state var builderPrograms = createFileMap(toPath); @@ -94204,16 +94174,7 @@ var ts; var value = builderPrograms.getValue(proj); if (value) return value; - var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options); - if (!buildInfoPath) - return undefined; - var content = readFileWithCache(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); - if (buildInfo.version !== ts.version) - return undefined; - return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + return ts.readBuilderProgram(parsed.options, readFileWithCache); } function updateBundle(proj) { if (options.dry) { @@ -104631,7 +104592,7 @@ var ts; function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); - var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); + var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -118689,7 +118650,7 @@ var ts; var movedSymbols = new SymbolSet(); var oldImportsNeededByNewFile = new SymbolSet(); var newFileImportsFromOldFile = new SymbolSet(); - var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 4 /* ContainsJsx */); }); + var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); }); var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code) oldImportsNeededByNewFile.add(jsxNamespaceSymbol); @@ -118723,7 +118684,7 @@ var ts; if (ts.contains(toMove, statement)) continue; // jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile. - if (jsxNamespaceSymbol && !!(statement.transformFlags & 4 /* ContainsJsx */)) { + if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { unusedImportsFromOldFile.delete(jsxNamespaceSymbol); } forEachReference(statement, checker, function (symbol) { diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 2ac08ff8378..83354bf1d1d 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -3853,75 +3853,69 @@ var ts; TransformFlags[TransformFlags["None"] = 0] = "None"; // Facts // - Flags used to indicate that a node or subtree contains syntax that requires transformation. - TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; - TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; - TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; - TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; - TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016"; TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; - TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; - TransformFlags[TransformFlags["ContainsES2018"] = 134217728] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2019"] = 268435456] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. - TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; - TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; - TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2019"] = 268435456] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 134217728] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; - TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes"; + // Propagating flags + // - Bitmasks for flags that should propagate from a child + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -8685,10 +8679,7 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - /** - * Prepends statements to an array while taking care of prologue directives. - */ - function addStatementsAfterPrologue(to, from) { + function insertStatementsAfterPrologue(to, from, isPrologueDirective) { if (from === undefined || from.length === 0) return to; var statementIndex = 0; @@ -8701,7 +8692,44 @@ var ts; to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + function insertStatementAfterPrologue(to, statement, isPrologueDirective) { + if (statement === undefined) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice(statementIndex, 0, statement); + return to; + } + function isAnyPrologueDirective(node) { + return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementsAfterStandardPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isPrologueDirective); + } + ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue; + function insertStatementsAfterCustomPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective); + } + ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementAfterStandardPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isPrologueDirective); + } + ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue; + function insertStatementAfterCustomPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective); + } + ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue; /** * Determine if the given comment is a triple-slash * @@ -9691,6 +9719,11 @@ var ts; } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + function isSuperOrSuperProperty(node) { + return node.kind === 98 /* SuperKeyword */ + || isSuperProperty(node); + } + ts.isSuperOrSuperProperty = isSuperOrSuperProperty; /** * Determines whether a node is a property or element access expression for `super`. */ @@ -30133,44 +30166,37 @@ var ts; ts.computeTransformFlagsForNode = computeTransformFlagsForNode; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; + var callee = ts.skipOuterExpressions(node.expression); var expression = node.expression; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */ - || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; - // super property or element accesses could be inside lambdas, etc, and need a captured `this`, - // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 67108864 /* ContainsSuper */) { - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 128 /* AssertES2015 */; + if (ts.isSuperProperty(callee)) { + transformFlags |= 2048 /* ContainsLexicalThis */; } } if (expression.kind === 92 /* ImportKeyword */) { - transformFlags |= 16777216 /* ContainsDynamicImport */; - // A dynamic 'import()' call that contains a lexical 'this' will - // require a captured 'this' when emitting down-level. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; - } + transformFlags |= 524288 /* ContainsDynamicImport */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30179,19 +30205,19 @@ var ts; if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ES2018 if they contain rest - transformFlags |= 134217728 /* AssertES2018 */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. - transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { // Exponentiation is ES2016 syntax. - transformFlags |= 32 /* AssertES2016 */; + transformFlags |= 64 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30202,147 +30228,131 @@ var ts; // syntax. if (node.questionToken || node.type - || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) + || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* ParameterExcludes */; + return transformFlags & ~536870912 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. if (expressionKind === 212 /* AsExpression */ || expressionKind === 194 /* TypeAssertionExpression */) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the expression of a ParenthesizedExpression is a destructuring assignment, - // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 1024 /* DestructuringAssignment */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* OuterExpressionExcludes */; + return transformFlags & ~536870912 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; if (ts.hasModifier(node, 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES2015 */; + transformFlags = subtreeFlags | 128 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, computed property name, or decorator is // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) + if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ + if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { case 86 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 109 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; default: ts.Debug.fail("Unexpected token for heritage clause"); break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; if (!node.variableDeclaration) { - transformFlags |= 268435456 /* AssertES2019 */; + transformFlags |= 8 /* AssertES2019 */; } else if (ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637797697 /* CatchClauseExcludes */; + return transformFlags & ~536879104 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; // TypeScript-specific modifiers and overloads are TypeScript syntax if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* ConstructorExcludes */; + return transformFlags & ~537372672 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and // overloads are TypeScript syntax. if (node.decorators @@ -30351,21 +30361,21 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // An async method declaration is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30376,25 +30386,25 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. - var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + var transformFlags = subtreeFlags | 1 /* AssertTypeScript */; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */); } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -30403,30 +30413,24 @@ var ts; if (!body || (modifierFlags & 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. // A FunctionDeclaration without a body is an overload and is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function declaration is ES2017 syntax. if (modifierFlags & 256 /* Async */) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If a FunctionDeclaration's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionDeclaration is generator function and is the body of a // transformed async function, then this node can be transformed to a @@ -30434,11 +30438,11 @@ var ts; // Currently we do not support transforming any other generator functions // down level. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30447,181 +30451,161 @@ var ts; if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function expression is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } // function expressions with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If a FunctionExpression's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionExpression is generator function and is the body of a // transformed async function, then this node can be transformed to a // down-level generator. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async arrow function is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= 16 /* AssertES2017 */; + transformFlags |= 32 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653604161 /* ArrowFunctionExcludes */; + return transformFlags & ~537371648 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 33554432 /* Super */) { - transformFlags ^= 33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). // same for super inside of an async generator, which is ES2018. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 134217728 /* ContainsES2018 */; + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 33554432 /* Super */) { - transformFlags &= ~33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). // same for super inside of an async generator, which is ES2018. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 134217728 /* ContainsES2018 */; + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally? // A VariableDeclaration containing ObjectRest is ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // Type annotations are TypeScript syntax. if (node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; var declarationListTransformFlags = node.declarationList.transformFlags; // An ambient declaration is TypeScript syntax. if (ts.hasModifier(node, 2 /* Ambient */)) { - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; // An ImportEqualsDeclaration with a namespace reference is TypeScript. if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - // If the expression of an expression statement is a destructuring assignment, - // then we treat the statement as ES6 so that we can indicate that we do not - // need to hold on to the right-hand side. - if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES2015 */; - } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3 /* AssertTypeScript */; + var transformFlags = 1 /* AssertTypeScript */; var modifierFlags = ts.getModifierFlags(node); if ((modifierFlags & 2 /* Ambient */) === 0) { transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~647001409 /* ModuleExcludes */; + return transformFlags & ~537168896 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; + transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; + return transformFlags & ~536944640 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 637535553 /* NodeExcludes */; + var excludeFlags = 536870912 /* NodeExcludes */; switch (kind) { case 121 /* AsyncKeyword */: case 201 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators) - transformFlags |= 134217728 /* AssertES2018 */ | 16 /* AssertES2017 */; + transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */; break; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: case 313 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; + transformFlags |= 1 /* AssertTypeScript */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; break; case 115 /* PublicKeyword */: case 113 /* PrivateKeyword */: @@ -30634,7 +30618,7 @@ var ts; case 213 /* NonNullExpression */: case 133 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; case 260 /* JsxElement */: case 261 /* JsxSelfClosingElement */: @@ -30649,7 +30633,7 @@ var ts; case 269 /* JsxSpreadAttribute */: case 270 /* JsxExpression */: // These nodes are Jsx syntax. - transformFlags |= 4 /* AssertJsx */; + transformFlags |= 2 /* AssertJsx */; break; case 14 /* NoSubstitutionTemplateLiteral */: case 15 /* TemplateHead */: @@ -30661,32 +30645,32 @@ var ts; case 116 /* StaticKeyword */: case 214 /* MetaProperty */: // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 10 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 8 /* NumericLiteral */: if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 9 /* BigIntLiteral */: - transformFlags |= 8 /* AssertESNext */; + transformFlags |= 4 /* AssertESNext */; break; case 227 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { - transformFlags |= 134217728 /* AssertES2018 */; + transformFlags |= 16 /* AssertES2018 */; } - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 207 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 134217728 /* AssertES2018 */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */; break; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: @@ -30727,115 +30711,93 @@ var ts; case 182 /* LiteralType */: case 247 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. - transformFlags = 3 /* AssertTypeScript */; - excludeFlags = -3 /* TypeExcludes */; + transformFlags = 1 /* AssertTypeScript */; + excludeFlags = -2 /* TypeExcludes */; break; case 149 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 524288 /* ContainsComputedPropertyName */; - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - // A computed method name like `[this.getName()](x: string) { ... }` needs to - // distinguish itself from the normal case of a method body containing `this`: - // `this` inside a method doesn't need to be rewritten (the method provides `this`), - // whereas `this` inside a computed name *might* need to be rewritten if the class/object - // is inside an arrow function: - // `_this = this; () => class K { [_this.getName()]() { ... } }` - // To make this distinction, use ContainsLexicalThisInComputedPropertyName - // instead of ContainsLexicalThis for computed property names - transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; - } + transformFlags |= 16384 /* ContainsComputedPropertyName */; break; case 208 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */; break; case 277 /* SpreadAssignment */: - transformFlags |= 134217728 /* AssertES2018 */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; break; case 98 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + transformFlags |= 128 /* AssertES2015 */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 100 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 2048 /* ContainsLexicalThis */; break; case 184 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; } - excludeFlags = 637666625 /* BindingPatternExcludes */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 185 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - excludeFlags = 637666625 /* BindingPatternExcludes */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 186 /* BindingElement */: - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 131072 /* ContainsRestOrSpread */; + transformFlags |= 4096 /* ContainsRestOrSpread */; } break; case 152 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; break; case 188 /* ObjectLiteralExpression */: - excludeFlags = 638358849 /* ObjectLiteralExcludes */; - if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + excludeFlags = 536896512 /* ObjectLiteralExcludes */; + if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; - } - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES2018 node. - transformFlags |= 134217728 /* AssertES2018 */; + transformFlags |= 16 /* AssertES2018 */; } break; case 187 /* ArrayLiteralExpression */: - case 192 /* NewExpression */: - excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - // If the this node contains a SpreadExpression, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } + excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */; break; case 223 /* DoStatement */: case 224 /* WhileStatement */: case 225 /* ForStatement */: case 226 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) { + transformFlags |= 128 /* AssertES2015 */; } break; case 284 /* SourceFile */: - if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES2015 */; - } break; case 230 /* ReturnStatement */: // Return statements may require an `await` in ES2018. - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 134217728 /* AssertES2018 */; + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */; break; case 228 /* ContinueStatement */: case 229 /* BreakStatement */: - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~excludeFlags; } + function propagatePropertyNameFlags(node, transformFlags) { + return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */); + } /** * Gets the transform flags to exclude when unioning the transform flags of a subtree. * @@ -30845,33 +30807,33 @@ var ts; */ function getTransformFlagsSubtreeExclusions(kind) { if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; } switch (kind) { case 191 /* CallExpression */: case 192 /* NewExpression */: case 187 /* ArrayLiteralExpression */: - return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return 536875008 /* ArrayLiteralOrCallOrNewExcludes */; case 244 /* ModuleDeclaration */: - return 647001409 /* ModuleExcludes */; + return 537168896 /* ModuleExcludes */; case 151 /* Parameter */: - return 637535553 /* ParameterExcludes */; + return 536870912 /* ParameterExcludes */; case 197 /* ArrowFunction */: - return 653604161 /* ArrowFunctionExcludes */; + return 537371648 /* ArrowFunctionExcludes */; case 196 /* FunctionExpression */: case 239 /* FunctionDeclaration */: - return 653620545 /* FunctionExcludes */; + return 537373696 /* FunctionExcludes */; case 238 /* VariableDeclarationList */: - return 639894849 /* VariableDeclarationListExcludes */; + return 536944640 /* VariableDeclarationListExcludes */; case 240 /* ClassDeclaration */: case 209 /* ClassExpression */: - return 638121281 /* ClassExcludes */; + return 536888320 /* ClassExcludes */; case 157 /* Constructor */: - return 653616449 /* ConstructorExcludes */; + return 537372672 /* ConstructorExcludes */; case 156 /* MethodDeclaration */: case 158 /* GetAccessor */: case 159 /* SetAccessor */: - return 653616449 /* MethodOrAccessorExcludes */; + return 537372672 /* MethodOrAccessorExcludes */; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: case 146 /* BigIntKeyword */: @@ -30889,25 +30851,25 @@ var ts; case 162 /* IndexSignature */: case 241 /* InterfaceDeclaration */: case 242 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; case 188 /* ObjectLiteralExpression */: - return 638358849 /* ObjectLiteralExcludes */; + return 536896512 /* ObjectLiteralExcludes */; case 274 /* CatchClause */: - return 637797697 /* CatchClauseExcludes */; + return 536879104 /* CatchClauseExcludes */; case 184 /* ObjectBindingPattern */: case 185 /* ArrayBindingPattern */: - return 637666625 /* BindingPatternExcludes */; + return 536875008 /* BindingPatternExcludes */; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: case 313 /* PartiallyEmittedExpression */: case 195 /* ParenthesizedExpression */: case 98 /* SuperKeyword */: - return 536872257 /* OuterExpressionExcludes */; + return 536870912 /* OuterExpressionExcludes */; case 189 /* PropertyAccessExpression */: case 190 /* ElementAccessExpression */: - return 570426689 /* PropertyAccessExcludes */; + return 536870912 /* PropertyAccessExcludes */; default: - return 637535553 /* NodeExcludes */; + return 536870912 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -31452,6 +31414,7 @@ var ts; var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); + var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -37980,15 +37943,24 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } + function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { + var rootTrueType = root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + return instantiateType(rootTrueConstraint, combinedMapper || mapper); + } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { - var rootTrueType = type.root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) - ? rootTrueType - : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + // An `any` branch of a conditional type would normally be viral - specifically, without special handling here, + // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to + // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type, + // in effect treating `any` like `never` rather than `unknown` in this location. + var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); + var falseConstraint = getFalseTypeFromConditionalType(type); + type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; } @@ -37998,7 +37970,13 @@ var ts; // with its constraint. We do this because if the constraint is a union type it will be distributed // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. - if (type.root.isDistributive) { + // We skip returning a distributive constraint for a restrictive instantiation of a conditional type + // as the constraint for all type params (check type included) have been replace with `unknown`, which + // is going to produce even more false positive/negative results than the distribute constraint already does. + // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter + // a union - once negated types exist and are applied to the conditional false branch, this "constraint" + // likely doesn't need to exist. + if (type.root.isDistributive && type.restrictiveInstantiation !== type) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint && constraint !== type.checkType) { @@ -40391,12 +40369,47 @@ var ts; function getActualTypeVariable(type) { return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; } + /** + * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent + */ + function isIntersectionEmpty(type1, type2) { + return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */); + } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); var extendsType = instantiateType(root.extendsType, mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } + var trueType = instantiateType(root.trueType, mapper); + var falseType = instantiateType(root.falseType, mapper); + var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; + } + var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); + conditionalTypes.set(instantiationId, newResult); + return newResult; + } + function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) { + // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`. + if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { + if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return getDefaultConstraintOfTrueBranchOfConditionalType(root, /*combinedMapper*/ undefined, mapper); + } + else if (isIntersectionEmpty(checkType, extendsType)) { // Always false + return neverType; + } + } + else if (trueType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(falseType), getActualTypeVariable(checkType))) { + if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return neverType; + } + else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false + return falseType; // TODO: Intersect negated `extends` type here + } + } var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); var combinedMapper; if (root.inferTypeParameters) { @@ -40414,18 +40427,18 @@ var ts; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) { if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { - return instantiateType(root.trueType, mapper); + return trueType; } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { - return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]); } // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { - return instantiateType(root.falseType, mapper); + return falseType; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -40444,6 +40457,10 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; + if (!combinedMapper) { + result.resolvedTrueType = trueType; + result.resolvedFalseType = falseType; + } result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; @@ -41348,8 +41365,20 @@ var ts; type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); } function getRestrictiveInstantiation(type) { - return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : - type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); + if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) { + return type; + } + if (type.restrictiveInstantiation) { + return type.restrictiveInstantiation; + } + type.restrictiveInstantiation = instantiateType(type, restrictiveMapper); + // We set the following so we don't attempt to set the restrictive instance of a restrictive instance + // which is redundant - we'll produce new type identities, but all type params have already been mapped. + // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint" + // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters + // are constrained to `unknown` and produce tons of false positives/negatives! + type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation; + return type.restrictiveInstantiation; } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -42894,16 +42923,26 @@ var ts; template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } - // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. - if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - return result; + if (!isGenericMappedType(source)) { + var targetConstraint = getConstraintTypeFromMappedType(target); + var sourceKeys_1 = getIndexType(source); + var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */; + var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined; + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X. + if (hasOptionalUnionKeys + ? !(filteredByApplicability.flags & 131072 /* Never */) + : isRelatedTo(targetConstraint, sourceKeys_1)) { + var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target); + var indexedAccessType = getIndexedAccessType(source, indexingType); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } - originalErrorInfo = errorInfo; - errorInfo = saveErrorInfo; } } if (source.flags & 8650752 /* TypeVariable */) { @@ -44579,6 +44618,7 @@ var ts; if (inference.priority === undefined || priority < inference.priority) { inference.candidates = undefined; inference.contraCandidates = undefined; + inference.topLevel = true; inference.priority = priority; } if (priority === inference.priority) { @@ -65600,8 +65640,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) - : ts.addStatementsAfterPrologue(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) + : ts.insertStatementsAfterStandardPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -66875,8 +66915,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -66942,7 +66982,7 @@ var ts; if (flattenContext.level >= 1 /* 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 & 262144 /* ContainsObjectRestOrSpread */) { + if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -67270,14 +67310,9 @@ var ts; * @param node The node to visit. */ function visitorWorker(node) { - if (node.transformFlags & 1 /* TypeScript */) { - // This node is explicitly marked as TypeScript, so we should transform the node. + if (node.transformFlags & 1 /* ContainsTypeScript */) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -67311,7 +67346,7 @@ var ts; // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, // and will trigger debug failures when debug verbosity is turned up - if (node.transformFlags & 2 /* ContainsTypeScript */) { + if (node.transformFlags & 1 /* ContainsTypeScript */) { // This node contains TypeScript, so we should visit its children. return ts.visitEachChild(node, visitor, context); } @@ -67353,15 +67388,9 @@ var ts; // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } - else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { - // This node is explicitly marked as TypeScript, or is exported at the namespace - // level, so we should transform the node. + else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -67412,7 +67441,7 @@ var ts; * @param node The node to visit. */ function visitTypeScript(node) { - if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) { // TypeScript ambient declarations are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); @@ -67479,7 +67508,7 @@ var ts; // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); case 240 /* ClassDeclaration */: - // This is a class declaration with TypeScript syntax extensions. + // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -67490,7 +67519,7 @@ var ts; // - method overload signatures return visitClassDeclaration(node); case 209 /* ClassExpression */: - // This is a class expression with TypeScript syntax extensions. + // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -67501,7 +67530,7 @@ var ts; // - method overload signatures return visitClassExpression(node); case 273 /* HeritageClause */: - // This is a heritage clause with TypeScript syntax extensions. + // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause @@ -67529,7 +67558,7 @@ var ts; // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); case 151 /* Parameter */: - // This is a parameter declaration with TypeScript syntax extensions. + // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: // - decorators @@ -67570,7 +67599,8 @@ var ts; // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: - return ts.Debug.failBadSyntaxKind(node); + // node contains some other TypeScript syntax + return ts.visitEachChild(node, visitor, context); } } function visitSourceFile(node) { @@ -67619,18 +67649,19 @@ var ts; facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; return facts; } - /** - * Transforms a class declaration with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has decorators. - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - The class is an export in a TypeScript namespace. - * - * @param node The node to transform. - */ + function hasTypeScriptClassSyntax(node) { + return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */); + } + function isClassLikeDeclarationWithTypeScriptSyntax(node) { + return ts.some(node.decorators) + || ts.some(node.typeParameters) + || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) + || ts.some(node.members, hasTypeScriptClassSyntax); + } function visitClassDeclaration(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -67683,7 +67714,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -67860,16 +67891,10 @@ var ts; ts.setCommentRange(statement, node); return statement; } - /** - * Transforms a class expression with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - * @param node The node to transform. - */ function visitClassExpression(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -67933,7 +67958,7 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); var hasParameterPropertyAssignments = constructor && - constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. @@ -68978,11 +69003,11 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 86 /* ExtendsKeyword */) { - var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); + if (node.token === 109 /* ImplementsKeyword */) { + // implements clauses are elided + return undefined; } - return undefined; + return ts.visitEachChild(node, visitor, context); } /** * Transforms an ExpressionWithTypeArguments with TypeScript syntax. @@ -69018,16 +69043,6 @@ var ts; } return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); } - /** - * Visits a method declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is marked as abstract, public, private, protected, or readonly - * - The node has a computed property name - * - * @param node The method node. - */ function visitMethodDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; @@ -69054,15 +69069,6 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); } - /** - * Visits a get accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The get accessor node. - */ function visitGetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -69078,15 +69084,6 @@ var ts; } return updated; } - /** - * Visits a set accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The set accessor node. - */ function visitSetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -69101,16 +69098,6 @@ var ts; } return updated; } - /** - * Visits a function declaration. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is exported from a TypeScript namespace - * - The node has decorators - * - * @param node The function node. - */ function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); @@ -69126,14 +69113,6 @@ var ts; } return updated; } - /** - * Visits a function expression node. - * - * This function will be called when one of the following conditions are met: - * - The node has type annotations - * - * @param node The function expression node. - */ function visitFunctionExpression(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createOmittedExpression(); @@ -69143,51 +69122,31 @@ var ts; /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); return updated; } - /** - * @remarks - * This function will be called when one of the following conditions are met: - * - The node has type annotations - */ function visitArrowFunction(node) { var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } - /** - * Visits a parameter declaration node. - * - * This function will be called when one of the following conditions are met: - * - The node has an accessibility modifier. - * - The node has a questionToken. - * - The node's kind is ThisKeyword. - * - * @param node The parameter declaration node. - */ function visitParameter(node) { if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameter( + var updated = ts.updateParameter(node, /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setOriginalNode(parameter, node); - ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); - ts.setCommentRange(parameter, node); - ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); - return parameter; + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */); + } + return updated; } - /** - * Visits a variable statement in a namespace. - * - * This function will be called when one of the following conditions are met: - * - The node is exported from a TypeScript namespace. - */ function visitVariableStatement(node) { if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); @@ -69216,12 +69175,6 @@ var ts; return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } - /** - * Visits a parenthesized expression that contains either a type assertion or an `as` - * expression. - * - * @param node The parenthesized expression node. - */ function visitParenthesizedExpression(node) { var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); if (ts.isAssertionExpression(innerExpression)) { @@ -69358,7 +69311,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -69605,7 +69558,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -70160,7 +70113,7 @@ var ts; return visited; } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { @@ -70437,7 +70390,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.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. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); @@ -70445,7 +70398,7 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -70739,7 +70692,7 @@ var ts; return node; } function visitorWorker(node, noDestructuringValue) { - if ((node.transformFlags & 134217728 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { @@ -70857,7 +70810,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -70883,7 +70836,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 27 /* CommaToken */) { @@ -70898,7 +70851,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -70915,7 +70868,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -71012,7 +70965,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -71125,10 +71078,10 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } statements.push(returnStatement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { @@ -71154,7 +71107,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.insertStatementsAfterStandardPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -71163,7 +71116,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -71371,7 +71324,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 268435456 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { @@ -71402,7 +71355,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { return node; } switch (node.kind) { @@ -71435,7 +71388,7 @@ var ts; return visited; } function visitor(node) { - if (node.transformFlags & 4 /* ContainsJsx */) { + if (node.transformFlags & 2 /* ContainsJsx */) { return visitorWorker(node); } else { @@ -71937,7 +71890,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { @@ -72017,30 +71970,6 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); - var SuperCaptureResult; - (function (SuperCaptureResult) { - /** - * A capture may have been added for calls to 'super', but - * the caller should emit subsequent statements normally. - */ - SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * var _this = _super.call(...) || this; - * - * Callers should skip the current statement. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * return _super.call(...) || this; - * - * Callers should skip the current statement and avoid any returns of '_this'. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; - })(SuperCaptureResult || (SuperCaptureResult = {})); // Facts we track as we traverse the tree var HierarchyFacts; (function (HierarchyFacts) { @@ -72061,12 +71990,12 @@ var ts; HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; - HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below. // // Ancestor masks // - HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask"; // We are always in *some* kind of block scope, but only specific block-scope containers are // top-level or Blocks. HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; @@ -72076,16 +72005,16 @@ var ts; HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; // Functions, methods, and accessors are both new lexical scopes and new block scopes. HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; - HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes"; HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes"; // Arrow functions are lexically scoped to their container, but are new block scopes. HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; - HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes"; // Constructors are both new lexical scopes and new block scopes. Constructors are also // always considered non-static members of a class. HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; - HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes"; // 'do' and 'while' statements are not block scopes. We track that the subtree is contained // within an IterationStatement to indicate whether the embedded statement is an // IterationStatementBlock. @@ -72103,19 +72032,17 @@ var ts; HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; - // Computed property names track subtree flags differently than their containing members. - HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; - HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; // // Subtree facts // - HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; - HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget"; + HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis"; // // Subtree masks // - HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; - HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes"; + HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes"; })(HierarchyFacts || (HierarchyFacts = {})); function transformES2015(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; @@ -72164,7 +72091,7 @@ var ts; */ function enterSubtree(excludeFacts, includeFacts) { var ancestorFacts = hierarchyFacts; - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */; return ancestorFacts; } /** @@ -72175,7 +72102,7 @@ var ts; * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. */ function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 @@ -72197,12 +72124,6 @@ var ts; return node; } } - function functionBodyVisitor(node) { - if (shouldVisitNode(node)) { - return visitBlock(node, /*isFunctionBody*/ true); - } - return node; - } function callExpressionVisitor(node) { if (node.kind === 98 /* SuperKeyword */) { return visitSuperKeyword(/*isExpressionOfCall*/ true); @@ -72309,18 +72230,19 @@ var ts; } function visitSourceFile(node) { var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + var prologue = []; var statements = []; startLexicalEnvironment(); - var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); - addCaptureThisForNodeIfNeeded(statements, node); - statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureThisForNodeIfNeeded(prologue, node); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements)); } function visitSwitchStatement(node) { if (convertedLoopState !== undefined) { @@ -72360,6 +72282,9 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitThisKeyword(node) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; + } if (convertedLoopState) { if (hierarchyFacts & 2 /* ArrowFunction */) { // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. @@ -72573,7 +72498,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -72601,7 +72526,7 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = ts.createFunctionDeclaration( @@ -72615,7 +72540,7 @@ var ts; ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); } statements.push(constructorFunction); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; } /** @@ -72634,6 +72559,24 @@ var ts; return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } + function createDefaultConstructorBody(node, isDerivedClass) { + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + var statements = []; + resumeLexicalEnvironment(); + ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + if (isDerivedClass) { + // return _super !== null && _super.apply(this, arguments) || this; + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + } + var statementsArray = ts.createNodeArray(statements); + ts.setTextRange(statementsArray, node.members); + var block = ts.createBlock(statementsArray, /*multiLine*/ true); + ts.setTextRange(block, node); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } /** * Transforms the body of a constructor declaration of a class. * @@ -72644,59 +72587,137 @@ var ts; * synthesized `super` call. */ function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { - var statements = []; - resumeLexicalEnvironment(); - var statementOffset = -1; - if (hasSynthesizedSuper) { - // If a super call has already been synthesized, - // we're going to assume that we should just transform everything after that. - // The assumption is that no prior step in the pipeline has added any prologue directives. - statementOffset = 0; - } - else if (constructor) { - statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); - } - if (constructor) { - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); - if (!hasSynthesizedSuper) { - // If no super call has been synthesized, emit custom prologue directives. - statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); - } - ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); - } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; - var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); - // The last statement expression was replaced. Skip it. - if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { - statementOffset++; + // When the subclass does not have a constructor, we synthesize a *default* constructor using the following + // representation: + // + // ``` + // // es2015 (source) + // class C extends Base { } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.apply(this, arguments) || this; + // } + // return C; + // })(Base); + // ``` + if (!constructor) + return createDefaultConstructorBody(node, isDerivedClass); + // The prologue will contain all leading standard and custom prologue statements added by this transform + var prologue = []; + var statements = []; + resumeLexicalEnvironment(); + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + var statementOffset = 0; + if (!hasSynthesizedSuper) + statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + // If the first statement is a call to `super()`, visit the statement directly + var superCallExpression; + if (hasSynthesizedSuper) { + superCallExpression = createDefaultSuperCallOrThis(); } - if (constructor) { - if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { - hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + else if (isDerivedClass && statementOffset < constructor.body.statements.length) { + var firstStatement = constructor.body.statements[statementOffset]; + if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); } - // Return `_this` unless we're sure enough that it would be pointless to add a return statement. - // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. - if (isDerivedClass - && superCaptureStatus !== 2 /* ReplaceWithReturn */ - && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { - statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + if (superCallExpression) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + statementOffset++; // skip this statement, we will add it after visiting the rest of the body. } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - if (constructor) { - prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); + // visit the remaining statements + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); + if (isDerivedClass) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) { + // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the + // following representation: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.call(this, "foo") || this; + // } + // return C; + // })(Base); + // ``` + var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); + var returnStatement = ts.createReturn(superCallExpression); + ts.setCommentRange(returnStatement, ts.getCommentRange(superCall)); + ts.setEmitFlags(superCall, 1536 /* NoComments */); + statements.push(returnStatement); + } + else { + // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // this.x = 1; + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // var _this = _super.call(this, "foo") || this; + // _this.x = 1; + // return _this; + // } + // return C; + // })(Base); + // ``` + // Since the `super()` call was the first statement, we insert the `this` capturing call to + // `super()` at the top of the list of `statements` (after any pre-existing custom prologues). + insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); + if (!isSufficientlyCoveredByReturnStatements(constructor.body)) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } + } } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), - /*location*/ constructor ? constructor.body.statements : node.members), + else { + // If a class is not derived from a base class or does not have a call to `super()`, `this` is only + // captured when necessitated by an arrow function capturing the lexical `this`: + // + // ``` + // // es2015 + // class C {} + // + // // es5 + // var C = (function () { + // function C() { + // } + // return C; + // })(); + // ``` + insertCaptureThisForNodeIfNeeded(prologue, constructor); + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), + /*location*/ constructor.body.statements), /*multiLine*/ true); - ts.setTextRange(block, constructor ? constructor.body : node); - if (!constructor) { - ts.setEmitFlags(block, 1536 /* NoComments */); - } + ts.setTextRange(block, constructor.body); return block; } /** @@ -72726,83 +72747,6 @@ var ts; } return false; } - /** - * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. - * - * @returns The new statement offset into the `statements` array. - */ - function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { - // If this isn't a derived class, just capture 'this' for arrow functions if necessary. - if (!isDerivedClass) { - if (ctor) { - addCaptureThisForNodeIfNeeded(statements, ctor); - } - return 0 /* NoReplacement */; - } - // We must be here because the user didn't write a constructor - // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. - // If that's the case we can just immediately return the result of a 'super()' call. - if (!ctor) { - statements.push(ts.createReturn(createDefaultSuperCallOrThis())); - return 2 /* ReplaceWithReturn */; - } - // The constructor exists, but it and the 'super()' call it contains were generated - // for something like property initializers. - // Create a captured '_this' variable and assume it will subsequently be used. - if (hasSynthesizedSuper) { - captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); - enableSubstitutionsForCapturedThis(); - return 1 /* ReplaceSuperCapture */; - } - // Most of the time, a 'super' call will be the first real statement in a constructor body. - // In these cases, we'd like to transform these into a *single* statement instead of a declaration - // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, - // we'd get: - // - // var _this; - // _this = _super.call(...) || this; - // - // instead of - // - // var _this = _super.call(...) || this; - // - // Additionally, if the 'super()' call is the last statement, we should just avoid capturing - // entirely and immediately return the result like so: - // - // return _super.call(...) || this; - // - var firstStatement; - var superCallExpression; - var ctorStatements = ctor.body.statements; - if (statementOffset < ctorStatements.length) { - firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { - superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); - } - } - // Return the result if we have an immediate super() call on the last statement, - // but only if the constructor itself doesn't use 'this' elsewhere. - if (superCallExpression - && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { - var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 204 /* BinaryExpression */ - || superCallExpression.left.kind !== 191 /* CallExpression */) { - ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); - } - // Shift comments from the original super call to the return statement. - ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); - statements.push(returnStatement); - return 2 /* ReplaceWithReturn */; - } - // Perform the capture. - captureThisForNode(statements, ctor, superCallExpression || createActualThis()); - // If we're actually replacing the original statement, we need to signal this to the caller. - if (superCallExpression) { - return 1 /* ReplaceSuperCapture */; - } - return 0 /* NoReplacement */; - } function createActualThis() { return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); } @@ -72848,14 +72792,9 @@ var ts; return node; } } - /** - * Gets a value indicating whether we need to add default value assignments for a - * function-like node. - * - * @param node A function-like node. - */ - function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + function hasDefaultValueOrBindingPattern(node) { + return node.initializer !== undefined + || ts.isBindingPattern(node.name); } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -72865,9 +72804,10 @@ var ts; * @param node A function-like node. */ function addDefaultValueAssignmentsIfNeeded(statements, node) { - if (!shouldAddDefaultValueAssignments(node)) { - return; + if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) { + return false; } + var added = false; for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; @@ -72877,12 +72817,14 @@ var ts; continue; } if (ts.isBindingPattern(name)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added; } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + added = true; } } + return added; } /** * Adds statements to the body of a function-like node for parameters with binding patterns @@ -72892,18 +72834,20 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { - var temp = ts.getGeneratedNameForNode(parameter); + function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { // In cases where a binding pattern is simply '[]' or '{}', // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { - statements.push(ts.setEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */)); + return true; } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + return true; } + return false; } /** * Adds statements to the body of a function-like node for parameters with initializers. @@ -72913,7 +72857,7 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) @@ -72921,7 +72865,7 @@ var ts; ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); - statements.push(statement); + ts.insertStatementAfterCustomPrologue(statements, statement); } /** * Gets a value indicating whether we need to add statements to handle a rest parameter. @@ -72944,9 +72888,10 @@ var ts; * synthesized call to `super` */ function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var prologueStatements = []; var parameter = ts.lastOrUndefined(node.parameters); if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { - return; + return false; } // `declarationName` is the name of the local declaration for the parameter. var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -72956,7 +72901,7 @@ var ts; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) @@ -72975,25 +72920,30 @@ var ts; ])); ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); - statements.push(forStatement); + prologueStatements.push(forStatement); if (parameter.name.kind !== 72 /* Identifier */) { // do the actual destructuring of the rest parameter if necessary - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */)); } + ts.insertStatementsAfterCustomPrologue(statements, prologueStatements); + return true; } /** * Adds a statement to capture the `this` of a function declaration if it is needed. + * NOTE: This must be executed *after* the subtree has been visited. * * @param statements The statements for the new function body. * @param node A node. */ - function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { - captureThisForNode(statements, node, ts.createThis()); + function insertCaptureThisForNodeIfNeeded(statements, node) { + if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { + insertCaptureThisForNode(statements, node, ts.createThis()); + return true; } + return false; } - function captureThisForNode(statements, node, initializer) { + function insertCaptureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -73002,10 +72952,10 @@ var ts; ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); ts.setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + ts.insertStatementAfterCustomPrologue(statements, captureThisStatement); } - function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { - if (hierarchyFacts & 16384 /* NewTarget */) { + function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 8192 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { case 197 /* ArrowFunction */: @@ -73036,10 +72986,11 @@ var ts; ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), /*type*/ undefined, newTarget) ])); + ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); if (copyOnWrite) { - return [captureNewTargetStatement].concat(statements); + statements = statements.slice(); } - statements.unshift(captureNewTargetStatement); + ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); } return statements; } @@ -73091,7 +73042,6 @@ var ts; * @param member The MethodDeclaration node. */ function transformClassMethodDeclarationToStatement(receiver, member, container) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var commentRange = ts.getCommentRange(member); var sourceMapRange = ts.getSourceMapRange(member); var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); @@ -73106,7 +73056,6 @@ var ts; // No source map should be emitted for this statement to align with the // old emitter. ts.setEmitFlags(statement, 48 /* NoSourceMap */); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return statement; } /** @@ -73132,7 +73081,6 @@ var ts; */ function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); // To align with source maps in the old emitter, the receiver and property name // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); @@ -73168,7 +73116,6 @@ var ts; if (startsOnNewLine) { ts.startOnNewLine(call); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return call; } /** @@ -73177,12 +73124,12 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* ContainsLexicalThis */) { - enableSubstitutionsForCapturedThis(); + if (node.transformFlags & 2048 /* ContainsLexicalThis */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); var func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -73192,7 +73139,11 @@ var ts; ts.setTextRange(func, node); ts.setOriginalNode(func, node); ts.setEmitFlags(func, 8 /* CapturesThis */); - exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + if (hierarchyFacts & 16384 /* CapturedLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + // If an arrow function contains + exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return func; } @@ -73203,18 +73154,16 @@ var ts; */ function visitFunctionExpression(node) { var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ - ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionExpression(node, /*modifiers*/ undefined, node.asteriskToken, name, @@ -73229,15 +73178,13 @@ var ts; function visitFunctionDeclaration(node) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionDeclaration(node, /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, @@ -73255,14 +73202,14 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) - ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { + if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( /*modifiers*/ undefined, node.asteriskToken, name, @@ -73280,7 +73227,7 @@ var ts; var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; - var leadingStatements = []; + var prologue = []; var statements = []; var body = node.body; var statementOffset; @@ -73288,14 +73235,13 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false); } - addCaptureThisForNodeIfNeeded(leadingStatements, node); - addDefaultValueAssignmentsIfNeeded(leadingStatements, node); - addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); + multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; + multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; if (ts.isBlock(body)) { // addCustomPrologue puts already-existing directives at the beginning of the target statement-array - statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); // If the original body was a multi-line block, this must be a multi-line block. @@ -73329,14 +73275,19 @@ var ts; // source map location for the close brace. closeBraceLocation = body; } - var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); - prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false); + insertCaptureThisForNodeIfNeeded(prologue, node); // If we added any final generated statements, this must be a multi-line block - if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + if (ts.some(prologue)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + statements.unshift.apply(statements, prologue); + if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) { + // no changes were made, preserve the tree + return body; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1 /* SingleLine */); @@ -73347,11 +73298,6 @@ var ts; ts.setOriginalNode(block, node.body); return block; } - function visitFunctionBodyDownLevel(node) { - var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); - return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), - /*location*/ updated.statements)); - } function visitBlock(node, isFunctionBody) { if (isFunctionBody) { // A function body is not a block scope. @@ -73456,7 +73402,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) { if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -73469,7 +73415,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + if (node.transformFlags & 65536 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -73791,7 +73737,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -74067,7 +74013,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = ts.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0 /* None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -74172,11 +74118,11 @@ var ts; statements.push(statement); } copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment); var loopBody = ts.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -74408,13 +74354,11 @@ var ts; * @param receiver The receiver for the assignment. */ function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { ts.startOnNewLine(expression); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return expression; } function visitCatchClause(node) { @@ -74466,19 +74410,17 @@ var ts; ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); + var body = transformFunctionBody(node); if (node.kind === 158 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return updated; } @@ -74492,10 +74434,7 @@ var ts; /*location*/ node); } function visitComputedPropertyName(node) { - var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); - var updated = ts.visitEachChild(node, visitor, context); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); - return updated; + return ts.visitEachChild(node, visitor, context); } /** * Visits a YieldExpression node. @@ -74512,7 +74451,7 @@ var ts; * @param node An ArrayLiteralExpression node. */ function visitArrayLiteralExpression(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (ts.some(node.elements, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); } @@ -74527,7 +74466,10 @@ var ts; if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { return visitTypeScriptClassWrapper(node); } - if (node.transformFlags & 64 /* ES2015 */) { + var expression = ts.skipOuterExpressions(node.expression); + if (expression.kind === 98 /* SuperKeyword */ || + ts.isSuperProperty(expression) || + ts.some(node.arguments, ts.isSpreadElement)) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), @@ -74648,7 +74590,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + if (node.transformFlags & 4096 /* ContainsRestOrSpread */ || node.expression.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -74656,7 +74598,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (node.transformFlags & 4096 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -74670,7 +74612,7 @@ var ts; // _super.apply(this, a.concat([b])) // _super.m.apply(this, a.concat([b])) // _super.prototype.m.apply(this, a.concat([b])) - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); } else { // [source] @@ -74682,13 +74624,11 @@ var ts; // _super.call(this, a) // _super.m.call(this, a) // _super.prototype.m.call(this, a) - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } if (node.expression.kind === 98 /* SuperKeyword */) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); - var initializer = ts.createLogicalOr(resultingCall, actualThis); + var initializer = ts.createLogicalOr(resultingCall, createActualThis()); resultingCall = assignToCapturedThis ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) : initializer; @@ -74703,7 +74643,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (ts.some(node.arguments, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -74966,12 +74906,7 @@ var ts; } function visitMetaProperty(node) { if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { - if (hierarchyFacts & 8192 /* ComputedPropertyName */) { - hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; - } - else { - hierarchyFacts |= 16384 /* NewTarget */; - } + hierarchyFacts |= 8192 /* NewTarget */; return ts.createFileLevelUniqueName("_newTarget"); } return node; @@ -74986,7 +74921,7 @@ var ts; function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ : 65 /* FunctionIncludes */); previousOnEmitNode(hint, node, emitCallback); @@ -75534,7 +75469,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -75554,10 +75489,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 256 /* Generator */) { + else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512 /* ContainsGenerator */) { + else if (transformFlags & 256 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -75610,10 +75545,10 @@ var ts; case 230 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -75789,7 +75724,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -75816,7 +75751,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -76874,7 +76809,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -77993,7 +77928,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 16777216 /* ContainsDynamicImport */ || + node.transformFlags & 524288 /* ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } @@ -78030,7 +77965,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -78256,7 +78191,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -78330,13 +78265,13 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + else if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else { @@ -78397,7 +78332,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -79362,7 +79297,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -79528,7 +79463,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -80440,14 +80375,13 @@ var ts; * @param node The node to visit. */ function destructuringAndImportCallVisitor(node) { - if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 204 /* BinaryExpression */) { + if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -92690,22 +92624,18 @@ var ts; var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics()); - var reportSemanticDiagnostics = false; // If we didn't have any syntactic errors, then also try getting the global and // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics()); ts.addRange(diagnostics, program.getGlobalDiagnostics()); if (diagnostics.length === configFileParsingDiagnosticsLength) { - reportSemanticDiagnostics = true; + ts.addRange(diagnostics, program.getSemanticDiagnostics()); } } // Emit and report any errors we ran into. var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); - if (reportSemanticDiagnostics) { - ts.addRange(diagnostics, program.getSemanticDiagnostics()); - } ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); if (writeFileName) { var currentDir_1 = program.getCurrentDirectory(); @@ -92826,6 +92756,22 @@ var ts; } } ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; + function setCreateSourceFileAsHashVersioned(compilerHost, host) { + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + ts.setCreateSourceFileAsHashVersioned = setCreateSourceFileAsHashVersioned; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -92900,6 +92846,23 @@ var ts; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; + function readBuilderProgram(compilerOptions, readFile) { + if (compilerOptions.out || compilerOptions.outFile) + return undefined; + var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions); + if (!buildInfoPath) + return undefined; + var content = readFile(buildInfoPath); + if (!content) + return undefined; + var buildInfo = ts.getBuildInfo(content); + if (buildInfo.version !== ts.version) + return undefined; + if (!buildInfo.program) + return undefined; + return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + } + ts.readBuilderProgram = readBuilderProgram; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -92911,7 +92874,6 @@ var ts; } } ts.createWatchCompilerHost = createWatchCompilerHost; - var initialVersion = 1; function createWatchProgram(host) { var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc @@ -92952,10 +92914,12 @@ var ts; var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + var configFileWatcher; if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); + configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); } var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); // Members for CompilerHost var getNewSourceFile = compilerHost.getSourceFile; compilerHost.getSourceFile = function (fileName) { @@ -92996,21 +92960,43 @@ var ts; (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); }); synchronizeProgram(); // Update the wild card directory watch watchConfigFileWildCardDirectories(); return configFileName ? - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close }; + function close() { + resolutionCache.clear(); + ts.clearMap(sourceFilesCache, function (value) { + if (value && value.fileWatcher) { + value.fileWatcher.close(); + value.fileWatcher = undefined; + } + }); + if (configFileWatcher) { + configFileWatcher.close(); + configFileWatcher = undefined; + } + if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + watchedWildcardDirectories = undefined; + } + if (missingFilesMap) { + ts.clearMap(missingFilesMap, ts.closeFileWatcher); + missingFilesMap = undefined; + } + } function getCurrentBuilderProgram() { return builderProgram; } function getCurrentProgram() { - return builderProgram && builderProgram.getProgram(); + return builderProgram && builderProgram.getProgramOrUndefined(); } function synchronizeProgram() { writeLog("Synchronizing program"); - var program = getCurrentProgram(); + var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { @@ -93026,19 +93012,19 @@ var ts; } } else { - createNewProgram(program, hasInvalidatedResolution); + createNewProgram(hasInvalidatedResolution); } if (host.afterProgramCreate) { host.afterProgramCreate(builderProgram); } return builderProgram; } - function createNewProgram(program, hasInvalidatedResolution) { + function createNewProgram(hasInvalidatedResolution) { // Compile the program writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); - var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); @@ -93078,10 +93064,10 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function isFileMissingOnHost(hostSourceFile) { - return typeof hostSourceFile === "number"; + return typeof hostSourceFile === "boolean"; } - function isFilePresentOnHost(hostSourceFile) { - return !!hostSourceFile.sourceFile; + function isFilePresenceUnknownOnHost(hostSourceFile) { + return typeof hostSourceFile.version === "boolean"; } function fileExists(fileName) { var path = toPath(fileName); @@ -93099,36 +93085,32 @@ var ts; return undefined; } // Create new source file if requested or the versions dont match - if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) { var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { - if (shouldCreateNewSourceFile) { - hostSourceFile.version++; - } if (sourceFile) { // Set the source file and create file watcher now that file was present on the disk hostSourceFile.sourceFile = sourceFile; - sourceFile.version = hostSourceFile.version.toString(); + hostSourceFile.version = sourceFile.version; if (!hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); } } else { // There is no source file on host any more, close the watch, missing file paths will track it - if (isFilePresentOnHost(hostSourceFile)) { + if (hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher.close(); } - sourceFilesCache.set(path, hostSourceFile.version); + sourceFilesCache.set(path, false); } } else { if (sourceFile) { - sourceFile.version = initialVersion.toString(); var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); - sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher }); } else { - sourceFilesCache.set(path, initialVersion); + sourceFilesCache.set(path, false); } } return sourceFile; @@ -93140,16 +93122,16 @@ var ts; if (hostSourceFile !== undefined) { if (isFileMissingOnHost(hostSourceFile)) { // The next version, lets set it as presence unknown file - sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + sourceFilesCache.set(path, { version: false }); } else { - hostSourceFile.version++; + hostSourceFile.version = false; } } } function getSourceVersion(path) { var hostSourceFile = sourceFilesCache.get(path); - return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version; } function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); @@ -93157,7 +93139,7 @@ var ts; // remove the cached entry. // Note we arent deleting entry if file became missing in new program or // there was version update and new source file was created. - if (hostSourceFileInfo) { + if (hostSourceFileInfo !== undefined) { // record the missing file paths so they can be removed later if watchers arent tracking them if (isFileMissingOnHost(hostSourceFileInfo)) { (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); @@ -93246,7 +93228,7 @@ var ts; function onSourceFileChange(fileName, eventKind, path) { updateCachedSystemWithFile(fileName, path, eventKind); // Update the source file cache - if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); @@ -93524,19 +93506,7 @@ var ts; var readFileWithCache = function (f) { return host.readFile(f); }; var projectCompilerOptions = baseCompilerOptions; var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); - var originalGetSourceFile = compilerHost.getSourceFile; - var computeHash = host.createHash || ts.generateDjb2Hash; - compilerHost.getSourceFile = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); - if (result) { - result.version = computeHash.call(host, result.text); - } - return result; - }; + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); var buildInfoChecked = createFileMap(toPath); // Watch state var builderPrograms = createFileMap(toPath); @@ -94203,16 +94173,7 @@ var ts; var value = builderPrograms.getValue(proj); if (value) return value; - var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options); - if (!buildInfoPath) - return undefined; - var content = readFileWithCache(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); - if (buildInfo.version !== ts.version) - return undefined; - return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + return ts.readBuilderProgram(parsed.options, readFileWithCache); } function updateBundle(proj) { if (options.dry) { @@ -104970,7 +104931,7 @@ var ts; function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); - var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); + var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -119028,7 +118989,7 @@ var ts; var movedSymbols = new SymbolSet(); var oldImportsNeededByNewFile = new SymbolSet(); var newFileImportsFromOldFile = new SymbolSet(); - var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 4 /* ContainsJsx */); }); + var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); }); var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code) oldImportsNeededByNewFile.add(jsxNamespaceSymbol); @@ -119062,7 +119023,7 @@ var ts; if (ts.contains(toMove, statement)) continue; // jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile. - if (jsxNamespaceSymbol && !!(statement.transformFlags & 4 /* ContainsJsx */)) { + if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { unusedImportsFromOldFile.delete(jsxNamespaceSymbol); } forEachReference(statement, checker, function (symbol) { diff --git a/lib/typescript.js b/lib/typescript.js index 4774041a6d7..1bf83511c51 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -3844,75 +3844,69 @@ var ts; TransformFlags[TransformFlags["None"] = 0] = "None"; // Facts // - Flags used to indicate that a node or subtree contains syntax that requires transformation. - TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; - TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; - TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; - TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; - TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016"; TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; - TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; - TransformFlags[TransformFlags["ContainsES2018"] = 134217728] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2019"] = 268435456] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. - TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; - TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; - TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2019"] = 268435456] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 134217728] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; - TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes"; + // Propagating flags + // - Bitmasks for flags that should propagate from a child + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -8676,10 +8670,7 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - /** - * Prepends statements to an array while taking care of prologue directives. - */ - function addStatementsAfterPrologue(to, from) { + function insertStatementsAfterPrologue(to, from, isPrologueDirective) { if (from === undefined || from.length === 0) return to; var statementIndex = 0; @@ -8692,7 +8683,44 @@ var ts; to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + function insertStatementAfterPrologue(to, statement, isPrologueDirective) { + if (statement === undefined) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice(statementIndex, 0, statement); + return to; + } + function isAnyPrologueDirective(node) { + return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementsAfterStandardPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isPrologueDirective); + } + ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue; + function insertStatementsAfterCustomPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective); + } + ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementAfterStandardPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isPrologueDirective); + } + ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue; + function insertStatementAfterCustomPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective); + } + ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue; /** * Determine if the given comment is a triple-slash * @@ -9682,6 +9710,11 @@ var ts; } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + function isSuperOrSuperProperty(node) { + return node.kind === 98 /* SuperKeyword */ + || isSuperProperty(node); + } + ts.isSuperOrSuperProperty = isSuperOrSuperProperty; /** * Determines whether a node is a property or element access expression for `super`. */ @@ -30124,44 +30157,37 @@ var ts; ts.computeTransformFlagsForNode = computeTransformFlagsForNode; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; + var callee = ts.skipOuterExpressions(node.expression); var expression = node.expression; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */ - || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; - // super property or element accesses could be inside lambdas, etc, and need a captured `this`, - // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 67108864 /* ContainsSuper */) { - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 128 /* AssertES2015 */; + if (ts.isSuperProperty(callee)) { + transformFlags |= 2048 /* ContainsLexicalThis */; } } if (expression.kind === 92 /* ImportKeyword */) { - transformFlags |= 16777216 /* ContainsDynamicImport */; - // A dynamic 'import()' call that contains a lexical 'this' will - // require a captured 'this' when emitting down-level. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; - } + transformFlags |= 524288 /* ContainsDynamicImport */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30170,19 +30196,19 @@ var ts; if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ES2018 if they contain rest - transformFlags |= 134217728 /* AssertES2018 */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. - transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { // Exponentiation is ES2016 syntax. - transformFlags |= 32 /* AssertES2016 */; + transformFlags |= 64 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30193,147 +30219,131 @@ var ts; // syntax. if (node.questionToken || node.type - || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) + || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* ParameterExcludes */; + return transformFlags & ~536870912 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. if (expressionKind === 212 /* AsExpression */ || expressionKind === 194 /* TypeAssertionExpression */) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the expression of a ParenthesizedExpression is a destructuring assignment, - // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 1024 /* DestructuringAssignment */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* OuterExpressionExcludes */; + return transformFlags & ~536870912 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; if (ts.hasModifier(node, 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES2015 */; + transformFlags = subtreeFlags | 128 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, computed property name, or decorator is // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) + if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ + if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { case 86 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 109 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; default: ts.Debug.fail("Unexpected token for heritage clause"); break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; if (!node.variableDeclaration) { - transformFlags |= 268435456 /* AssertES2019 */; + transformFlags |= 8 /* AssertES2019 */; } else if (ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637797697 /* CatchClauseExcludes */; + return transformFlags & ~536879104 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; // TypeScript-specific modifiers and overloads are TypeScript syntax if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* ConstructorExcludes */; + return transformFlags & ~537372672 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and // overloads are TypeScript syntax. if (node.decorators @@ -30342,21 +30352,21 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // An async method declaration is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30367,25 +30377,25 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. - var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + var transformFlags = subtreeFlags | 1 /* AssertTypeScript */; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */); } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -30394,30 +30404,24 @@ var ts; if (!body || (modifierFlags & 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. // A FunctionDeclaration without a body is an overload and is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function declaration is ES2017 syntax. if (modifierFlags & 256 /* Async */) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If a FunctionDeclaration's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionDeclaration is generator function and is the body of a // transformed async function, then this node can be transformed to a @@ -30425,11 +30429,11 @@ var ts; // Currently we do not support transforming any other generator functions // down level. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30438,181 +30442,161 @@ var ts; if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function expression is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } // function expressions with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If a FunctionExpression's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionExpression is generator function and is the body of a // transformed async function, then this node can be transformed to a // down-level generator. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async arrow function is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= 16 /* AssertES2017 */; + transformFlags |= 32 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653604161 /* ArrowFunctionExcludes */; + return transformFlags & ~537371648 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 33554432 /* Super */) { - transformFlags ^= 33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). // same for super inside of an async generator, which is ES2018. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 134217728 /* ContainsES2018 */; + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 33554432 /* Super */) { - transformFlags &= ~33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). // same for super inside of an async generator, which is ES2018. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 134217728 /* ContainsES2018 */; + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally? // A VariableDeclaration containing ObjectRest is ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // Type annotations are TypeScript syntax. if (node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; var declarationListTransformFlags = node.declarationList.transformFlags; // An ambient declaration is TypeScript syntax. if (ts.hasModifier(node, 2 /* Ambient */)) { - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; // An ImportEqualsDeclaration with a namespace reference is TypeScript. if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - // If the expression of an expression statement is a destructuring assignment, - // then we treat the statement as ES6 so that we can indicate that we do not - // need to hold on to the right-hand side. - if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES2015 */; - } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3 /* AssertTypeScript */; + var transformFlags = 1 /* AssertTypeScript */; var modifierFlags = ts.getModifierFlags(node); if ((modifierFlags & 2 /* Ambient */) === 0) { transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~647001409 /* ModuleExcludes */; + return transformFlags & ~537168896 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; + transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; + return transformFlags & ~536944640 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 637535553 /* NodeExcludes */; + var excludeFlags = 536870912 /* NodeExcludes */; switch (kind) { case 121 /* AsyncKeyword */: case 201 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators) - transformFlags |= 134217728 /* AssertES2018 */ | 16 /* AssertES2017 */; + transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */; break; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: case 313 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; + transformFlags |= 1 /* AssertTypeScript */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; break; case 115 /* PublicKeyword */: case 113 /* PrivateKeyword */: @@ -30625,7 +30609,7 @@ var ts; case 213 /* NonNullExpression */: case 133 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; case 260 /* JsxElement */: case 261 /* JsxSelfClosingElement */: @@ -30640,7 +30624,7 @@ var ts; case 269 /* JsxSpreadAttribute */: case 270 /* JsxExpression */: // These nodes are Jsx syntax. - transformFlags |= 4 /* AssertJsx */; + transformFlags |= 2 /* AssertJsx */; break; case 14 /* NoSubstitutionTemplateLiteral */: case 15 /* TemplateHead */: @@ -30652,32 +30636,32 @@ var ts; case 116 /* StaticKeyword */: case 214 /* MetaProperty */: // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 10 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 8 /* NumericLiteral */: if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 9 /* BigIntLiteral */: - transformFlags |= 8 /* AssertESNext */; + transformFlags |= 4 /* AssertESNext */; break; case 227 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { - transformFlags |= 134217728 /* AssertES2018 */; + transformFlags |= 16 /* AssertES2018 */; } - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 207 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 134217728 /* AssertES2018 */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */; break; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: @@ -30718,115 +30702,93 @@ var ts; case 182 /* LiteralType */: case 247 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. - transformFlags = 3 /* AssertTypeScript */; - excludeFlags = -3 /* TypeExcludes */; + transformFlags = 1 /* AssertTypeScript */; + excludeFlags = -2 /* TypeExcludes */; break; case 149 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 524288 /* ContainsComputedPropertyName */; - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - // A computed method name like `[this.getName()](x: string) { ... }` needs to - // distinguish itself from the normal case of a method body containing `this`: - // `this` inside a method doesn't need to be rewritten (the method provides `this`), - // whereas `this` inside a computed name *might* need to be rewritten if the class/object - // is inside an arrow function: - // `_this = this; () => class K { [_this.getName()]() { ... } }` - // To make this distinction, use ContainsLexicalThisInComputedPropertyName - // instead of ContainsLexicalThis for computed property names - transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; - } + transformFlags |= 16384 /* ContainsComputedPropertyName */; break; case 208 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */; break; case 277 /* SpreadAssignment */: - transformFlags |= 134217728 /* AssertES2018 */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; break; case 98 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + transformFlags |= 128 /* AssertES2015 */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 100 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 2048 /* ContainsLexicalThis */; break; case 184 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; } - excludeFlags = 637666625 /* BindingPatternExcludes */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 185 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - excludeFlags = 637666625 /* BindingPatternExcludes */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 186 /* BindingElement */: - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 131072 /* ContainsRestOrSpread */; + transformFlags |= 4096 /* ContainsRestOrSpread */; } break; case 152 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; break; case 188 /* ObjectLiteralExpression */: - excludeFlags = 638358849 /* ObjectLiteralExcludes */; - if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + excludeFlags = 536896512 /* ObjectLiteralExcludes */; + if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; - } - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES2018 node. - transformFlags |= 134217728 /* AssertES2018 */; + transformFlags |= 16 /* AssertES2018 */; } break; case 187 /* ArrayLiteralExpression */: - case 192 /* NewExpression */: - excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - // If the this node contains a SpreadExpression, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } + excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */; break; case 223 /* DoStatement */: case 224 /* WhileStatement */: case 225 /* ForStatement */: case 226 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) { + transformFlags |= 128 /* AssertES2015 */; } break; case 284 /* SourceFile */: - if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES2015 */; - } break; case 230 /* ReturnStatement */: // Return statements may require an `await` in ES2018. - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 134217728 /* AssertES2018 */; + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */; break; case 228 /* ContinueStatement */: case 229 /* BreakStatement */: - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~excludeFlags; } + function propagatePropertyNameFlags(node, transformFlags) { + return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */); + } /** * Gets the transform flags to exclude when unioning the transform flags of a subtree. * @@ -30836,33 +30798,33 @@ var ts; */ function getTransformFlagsSubtreeExclusions(kind) { if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; } switch (kind) { case 191 /* CallExpression */: case 192 /* NewExpression */: case 187 /* ArrayLiteralExpression */: - return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return 536875008 /* ArrayLiteralOrCallOrNewExcludes */; case 244 /* ModuleDeclaration */: - return 647001409 /* ModuleExcludes */; + return 537168896 /* ModuleExcludes */; case 151 /* Parameter */: - return 637535553 /* ParameterExcludes */; + return 536870912 /* ParameterExcludes */; case 197 /* ArrowFunction */: - return 653604161 /* ArrowFunctionExcludes */; + return 537371648 /* ArrowFunctionExcludes */; case 196 /* FunctionExpression */: case 239 /* FunctionDeclaration */: - return 653620545 /* FunctionExcludes */; + return 537373696 /* FunctionExcludes */; case 238 /* VariableDeclarationList */: - return 639894849 /* VariableDeclarationListExcludes */; + return 536944640 /* VariableDeclarationListExcludes */; case 240 /* ClassDeclaration */: case 209 /* ClassExpression */: - return 638121281 /* ClassExcludes */; + return 536888320 /* ClassExcludes */; case 157 /* Constructor */: - return 653616449 /* ConstructorExcludes */; + return 537372672 /* ConstructorExcludes */; case 156 /* MethodDeclaration */: case 158 /* GetAccessor */: case 159 /* SetAccessor */: - return 653616449 /* MethodOrAccessorExcludes */; + return 537372672 /* MethodOrAccessorExcludes */; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: case 146 /* BigIntKeyword */: @@ -30880,25 +30842,25 @@ var ts; case 162 /* IndexSignature */: case 241 /* InterfaceDeclaration */: case 242 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; case 188 /* ObjectLiteralExpression */: - return 638358849 /* ObjectLiteralExcludes */; + return 536896512 /* ObjectLiteralExcludes */; case 274 /* CatchClause */: - return 637797697 /* CatchClauseExcludes */; + return 536879104 /* CatchClauseExcludes */; case 184 /* ObjectBindingPattern */: case 185 /* ArrayBindingPattern */: - return 637666625 /* BindingPatternExcludes */; + return 536875008 /* BindingPatternExcludes */; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: case 313 /* PartiallyEmittedExpression */: case 195 /* ParenthesizedExpression */: case 98 /* SuperKeyword */: - return 536872257 /* OuterExpressionExcludes */; + return 536870912 /* OuterExpressionExcludes */; case 189 /* PropertyAccessExpression */: case 190 /* ElementAccessExpression */: - return 570426689 /* PropertyAccessExcludes */; + return 536870912 /* PropertyAccessExcludes */; default: - return 637535553 /* NodeExcludes */; + return 536870912 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -31443,6 +31405,7 @@ var ts; var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); + var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -37971,15 +37934,24 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } + function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { + var rootTrueType = root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + return instantiateType(rootTrueConstraint, combinedMapper || mapper); + } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { - var rootTrueType = type.root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) - ? rootTrueType - : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + // An `any` branch of a conditional type would normally be viral - specifically, without special handling here, + // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to + // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type, + // in effect treating `any` like `never` rather than `unknown` in this location. + var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); + var falseConstraint = getFalseTypeFromConditionalType(type); + type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; } @@ -37989,7 +37961,13 @@ var ts; // with its constraint. We do this because if the constraint is a union type it will be distributed // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. - if (type.root.isDistributive) { + // We skip returning a distributive constraint for a restrictive instantiation of a conditional type + // as the constraint for all type params (check type included) have been replace with `unknown`, which + // is going to produce even more false positive/negative results than the distribute constraint already does. + // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter + // a union - once negated types exist and are applied to the conditional false branch, this "constraint" + // likely doesn't need to exist. + if (type.root.isDistributive && type.restrictiveInstantiation !== type) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint && constraint !== type.checkType) { @@ -40382,12 +40360,47 @@ var ts; function getActualTypeVariable(type) { return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; } + /** + * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent + */ + function isIntersectionEmpty(type1, type2) { + return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */); + } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); var extendsType = instantiateType(root.extendsType, mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } + var trueType = instantiateType(root.trueType, mapper); + var falseType = instantiateType(root.falseType, mapper); + var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; + } + var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); + conditionalTypes.set(instantiationId, newResult); + return newResult; + } + function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) { + // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`. + if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { + if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return getDefaultConstraintOfTrueBranchOfConditionalType(root, /*combinedMapper*/ undefined, mapper); + } + else if (isIntersectionEmpty(checkType, extendsType)) { // Always false + return neverType; + } + } + else if (trueType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(falseType), getActualTypeVariable(checkType))) { + if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return neverType; + } + else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false + return falseType; // TODO: Intersect negated `extends` type here + } + } var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); var combinedMapper; if (root.inferTypeParameters) { @@ -40405,18 +40418,18 @@ var ts; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) { if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { - return instantiateType(root.trueType, mapper); + return trueType; } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { - return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]); } // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { - return instantiateType(root.falseType, mapper); + return falseType; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -40435,6 +40448,10 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; + if (!combinedMapper) { + result.resolvedTrueType = trueType; + result.resolvedFalseType = falseType; + } result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; @@ -41339,8 +41356,20 @@ var ts; type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); } function getRestrictiveInstantiation(type) { - return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : - type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); + if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) { + return type; + } + if (type.restrictiveInstantiation) { + return type.restrictiveInstantiation; + } + type.restrictiveInstantiation = instantiateType(type, restrictiveMapper); + // We set the following so we don't attempt to set the restrictive instance of a restrictive instance + // which is redundant - we'll produce new type identities, but all type params have already been mapped. + // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint" + // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters + // are constrained to `unknown` and produce tons of false positives/negatives! + type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation; + return type.restrictiveInstantiation; } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -42885,16 +42914,26 @@ var ts; template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } - // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. - if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - return result; + if (!isGenericMappedType(source)) { + var targetConstraint = getConstraintTypeFromMappedType(target); + var sourceKeys_1 = getIndexType(source); + var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */; + var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined; + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X. + if (hasOptionalUnionKeys + ? !(filteredByApplicability.flags & 131072 /* Never */) + : isRelatedTo(targetConstraint, sourceKeys_1)) { + var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target); + var indexedAccessType = getIndexedAccessType(source, indexingType); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } - originalErrorInfo = errorInfo; - errorInfo = saveErrorInfo; } } if (source.flags & 8650752 /* TypeVariable */) { @@ -44570,6 +44609,7 @@ var ts; if (inference.priority === undefined || priority < inference.priority) { inference.candidates = undefined; inference.contraCandidates = undefined; + inference.topLevel = true; inference.priority = priority; } if (priority === inference.priority) { @@ -65591,8 +65631,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) - : ts.addStatementsAfterPrologue(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) + : ts.insertStatementsAfterStandardPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -66866,8 +66906,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -66933,7 +66973,7 @@ var ts; if (flattenContext.level >= 1 /* 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 & 262144 /* ContainsObjectRestOrSpread */) { + if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -67261,14 +67301,9 @@ var ts; * @param node The node to visit. */ function visitorWorker(node) { - if (node.transformFlags & 1 /* TypeScript */) { - // This node is explicitly marked as TypeScript, so we should transform the node. + if (node.transformFlags & 1 /* ContainsTypeScript */) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -67302,7 +67337,7 @@ var ts; // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, // and will trigger debug failures when debug verbosity is turned up - if (node.transformFlags & 2 /* ContainsTypeScript */) { + if (node.transformFlags & 1 /* ContainsTypeScript */) { // This node contains TypeScript, so we should visit its children. return ts.visitEachChild(node, visitor, context); } @@ -67344,15 +67379,9 @@ var ts; // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } - else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { - // This node is explicitly marked as TypeScript, or is exported at the namespace - // level, so we should transform the node. + else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -67403,7 +67432,7 @@ var ts; * @param node The node to visit. */ function visitTypeScript(node) { - if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) { // TypeScript ambient declarations are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); @@ -67470,7 +67499,7 @@ var ts; // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); case 240 /* ClassDeclaration */: - // This is a class declaration with TypeScript syntax extensions. + // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -67481,7 +67510,7 @@ var ts; // - method overload signatures return visitClassDeclaration(node); case 209 /* ClassExpression */: - // This is a class expression with TypeScript syntax extensions. + // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -67492,7 +67521,7 @@ var ts; // - method overload signatures return visitClassExpression(node); case 273 /* HeritageClause */: - // This is a heritage clause with TypeScript syntax extensions. + // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause @@ -67520,7 +67549,7 @@ var ts; // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); case 151 /* Parameter */: - // This is a parameter declaration with TypeScript syntax extensions. + // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: // - decorators @@ -67561,7 +67590,8 @@ var ts; // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: - return ts.Debug.failBadSyntaxKind(node); + // node contains some other TypeScript syntax + return ts.visitEachChild(node, visitor, context); } } function visitSourceFile(node) { @@ -67610,18 +67640,19 @@ var ts; facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; return facts; } - /** - * Transforms a class declaration with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has decorators. - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - The class is an export in a TypeScript namespace. - * - * @param node The node to transform. - */ + function hasTypeScriptClassSyntax(node) { + return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */); + } + function isClassLikeDeclarationWithTypeScriptSyntax(node) { + return ts.some(node.decorators) + || ts.some(node.typeParameters) + || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) + || ts.some(node.members, hasTypeScriptClassSyntax); + } function visitClassDeclaration(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -67674,7 +67705,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -67851,16 +67882,10 @@ var ts; ts.setCommentRange(statement, node); return statement; } - /** - * Transforms a class expression with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - * @param node The node to transform. - */ function visitClassExpression(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -67924,7 +67949,7 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); var hasParameterPropertyAssignments = constructor && - constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. @@ -68969,11 +68994,11 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 86 /* ExtendsKeyword */) { - var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); + if (node.token === 109 /* ImplementsKeyword */) { + // implements clauses are elided + return undefined; } - return undefined; + return ts.visitEachChild(node, visitor, context); } /** * Transforms an ExpressionWithTypeArguments with TypeScript syntax. @@ -69009,16 +69034,6 @@ var ts; } return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); } - /** - * Visits a method declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is marked as abstract, public, private, protected, or readonly - * - The node has a computed property name - * - * @param node The method node. - */ function visitMethodDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; @@ -69045,15 +69060,6 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); } - /** - * Visits a get accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The get accessor node. - */ function visitGetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -69069,15 +69075,6 @@ var ts; } return updated; } - /** - * Visits a set accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The set accessor node. - */ function visitSetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -69092,16 +69089,6 @@ var ts; } return updated; } - /** - * Visits a function declaration. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is exported from a TypeScript namespace - * - The node has decorators - * - * @param node The function node. - */ function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); @@ -69117,14 +69104,6 @@ var ts; } return updated; } - /** - * Visits a function expression node. - * - * This function will be called when one of the following conditions are met: - * - The node has type annotations - * - * @param node The function expression node. - */ function visitFunctionExpression(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createOmittedExpression(); @@ -69134,51 +69113,31 @@ var ts; /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); return updated; } - /** - * @remarks - * This function will be called when one of the following conditions are met: - * - The node has type annotations - */ function visitArrowFunction(node) { var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } - /** - * Visits a parameter declaration node. - * - * This function will be called when one of the following conditions are met: - * - The node has an accessibility modifier. - * - The node has a questionToken. - * - The node's kind is ThisKeyword. - * - * @param node The parameter declaration node. - */ function visitParameter(node) { if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameter( + var updated = ts.updateParameter(node, /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setOriginalNode(parameter, node); - ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); - ts.setCommentRange(parameter, node); - ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); - return parameter; + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */); + } + return updated; } - /** - * Visits a variable statement in a namespace. - * - * This function will be called when one of the following conditions are met: - * - The node is exported from a TypeScript namespace. - */ function visitVariableStatement(node) { if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); @@ -69207,12 +69166,6 @@ var ts; return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } - /** - * Visits a parenthesized expression that contains either a type assertion or an `as` - * expression. - * - * @param node The parenthesized expression node. - */ function visitParenthesizedExpression(node) { var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); if (ts.isAssertionExpression(innerExpression)) { @@ -69349,7 +69302,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -69596,7 +69549,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -70151,7 +70104,7 @@ var ts; return visited; } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { @@ -70428,7 +70381,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.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. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); @@ -70436,7 +70389,7 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -70730,7 +70683,7 @@ var ts; return node; } function visitorWorker(node, noDestructuringValue) { - if ((node.transformFlags & 134217728 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { @@ -70848,7 +70801,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -70874,7 +70827,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 27 /* CommaToken */) { @@ -70889,7 +70842,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -70906,7 +70859,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -71003,7 +70956,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -71116,10 +71069,10 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } statements.push(returnStatement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { @@ -71145,7 +71098,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.insertStatementsAfterStandardPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -71154,7 +71107,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -71362,7 +71315,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 268435456 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { @@ -71393,7 +71346,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { return node; } switch (node.kind) { @@ -71426,7 +71379,7 @@ var ts; return visited; } function visitor(node) { - if (node.transformFlags & 4 /* ContainsJsx */) { + if (node.transformFlags & 2 /* ContainsJsx */) { return visitorWorker(node); } else { @@ -71928,7 +71881,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { @@ -72008,30 +71961,6 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); - var SuperCaptureResult; - (function (SuperCaptureResult) { - /** - * A capture may have been added for calls to 'super', but - * the caller should emit subsequent statements normally. - */ - SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * var _this = _super.call(...) || this; - * - * Callers should skip the current statement. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * return _super.call(...) || this; - * - * Callers should skip the current statement and avoid any returns of '_this'. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; - })(SuperCaptureResult || (SuperCaptureResult = {})); // Facts we track as we traverse the tree var HierarchyFacts; (function (HierarchyFacts) { @@ -72052,12 +71981,12 @@ var ts; HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; - HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below. // // Ancestor masks // - HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask"; // We are always in *some* kind of block scope, but only specific block-scope containers are // top-level or Blocks. HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; @@ -72067,16 +71996,16 @@ var ts; HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; // Functions, methods, and accessors are both new lexical scopes and new block scopes. HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; - HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes"; HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes"; // Arrow functions are lexically scoped to their container, but are new block scopes. HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; - HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes"; // Constructors are both new lexical scopes and new block scopes. Constructors are also // always considered non-static members of a class. HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; - HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes"; // 'do' and 'while' statements are not block scopes. We track that the subtree is contained // within an IterationStatement to indicate whether the embedded statement is an // IterationStatementBlock. @@ -72094,19 +72023,17 @@ var ts; HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; - // Computed property names track subtree flags differently than their containing members. - HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; - HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; // // Subtree facts // - HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; - HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget"; + HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis"; // // Subtree masks // - HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; - HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes"; + HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes"; })(HierarchyFacts || (HierarchyFacts = {})); function transformES2015(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; @@ -72155,7 +72082,7 @@ var ts; */ function enterSubtree(excludeFacts, includeFacts) { var ancestorFacts = hierarchyFacts; - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */; return ancestorFacts; } /** @@ -72166,7 +72093,7 @@ var ts; * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. */ function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 @@ -72188,12 +72115,6 @@ var ts; return node; } } - function functionBodyVisitor(node) { - if (shouldVisitNode(node)) { - return visitBlock(node, /*isFunctionBody*/ true); - } - return node; - } function callExpressionVisitor(node) { if (node.kind === 98 /* SuperKeyword */) { return visitSuperKeyword(/*isExpressionOfCall*/ true); @@ -72300,18 +72221,19 @@ var ts; } function visitSourceFile(node) { var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + var prologue = []; var statements = []; startLexicalEnvironment(); - var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); - addCaptureThisForNodeIfNeeded(statements, node); - statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureThisForNodeIfNeeded(prologue, node); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements)); } function visitSwitchStatement(node) { if (convertedLoopState !== undefined) { @@ -72351,6 +72273,9 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitThisKeyword(node) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; + } if (convertedLoopState) { if (hierarchyFacts & 2 /* ArrowFunction */) { // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. @@ -72564,7 +72489,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -72592,7 +72517,7 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = ts.createFunctionDeclaration( @@ -72606,7 +72531,7 @@ var ts; ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); } statements.push(constructorFunction); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; } /** @@ -72625,6 +72550,24 @@ var ts; return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } + function createDefaultConstructorBody(node, isDerivedClass) { + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + var statements = []; + resumeLexicalEnvironment(); + ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + if (isDerivedClass) { + // return _super !== null && _super.apply(this, arguments) || this; + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + } + var statementsArray = ts.createNodeArray(statements); + ts.setTextRange(statementsArray, node.members); + var block = ts.createBlock(statementsArray, /*multiLine*/ true); + ts.setTextRange(block, node); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } /** * Transforms the body of a constructor declaration of a class. * @@ -72635,59 +72578,137 @@ var ts; * synthesized `super` call. */ function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { - var statements = []; - resumeLexicalEnvironment(); - var statementOffset = -1; - if (hasSynthesizedSuper) { - // If a super call has already been synthesized, - // we're going to assume that we should just transform everything after that. - // The assumption is that no prior step in the pipeline has added any prologue directives. - statementOffset = 0; - } - else if (constructor) { - statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); - } - if (constructor) { - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); - if (!hasSynthesizedSuper) { - // If no super call has been synthesized, emit custom prologue directives. - statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); - } - ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); - } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; - var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); - // The last statement expression was replaced. Skip it. - if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { - statementOffset++; + // When the subclass does not have a constructor, we synthesize a *default* constructor using the following + // representation: + // + // ``` + // // es2015 (source) + // class C extends Base { } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.apply(this, arguments) || this; + // } + // return C; + // })(Base); + // ``` + if (!constructor) + return createDefaultConstructorBody(node, isDerivedClass); + // The prologue will contain all leading standard and custom prologue statements added by this transform + var prologue = []; + var statements = []; + resumeLexicalEnvironment(); + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + var statementOffset = 0; + if (!hasSynthesizedSuper) + statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + // If the first statement is a call to `super()`, visit the statement directly + var superCallExpression; + if (hasSynthesizedSuper) { + superCallExpression = createDefaultSuperCallOrThis(); } - if (constructor) { - if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { - hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + else if (isDerivedClass && statementOffset < constructor.body.statements.length) { + var firstStatement = constructor.body.statements[statementOffset]; + if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); } - // Return `_this` unless we're sure enough that it would be pointless to add a return statement. - // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. - if (isDerivedClass - && superCaptureStatus !== 2 /* ReplaceWithReturn */ - && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { - statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + if (superCallExpression) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + statementOffset++; // skip this statement, we will add it after visiting the rest of the body. } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - if (constructor) { - prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); + // visit the remaining statements + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); + if (isDerivedClass) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) { + // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the + // following representation: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.call(this, "foo") || this; + // } + // return C; + // })(Base); + // ``` + var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); + var returnStatement = ts.createReturn(superCallExpression); + ts.setCommentRange(returnStatement, ts.getCommentRange(superCall)); + ts.setEmitFlags(superCall, 1536 /* NoComments */); + statements.push(returnStatement); + } + else { + // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // this.x = 1; + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // var _this = _super.call(this, "foo") || this; + // _this.x = 1; + // return _this; + // } + // return C; + // })(Base); + // ``` + // Since the `super()` call was the first statement, we insert the `this` capturing call to + // `super()` at the top of the list of `statements` (after any pre-existing custom prologues). + insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); + if (!isSufficientlyCoveredByReturnStatements(constructor.body)) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } + } } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), - /*location*/ constructor ? constructor.body.statements : node.members), + else { + // If a class is not derived from a base class or does not have a call to `super()`, `this` is only + // captured when necessitated by an arrow function capturing the lexical `this`: + // + // ``` + // // es2015 + // class C {} + // + // // es5 + // var C = (function () { + // function C() { + // } + // return C; + // })(); + // ``` + insertCaptureThisForNodeIfNeeded(prologue, constructor); + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), + /*location*/ constructor.body.statements), /*multiLine*/ true); - ts.setTextRange(block, constructor ? constructor.body : node); - if (!constructor) { - ts.setEmitFlags(block, 1536 /* NoComments */); - } + ts.setTextRange(block, constructor.body); return block; } /** @@ -72717,83 +72738,6 @@ var ts; } return false; } - /** - * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. - * - * @returns The new statement offset into the `statements` array. - */ - function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { - // If this isn't a derived class, just capture 'this' for arrow functions if necessary. - if (!isDerivedClass) { - if (ctor) { - addCaptureThisForNodeIfNeeded(statements, ctor); - } - return 0 /* NoReplacement */; - } - // We must be here because the user didn't write a constructor - // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. - // If that's the case we can just immediately return the result of a 'super()' call. - if (!ctor) { - statements.push(ts.createReturn(createDefaultSuperCallOrThis())); - return 2 /* ReplaceWithReturn */; - } - // The constructor exists, but it and the 'super()' call it contains were generated - // for something like property initializers. - // Create a captured '_this' variable and assume it will subsequently be used. - if (hasSynthesizedSuper) { - captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); - enableSubstitutionsForCapturedThis(); - return 1 /* ReplaceSuperCapture */; - } - // Most of the time, a 'super' call will be the first real statement in a constructor body. - // In these cases, we'd like to transform these into a *single* statement instead of a declaration - // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, - // we'd get: - // - // var _this; - // _this = _super.call(...) || this; - // - // instead of - // - // var _this = _super.call(...) || this; - // - // Additionally, if the 'super()' call is the last statement, we should just avoid capturing - // entirely and immediately return the result like so: - // - // return _super.call(...) || this; - // - var firstStatement; - var superCallExpression; - var ctorStatements = ctor.body.statements; - if (statementOffset < ctorStatements.length) { - firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { - superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); - } - } - // Return the result if we have an immediate super() call on the last statement, - // but only if the constructor itself doesn't use 'this' elsewhere. - if (superCallExpression - && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { - var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 204 /* BinaryExpression */ - || superCallExpression.left.kind !== 191 /* CallExpression */) { - ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); - } - // Shift comments from the original super call to the return statement. - ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); - statements.push(returnStatement); - return 2 /* ReplaceWithReturn */; - } - // Perform the capture. - captureThisForNode(statements, ctor, superCallExpression || createActualThis()); - // If we're actually replacing the original statement, we need to signal this to the caller. - if (superCallExpression) { - return 1 /* ReplaceSuperCapture */; - } - return 0 /* NoReplacement */; - } function createActualThis() { return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); } @@ -72839,14 +72783,9 @@ var ts; return node; } } - /** - * Gets a value indicating whether we need to add default value assignments for a - * function-like node. - * - * @param node A function-like node. - */ - function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + function hasDefaultValueOrBindingPattern(node) { + return node.initializer !== undefined + || ts.isBindingPattern(node.name); } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -72856,9 +72795,10 @@ var ts; * @param node A function-like node. */ function addDefaultValueAssignmentsIfNeeded(statements, node) { - if (!shouldAddDefaultValueAssignments(node)) { - return; + if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) { + return false; } + var added = false; for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; @@ -72868,12 +72808,14 @@ var ts; continue; } if (ts.isBindingPattern(name)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added; } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + added = true; } } + return added; } /** * Adds statements to the body of a function-like node for parameters with binding patterns @@ -72883,18 +72825,20 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { - var temp = ts.getGeneratedNameForNode(parameter); + function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { // In cases where a binding pattern is simply '[]' or '{}', // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { - statements.push(ts.setEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */)); + return true; } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + return true; } + return false; } /** * Adds statements to the body of a function-like node for parameters with initializers. @@ -72904,7 +72848,7 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) @@ -72912,7 +72856,7 @@ var ts; ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); - statements.push(statement); + ts.insertStatementAfterCustomPrologue(statements, statement); } /** * Gets a value indicating whether we need to add statements to handle a rest parameter. @@ -72935,9 +72879,10 @@ var ts; * synthesized call to `super` */ function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var prologueStatements = []; var parameter = ts.lastOrUndefined(node.parameters); if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { - return; + return false; } // `declarationName` is the name of the local declaration for the parameter. var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -72947,7 +72892,7 @@ var ts; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) @@ -72966,25 +72911,30 @@ var ts; ])); ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); - statements.push(forStatement); + prologueStatements.push(forStatement); if (parameter.name.kind !== 72 /* Identifier */) { // do the actual destructuring of the rest parameter if necessary - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */)); } + ts.insertStatementsAfterCustomPrologue(statements, prologueStatements); + return true; } /** * Adds a statement to capture the `this` of a function declaration if it is needed. + * NOTE: This must be executed *after* the subtree has been visited. * * @param statements The statements for the new function body. * @param node A node. */ - function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { - captureThisForNode(statements, node, ts.createThis()); + function insertCaptureThisForNodeIfNeeded(statements, node) { + if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { + insertCaptureThisForNode(statements, node, ts.createThis()); + return true; } + return false; } - function captureThisForNode(statements, node, initializer) { + function insertCaptureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -72993,10 +72943,10 @@ var ts; ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); ts.setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + ts.insertStatementAfterCustomPrologue(statements, captureThisStatement); } - function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { - if (hierarchyFacts & 16384 /* NewTarget */) { + function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 8192 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { case 197 /* ArrowFunction */: @@ -73027,10 +72977,11 @@ var ts; ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), /*type*/ undefined, newTarget) ])); + ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); if (copyOnWrite) { - return [captureNewTargetStatement].concat(statements); + statements = statements.slice(); } - statements.unshift(captureNewTargetStatement); + ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); } return statements; } @@ -73082,7 +73033,6 @@ var ts; * @param member The MethodDeclaration node. */ function transformClassMethodDeclarationToStatement(receiver, member, container) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var commentRange = ts.getCommentRange(member); var sourceMapRange = ts.getSourceMapRange(member); var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); @@ -73097,7 +73047,6 @@ var ts; // No source map should be emitted for this statement to align with the // old emitter. ts.setEmitFlags(statement, 48 /* NoSourceMap */); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return statement; } /** @@ -73123,7 +73072,6 @@ var ts; */ function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); // To align with source maps in the old emitter, the receiver and property name // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); @@ -73159,7 +73107,6 @@ var ts; if (startsOnNewLine) { ts.startOnNewLine(call); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return call; } /** @@ -73168,12 +73115,12 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* ContainsLexicalThis */) { - enableSubstitutionsForCapturedThis(); + if (node.transformFlags & 2048 /* ContainsLexicalThis */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); var func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -73183,7 +73130,11 @@ var ts; ts.setTextRange(func, node); ts.setOriginalNode(func, node); ts.setEmitFlags(func, 8 /* CapturesThis */); - exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + if (hierarchyFacts & 16384 /* CapturedLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + // If an arrow function contains + exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return func; } @@ -73194,18 +73145,16 @@ var ts; */ function visitFunctionExpression(node) { var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ - ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionExpression(node, /*modifiers*/ undefined, node.asteriskToken, name, @@ -73220,15 +73169,13 @@ var ts; function visitFunctionDeclaration(node) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionDeclaration(node, /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, @@ -73246,14 +73193,14 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) - ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { + if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( /*modifiers*/ undefined, node.asteriskToken, name, @@ -73271,7 +73218,7 @@ var ts; var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; - var leadingStatements = []; + var prologue = []; var statements = []; var body = node.body; var statementOffset; @@ -73279,14 +73226,13 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false); } - addCaptureThisForNodeIfNeeded(leadingStatements, node); - addDefaultValueAssignmentsIfNeeded(leadingStatements, node); - addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); + multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; + multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; if (ts.isBlock(body)) { // addCustomPrologue puts already-existing directives at the beginning of the target statement-array - statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); // If the original body was a multi-line block, this must be a multi-line block. @@ -73320,14 +73266,19 @@ var ts; // source map location for the close brace. closeBraceLocation = body; } - var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); - prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false); + insertCaptureThisForNodeIfNeeded(prologue, node); // If we added any final generated statements, this must be a multi-line block - if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + if (ts.some(prologue)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + statements.unshift.apply(statements, prologue); + if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) { + // no changes were made, preserve the tree + return body; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1 /* SingleLine */); @@ -73338,11 +73289,6 @@ var ts; ts.setOriginalNode(block, node.body); return block; } - function visitFunctionBodyDownLevel(node) { - var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); - return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), - /*location*/ updated.statements)); - } function visitBlock(node, isFunctionBody) { if (isFunctionBody) { // A function body is not a block scope. @@ -73447,7 +73393,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) { if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -73460,7 +73406,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + if (node.transformFlags & 65536 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -73782,7 +73728,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -74058,7 +74004,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = ts.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0 /* None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -74163,11 +74109,11 @@ var ts; statements.push(statement); } copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment); var loopBody = ts.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -74399,13 +74345,11 @@ var ts; * @param receiver The receiver for the assignment. */ function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { ts.startOnNewLine(expression); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return expression; } function visitCatchClause(node) { @@ -74457,19 +74401,17 @@ var ts; ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); + var body = transformFunctionBody(node); if (node.kind === 158 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return updated; } @@ -74483,10 +74425,7 @@ var ts; /*location*/ node); } function visitComputedPropertyName(node) { - var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); - var updated = ts.visitEachChild(node, visitor, context); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); - return updated; + return ts.visitEachChild(node, visitor, context); } /** * Visits a YieldExpression node. @@ -74503,7 +74442,7 @@ var ts; * @param node An ArrayLiteralExpression node. */ function visitArrayLiteralExpression(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (ts.some(node.elements, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); } @@ -74518,7 +74457,10 @@ var ts; if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { return visitTypeScriptClassWrapper(node); } - if (node.transformFlags & 64 /* ES2015 */) { + var expression = ts.skipOuterExpressions(node.expression); + if (expression.kind === 98 /* SuperKeyword */ || + ts.isSuperProperty(expression) || + ts.some(node.arguments, ts.isSpreadElement)) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), @@ -74639,7 +74581,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + if (node.transformFlags & 4096 /* ContainsRestOrSpread */ || node.expression.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -74647,7 +74589,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (node.transformFlags & 4096 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -74661,7 +74603,7 @@ var ts; // _super.apply(this, a.concat([b])) // _super.m.apply(this, a.concat([b])) // _super.prototype.m.apply(this, a.concat([b])) - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); } else { // [source] @@ -74673,13 +74615,11 @@ var ts; // _super.call(this, a) // _super.m.call(this, a) // _super.prototype.m.call(this, a) - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } if (node.expression.kind === 98 /* SuperKeyword */) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); - var initializer = ts.createLogicalOr(resultingCall, actualThis); + var initializer = ts.createLogicalOr(resultingCall, createActualThis()); resultingCall = assignToCapturedThis ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) : initializer; @@ -74694,7 +74634,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (ts.some(node.arguments, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -74957,12 +74897,7 @@ var ts; } function visitMetaProperty(node) { if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { - if (hierarchyFacts & 8192 /* ComputedPropertyName */) { - hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; - } - else { - hierarchyFacts |= 16384 /* NewTarget */; - } + hierarchyFacts |= 8192 /* NewTarget */; return ts.createFileLevelUniqueName("_newTarget"); } return node; @@ -74977,7 +74912,7 @@ var ts; function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ : 65 /* FunctionIncludes */); previousOnEmitNode(hint, node, emitCallback); @@ -75525,7 +75460,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -75545,10 +75480,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 256 /* Generator */) { + else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512 /* ContainsGenerator */) { + else if (transformFlags & 256 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -75601,10 +75536,10 @@ var ts; case 230 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -75780,7 +75715,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -75807,7 +75742,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -76865,7 +76800,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -77984,7 +77919,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 16777216 /* ContainsDynamicImport */ || + node.transformFlags & 524288 /* ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } @@ -78021,7 +77956,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -78247,7 +78182,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -78321,13 +78256,13 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + else if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else { @@ -78388,7 +78323,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -79353,7 +79288,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -79519,7 +79454,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -80431,14 +80366,13 @@ var ts; * @param node The node to visit. */ function destructuringAndImportCallVisitor(node) { - if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 204 /* BinaryExpression */) { + if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -92681,22 +92615,18 @@ var ts; var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics()); - var reportSemanticDiagnostics = false; // If we didn't have any syntactic errors, then also try getting the global and // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics()); ts.addRange(diagnostics, program.getGlobalDiagnostics()); if (diagnostics.length === configFileParsingDiagnosticsLength) { - reportSemanticDiagnostics = true; + ts.addRange(diagnostics, program.getSemanticDiagnostics()); } } // Emit and report any errors we ran into. var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); - if (reportSemanticDiagnostics) { - ts.addRange(diagnostics, program.getSemanticDiagnostics()); - } ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); if (writeFileName) { var currentDir_1 = program.getCurrentDirectory(); @@ -92817,6 +92747,22 @@ var ts; } } ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; + function setCreateSourceFileAsHashVersioned(compilerHost, host) { + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + ts.setCreateSourceFileAsHashVersioned = setCreateSourceFileAsHashVersioned; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -92891,6 +92837,23 @@ var ts; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; + function readBuilderProgram(compilerOptions, readFile) { + if (compilerOptions.out || compilerOptions.outFile) + return undefined; + var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions); + if (!buildInfoPath) + return undefined; + var content = readFile(buildInfoPath); + if (!content) + return undefined; + var buildInfo = ts.getBuildInfo(content); + if (buildInfo.version !== ts.version) + return undefined; + if (!buildInfo.program) + return undefined; + return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + } + ts.readBuilderProgram = readBuilderProgram; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -92902,7 +92865,6 @@ var ts; } } ts.createWatchCompilerHost = createWatchCompilerHost; - var initialVersion = 1; function createWatchProgram(host) { var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc @@ -92943,10 +92905,12 @@ var ts; var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + var configFileWatcher; if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); + configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); } var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); // Members for CompilerHost var getNewSourceFile = compilerHost.getSourceFile; compilerHost.getSourceFile = function (fileName) { @@ -92987,21 +92951,43 @@ var ts; (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); }); synchronizeProgram(); // Update the wild card directory watch watchConfigFileWildCardDirectories(); return configFileName ? - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close }; + function close() { + resolutionCache.clear(); + ts.clearMap(sourceFilesCache, function (value) { + if (value && value.fileWatcher) { + value.fileWatcher.close(); + value.fileWatcher = undefined; + } + }); + if (configFileWatcher) { + configFileWatcher.close(); + configFileWatcher = undefined; + } + if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + watchedWildcardDirectories = undefined; + } + if (missingFilesMap) { + ts.clearMap(missingFilesMap, ts.closeFileWatcher); + missingFilesMap = undefined; + } + } function getCurrentBuilderProgram() { return builderProgram; } function getCurrentProgram() { - return builderProgram && builderProgram.getProgram(); + return builderProgram && builderProgram.getProgramOrUndefined(); } function synchronizeProgram() { writeLog("Synchronizing program"); - var program = getCurrentProgram(); + var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { @@ -93017,19 +93003,19 @@ var ts; } } else { - createNewProgram(program, hasInvalidatedResolution); + createNewProgram(hasInvalidatedResolution); } if (host.afterProgramCreate) { host.afterProgramCreate(builderProgram); } return builderProgram; } - function createNewProgram(program, hasInvalidatedResolution) { + function createNewProgram(hasInvalidatedResolution) { // Compile the program writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); - var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); @@ -93069,10 +93055,10 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function isFileMissingOnHost(hostSourceFile) { - return typeof hostSourceFile === "number"; + return typeof hostSourceFile === "boolean"; } - function isFilePresentOnHost(hostSourceFile) { - return !!hostSourceFile.sourceFile; + function isFilePresenceUnknownOnHost(hostSourceFile) { + return typeof hostSourceFile.version === "boolean"; } function fileExists(fileName) { var path = toPath(fileName); @@ -93090,36 +93076,32 @@ var ts; return undefined; } // Create new source file if requested or the versions dont match - if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) { var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { - if (shouldCreateNewSourceFile) { - hostSourceFile.version++; - } if (sourceFile) { // Set the source file and create file watcher now that file was present on the disk hostSourceFile.sourceFile = sourceFile; - sourceFile.version = hostSourceFile.version.toString(); + hostSourceFile.version = sourceFile.version; if (!hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); } } else { // There is no source file on host any more, close the watch, missing file paths will track it - if (isFilePresentOnHost(hostSourceFile)) { + if (hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher.close(); } - sourceFilesCache.set(path, hostSourceFile.version); + sourceFilesCache.set(path, false); } } else { if (sourceFile) { - sourceFile.version = initialVersion.toString(); var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); - sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher }); } else { - sourceFilesCache.set(path, initialVersion); + sourceFilesCache.set(path, false); } } return sourceFile; @@ -93131,16 +93113,16 @@ var ts; if (hostSourceFile !== undefined) { if (isFileMissingOnHost(hostSourceFile)) { // The next version, lets set it as presence unknown file - sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + sourceFilesCache.set(path, { version: false }); } else { - hostSourceFile.version++; + hostSourceFile.version = false; } } } function getSourceVersion(path) { var hostSourceFile = sourceFilesCache.get(path); - return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version; } function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); @@ -93148,7 +93130,7 @@ var ts; // remove the cached entry. // Note we arent deleting entry if file became missing in new program or // there was version update and new source file was created. - if (hostSourceFileInfo) { + if (hostSourceFileInfo !== undefined) { // record the missing file paths so they can be removed later if watchers arent tracking them if (isFileMissingOnHost(hostSourceFileInfo)) { (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); @@ -93237,7 +93219,7 @@ var ts; function onSourceFileChange(fileName, eventKind, path) { updateCachedSystemWithFile(fileName, path, eventKind); // Update the source file cache - if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); @@ -93515,19 +93497,7 @@ var ts; var readFileWithCache = function (f) { return host.readFile(f); }; var projectCompilerOptions = baseCompilerOptions; var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); - var originalGetSourceFile = compilerHost.getSourceFile; - var computeHash = host.createHash || ts.generateDjb2Hash; - compilerHost.getSourceFile = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); - if (result) { - result.version = computeHash.call(host, result.text); - } - return result; - }; + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); var buildInfoChecked = createFileMap(toPath); // Watch state var builderPrograms = createFileMap(toPath); @@ -94194,16 +94164,7 @@ var ts; var value = builderPrograms.getValue(proj); if (value) return value; - var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options); - if (!buildInfoPath) - return undefined; - var content = readFileWithCache(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); - if (buildInfo.version !== ts.version) - return undefined; - return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + return ts.readBuilderProgram(parsed.options, readFileWithCache); } function updateBundle(proj) { if (options.dry) { @@ -104961,7 +104922,7 @@ var ts; function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); - var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); + var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -119019,7 +118980,7 @@ var ts; var movedSymbols = new SymbolSet(); var oldImportsNeededByNewFile = new SymbolSet(); var newFileImportsFromOldFile = new SymbolSet(); - var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 4 /* ContainsJsx */); }); + var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); }); var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code) oldImportsNeededByNewFile.add(jsxNamespaceSymbol); @@ -119053,7 +119014,7 @@ var ts; if (ts.contains(toMove, statement)) continue; // jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile. - if (jsxNamespaceSymbol && !!(statement.transformFlags & 4 /* ContainsJsx */)) { + if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { unusedImportsFromOldFile.delete(jsxNamespaceSymbol); } forEachReference(statement, checker, function (symbol) { diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 38cecfac882..06c7e3c046f 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -3844,75 +3844,69 @@ var ts; TransformFlags[TransformFlags["None"] = 0] = "None"; // Facts // - Flags used to indicate that a node or subtree contains syntax that requires transformation. - TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; - TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; - TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; - TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; - TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016"; TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; - TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; - TransformFlags[TransformFlags["ContainsES2018"] = 134217728] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2019"] = 268435456] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. - TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; - TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; - TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2019"] = 268435456] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 134217728] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; - TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes"; + // Propagating flags + // - Bitmasks for flags that should propagate from a child + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -8676,10 +8670,7 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - /** - * Prepends statements to an array while taking care of prologue directives. - */ - function addStatementsAfterPrologue(to, from) { + function insertStatementsAfterPrologue(to, from, isPrologueDirective) { if (from === undefined || from.length === 0) return to; var statementIndex = 0; @@ -8692,7 +8683,44 @@ var ts; to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + function insertStatementAfterPrologue(to, statement, isPrologueDirective) { + if (statement === undefined) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice(statementIndex, 0, statement); + return to; + } + function isAnyPrologueDirective(node) { + return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementsAfterStandardPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isPrologueDirective); + } + ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue; + function insertStatementsAfterCustomPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective); + } + ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementAfterStandardPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isPrologueDirective); + } + ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue; + function insertStatementAfterCustomPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective); + } + ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue; /** * Determine if the given comment is a triple-slash * @@ -9682,6 +9710,11 @@ var ts; } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + function isSuperOrSuperProperty(node) { + return node.kind === 98 /* SuperKeyword */ + || isSuperProperty(node); + } + ts.isSuperOrSuperProperty = isSuperOrSuperProperty; /** * Determines whether a node is a property or element access expression for `super`. */ @@ -30124,44 +30157,37 @@ var ts; ts.computeTransformFlagsForNode = computeTransformFlagsForNode; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; + var callee = ts.skipOuterExpressions(node.expression); var expression = node.expression; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */ - || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; - // super property or element accesses could be inside lambdas, etc, and need a captured `this`, - // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 67108864 /* ContainsSuper */) { - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 128 /* AssertES2015 */; + if (ts.isSuperProperty(callee)) { + transformFlags |= 2048 /* ContainsLexicalThis */; } } if (expression.kind === 92 /* ImportKeyword */) { - transformFlags |= 16777216 /* ContainsDynamicImport */; - // A dynamic 'import()' call that contains a lexical 'this' will - // require a captured 'this' when emitting down-level. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; - } + transformFlags |= 524288 /* ContainsDynamicImport */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30170,19 +30196,19 @@ var ts; if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ES2018 if they contain rest - transformFlags |= 134217728 /* AssertES2018 */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. - transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { // Exponentiation is ES2016 syntax. - transformFlags |= 32 /* AssertES2016 */; + transformFlags |= 64 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30193,147 +30219,131 @@ var ts; // syntax. if (node.questionToken || node.type - || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) + || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* ParameterExcludes */; + return transformFlags & ~536870912 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. if (expressionKind === 212 /* AsExpression */ || expressionKind === 194 /* TypeAssertionExpression */) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the expression of a ParenthesizedExpression is a destructuring assignment, - // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 1024 /* DestructuringAssignment */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* OuterExpressionExcludes */; + return transformFlags & ~536870912 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; if (ts.hasModifier(node, 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES2015 */; + transformFlags = subtreeFlags | 128 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, computed property name, or decorator is // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) + if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ + if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { case 86 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 109 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; default: ts.Debug.fail("Unexpected token for heritage clause"); break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; if (!node.variableDeclaration) { - transformFlags |= 268435456 /* AssertES2019 */; + transformFlags |= 8 /* AssertES2019 */; } else if (ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637797697 /* CatchClauseExcludes */; + return transformFlags & ~536879104 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; // TypeScript-specific modifiers and overloads are TypeScript syntax if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* ConstructorExcludes */; + return transformFlags & ~537372672 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and // overloads are TypeScript syntax. if (node.decorators @@ -30342,21 +30352,21 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // An async method declaration is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30367,25 +30377,25 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. - var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + var transformFlags = subtreeFlags | 1 /* AssertTypeScript */; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */); } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -30394,30 +30404,24 @@ var ts; if (!body || (modifierFlags & 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. // A FunctionDeclaration without a body is an overload and is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function declaration is ES2017 syntax. if (modifierFlags & 256 /* Async */) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If a FunctionDeclaration's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionDeclaration is generator function and is the body of a // transformed async function, then this node can be transformed to a @@ -30425,11 +30429,11 @@ var ts; // Currently we do not support transforming any other generator functions // down level. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30438,181 +30442,161 @@ var ts; if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function expression is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } // function expressions with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If a FunctionExpression's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionExpression is generator function and is the body of a // transformed async function, then this node can be transformed to a // down-level generator. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async arrow function is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= 16 /* AssertES2017 */; + transformFlags |= 32 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653604161 /* ArrowFunctionExcludes */; + return transformFlags & ~537371648 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 33554432 /* Super */) { - transformFlags ^= 33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). // same for super inside of an async generator, which is ES2018. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 134217728 /* ContainsES2018 */; + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 33554432 /* Super */) { - transformFlags &= ~33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). // same for super inside of an async generator, which is ES2018. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 134217728 /* ContainsES2018 */; + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally? // A VariableDeclaration containing ObjectRest is ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // Type annotations are TypeScript syntax. if (node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; var declarationListTransformFlags = node.declarationList.transformFlags; // An ambient declaration is TypeScript syntax. if (ts.hasModifier(node, 2 /* Ambient */)) { - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; // An ImportEqualsDeclaration with a namespace reference is TypeScript. if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - // If the expression of an expression statement is a destructuring assignment, - // then we treat the statement as ES6 so that we can indicate that we do not - // need to hold on to the right-hand side. - if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES2015 */; - } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3 /* AssertTypeScript */; + var transformFlags = 1 /* AssertTypeScript */; var modifierFlags = ts.getModifierFlags(node); if ((modifierFlags & 2 /* Ambient */) === 0) { transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~647001409 /* ModuleExcludes */; + return transformFlags & ~537168896 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; + transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; + return transformFlags & ~536944640 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 637535553 /* NodeExcludes */; + var excludeFlags = 536870912 /* NodeExcludes */; switch (kind) { case 121 /* AsyncKeyword */: case 201 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators) - transformFlags |= 134217728 /* AssertES2018 */ | 16 /* AssertES2017 */; + transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */; break; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: case 313 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; + transformFlags |= 1 /* AssertTypeScript */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; break; case 115 /* PublicKeyword */: case 113 /* PrivateKeyword */: @@ -30625,7 +30609,7 @@ var ts; case 213 /* NonNullExpression */: case 133 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; case 260 /* JsxElement */: case 261 /* JsxSelfClosingElement */: @@ -30640,7 +30624,7 @@ var ts; case 269 /* JsxSpreadAttribute */: case 270 /* JsxExpression */: // These nodes are Jsx syntax. - transformFlags |= 4 /* AssertJsx */; + transformFlags |= 2 /* AssertJsx */; break; case 14 /* NoSubstitutionTemplateLiteral */: case 15 /* TemplateHead */: @@ -30652,32 +30636,32 @@ var ts; case 116 /* StaticKeyword */: case 214 /* MetaProperty */: // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 10 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 8 /* NumericLiteral */: if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 9 /* BigIntLiteral */: - transformFlags |= 8 /* AssertESNext */; + transformFlags |= 4 /* AssertESNext */; break; case 227 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { - transformFlags |= 134217728 /* AssertES2018 */; + transformFlags |= 16 /* AssertES2018 */; } - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 207 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 134217728 /* AssertES2018 */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */; break; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: @@ -30718,115 +30702,93 @@ var ts; case 182 /* LiteralType */: case 247 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. - transformFlags = 3 /* AssertTypeScript */; - excludeFlags = -3 /* TypeExcludes */; + transformFlags = 1 /* AssertTypeScript */; + excludeFlags = -2 /* TypeExcludes */; break; case 149 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 524288 /* ContainsComputedPropertyName */; - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - // A computed method name like `[this.getName()](x: string) { ... }` needs to - // distinguish itself from the normal case of a method body containing `this`: - // `this` inside a method doesn't need to be rewritten (the method provides `this`), - // whereas `this` inside a computed name *might* need to be rewritten if the class/object - // is inside an arrow function: - // `_this = this; () => class K { [_this.getName()]() { ... } }` - // To make this distinction, use ContainsLexicalThisInComputedPropertyName - // instead of ContainsLexicalThis for computed property names - transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; - } + transformFlags |= 16384 /* ContainsComputedPropertyName */; break; case 208 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */; break; case 277 /* SpreadAssignment */: - transformFlags |= 134217728 /* AssertES2018 */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; break; case 98 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + transformFlags |= 128 /* AssertES2015 */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 100 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 2048 /* ContainsLexicalThis */; break; case 184 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; } - excludeFlags = 637666625 /* BindingPatternExcludes */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 185 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - excludeFlags = 637666625 /* BindingPatternExcludes */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 186 /* BindingElement */: - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 131072 /* ContainsRestOrSpread */; + transformFlags |= 4096 /* ContainsRestOrSpread */; } break; case 152 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; break; case 188 /* ObjectLiteralExpression */: - excludeFlags = 638358849 /* ObjectLiteralExcludes */; - if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + excludeFlags = 536896512 /* ObjectLiteralExcludes */; + if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; - } - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES2018 node. - transformFlags |= 134217728 /* AssertES2018 */; + transformFlags |= 16 /* AssertES2018 */; } break; case 187 /* ArrayLiteralExpression */: - case 192 /* NewExpression */: - excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - // If the this node contains a SpreadExpression, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } + excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */; break; case 223 /* DoStatement */: case 224 /* WhileStatement */: case 225 /* ForStatement */: case 226 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) { + transformFlags |= 128 /* AssertES2015 */; } break; case 284 /* SourceFile */: - if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES2015 */; - } break; case 230 /* ReturnStatement */: // Return statements may require an `await` in ES2018. - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 134217728 /* AssertES2018 */; + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */; break; case 228 /* ContinueStatement */: case 229 /* BreakStatement */: - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~excludeFlags; } + function propagatePropertyNameFlags(node, transformFlags) { + return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */); + } /** * Gets the transform flags to exclude when unioning the transform flags of a subtree. * @@ -30836,33 +30798,33 @@ var ts; */ function getTransformFlagsSubtreeExclusions(kind) { if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; } switch (kind) { case 191 /* CallExpression */: case 192 /* NewExpression */: case 187 /* ArrayLiteralExpression */: - return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return 536875008 /* ArrayLiteralOrCallOrNewExcludes */; case 244 /* ModuleDeclaration */: - return 647001409 /* ModuleExcludes */; + return 537168896 /* ModuleExcludes */; case 151 /* Parameter */: - return 637535553 /* ParameterExcludes */; + return 536870912 /* ParameterExcludes */; case 197 /* ArrowFunction */: - return 653604161 /* ArrowFunctionExcludes */; + return 537371648 /* ArrowFunctionExcludes */; case 196 /* FunctionExpression */: case 239 /* FunctionDeclaration */: - return 653620545 /* FunctionExcludes */; + return 537373696 /* FunctionExcludes */; case 238 /* VariableDeclarationList */: - return 639894849 /* VariableDeclarationListExcludes */; + return 536944640 /* VariableDeclarationListExcludes */; case 240 /* ClassDeclaration */: case 209 /* ClassExpression */: - return 638121281 /* ClassExcludes */; + return 536888320 /* ClassExcludes */; case 157 /* Constructor */: - return 653616449 /* ConstructorExcludes */; + return 537372672 /* ConstructorExcludes */; case 156 /* MethodDeclaration */: case 158 /* GetAccessor */: case 159 /* SetAccessor */: - return 653616449 /* MethodOrAccessorExcludes */; + return 537372672 /* MethodOrAccessorExcludes */; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: case 146 /* BigIntKeyword */: @@ -30880,25 +30842,25 @@ var ts; case 162 /* IndexSignature */: case 241 /* InterfaceDeclaration */: case 242 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; case 188 /* ObjectLiteralExpression */: - return 638358849 /* ObjectLiteralExcludes */; + return 536896512 /* ObjectLiteralExcludes */; case 274 /* CatchClause */: - return 637797697 /* CatchClauseExcludes */; + return 536879104 /* CatchClauseExcludes */; case 184 /* ObjectBindingPattern */: case 185 /* ArrayBindingPattern */: - return 637666625 /* BindingPatternExcludes */; + return 536875008 /* BindingPatternExcludes */; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: case 313 /* PartiallyEmittedExpression */: case 195 /* ParenthesizedExpression */: case 98 /* SuperKeyword */: - return 536872257 /* OuterExpressionExcludes */; + return 536870912 /* OuterExpressionExcludes */; case 189 /* PropertyAccessExpression */: case 190 /* ElementAccessExpression */: - return 570426689 /* PropertyAccessExcludes */; + return 536870912 /* PropertyAccessExcludes */; default: - return 637535553 /* NodeExcludes */; + return 536870912 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -31443,6 +31405,7 @@ var ts; var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); + var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -37971,15 +37934,24 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } + function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { + var rootTrueType = root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + return instantiateType(rootTrueConstraint, combinedMapper || mapper); + } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { - var rootTrueType = type.root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) - ? rootTrueType - : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + // An `any` branch of a conditional type would normally be viral - specifically, without special handling here, + // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to + // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type, + // in effect treating `any` like `never` rather than `unknown` in this location. + var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); + var falseConstraint = getFalseTypeFromConditionalType(type); + type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; } @@ -37989,7 +37961,13 @@ var ts; // with its constraint. We do this because if the constraint is a union type it will be distributed // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. - if (type.root.isDistributive) { + // We skip returning a distributive constraint for a restrictive instantiation of a conditional type + // as the constraint for all type params (check type included) have been replace with `unknown`, which + // is going to produce even more false positive/negative results than the distribute constraint already does. + // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter + // a union - once negated types exist and are applied to the conditional false branch, this "constraint" + // likely doesn't need to exist. + if (type.root.isDistributive && type.restrictiveInstantiation !== type) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint && constraint !== type.checkType) { @@ -40382,12 +40360,47 @@ var ts; function getActualTypeVariable(type) { return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; } + /** + * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent + */ + function isIntersectionEmpty(type1, type2) { + return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */); + } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); var extendsType = instantiateType(root.extendsType, mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } + var trueType = instantiateType(root.trueType, mapper); + var falseType = instantiateType(root.falseType, mapper); + var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; + } + var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); + conditionalTypes.set(instantiationId, newResult); + return newResult; + } + function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) { + // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`. + if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { + if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return getDefaultConstraintOfTrueBranchOfConditionalType(root, /*combinedMapper*/ undefined, mapper); + } + else if (isIntersectionEmpty(checkType, extendsType)) { // Always false + return neverType; + } + } + else if (trueType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(falseType), getActualTypeVariable(checkType))) { + if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return neverType; + } + else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false + return falseType; // TODO: Intersect negated `extends` type here + } + } var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); var combinedMapper; if (root.inferTypeParameters) { @@ -40405,18 +40418,18 @@ var ts; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) { if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { - return instantiateType(root.trueType, mapper); + return trueType; } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { - return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]); } // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { - return instantiateType(root.falseType, mapper); + return falseType; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -40435,6 +40448,10 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; + if (!combinedMapper) { + result.resolvedTrueType = trueType; + result.resolvedFalseType = falseType; + } result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; @@ -41339,8 +41356,20 @@ var ts; type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); } function getRestrictiveInstantiation(type) { - return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : - type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); + if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) { + return type; + } + if (type.restrictiveInstantiation) { + return type.restrictiveInstantiation; + } + type.restrictiveInstantiation = instantiateType(type, restrictiveMapper); + // We set the following so we don't attempt to set the restrictive instance of a restrictive instance + // which is redundant - we'll produce new type identities, but all type params have already been mapped. + // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint" + // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters + // are constrained to `unknown` and produce tons of false positives/negatives! + type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation; + return type.restrictiveInstantiation; } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -42885,16 +42914,26 @@ var ts; template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } - // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. - if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - return result; + if (!isGenericMappedType(source)) { + var targetConstraint = getConstraintTypeFromMappedType(target); + var sourceKeys_1 = getIndexType(source); + var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */; + var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined; + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X. + if (hasOptionalUnionKeys + ? !(filteredByApplicability.flags & 131072 /* Never */) + : isRelatedTo(targetConstraint, sourceKeys_1)) { + var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target); + var indexedAccessType = getIndexedAccessType(source, indexingType); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } - originalErrorInfo = errorInfo; - errorInfo = saveErrorInfo; } } if (source.flags & 8650752 /* TypeVariable */) { @@ -44570,6 +44609,7 @@ var ts; if (inference.priority === undefined || priority < inference.priority) { inference.candidates = undefined; inference.contraCandidates = undefined; + inference.topLevel = true; inference.priority = priority; } if (priority === inference.priority) { @@ -65591,8 +65631,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) - : ts.addStatementsAfterPrologue(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) + : ts.insertStatementsAfterStandardPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -66866,8 +66906,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -66933,7 +66973,7 @@ var ts; if (flattenContext.level >= 1 /* 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 & 262144 /* ContainsObjectRestOrSpread */) { + if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -67261,14 +67301,9 @@ var ts; * @param node The node to visit. */ function visitorWorker(node) { - if (node.transformFlags & 1 /* TypeScript */) { - // This node is explicitly marked as TypeScript, so we should transform the node. + if (node.transformFlags & 1 /* ContainsTypeScript */) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -67302,7 +67337,7 @@ var ts; // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, // and will trigger debug failures when debug verbosity is turned up - if (node.transformFlags & 2 /* ContainsTypeScript */) { + if (node.transformFlags & 1 /* ContainsTypeScript */) { // This node contains TypeScript, so we should visit its children. return ts.visitEachChild(node, visitor, context); } @@ -67344,15 +67379,9 @@ var ts; // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } - else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { - // This node is explicitly marked as TypeScript, or is exported at the namespace - // level, so we should transform the node. + else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -67403,7 +67432,7 @@ var ts; * @param node The node to visit. */ function visitTypeScript(node) { - if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) { // TypeScript ambient declarations are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); @@ -67470,7 +67499,7 @@ var ts; // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); case 240 /* ClassDeclaration */: - // This is a class declaration with TypeScript syntax extensions. + // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -67481,7 +67510,7 @@ var ts; // - method overload signatures return visitClassDeclaration(node); case 209 /* ClassExpression */: - // This is a class expression with TypeScript syntax extensions. + // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -67492,7 +67521,7 @@ var ts; // - method overload signatures return visitClassExpression(node); case 273 /* HeritageClause */: - // This is a heritage clause with TypeScript syntax extensions. + // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause @@ -67520,7 +67549,7 @@ var ts; // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); case 151 /* Parameter */: - // This is a parameter declaration with TypeScript syntax extensions. + // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: // - decorators @@ -67561,7 +67590,8 @@ var ts; // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: - return ts.Debug.failBadSyntaxKind(node); + // node contains some other TypeScript syntax + return ts.visitEachChild(node, visitor, context); } } function visitSourceFile(node) { @@ -67610,18 +67640,19 @@ var ts; facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; return facts; } - /** - * Transforms a class declaration with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has decorators. - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - The class is an export in a TypeScript namespace. - * - * @param node The node to transform. - */ + function hasTypeScriptClassSyntax(node) { + return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */); + } + function isClassLikeDeclarationWithTypeScriptSyntax(node) { + return ts.some(node.decorators) + || ts.some(node.typeParameters) + || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) + || ts.some(node.members, hasTypeScriptClassSyntax); + } function visitClassDeclaration(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -67674,7 +67705,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -67851,16 +67882,10 @@ var ts; ts.setCommentRange(statement, node); return statement; } - /** - * Transforms a class expression with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - * @param node The node to transform. - */ function visitClassExpression(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -67924,7 +67949,7 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); var hasParameterPropertyAssignments = constructor && - constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. @@ -68969,11 +68994,11 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 86 /* ExtendsKeyword */) { - var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); + if (node.token === 109 /* ImplementsKeyword */) { + // implements clauses are elided + return undefined; } - return undefined; + return ts.visitEachChild(node, visitor, context); } /** * Transforms an ExpressionWithTypeArguments with TypeScript syntax. @@ -69009,16 +69034,6 @@ var ts; } return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); } - /** - * Visits a method declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is marked as abstract, public, private, protected, or readonly - * - The node has a computed property name - * - * @param node The method node. - */ function visitMethodDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; @@ -69045,15 +69060,6 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); } - /** - * Visits a get accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The get accessor node. - */ function visitGetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -69069,15 +69075,6 @@ var ts; } return updated; } - /** - * Visits a set accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The set accessor node. - */ function visitSetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -69092,16 +69089,6 @@ var ts; } return updated; } - /** - * Visits a function declaration. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is exported from a TypeScript namespace - * - The node has decorators - * - * @param node The function node. - */ function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); @@ -69117,14 +69104,6 @@ var ts; } return updated; } - /** - * Visits a function expression node. - * - * This function will be called when one of the following conditions are met: - * - The node has type annotations - * - * @param node The function expression node. - */ function visitFunctionExpression(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createOmittedExpression(); @@ -69134,51 +69113,31 @@ var ts; /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); return updated; } - /** - * @remarks - * This function will be called when one of the following conditions are met: - * - The node has type annotations - */ function visitArrowFunction(node) { var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } - /** - * Visits a parameter declaration node. - * - * This function will be called when one of the following conditions are met: - * - The node has an accessibility modifier. - * - The node has a questionToken. - * - The node's kind is ThisKeyword. - * - * @param node The parameter declaration node. - */ function visitParameter(node) { if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameter( + var updated = ts.updateParameter(node, /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setOriginalNode(parameter, node); - ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); - ts.setCommentRange(parameter, node); - ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); - return parameter; + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */); + } + return updated; } - /** - * Visits a variable statement in a namespace. - * - * This function will be called when one of the following conditions are met: - * - The node is exported from a TypeScript namespace. - */ function visitVariableStatement(node) { if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); @@ -69207,12 +69166,6 @@ var ts; return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } - /** - * Visits a parenthesized expression that contains either a type assertion or an `as` - * expression. - * - * @param node The parenthesized expression node. - */ function visitParenthesizedExpression(node) { var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); if (ts.isAssertionExpression(innerExpression)) { @@ -69349,7 +69302,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -69596,7 +69549,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -70151,7 +70104,7 @@ var ts; return visited; } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { @@ -70428,7 +70381,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.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. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); @@ -70436,7 +70389,7 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -70730,7 +70683,7 @@ var ts; return node; } function visitorWorker(node, noDestructuringValue) { - if ((node.transformFlags & 134217728 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { @@ -70848,7 +70801,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -70874,7 +70827,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 27 /* CommaToken */) { @@ -70889,7 +70842,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -70906,7 +70859,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -71003,7 +70956,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -71116,10 +71069,10 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } statements.push(returnStatement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { @@ -71145,7 +71098,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.insertStatementsAfterStandardPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -71154,7 +71107,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -71362,7 +71315,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 268435456 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { @@ -71393,7 +71346,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { return node; } switch (node.kind) { @@ -71426,7 +71379,7 @@ var ts; return visited; } function visitor(node) { - if (node.transformFlags & 4 /* ContainsJsx */) { + if (node.transformFlags & 2 /* ContainsJsx */) { return visitorWorker(node); } else { @@ -71928,7 +71881,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { @@ -72008,30 +71961,6 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); - var SuperCaptureResult; - (function (SuperCaptureResult) { - /** - * A capture may have been added for calls to 'super', but - * the caller should emit subsequent statements normally. - */ - SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * var _this = _super.call(...) || this; - * - * Callers should skip the current statement. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * return _super.call(...) || this; - * - * Callers should skip the current statement and avoid any returns of '_this'. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; - })(SuperCaptureResult || (SuperCaptureResult = {})); // Facts we track as we traverse the tree var HierarchyFacts; (function (HierarchyFacts) { @@ -72052,12 +71981,12 @@ var ts; HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; - HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below. // // Ancestor masks // - HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask"; // We are always in *some* kind of block scope, but only specific block-scope containers are // top-level or Blocks. HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; @@ -72067,16 +71996,16 @@ var ts; HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; // Functions, methods, and accessors are both new lexical scopes and new block scopes. HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; - HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes"; HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes"; // Arrow functions are lexically scoped to their container, but are new block scopes. HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; - HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes"; // Constructors are both new lexical scopes and new block scopes. Constructors are also // always considered non-static members of a class. HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; - HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes"; // 'do' and 'while' statements are not block scopes. We track that the subtree is contained // within an IterationStatement to indicate whether the embedded statement is an // IterationStatementBlock. @@ -72094,19 +72023,17 @@ var ts; HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; - // Computed property names track subtree flags differently than their containing members. - HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; - HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; // // Subtree facts // - HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; - HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget"; + HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis"; // // Subtree masks // - HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; - HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes"; + HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes"; })(HierarchyFacts || (HierarchyFacts = {})); function transformES2015(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; @@ -72155,7 +72082,7 @@ var ts; */ function enterSubtree(excludeFacts, includeFacts) { var ancestorFacts = hierarchyFacts; - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */; return ancestorFacts; } /** @@ -72166,7 +72093,7 @@ var ts; * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. */ function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 @@ -72188,12 +72115,6 @@ var ts; return node; } } - function functionBodyVisitor(node) { - if (shouldVisitNode(node)) { - return visitBlock(node, /*isFunctionBody*/ true); - } - return node; - } function callExpressionVisitor(node) { if (node.kind === 98 /* SuperKeyword */) { return visitSuperKeyword(/*isExpressionOfCall*/ true); @@ -72300,18 +72221,19 @@ var ts; } function visitSourceFile(node) { var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + var prologue = []; var statements = []; startLexicalEnvironment(); - var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); - addCaptureThisForNodeIfNeeded(statements, node); - statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureThisForNodeIfNeeded(prologue, node); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements)); } function visitSwitchStatement(node) { if (convertedLoopState !== undefined) { @@ -72351,6 +72273,9 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitThisKeyword(node) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; + } if (convertedLoopState) { if (hierarchyFacts & 2 /* ArrowFunction */) { // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. @@ -72564,7 +72489,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -72592,7 +72517,7 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = ts.createFunctionDeclaration( @@ -72606,7 +72531,7 @@ var ts; ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); } statements.push(constructorFunction); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; } /** @@ -72625,6 +72550,24 @@ var ts; return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } + function createDefaultConstructorBody(node, isDerivedClass) { + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + var statements = []; + resumeLexicalEnvironment(); + ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + if (isDerivedClass) { + // return _super !== null && _super.apply(this, arguments) || this; + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + } + var statementsArray = ts.createNodeArray(statements); + ts.setTextRange(statementsArray, node.members); + var block = ts.createBlock(statementsArray, /*multiLine*/ true); + ts.setTextRange(block, node); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } /** * Transforms the body of a constructor declaration of a class. * @@ -72635,59 +72578,137 @@ var ts; * synthesized `super` call. */ function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { - var statements = []; - resumeLexicalEnvironment(); - var statementOffset = -1; - if (hasSynthesizedSuper) { - // If a super call has already been synthesized, - // we're going to assume that we should just transform everything after that. - // The assumption is that no prior step in the pipeline has added any prologue directives. - statementOffset = 0; - } - else if (constructor) { - statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); - } - if (constructor) { - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); - if (!hasSynthesizedSuper) { - // If no super call has been synthesized, emit custom prologue directives. - statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); - } - ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); - } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; - var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); - // The last statement expression was replaced. Skip it. - if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { - statementOffset++; + // When the subclass does not have a constructor, we synthesize a *default* constructor using the following + // representation: + // + // ``` + // // es2015 (source) + // class C extends Base { } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.apply(this, arguments) || this; + // } + // return C; + // })(Base); + // ``` + if (!constructor) + return createDefaultConstructorBody(node, isDerivedClass); + // The prologue will contain all leading standard and custom prologue statements added by this transform + var prologue = []; + var statements = []; + resumeLexicalEnvironment(); + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + var statementOffset = 0; + if (!hasSynthesizedSuper) + statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + // If the first statement is a call to `super()`, visit the statement directly + var superCallExpression; + if (hasSynthesizedSuper) { + superCallExpression = createDefaultSuperCallOrThis(); } - if (constructor) { - if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { - hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + else if (isDerivedClass && statementOffset < constructor.body.statements.length) { + var firstStatement = constructor.body.statements[statementOffset]; + if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); } - // Return `_this` unless we're sure enough that it would be pointless to add a return statement. - // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. - if (isDerivedClass - && superCaptureStatus !== 2 /* ReplaceWithReturn */ - && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { - statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + if (superCallExpression) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + statementOffset++; // skip this statement, we will add it after visiting the rest of the body. } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - if (constructor) { - prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); + // visit the remaining statements + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); + if (isDerivedClass) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) { + // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the + // following representation: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.call(this, "foo") || this; + // } + // return C; + // })(Base); + // ``` + var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); + var returnStatement = ts.createReturn(superCallExpression); + ts.setCommentRange(returnStatement, ts.getCommentRange(superCall)); + ts.setEmitFlags(superCall, 1536 /* NoComments */); + statements.push(returnStatement); + } + else { + // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // this.x = 1; + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // var _this = _super.call(this, "foo") || this; + // _this.x = 1; + // return _this; + // } + // return C; + // })(Base); + // ``` + // Since the `super()` call was the first statement, we insert the `this` capturing call to + // `super()` at the top of the list of `statements` (after any pre-existing custom prologues). + insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); + if (!isSufficientlyCoveredByReturnStatements(constructor.body)) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } + } } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), - /*location*/ constructor ? constructor.body.statements : node.members), + else { + // If a class is not derived from a base class or does not have a call to `super()`, `this` is only + // captured when necessitated by an arrow function capturing the lexical `this`: + // + // ``` + // // es2015 + // class C {} + // + // // es5 + // var C = (function () { + // function C() { + // } + // return C; + // })(); + // ``` + insertCaptureThisForNodeIfNeeded(prologue, constructor); + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), + /*location*/ constructor.body.statements), /*multiLine*/ true); - ts.setTextRange(block, constructor ? constructor.body : node); - if (!constructor) { - ts.setEmitFlags(block, 1536 /* NoComments */); - } + ts.setTextRange(block, constructor.body); return block; } /** @@ -72717,83 +72738,6 @@ var ts; } return false; } - /** - * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. - * - * @returns The new statement offset into the `statements` array. - */ - function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { - // If this isn't a derived class, just capture 'this' for arrow functions if necessary. - if (!isDerivedClass) { - if (ctor) { - addCaptureThisForNodeIfNeeded(statements, ctor); - } - return 0 /* NoReplacement */; - } - // We must be here because the user didn't write a constructor - // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. - // If that's the case we can just immediately return the result of a 'super()' call. - if (!ctor) { - statements.push(ts.createReturn(createDefaultSuperCallOrThis())); - return 2 /* ReplaceWithReturn */; - } - // The constructor exists, but it and the 'super()' call it contains were generated - // for something like property initializers. - // Create a captured '_this' variable and assume it will subsequently be used. - if (hasSynthesizedSuper) { - captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); - enableSubstitutionsForCapturedThis(); - return 1 /* ReplaceSuperCapture */; - } - // Most of the time, a 'super' call will be the first real statement in a constructor body. - // In these cases, we'd like to transform these into a *single* statement instead of a declaration - // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, - // we'd get: - // - // var _this; - // _this = _super.call(...) || this; - // - // instead of - // - // var _this = _super.call(...) || this; - // - // Additionally, if the 'super()' call is the last statement, we should just avoid capturing - // entirely and immediately return the result like so: - // - // return _super.call(...) || this; - // - var firstStatement; - var superCallExpression; - var ctorStatements = ctor.body.statements; - if (statementOffset < ctorStatements.length) { - firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { - superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); - } - } - // Return the result if we have an immediate super() call on the last statement, - // but only if the constructor itself doesn't use 'this' elsewhere. - if (superCallExpression - && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { - var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 204 /* BinaryExpression */ - || superCallExpression.left.kind !== 191 /* CallExpression */) { - ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); - } - // Shift comments from the original super call to the return statement. - ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); - statements.push(returnStatement); - return 2 /* ReplaceWithReturn */; - } - // Perform the capture. - captureThisForNode(statements, ctor, superCallExpression || createActualThis()); - // If we're actually replacing the original statement, we need to signal this to the caller. - if (superCallExpression) { - return 1 /* ReplaceSuperCapture */; - } - return 0 /* NoReplacement */; - } function createActualThis() { return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); } @@ -72839,14 +72783,9 @@ var ts; return node; } } - /** - * Gets a value indicating whether we need to add default value assignments for a - * function-like node. - * - * @param node A function-like node. - */ - function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + function hasDefaultValueOrBindingPattern(node) { + return node.initializer !== undefined + || ts.isBindingPattern(node.name); } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -72856,9 +72795,10 @@ var ts; * @param node A function-like node. */ function addDefaultValueAssignmentsIfNeeded(statements, node) { - if (!shouldAddDefaultValueAssignments(node)) { - return; + if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) { + return false; } + var added = false; for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; @@ -72868,12 +72808,14 @@ var ts; continue; } if (ts.isBindingPattern(name)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added; } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + added = true; } } + return added; } /** * Adds statements to the body of a function-like node for parameters with binding patterns @@ -72883,18 +72825,20 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { - var temp = ts.getGeneratedNameForNode(parameter); + function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { // In cases where a binding pattern is simply '[]' or '{}', // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { - statements.push(ts.setEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */)); + return true; } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + return true; } + return false; } /** * Adds statements to the body of a function-like node for parameters with initializers. @@ -72904,7 +72848,7 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) @@ -72912,7 +72856,7 @@ var ts; ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); - statements.push(statement); + ts.insertStatementAfterCustomPrologue(statements, statement); } /** * Gets a value indicating whether we need to add statements to handle a rest parameter. @@ -72935,9 +72879,10 @@ var ts; * synthesized call to `super` */ function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var prologueStatements = []; var parameter = ts.lastOrUndefined(node.parameters); if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { - return; + return false; } // `declarationName` is the name of the local declaration for the parameter. var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -72947,7 +72892,7 @@ var ts; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) @@ -72966,25 +72911,30 @@ var ts; ])); ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); - statements.push(forStatement); + prologueStatements.push(forStatement); if (parameter.name.kind !== 72 /* Identifier */) { // do the actual destructuring of the rest parameter if necessary - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */)); } + ts.insertStatementsAfterCustomPrologue(statements, prologueStatements); + return true; } /** * Adds a statement to capture the `this` of a function declaration if it is needed. + * NOTE: This must be executed *after* the subtree has been visited. * * @param statements The statements for the new function body. * @param node A node. */ - function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { - captureThisForNode(statements, node, ts.createThis()); + function insertCaptureThisForNodeIfNeeded(statements, node) { + if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { + insertCaptureThisForNode(statements, node, ts.createThis()); + return true; } + return false; } - function captureThisForNode(statements, node, initializer) { + function insertCaptureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -72993,10 +72943,10 @@ var ts; ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); ts.setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + ts.insertStatementAfterCustomPrologue(statements, captureThisStatement); } - function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { - if (hierarchyFacts & 16384 /* NewTarget */) { + function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 8192 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { case 197 /* ArrowFunction */: @@ -73027,10 +72977,11 @@ var ts; ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), /*type*/ undefined, newTarget) ])); + ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); if (copyOnWrite) { - return [captureNewTargetStatement].concat(statements); + statements = statements.slice(); } - statements.unshift(captureNewTargetStatement); + ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); } return statements; } @@ -73082,7 +73033,6 @@ var ts; * @param member The MethodDeclaration node. */ function transformClassMethodDeclarationToStatement(receiver, member, container) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var commentRange = ts.getCommentRange(member); var sourceMapRange = ts.getSourceMapRange(member); var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); @@ -73097,7 +73047,6 @@ var ts; // No source map should be emitted for this statement to align with the // old emitter. ts.setEmitFlags(statement, 48 /* NoSourceMap */); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return statement; } /** @@ -73123,7 +73072,6 @@ var ts; */ function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); // To align with source maps in the old emitter, the receiver and property name // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); @@ -73159,7 +73107,6 @@ var ts; if (startsOnNewLine) { ts.startOnNewLine(call); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return call; } /** @@ -73168,12 +73115,12 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* ContainsLexicalThis */) { - enableSubstitutionsForCapturedThis(); + if (node.transformFlags & 2048 /* ContainsLexicalThis */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); var func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -73183,7 +73130,11 @@ var ts; ts.setTextRange(func, node); ts.setOriginalNode(func, node); ts.setEmitFlags(func, 8 /* CapturesThis */); - exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + if (hierarchyFacts & 16384 /* CapturedLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + // If an arrow function contains + exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return func; } @@ -73194,18 +73145,16 @@ var ts; */ function visitFunctionExpression(node) { var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ - ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionExpression(node, /*modifiers*/ undefined, node.asteriskToken, name, @@ -73220,15 +73169,13 @@ var ts; function visitFunctionDeclaration(node) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionDeclaration(node, /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, @@ -73246,14 +73193,14 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) - ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { + if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( /*modifiers*/ undefined, node.asteriskToken, name, @@ -73271,7 +73218,7 @@ var ts; var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; - var leadingStatements = []; + var prologue = []; var statements = []; var body = node.body; var statementOffset; @@ -73279,14 +73226,13 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false); } - addCaptureThisForNodeIfNeeded(leadingStatements, node); - addDefaultValueAssignmentsIfNeeded(leadingStatements, node); - addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); + multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; + multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; if (ts.isBlock(body)) { // addCustomPrologue puts already-existing directives at the beginning of the target statement-array - statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); // If the original body was a multi-line block, this must be a multi-line block. @@ -73320,14 +73266,19 @@ var ts; // source map location for the close brace. closeBraceLocation = body; } - var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); - prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false); + insertCaptureThisForNodeIfNeeded(prologue, node); // If we added any final generated statements, this must be a multi-line block - if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + if (ts.some(prologue)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + statements.unshift.apply(statements, prologue); + if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) { + // no changes were made, preserve the tree + return body; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1 /* SingleLine */); @@ -73338,11 +73289,6 @@ var ts; ts.setOriginalNode(block, node.body); return block; } - function visitFunctionBodyDownLevel(node) { - var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); - return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), - /*location*/ updated.statements)); - } function visitBlock(node, isFunctionBody) { if (isFunctionBody) { // A function body is not a block scope. @@ -73447,7 +73393,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) { if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -73460,7 +73406,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + if (node.transformFlags & 65536 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -73782,7 +73728,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -74058,7 +74004,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = ts.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0 /* None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -74163,11 +74109,11 @@ var ts; statements.push(statement); } copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment); var loopBody = ts.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -74399,13 +74345,11 @@ var ts; * @param receiver The receiver for the assignment. */ function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { ts.startOnNewLine(expression); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return expression; } function visitCatchClause(node) { @@ -74457,19 +74401,17 @@ var ts; ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); + var body = transformFunctionBody(node); if (node.kind === 158 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return updated; } @@ -74483,10 +74425,7 @@ var ts; /*location*/ node); } function visitComputedPropertyName(node) { - var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); - var updated = ts.visitEachChild(node, visitor, context); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); - return updated; + return ts.visitEachChild(node, visitor, context); } /** * Visits a YieldExpression node. @@ -74503,7 +74442,7 @@ var ts; * @param node An ArrayLiteralExpression node. */ function visitArrayLiteralExpression(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (ts.some(node.elements, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); } @@ -74518,7 +74457,10 @@ var ts; if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { return visitTypeScriptClassWrapper(node); } - if (node.transformFlags & 64 /* ES2015 */) { + var expression = ts.skipOuterExpressions(node.expression); + if (expression.kind === 98 /* SuperKeyword */ || + ts.isSuperProperty(expression) || + ts.some(node.arguments, ts.isSpreadElement)) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), @@ -74639,7 +74581,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + if (node.transformFlags & 4096 /* ContainsRestOrSpread */ || node.expression.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -74647,7 +74589,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (node.transformFlags & 4096 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -74661,7 +74603,7 @@ var ts; // _super.apply(this, a.concat([b])) // _super.m.apply(this, a.concat([b])) // _super.prototype.m.apply(this, a.concat([b])) - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); } else { // [source] @@ -74673,13 +74615,11 @@ var ts; // _super.call(this, a) // _super.m.call(this, a) // _super.prototype.m.call(this, a) - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } if (node.expression.kind === 98 /* SuperKeyword */) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); - var initializer = ts.createLogicalOr(resultingCall, actualThis); + var initializer = ts.createLogicalOr(resultingCall, createActualThis()); resultingCall = assignToCapturedThis ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) : initializer; @@ -74694,7 +74634,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (ts.some(node.arguments, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -74957,12 +74897,7 @@ var ts; } function visitMetaProperty(node) { if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { - if (hierarchyFacts & 8192 /* ComputedPropertyName */) { - hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; - } - else { - hierarchyFacts |= 16384 /* NewTarget */; - } + hierarchyFacts |= 8192 /* NewTarget */; return ts.createFileLevelUniqueName("_newTarget"); } return node; @@ -74977,7 +74912,7 @@ var ts; function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ : 65 /* FunctionIncludes */); previousOnEmitNode(hint, node, emitCallback); @@ -75525,7 +75460,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -75545,10 +75480,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 256 /* Generator */) { + else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512 /* ContainsGenerator */) { + else if (transformFlags & 256 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -75601,10 +75536,10 @@ var ts; case 230 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -75780,7 +75715,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -75807,7 +75742,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -76865,7 +76800,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -77984,7 +77919,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 16777216 /* ContainsDynamicImport */ || + node.transformFlags & 524288 /* ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } @@ -78021,7 +77956,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -78247,7 +78182,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -78321,13 +78256,13 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + else if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else { @@ -78388,7 +78323,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -79353,7 +79288,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -79519,7 +79454,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -80431,14 +80366,13 @@ var ts; * @param node The node to visit. */ function destructuringAndImportCallVisitor(node) { - if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 204 /* BinaryExpression */) { + if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -92681,22 +92615,18 @@ var ts; var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics()); - var reportSemanticDiagnostics = false; // If we didn't have any syntactic errors, then also try getting the global and // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics()); ts.addRange(diagnostics, program.getGlobalDiagnostics()); if (diagnostics.length === configFileParsingDiagnosticsLength) { - reportSemanticDiagnostics = true; + ts.addRange(diagnostics, program.getSemanticDiagnostics()); } } // Emit and report any errors we ran into. var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); - if (reportSemanticDiagnostics) { - ts.addRange(diagnostics, program.getSemanticDiagnostics()); - } ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); if (writeFileName) { var currentDir_1 = program.getCurrentDirectory(); @@ -92817,6 +92747,22 @@ var ts; } } ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; + function setCreateSourceFileAsHashVersioned(compilerHost, host) { + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + ts.setCreateSourceFileAsHashVersioned = setCreateSourceFileAsHashVersioned; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -92891,6 +92837,23 @@ var ts; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; + function readBuilderProgram(compilerOptions, readFile) { + if (compilerOptions.out || compilerOptions.outFile) + return undefined; + var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions); + if (!buildInfoPath) + return undefined; + var content = readFile(buildInfoPath); + if (!content) + return undefined; + var buildInfo = ts.getBuildInfo(content); + if (buildInfo.version !== ts.version) + return undefined; + if (!buildInfo.program) + return undefined; + return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + } + ts.readBuilderProgram = readBuilderProgram; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -92902,7 +92865,6 @@ var ts; } } ts.createWatchCompilerHost = createWatchCompilerHost; - var initialVersion = 1; function createWatchProgram(host) { var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc @@ -92943,10 +92905,12 @@ var ts; var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + var configFileWatcher; if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); + configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); } var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); // Members for CompilerHost var getNewSourceFile = compilerHost.getSourceFile; compilerHost.getSourceFile = function (fileName) { @@ -92987,21 +92951,43 @@ var ts; (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); }); synchronizeProgram(); // Update the wild card directory watch watchConfigFileWildCardDirectories(); return configFileName ? - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close }; + function close() { + resolutionCache.clear(); + ts.clearMap(sourceFilesCache, function (value) { + if (value && value.fileWatcher) { + value.fileWatcher.close(); + value.fileWatcher = undefined; + } + }); + if (configFileWatcher) { + configFileWatcher.close(); + configFileWatcher = undefined; + } + if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + watchedWildcardDirectories = undefined; + } + if (missingFilesMap) { + ts.clearMap(missingFilesMap, ts.closeFileWatcher); + missingFilesMap = undefined; + } + } function getCurrentBuilderProgram() { return builderProgram; } function getCurrentProgram() { - return builderProgram && builderProgram.getProgram(); + return builderProgram && builderProgram.getProgramOrUndefined(); } function synchronizeProgram() { writeLog("Synchronizing program"); - var program = getCurrentProgram(); + var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { @@ -93017,19 +93003,19 @@ var ts; } } else { - createNewProgram(program, hasInvalidatedResolution); + createNewProgram(hasInvalidatedResolution); } if (host.afterProgramCreate) { host.afterProgramCreate(builderProgram); } return builderProgram; } - function createNewProgram(program, hasInvalidatedResolution) { + function createNewProgram(hasInvalidatedResolution) { // Compile the program writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); - var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); @@ -93069,10 +93055,10 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function isFileMissingOnHost(hostSourceFile) { - return typeof hostSourceFile === "number"; + return typeof hostSourceFile === "boolean"; } - function isFilePresentOnHost(hostSourceFile) { - return !!hostSourceFile.sourceFile; + function isFilePresenceUnknownOnHost(hostSourceFile) { + return typeof hostSourceFile.version === "boolean"; } function fileExists(fileName) { var path = toPath(fileName); @@ -93090,36 +93076,32 @@ var ts; return undefined; } // Create new source file if requested or the versions dont match - if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) { var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { - if (shouldCreateNewSourceFile) { - hostSourceFile.version++; - } if (sourceFile) { // Set the source file and create file watcher now that file was present on the disk hostSourceFile.sourceFile = sourceFile; - sourceFile.version = hostSourceFile.version.toString(); + hostSourceFile.version = sourceFile.version; if (!hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); } } else { // There is no source file on host any more, close the watch, missing file paths will track it - if (isFilePresentOnHost(hostSourceFile)) { + if (hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher.close(); } - sourceFilesCache.set(path, hostSourceFile.version); + sourceFilesCache.set(path, false); } } else { if (sourceFile) { - sourceFile.version = initialVersion.toString(); var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); - sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher }); } else { - sourceFilesCache.set(path, initialVersion); + sourceFilesCache.set(path, false); } } return sourceFile; @@ -93131,16 +93113,16 @@ var ts; if (hostSourceFile !== undefined) { if (isFileMissingOnHost(hostSourceFile)) { // The next version, lets set it as presence unknown file - sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + sourceFilesCache.set(path, { version: false }); } else { - hostSourceFile.version++; + hostSourceFile.version = false; } } } function getSourceVersion(path) { var hostSourceFile = sourceFilesCache.get(path); - return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version; } function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); @@ -93148,7 +93130,7 @@ var ts; // remove the cached entry. // Note we arent deleting entry if file became missing in new program or // there was version update and new source file was created. - if (hostSourceFileInfo) { + if (hostSourceFileInfo !== undefined) { // record the missing file paths so they can be removed later if watchers arent tracking them if (isFileMissingOnHost(hostSourceFileInfo)) { (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); @@ -93237,7 +93219,7 @@ var ts; function onSourceFileChange(fileName, eventKind, path) { updateCachedSystemWithFile(fileName, path, eventKind); // Update the source file cache - if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); @@ -93515,19 +93497,7 @@ var ts; var readFileWithCache = function (f) { return host.readFile(f); }; var projectCompilerOptions = baseCompilerOptions; var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); - var originalGetSourceFile = compilerHost.getSourceFile; - var computeHash = host.createHash || ts.generateDjb2Hash; - compilerHost.getSourceFile = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); - if (result) { - result.version = computeHash.call(host, result.text); - } - return result; - }; + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); var buildInfoChecked = createFileMap(toPath); // Watch state var builderPrograms = createFileMap(toPath); @@ -94194,16 +94164,7 @@ var ts; var value = builderPrograms.getValue(proj); if (value) return value; - var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options); - if (!buildInfoPath) - return undefined; - var content = readFileWithCache(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); - if (buildInfo.version !== ts.version) - return undefined; - return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + return ts.readBuilderProgram(parsed.options, readFileWithCache); } function updateBundle(proj) { if (options.dry) { @@ -104961,7 +104922,7 @@ var ts; function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); - var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); + var jsxElementsPresent = !!(sourceFile.transformFlags & 2 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { var importDecl = oldImports_1[_i]; @@ -119019,7 +118980,7 @@ var ts; var movedSymbols = new SymbolSet(); var oldImportsNeededByNewFile = new SymbolSet(); var newFileImportsFromOldFile = new SymbolSet(); - var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 4 /* ContainsJsx */); }); + var containsJsx = ts.find(toMove, function (statement) { return !!(statement.transformFlags & 2 /* ContainsJsx */); }); var jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); if (jsxNamespaceSymbol) { // Might not exist (e.g. in non-compiling code) oldImportsNeededByNewFile.add(jsxNamespaceSymbol); @@ -119053,7 +119014,7 @@ var ts; if (ts.contains(toMove, statement)) continue; // jsxNamespaceSymbol will only be set iff it is in oldImportsNeededByNewFile. - if (jsxNamespaceSymbol && !!(statement.transformFlags & 4 /* ContainsJsx */)) { + if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { unusedImportsFromOldFile.delete(jsxNamespaceSymbol); } forEachReference(statement, checker, function (symbol) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index f655e83d649..5951fd86199 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -3845,75 +3845,69 @@ var ts; TransformFlags[TransformFlags["None"] = 0] = "None"; // Facts // - Flags used to indicate that a node or subtree contains syntax that requires transformation. - TransformFlags[TransformFlags["TypeScript"] = 1] = "TypeScript"; - TransformFlags[TransformFlags["ContainsTypeScript"] = 2] = "ContainsTypeScript"; - TransformFlags[TransformFlags["ContainsJsx"] = 4] = "ContainsJsx"; - TransformFlags[TransformFlags["ContainsESNext"] = 8] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2017"] = 16] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 32] = "ContainsES2016"; - TransformFlags[TransformFlags["ES2015"] = 64] = "ES2015"; + TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; + TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; + TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; + TransformFlags[TransformFlags["ContainsES2019"] = 8] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 16] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 32] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 64] = "ContainsES2016"; TransformFlags[TransformFlags["ContainsES2015"] = 128] = "ContainsES2015"; - TransformFlags[TransformFlags["Generator"] = 256] = "Generator"; - TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator"; - TransformFlags[TransformFlags["DestructuringAssignment"] = 1024] = "DestructuringAssignment"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsGenerator"] = 256] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 512] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. - TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; - TransformFlags[TransformFlags["ContainsLexicalThis"] = 8192] = "ContainsLexicalThis"; - TransformFlags[TransformFlags["ContainsCapturedLexicalThis"] = 16384] = "ContainsCapturedLexicalThis"; - TransformFlags[TransformFlags["ContainsLexicalThisInComputedPropertyName"] = 32768] = "ContainsLexicalThisInComputedPropertyName"; - TransformFlags[TransformFlags["ContainsDefaultValueAssignments"] = 65536] = "ContainsDefaultValueAssignments"; - TransformFlags[TransformFlags["ContainsRestOrSpread"] = 131072] = "ContainsRestOrSpread"; - TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 262144] = "ContainsObjectRestOrSpread"; - TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 524288] = "ContainsComputedPropertyName"; - TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 1048576] = "ContainsBlockScopedBinding"; - TransformFlags[TransformFlags["ContainsBindingPattern"] = 2097152] = "ContainsBindingPattern"; - TransformFlags[TransformFlags["ContainsYield"] = 4194304] = "ContainsYield"; - TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 8388608] = "ContainsHoistedDeclarationOrCompletion"; - TransformFlags[TransformFlags["ContainsDynamicImport"] = 16777216] = "ContainsDynamicImport"; - TransformFlags[TransformFlags["Super"] = 33554432] = "Super"; - TransformFlags[TransformFlags["ContainsSuper"] = 67108864] = "ContainsSuper"; - TransformFlags[TransformFlags["ContainsES2018"] = 134217728] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2019"] = 268435456] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 1024] = "ContainsTypeScriptClassSyntax"; + TransformFlags[TransformFlags["ContainsLexicalThis"] = 2048] = "ContainsLexicalThis"; + TransformFlags[TransformFlags["ContainsRestOrSpread"] = 4096] = "ContainsRestOrSpread"; + TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 8192] = "ContainsObjectRestOrSpread"; + TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 16384] = "ContainsComputedPropertyName"; + TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 32768] = "ContainsBlockScopedBinding"; + TransformFlags[TransformFlags["ContainsBindingPattern"] = 65536] = "ContainsBindingPattern"; + TransformFlags[TransformFlags["ContainsYield"] = 131072] = "ContainsYield"; + TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 262144] = "ContainsHoistedDeclarationOrCompletion"; + TransformFlags[TransformFlags["ContainsDynamicImport"] = 524288] = "ContainsDynamicImport"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags"; // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. - TransformFlags[TransformFlags["AssertTypeScript"] = 3] = "AssertTypeScript"; - TransformFlags[TransformFlags["AssertJsx"] = 4] = "AssertJsx"; - TransformFlags[TransformFlags["AssertESNext"] = 8] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2019"] = 268435456] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 134217728] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 16] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 32] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; + TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; + TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; + TransformFlags[TransformFlags["AssertES2019"] = 8] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 16] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 32] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 64] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 128] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 256] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 512] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536872257] = "OuterExpressionExcludes"; - TransformFlags[TransformFlags["PropertyAccessExcludes"] = 570426689] = "PropertyAccessExcludes"; - TransformFlags[TransformFlags["NodeExcludes"] = 637535553] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 653604161] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 653620545] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 653616449] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 653616449] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 638121281] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 647001409] = "ModuleExcludes"; - TransformFlags[TransformFlags["TypeExcludes"] = -3] = "TypeExcludes"; - TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 638358849] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 637666625] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 639894849] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 637535553] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 637797697] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 637666625] = "BindingPatternExcludes"; + TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes"; + TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes"; + TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes"; + TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 537371648] = "ArrowFunctionExcludes"; + TransformFlags[TransformFlags["FunctionExcludes"] = 537373696] = "FunctionExcludes"; + TransformFlags[TransformFlags["ConstructorExcludes"] = 537372672] = "ConstructorExcludes"; + TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 537372672] = "MethodOrAccessorExcludes"; + TransformFlags[TransformFlags["PropertyExcludes"] = 536872960] = "PropertyExcludes"; + TransformFlags[TransformFlags["ClassExcludes"] = 536888320] = "ClassExcludes"; + TransformFlags[TransformFlags["ModuleExcludes"] = 537168896] = "ModuleExcludes"; + TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes"; + TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536896512] = "ObjectLiteralExcludes"; + TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536875008] = "ArrayLiteralOrCallOrNewExcludes"; + TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 536944640] = "VariableDeclarationListExcludes"; + TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes"; + TransformFlags[TransformFlags["CatchClauseExcludes"] = 536879104] = "CatchClauseExcludes"; + TransformFlags[TransformFlags["BindingPatternExcludes"] = 536875008] = "BindingPatternExcludes"; + // Propagating flags + // - Bitmasks for flags that should propagate from a child + TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 2048] = "PropertyNamePropagatingFlags"; // Masks // - Additional bitmasks - TransformFlags[TransformFlags["ES2015FunctionSyntaxMask"] = 81920] = "ES2015FunctionSyntaxMask"; })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {})); var EmitFlags; (function (EmitFlags) { @@ -8677,10 +8671,7 @@ var ts; return !nodeIsMissing(node); } ts.nodeIsPresent = nodeIsPresent; - /** - * Prepends statements to an array while taking care of prologue directives. - */ - function addStatementsAfterPrologue(to, from) { + function insertStatementsAfterPrologue(to, from, isPrologueDirective) { if (from === undefined || from.length === 0) return to; var statementIndex = 0; @@ -8693,7 +8684,44 @@ var ts; to.splice.apply(to, [statementIndex, 0].concat(from)); return to; } - ts.addStatementsAfterPrologue = addStatementsAfterPrologue; + function insertStatementAfterPrologue(to, statement, isPrologueDirective) { + if (statement === undefined) + return to; + var statementIndex = 0; + // skip all prologue directives to insert at the correct position + for (; statementIndex < to.length; ++statementIndex) { + if (!isPrologueDirective(to[statementIndex])) { + break; + } + } + to.splice(statementIndex, 0, statement); + return to; + } + function isAnyPrologueDirective(node) { + return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */); + } + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementsAfterStandardPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isPrologueDirective); + } + ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue; + function insertStatementsAfterCustomPrologue(to, from) { + return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective); + } + ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue; + /** + * Prepends statements to an array while taking care of prologue directives. + */ + function insertStatementAfterStandardPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isPrologueDirective); + } + ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue; + function insertStatementAfterCustomPrologue(to, statement) { + return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective); + } + ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue; /** * Determine if the given comment is a triple-slash * @@ -9683,6 +9711,11 @@ var ts; } } ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression; + function isSuperOrSuperProperty(node) { + return node.kind === 98 /* SuperKeyword */ + || isSuperProperty(node); + } + ts.isSuperOrSuperProperty = isSuperOrSuperProperty; /** * Determines whether a node is a property or element access expression for `super`. */ @@ -30125,44 +30158,37 @@ var ts; ts.computeTransformFlagsForNode = computeTransformFlagsForNode; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; + var callee = ts.skipOuterExpressions(node.expression); var expression = node.expression; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */ - || (expression.transformFlags & (33554432 /* Super */ | 67108864 /* ContainsSuper */))) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; - // super property or element accesses could be inside lambdas, etc, and need a captured `this`, - // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) - if (expression.transformFlags & 67108864 /* ContainsSuper */) { - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 128 /* AssertES2015 */; + if (ts.isSuperProperty(callee)) { + transformFlags |= 2048 /* ContainsLexicalThis */; } } if (expression.kind === 92 /* ImportKeyword */) { - transformFlags |= 16777216 /* ContainsDynamicImport */; - // A dynamic 'import()' call that contains a lexical 'this' will - // require a captured 'this' when emitting down-level. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; - } + transformFlags |= 524288 /* ContainsDynamicImport */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~536875008 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30171,19 +30197,19 @@ var ts; if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 188 /* ObjectLiteralExpression */) { // Destructuring object assignments with are ES2015 syntax // and possibly ES2018 if they contain rest - transformFlags |= 134217728 /* AssertES2018 */ | 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 59 /* EqualsToken */ && leftKind === 187 /* ArrayLiteralExpression */) { // Destructuring assignments are ES2015 syntax. - transformFlags |= 192 /* AssertES2015 */ | 3072 /* AssertDestructuringAssignment */; + transformFlags |= 128 /* AssertES2015 */ | 512 /* AssertDestructuringAssignment */; } else if (operatorTokenKind === 41 /* AsteriskAsteriskToken */ || operatorTokenKind === 63 /* AsteriskAsteriskEqualsToken */) { // Exponentiation is ES2016 syntax. - transformFlags |= 32 /* AssertES2016 */; + transformFlags |= 64 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30194,147 +30220,131 @@ var ts; // syntax. if (node.questionToken || node.type - || (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) + || (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators)) || ts.isThisIdentifier(name)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) { - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; } // parameters with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & 2097152 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { - transformFlags |= 192 /* AssertES2015 */ | 65536 /* ContainsDefaultValueAssignments */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */ || initializer || dotDotDotToken) { + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* ParameterExcludes */; + return transformFlags & ~536870912 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; var expressionKind = expression.kind; - var expressionTransformFlags = expression.transformFlags; // If the node is synthesized, it means the emitter put the parentheses there, // not the user. If we didn't want them, the emitter would not have put them // there. if (expressionKind === 212 /* AsExpression */ || expressionKind === 194 /* TypeAssertionExpression */) { - transformFlags |= 3 /* AssertTypeScript */; - } - // If the expression of a ParenthesizedExpression is a destructuring assignment, - // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 1024 /* DestructuringAssignment */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* OuterExpressionExcludes */; + return transformFlags & ~536870912 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; if (ts.hasModifier(node, 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | 192 /* AssertES2015 */; + transformFlags = subtreeFlags | 128 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, computed property name, or decorator is // TypeScript syntax. // An exported declaration may be TypeScript syntax, but is handled by the visitor // for a namespace declaration. - if ((subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */) + if ((subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */) || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & 4096 /* ContainsTypeScriptClassSyntax */ + if (subtreeFlags & 1024 /* ContainsTypeScriptClassSyntax */ || node.typeParameters) { - transformFlags |= 3 /* AssertTypeScript */; - } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~638121281 /* ClassExcludes */; + return transformFlags & ~536888320 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; switch (node.token) { case 86 /* ExtendsKeyword */: // An `extends` HeritageClause is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 109 /* ImplementsKeyword */: // An `implements` HeritageClause is TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; default: ts.Debug.fail("Unexpected token for heritage clause"); break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; if (!node.variableDeclaration) { - transformFlags |= 268435456 /* AssertES2019 */; + transformFlags |= 8 /* AssertES2019 */; } else if (ts.isBindingPattern(node.variableDeclaration.name)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637797697 /* CatchClauseExcludes */; + return transformFlags & ~536879104 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the // extends clause of a class. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. if (node.typeArguments) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; // TypeScript-specific modifiers and overloads are TypeScript syntax if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* ConstructorExcludes */; + return transformFlags & ~537372672 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and // overloads are TypeScript syntax. if (node.decorators @@ -30343,21 +30353,21 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed method names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // An async method declaration is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30368,25 +30378,25 @@ var ts; || node.type || (node.name && ts.isComputedPropertyName(node.name)) // While computed accessor names aren't typescript, the TS transform must visit them to emit property declarations correctly || !node.body) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653616449 /* MethodOrAccessorExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~537372672 /* MethodOrAccessorExcludes */); } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. - var transformFlags = subtreeFlags | 3 /* AssertTypeScript */; + var transformFlags = subtreeFlags | 1 /* AssertTypeScript */; // If the PropertyDeclaration has an initializer or a computed name, we need to inform its ancestor // so that it handle the transformation. if (node.initializer || ts.isComputedPropertyName(node.name)) { - transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1024 /* ContainsTypeScriptClassSyntax */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return propagatePropertyNameFlags(node.name, transformFlags & ~536872960 /* PropertyExcludes */); } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -30395,30 +30405,24 @@ var ts; if (!body || (modifierFlags & 2 /* Ambient */)) { // An ambient declaration is TypeScript syntax. // A FunctionDeclaration without a body is an overload and is TypeScript syntax. - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { - transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (modifierFlags & 2270 /* TypeScriptModifier */ || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function declaration is ES2017 syntax. if (modifierFlags & 256 /* Async */) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } // function declarations with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If a FunctionDeclaration's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionDeclaration is generator function and is the body of a // transformed async function, then this node can be transformed to a @@ -30426,11 +30430,11 @@ var ts; // Currently we do not support transforming any other generator functions // down level. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -30439,181 +30443,161 @@ var ts; if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async function expression is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= node.asteriskToken ? 134217728 /* AssertES2018 */ : 16 /* AssertES2017 */; + transformFlags |= node.asteriskToken ? 16 /* AssertES2018 */ : 32 /* AssertES2017 */; } // function expressions with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If a FunctionExpression's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & 81920 /* ES2015FunctionSyntaxMask */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // If a FunctionExpression is generator function and is the body of a // transformed async function, then this node can be transformed to a // down-level generator. if (node.asteriskToken) { - transformFlags |= 768 /* AssertGenerator */; + transformFlags |= 256 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653620545 /* FunctionExcludes */; + return transformFlags & ~537373696 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - var transformFlags = subtreeFlags | 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 128 /* AssertES2015 */; // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript // syntax. if (ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.typeParameters || node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } // An async arrow function is ES2017 syntax. if (ts.hasModifier(node, 256 /* Async */)) { - transformFlags |= 16 /* AssertES2017 */; + transformFlags |= 32 /* AssertES2017 */; } // arrow functions with object rest destructuring are ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; - } - // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - transformFlags |= 16384 /* ContainsCapturedLexicalThis */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~653604161 /* ArrowFunctionExcludes */; + return transformFlags & ~537371648 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (transformFlags & 33554432 /* Super */) { - transformFlags ^= 33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). // same for super inside of an async generator, which is ES2018. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 134217728 /* ContainsES2018 */; + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeElementAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing // If an ElementAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionFlags & 33554432 /* Super */) { - transformFlags &= ~33554432 /* Super */; + if (node.expression.kind === 98 /* SuperKeyword */) { // super inside of an async function requires hoisting the super access (ES2017). // same for super inside of an async generator, which is ES2018. - transformFlags |= 67108864 /* ContainsSuper */ | 16 /* ContainsES2017 */ | 134217728 /* ContainsES2018 */; + transformFlags |= 32 /* ContainsES2017 */ | 16 /* ContainsES2018 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~570426689 /* PropertyAccessExcludes */; + return transformFlags & ~536870912 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally? // A VariableDeclaration containing ObjectRest is ES2018 syntax - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */; + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */; } // Type annotations are TypeScript syntax. if (node.type) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; var declarationListTransformFlags = node.declarationList.transformFlags; // An ambient declaration is TypeScript syntax. if (ts.hasModifier(node, 2 /* Ambient */)) { - transformFlags = 3 /* AssertTypeScript */; + transformFlags = 1 /* AssertTypeScript */; } else { transformFlags = subtreeFlags; - if (declarationListTransformFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + if (declarationListTransformFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */ + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */ && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; // An ImportEqualsDeclaration with a namespace reference is TypeScript. if (!ts.isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; - // If the expression of an expression statement is a destructuring assignment, - // then we treat the statement as ES6 so that we can indicate that we do not - // need to hold on to the right-hand side. - if (node.expression.transformFlags & 1024 /* DestructuringAssignment */) { - transformFlags |= 192 /* AssertES2015 */; - } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~637535553 /* NodeExcludes */; + return transformFlags & ~536870912 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { - var transformFlags = 3 /* AssertTypeScript */; + var transformFlags = 1 /* AssertTypeScript */; var modifierFlags = ts.getModifierFlags(node); if ((modifierFlags & 2 /* Ambient */) === 0) { transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~647001409 /* ModuleExcludes */; + return transformFlags & ~537168896 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { - var transformFlags = subtreeFlags | 8388608 /* ContainsHoistedDeclarationOrCompletion */; - if (subtreeFlags & 2097152 /* ContainsBindingPattern */) { - transformFlags |= 192 /* AssertES2015 */; + var transformFlags = subtreeFlags | 262144 /* ContainsHoistedDeclarationOrCompletion */; + if (subtreeFlags & 65536 /* ContainsBindingPattern */) { + transformFlags |= 128 /* AssertES2015 */; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & 3 /* BlockScoped */) { - transformFlags |= 192 /* AssertES2015 */ | 1048576 /* ContainsBlockScopedBinding */; + transformFlags |= 128 /* AssertES2015 */ | 32768 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~639894849 /* VariableDeclarationListExcludes */; + return transformFlags & ~536944640 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 637535553 /* NodeExcludes */; + var excludeFlags = 536870912 /* NodeExcludes */; switch (kind) { case 121 /* AsyncKeyword */: case 201 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ES2018 syntax (for async generators) - transformFlags |= 134217728 /* AssertES2018 */ | 16 /* AssertES2017 */; + transformFlags |= 16 /* AssertES2018 */ | 32 /* AssertES2017 */; break; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: case 313 /* PartiallyEmittedExpression */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; + transformFlags |= 1 /* AssertTypeScript */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; break; case 115 /* PublicKeyword */: case 113 /* PrivateKeyword */: @@ -30626,7 +30610,7 @@ var ts; case 213 /* NonNullExpression */: case 133 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */; + transformFlags |= 1 /* AssertTypeScript */; break; case 260 /* JsxElement */: case 261 /* JsxSelfClosingElement */: @@ -30641,7 +30625,7 @@ var ts; case 269 /* JsxSpreadAttribute */: case 270 /* JsxExpression */: // These nodes are Jsx syntax. - transformFlags |= 4 /* AssertJsx */; + transformFlags |= 2 /* AssertJsx */; break; case 14 /* NoSubstitutionTemplateLiteral */: case 15 /* TemplateHead */: @@ -30653,32 +30637,32 @@ var ts; case 116 /* StaticKeyword */: case 214 /* MetaProperty */: // These nodes are ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 10 /* StringLiteral */: if (node.hasExtendedUnicodeEscape) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 8 /* NumericLiteral */: if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) { - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } break; case 9 /* BigIntLiteral */: - transformFlags |= 8 /* AssertESNext */; + transformFlags |= 4 /* AssertESNext */; break; case 227 /* ForOfStatement */: // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of). if (node.awaitModifier) { - transformFlags |= 134217728 /* AssertES2018 */; + transformFlags |= 16 /* AssertES2018 */; } - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; break; case 207 /* YieldExpression */: // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async // generator). - transformFlags |= 134217728 /* AssertES2018 */ | 192 /* AssertES2015 */ | 4194304 /* ContainsYield */; + transformFlags |= 16 /* AssertES2018 */ | 128 /* AssertES2015 */ | 131072 /* ContainsYield */; break; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: @@ -30719,115 +30703,93 @@ var ts; case 182 /* LiteralType */: case 247 /* NamespaceExportDeclaration */: // Types and signatures are TypeScript syntax, and exclude all other facts. - transformFlags = 3 /* AssertTypeScript */; - excludeFlags = -3 /* TypeExcludes */; + transformFlags = 1 /* AssertTypeScript */; + excludeFlags = -2 /* TypeExcludes */; break; case 149 /* ComputedPropertyName */: // Even though computed property names are ES6, we don't treat them as such. // This is so that they can flow through PropertyName transforms unaffected. // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= 524288 /* ContainsComputedPropertyName */; - if (subtreeFlags & 8192 /* ContainsLexicalThis */) { - // A computed method name like `[this.getName()](x: string) { ... }` needs to - // distinguish itself from the normal case of a method body containing `this`: - // `this` inside a method doesn't need to be rewritten (the method provides `this`), - // whereas `this` inside a computed name *might* need to be rewritten if the class/object - // is inside an arrow function: - // `_this = this; () => class K { [_this.getName()]() { ... } }` - // To make this distinction, use ContainsLexicalThisInComputedPropertyName - // instead of ContainsLexicalThis for computed property names - transformFlags |= 32768 /* ContainsLexicalThisInComputedPropertyName */; - } + transformFlags |= 16384 /* ContainsComputedPropertyName */; break; case 208 /* SpreadElement */: - transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 4096 /* ContainsRestOrSpread */; break; case 277 /* SpreadAssignment */: - transformFlags |= 134217728 /* AssertES2018 */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; break; case 98 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */ | 33554432 /* Super */; - excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` + transformFlags |= 128 /* AssertES2015 */; + excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 100 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= 8192 /* ContainsLexicalThis */; + transformFlags |= 2048 /* ContainsLexicalThis */; break; case 184 /* ObjectBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - transformFlags |= 134217728 /* AssertES2018 */ | 262144 /* ContainsObjectRestOrSpread */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + if (subtreeFlags & 4096 /* ContainsRestOrSpread */) { + transformFlags |= 16 /* AssertES2018 */ | 8192 /* ContainsObjectRestOrSpread */; } - excludeFlags = 637666625 /* BindingPatternExcludes */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 185 /* ArrayBindingPattern */: - transformFlags |= 192 /* AssertES2015 */ | 2097152 /* ContainsBindingPattern */; - excludeFlags = 637666625 /* BindingPatternExcludes */; + transformFlags |= 128 /* AssertES2015 */ | 65536 /* ContainsBindingPattern */; + excludeFlags = 536875008 /* BindingPatternExcludes */; break; case 186 /* BindingElement */: - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; if (node.dotDotDotToken) { - transformFlags |= 131072 /* ContainsRestOrSpread */; + transformFlags |= 4096 /* ContainsRestOrSpread */; } break; case 152 /* Decorator */: // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsTypeScriptClassSyntax */; + transformFlags |= 1 /* AssertTypeScript */ | 1024 /* ContainsTypeScriptClassSyntax */; break; case 188 /* ObjectLiteralExpression */: - excludeFlags = 638358849 /* ObjectLiteralExcludes */; - if (subtreeFlags & 524288 /* ContainsComputedPropertyName */) { + excludeFlags = 536896512 /* ObjectLiteralExcludes */; + if (subtreeFlags & 16384 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 128 /* AssertES2015 */; } - if (subtreeFlags & 32768 /* ContainsLexicalThisInComputedPropertyName */) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= 8192 /* ContainsLexicalThis */; - } - if (subtreeFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (subtreeFlags & 8192 /* ContainsObjectRestOrSpread */) { // If an ObjectLiteralExpression contains a spread element, then it // is an ES2018 node. - transformFlags |= 134217728 /* AssertES2018 */; + transformFlags |= 16 /* AssertES2018 */; } break; case 187 /* ArrayLiteralExpression */: - case 192 /* NewExpression */: - excludeFlags = 637666625 /* ArrayLiteralOrCallOrNewExcludes */; - if (subtreeFlags & 131072 /* ContainsRestOrSpread */) { - // If the this node contains a SpreadExpression, then it is an ES6 - // node. - transformFlags |= 192 /* AssertES2015 */; - } + excludeFlags = 536875008 /* ArrayLiteralOrCallOrNewExcludes */; break; case 223 /* DoStatement */: case 224 /* WhileStatement */: case 225 /* ForStatement */: case 226 /* ForInStatement */: // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & 1048576 /* ContainsBlockScopedBinding */) { - transformFlags |= 192 /* AssertES2015 */; + if (subtreeFlags & 32768 /* ContainsBlockScopedBinding */) { + transformFlags |= 128 /* AssertES2015 */; } break; case 284 /* SourceFile */: - if (subtreeFlags & 16384 /* ContainsCapturedLexicalThis */) { - transformFlags |= 192 /* AssertES2015 */; - } break; case 230 /* ReturnStatement */: // Return statements may require an `await` in ES2018. - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */ | 134217728 /* AssertES2018 */; + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */ | 16 /* AssertES2018 */; break; case 228 /* ContinueStatement */: case 229 /* BreakStatement */: - transformFlags |= 8388608 /* ContainsHoistedDeclarationOrCompletion */; + transformFlags |= 262144 /* ContainsHoistedDeclarationOrCompletion */; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; return transformFlags & ~excludeFlags; } + function propagatePropertyNameFlags(node, transformFlags) { + return transformFlags | (node.transformFlags & 2048 /* PropertyNamePropagatingFlags */); + } /** * Gets the transform flags to exclude when unioning the transform flags of a subtree. * @@ -30837,33 +30799,33 @@ var ts; */ function getTransformFlagsSubtreeExclusions(kind) { if (kind >= 163 /* FirstTypeNode */ && kind <= 183 /* LastTypeNode */) { - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; } switch (kind) { case 191 /* CallExpression */: case 192 /* NewExpression */: case 187 /* ArrayLiteralExpression */: - return 637666625 /* ArrayLiteralOrCallOrNewExcludes */; + return 536875008 /* ArrayLiteralOrCallOrNewExcludes */; case 244 /* ModuleDeclaration */: - return 647001409 /* ModuleExcludes */; + return 537168896 /* ModuleExcludes */; case 151 /* Parameter */: - return 637535553 /* ParameterExcludes */; + return 536870912 /* ParameterExcludes */; case 197 /* ArrowFunction */: - return 653604161 /* ArrowFunctionExcludes */; + return 537371648 /* ArrowFunctionExcludes */; case 196 /* FunctionExpression */: case 239 /* FunctionDeclaration */: - return 653620545 /* FunctionExcludes */; + return 537373696 /* FunctionExcludes */; case 238 /* VariableDeclarationList */: - return 639894849 /* VariableDeclarationListExcludes */; + return 536944640 /* VariableDeclarationListExcludes */; case 240 /* ClassDeclaration */: case 209 /* ClassExpression */: - return 638121281 /* ClassExcludes */; + return 536888320 /* ClassExcludes */; case 157 /* Constructor */: - return 653616449 /* ConstructorExcludes */; + return 537372672 /* ConstructorExcludes */; case 156 /* MethodDeclaration */: case 158 /* GetAccessor */: case 159 /* SetAccessor */: - return 653616449 /* MethodOrAccessorExcludes */; + return 537372672 /* MethodOrAccessorExcludes */; case 120 /* AnyKeyword */: case 135 /* NumberKeyword */: case 146 /* BigIntKeyword */: @@ -30881,25 +30843,25 @@ var ts; case 162 /* IndexSignature */: case 241 /* InterfaceDeclaration */: case 242 /* TypeAliasDeclaration */: - return -3 /* TypeExcludes */; + return -2 /* TypeExcludes */; case 188 /* ObjectLiteralExpression */: - return 638358849 /* ObjectLiteralExcludes */; + return 536896512 /* ObjectLiteralExcludes */; case 274 /* CatchClause */: - return 637797697 /* CatchClauseExcludes */; + return 536879104 /* CatchClauseExcludes */; case 184 /* ObjectBindingPattern */: case 185 /* ArrayBindingPattern */: - return 637666625 /* BindingPatternExcludes */; + return 536875008 /* BindingPatternExcludes */; case 194 /* TypeAssertionExpression */: case 212 /* AsExpression */: case 313 /* PartiallyEmittedExpression */: case 195 /* ParenthesizedExpression */: case 98 /* SuperKeyword */: - return 536872257 /* OuterExpressionExcludes */; + return 536870912 /* OuterExpressionExcludes */; case 189 /* PropertyAccessExpression */: case 190 /* ElementAccessExpression */: - return 570426689 /* PropertyAccessExcludes */; + return 536870912 /* PropertyAccessExcludes */; default: - return 637535553 /* NodeExcludes */; + return 536870912 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -31444,6 +31406,7 @@ var ts; var intersectionTypes = ts.createMap(); var literalTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); + var conditionalTypes = ts.createMap(); var evolvingArrayTypes = []; var undefinedProperties = ts.createMap(); var unknownSymbol = createSymbol(4 /* Property */, "unknown"); @@ -37972,15 +37935,24 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } + function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { + var rootTrueType = root.trueType; + var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) + ? rootTrueType + : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 /* AnyOrUnknown */ + ? rootTrueType.typeVariable + : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); + return instantiateType(rootTrueConstraint, combinedMapper || mapper); + } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { - var rootTrueType = type.root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) - ? rootTrueType - : (rootTrueType.substitute).flags & 3 /* AnyOrUnknown */ - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - type.resolvedDefaultConstraint = getUnionType([instantiateType(rootTrueConstraint, type.combinedMapper || type.mapper), getFalseTypeFromConditionalType(type)]); + // An `any` branch of a conditional type would normally be viral - specifically, without special handling here, + // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to + // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type, + // in effect treating `any` like `never` rather than `unknown` in this location. + var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); + var falseConstraint = getFalseTypeFromConditionalType(type); + type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; } @@ -37990,7 +37962,13 @@ var ts; // with its constraint. We do this because if the constraint is a union type it will be distributed // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T' // removes 'undefined' from T. - if (type.root.isDistributive) { + // We skip returning a distributive constraint for a restrictive instantiation of a conditional type + // as the constraint for all type params (check type included) have been replace with `unknown`, which + // is going to produce even more false positive/negative results than the distribute constraint already does. + // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter + // a union - once negated types exist and are applied to the conditional false branch, this "constraint" + // likely doesn't need to exist. + if (type.root.isDistributive && type.restrictiveInstantiation !== type) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; if (constraint && constraint !== type.checkType) { @@ -40383,12 +40361,47 @@ var ts; function getActualTypeVariable(type) { return type.flags & 33554432 /* Substitution */ ? type.typeVariable : type; } + /** + * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent + */ + function isIntersectionEmpty(type1, type2) { + return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */); + } function getConditionalType(root, mapper) { var checkType = instantiateType(root.checkType, mapper); var extendsType = instantiateType(root.extendsType, mapper); if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } + var trueType = instantiateType(root.trueType, mapper); + var falseType = instantiateType(root.falseType, mapper); + var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; + } + var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); + conditionalTypes.set(instantiationId, newResult); + return newResult; + } + function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) { + // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`. + if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { + if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return getDefaultConstraintOfTrueBranchOfConditionalType(root, /*combinedMapper*/ undefined, mapper); + } + else if (isIntersectionEmpty(checkType, extendsType)) { // Always false + return neverType; + } + } + else if (trueType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(falseType), getActualTypeVariable(checkType))) { + if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true + return neverType; + } + else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false + return falseType; // TODO: Intersect negated `extends` type here + } + } var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); var combinedMapper; if (root.inferTypeParameters) { @@ -40406,18 +40419,18 @@ var ts; // We attempt to resolve the conditional type only when the check and extends types are non-generic if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */)) { if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { - return instantiateType(root.trueType, mapper); + return trueType; } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { - return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); + return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), falseType]); } // Return falseType for a definitely false extends check. We check an instantiations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instantiations will be and we can just return the false branch type. if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { - return instantiateType(root.falseType, mapper); + return falseType; } // Return trueType for a definitely true extends check. We check instantiations of the two // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter @@ -40436,6 +40449,10 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; + if (!combinedMapper) { + result.resolvedTrueType = trueType; + result.resolvedFalseType = falseType; + } result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; @@ -41340,8 +41357,20 @@ var ts; type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); } function getRestrictiveInstantiation(type) { - return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : - type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); + if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) { + return type; + } + if (type.restrictiveInstantiation) { + return type.restrictiveInstantiation; + } + type.restrictiveInstantiation = instantiateType(type, restrictiveMapper); + // We set the following so we don't attempt to set the restrictive instance of a restrictive instance + // which is redundant - we'll produce new type identities, but all type params have already been mapped. + // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint" + // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters + // are constrained to `unknown` and produce tons of false positives/negatives! + type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation; + return type.restrictiveInstantiation; } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -42886,16 +42915,26 @@ var ts; template.indexType === getTypeParameterFromMappedType(target)) { return -1 /* True */; } - // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. - if (!isGenericMappedType(source) && isRelatedTo(getConstraintTypeFromMappedType(target), getIndexType(source))) { - var indexedAccessType = getIndexedAccessType(source, getTypeParameterFromMappedType(target)); - var templateType = getTemplateTypeFromMappedType(target); - if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { - return result; + if (!isGenericMappedType(source)) { + var targetConstraint = getConstraintTypeFromMappedType(target); + var sourceKeys_1 = getIndexType(source); + var hasOptionalUnionKeys = modifiers & 4 /* IncludeOptional */ && targetConstraint.flags & 1048576 /* Union */; + var filteredByApplicability = hasOptionalUnionKeys ? filterType(targetConstraint, function (t) { return !!isRelatedTo(t, sourceKeys_1); }) : undefined; + // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X. + // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X. + if (hasOptionalUnionKeys + ? !(filteredByApplicability.flags & 131072 /* Never */) + : isRelatedTo(targetConstraint, sourceKeys_1)) { + var indexingType = hasOptionalUnionKeys ? filteredByApplicability : getTypeParameterFromMappedType(target); + var indexedAccessType = getIndexedAccessType(source, indexingType); + var templateType = getTemplateTypeFromMappedType(target); + if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) { + return result; + } } + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; } - originalErrorInfo = errorInfo; - errorInfo = saveErrorInfo; } } if (source.flags & 8650752 /* TypeVariable */) { @@ -44571,6 +44610,7 @@ var ts; if (inference.priority === undefined || priority < inference.priority) { inference.candidates = undefined; inference.contraCandidates = undefined; + inference.topLevel = true; inference.priority = priority; } if (priority === inference.priority) { @@ -65592,8 +65632,8 @@ var ts; return statements; } return ts.isNodeArray(statements) - ? ts.setTextRange(ts.createNodeArray(ts.addStatementsAfterPrologue(statements.slice(), declarations)), statements) - : ts.addStatementsAfterPrologue(statements, declarations); + ? ts.setTextRange(ts.createNodeArray(ts.insertStatementsAfterStandardPrologue(statements.slice(), declarations)), statements) + : ts.insertStatementsAfterStandardPrologue(statements, declarations); } ts.mergeLexicalEnvironment = mergeLexicalEnvironment; /** @@ -66867,8 +66907,8 @@ var ts; if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) { var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element); if (flattenContext.level >= 1 /* ObjectRest */ - && !(element.transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) - && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (131072 /* ContainsRestOrSpread */ | 262144 /* ContainsObjectRestOrSpread */)) + && !(element.transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) + && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (4096 /* ContainsRestOrSpread */ | 8192 /* ContainsObjectRestOrSpread */)) && !ts.isComputedPropertyName(propertyName)) { bindingElements = ts.append(bindingElements, element); } @@ -66934,7 +66974,7 @@ var ts; if (flattenContext.level >= 1 /* 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 & 262144 /* ContainsObjectRestOrSpread */) { + if (element.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); if (flattenContext.hoistTempVariables) { flattenContext.context.hoistVariableDeclaration(temp); @@ -67262,14 +67302,9 @@ var ts; * @param node The node to visit. */ function visitorWorker(node) { - if (node.transformFlags & 1 /* TypeScript */) { - // This node is explicitly marked as TypeScript, so we should transform the node. + if (node.transformFlags & 1 /* ContainsTypeScript */) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -67303,7 +67338,7 @@ var ts; // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`, // and will trigger debug failures when debug verbosity is turned up - if (node.transformFlags & 2 /* ContainsTypeScript */) { + if (node.transformFlags & 1 /* ContainsTypeScript */) { // This node contains TypeScript, so we should visit its children. return ts.visitEachChild(node, visitor, context); } @@ -67345,15 +67380,9 @@ var ts; // do not emit ES6 imports and exports since they are illegal inside a namespace return undefined; } - else if (node.transformFlags & 1 /* TypeScript */ || ts.hasModifier(node, 1 /* Export */)) { - // This node is explicitly marked as TypeScript, or is exported at the namespace - // level, so we should transform the node. + else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) { return visitTypeScript(node); } - else if (node.transformFlags & 2 /* ContainsTypeScript */) { - // This node contains TypeScript, so we should visit its children. - return ts.visitEachChild(node, visitor, context); - } return node; } /** @@ -67404,7 +67433,7 @@ var ts; * @param node The node to visit. */ function visitTypeScript(node) { - if (ts.hasModifier(node, 2 /* Ambient */) && ts.isStatement(node)) { + if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) { // TypeScript ambient declarations are elided, but some comments may be preserved. // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); @@ -67471,7 +67500,7 @@ var ts; // See the implementation of `getLeadingComments` in comments.ts for more details. return ts.createNotEmittedStatement(node); case 240 /* ClassDeclaration */: - // This is a class declaration with TypeScript syntax extensions. + // This may be a class declaration with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -67482,7 +67511,7 @@ var ts; // - method overload signatures return visitClassDeclaration(node); case 209 /* ClassExpression */: - // This is a class expression with TypeScript syntax extensions. + // This may be a class expression with TypeScript syntax extensions. // // TypeScript class syntax extensions include: // - decorators @@ -67493,7 +67522,7 @@ var ts; // - method overload signatures return visitClassExpression(node); case 273 /* HeritageClause */: - // This is a heritage clause with TypeScript syntax extensions. + // This may be a heritage clause with TypeScript syntax extensions. // // TypeScript heritage clause extensions include: // - `implements` clause @@ -67521,7 +67550,7 @@ var ts; // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); case 151 /* Parameter */: - // This is a parameter declaration with TypeScript syntax extensions. + // This may be a parameter declaration with TypeScript syntax extensions. // // TypeScript parameter declaration syntax extensions include: // - decorators @@ -67562,7 +67591,8 @@ var ts; // TypeScript namespace or external module import. return visitImportEqualsDeclaration(node); default: - return ts.Debug.failBadSyntaxKind(node); + // node contains some other TypeScript syntax + return ts.visitEachChild(node, visitor, context); } } function visitSourceFile(node) { @@ -67611,18 +67641,19 @@ var ts; facts |= 128 /* UseImmediatelyInvokedFunctionExpression */; return facts; } - /** - * Transforms a class declaration with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has decorators. - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - The class is an export in a TypeScript namespace. - * - * @param node The node to transform. - */ + function hasTypeScriptClassSyntax(node) { + return !!(node.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */); + } + function isClassLikeDeclarationWithTypeScriptSyntax(node) { + return ts.some(node.decorators) + || ts.some(node.typeParameters) + || ts.some(node.heritageClauses, hasTypeScriptClassSyntax) + || ts.some(node.members, hasTypeScriptClassSyntax); + } function visitClassDeclaration(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -67675,7 +67706,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, context.endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment()); var iife = ts.createImmediatelyInvokedArrowFunction(statements); ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */); var varStatement = ts.createVariableStatement( @@ -67852,16 +67883,10 @@ var ts; ts.setCommentRange(statement, node); return statement; } - /** - * Transforms a class expression with TypeScript syntax into compatible ES6. - * - * This function will only be called when one of the following conditions are met: - * - The class has property declarations with initializers. - * - The class contains a constructor that contains parameters with accessibility modifiers. - * - * @param node The node to transform. - */ function visitClassExpression(node) { + if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) { + return ts.visitEachChild(node, visitor, context); + } var savedPendingExpressions = pendingExpressions; pendingExpressions = undefined; var staticProperties = getInitializedProperties(node, /*isStatic*/ true); @@ -67925,7 +67950,7 @@ var ts; var constructor = ts.getFirstConstructorWithBody(node); var hasInstancePropertyWithInitializer = ts.forEach(node.members, isInstanceInitializedProperty); var hasParameterPropertyAssignments = constructor && - constructor.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */ && + constructor.transformFlags & 1024 /* ContainsTypeScriptClassSyntax */ && ts.forEach(constructor.parameters, isParameterWithPropertyAssignment); // If the class does not contain nodes that require a synthesized constructor, // accept the current constructor if it exists. @@ -68970,11 +68995,11 @@ var ts; * @param node The HeritageClause to transform. */ function visitHeritageClause(node) { - if (node.token === 86 /* ExtendsKeyword */) { - var types = ts.visitNodes(node.types, visitor, ts.isExpressionWithTypeArguments, 0, 1); - return ts.setTextRange(ts.createHeritageClause(86 /* ExtendsKeyword */, types), node); + if (node.token === 109 /* ImplementsKeyword */) { + // implements clauses are elided + return undefined; } - return undefined; + return ts.visitEachChild(node, visitor, context); } /** * Transforms an ExpressionWithTypeArguments with TypeScript syntax. @@ -69010,16 +69035,6 @@ var ts; } return ts.updateConstructor(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context)); } - /** - * Visits a method declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is marked as abstract, public, private, protected, or readonly - * - The node has a computed property name - * - * @param node The method node. - */ function visitMethodDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return undefined; @@ -69046,15 +69061,6 @@ var ts; function shouldEmitAccessorDeclaration(node) { return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */)); } - /** - * Visits a get accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The get accessor node. - */ function visitGetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -69070,15 +69076,6 @@ var ts; } return updated; } - /** - * Visits a set accessor declaration of a class. - * - * This function will be called when one of the following conditions are met: - * - The node is marked as abstract, public, private, or protected - * - The node has a computed property name - * - * @param node The set accessor node. - */ function visitSetAccessor(node) { if (!shouldEmitAccessorDeclaration(node)) { return undefined; @@ -69093,16 +69090,6 @@ var ts; } return updated; } - /** - * Visits a function declaration. - * - * This function will be called when one of the following conditions are met: - * - The node is an overload - * - The node is exported from a TypeScript namespace - * - The node has decorators - * - * @param node The function node. - */ function visitFunctionDeclaration(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createNotEmittedStatement(node); @@ -69118,14 +69105,6 @@ var ts; } return updated; } - /** - * Visits a function expression node. - * - * This function will be called when one of the following conditions are met: - * - The node has type annotations - * - * @param node The function expression node. - */ function visitFunctionExpression(node) { if (!shouldEmitFunctionLikeDeclaration(node)) { return ts.createOmittedExpression(); @@ -69135,51 +69114,31 @@ var ts; /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([])); return updated; } - /** - * @remarks - * This function will be called when one of the following conditions are met: - * - The node has type annotations - */ function visitArrowFunction(node) { var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context)); return updated; } - /** - * Visits a parameter declaration node. - * - * This function will be called when one of the following conditions are met: - * - The node has an accessibility modifier. - * - The node has a questionToken. - * - The node's kind is ThisKeyword. - * - * @param node The parameter declaration node. - */ function visitParameter(node) { if (ts.parameterIsThisKeyword(node)) { return undefined; } - var parameter = ts.createParameter( + var updated = ts.updateParameter(node, /*decorators*/ undefined, /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), /*questionToken*/ undefined, /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); - // While we emit the source map for the node after skipping decorators and modifiers, - // we need to emit the comments for the original range. - ts.setOriginalNode(parameter, node); - ts.setTextRange(parameter, ts.moveRangePastModifiers(node)); - ts.setCommentRange(parameter, node); - ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - ts.setEmitFlags(parameter.name, 32 /* NoTrailingSourceMap */); - return parameter; + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + ts.setCommentRange(updated, node); + ts.setTextRange(updated, ts.moveRangePastModifiers(node)); + ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */); + } + return updated; } - /** - * Visits a variable statement in a namespace. - * - * This function will be called when one of the following conditions are met: - * - The node is exported from a TypeScript namespace. - */ function visitVariableStatement(node) { if (isExportOfNamespace(node)) { var variables = ts.getInitializedVariables(node.declarationList); @@ -69208,12 +69167,6 @@ var ts; return ts.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression)); } - /** - * Visits a parenthesized expression that contains either a type assertion or an `as` - * expression. - * - * @param node The parenthesized expression node. - */ function visitParenthesizedExpression(node) { var innerExpression = ts.skipOuterExpressions(node.expression, ~2 /* Assertions */); if (ts.isAssertionExpression(innerExpression)) { @@ -69350,7 +69303,7 @@ var ts; var statements = []; startLexicalEnvironment(); var members = ts.map(node.members, transformEnumMember); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); ts.addRange(statements, members); currentNamespaceContainerName = savedCurrentNamespaceLocalName; return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), @@ -69597,7 +69550,7 @@ var ts; var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; statementsLocation = ts.moveRangePos(moduleBlock.statements, -1); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; @@ -70152,7 +70105,7 @@ var ts; return visited; } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { @@ -70429,7 +70382,7 @@ var ts; var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.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. var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); @@ -70437,7 +70390,7 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -70731,7 +70684,7 @@ var ts; return node; } function visitorWorker(node, noDestructuringValue) { - if ((node.transformFlags & 134217728 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { @@ -70849,7 +70802,7 @@ var ts; return objects; } function visitObjectLiteralExpression(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // spread elements emit like so: // non-spread elements are chunked together into object literals, and then all are passed to __assign: // { a, ...o, b } => __assign({a}, o, {b}); @@ -70875,7 +70828,7 @@ var ts; * @param node A BinaryExpression node. */ function visitBinaryExpression(node, noDestructuringValue) { - if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue); } else if (node.operatorToken.kind === 27 /* CommaToken */) { @@ -70890,7 +70843,7 @@ var ts; */ function visitVariableDeclaration(node) { // If we are here it is because the name contains a binding pattern with a rest somewhere in it. - if (ts.isBindingPattern(node.name) && node.name.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (ts.isBindingPattern(node.name) && node.name.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */); } return ts.visitEachChild(node, visitor, context); @@ -70907,7 +70860,7 @@ var ts; * @param node A ForOfStatement. */ function visitForOfStatement(node, outermostLabeledStatement) { - if (node.initializer.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.initializer.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { node = transformForOfStatementWithObjectRest(node); } if (node.awaitModifier) { @@ -71004,7 +70957,7 @@ var ts; ])); } function visitParameter(node) { - if (node.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (node.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. return ts.updateParameter(node, @@ -71117,10 +71070,10 @@ var ts; enableSubstitutionForAsyncMethodsWithSuper(); var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.addStatementsAfterPrologue(statements, [variableStatement]); + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); } statements.push(returnStatement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.updateBlock(node.body, statements); if (emitSuperHelpers && hasSuperElementAccess) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { @@ -71146,7 +71099,7 @@ var ts; var leadingStatements = endLexicalEnvironment(); if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) { var block = ts.convertToFunctionBody(body, /*multiLine*/ true); - ts.addStatementsAfterPrologue(statements, leadingStatements); + ts.insertStatementsAfterStandardPrologue(statements, leadingStatements); ts.addRange(statements, block.statements.slice(statementOffset)); return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements)); } @@ -71155,7 +71108,7 @@ var ts; function appendObjectRestAssignmentsIfNeeded(statements, node) { for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 262144 /* ContainsObjectRestOrSpread */) { + if (parameter.transformFlags & 8192 /* ContainsObjectRestOrSpread */) { var temp = ts.getGeneratedNameForNode(parameter); var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, /*doNotRecordTempVariablesInLine*/ false, @@ -71363,7 +71316,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 268435456 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 8 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { @@ -71394,7 +71347,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsESNext */) === 0) { + if ((node.transformFlags & 4 /* ContainsESNext */) === 0) { return node; } switch (node.kind) { @@ -71427,7 +71380,7 @@ var ts; return visited; } function visitor(node) { - if (node.transformFlags & 4 /* ContainsJsx */) { + if (node.transformFlags & 2 /* ContainsJsx */) { return visitorWorker(node); } else { @@ -71929,7 +71882,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 32 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { @@ -72009,30 +71962,6 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); - var SuperCaptureResult; - (function (SuperCaptureResult) { - /** - * A capture may have been added for calls to 'super', but - * the caller should emit subsequent statements normally. - */ - SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * var _this = _super.call(...) || this; - * - * Callers should skip the current statement. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; - /** - * A call to 'super()' got replaced with a capturing statement like: - * - * return _super.call(...) || this; - * - * Callers should skip the current statement and avoid any returns of '_this'. - */ - SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; - })(SuperCaptureResult || (SuperCaptureResult = {})); // Facts we track as we traverse the tree var HierarchyFacts; (function (HierarchyFacts) { @@ -72053,12 +71982,12 @@ var ts; HierarchyFacts[HierarchyFacts["ForStatement"] = 1024] = "ForStatement"; HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 2048] = "ForInOrForOfStatement"; HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 4096] = "ConstructorWithCapturedSuper"; - HierarchyFacts[HierarchyFacts["ComputedPropertyName"] = 8192] = "ComputedPropertyName"; // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below. + // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below. // // Ancestor masks // - HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask"; + HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 8191] = "AncestorFactsMask"; // We are always in *some* kind of block scope, but only specific block-scope containers are // top-level or Blocks. HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes"; @@ -72068,16 +71997,16 @@ var ts; HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 3968] = "SourceFileExcludes"; // Functions, methods, and accessors are both new lexical scopes and new block scopes. HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes"; - HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes"; + HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 8094] = "FunctionExcludes"; HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes"; - HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes"; + HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 8086] = "AsyncFunctionBodyExcludes"; // Arrow functions are lexically scoped to their container, but are new block scopes. HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes"; - HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 16256] = "ArrowFunctionExcludes"; + HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 8064] = "ArrowFunctionExcludes"; // Constructors are both new lexical scopes and new block scopes. Constructors are also // always considered non-static members of a class. HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes"; - HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes"; + HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 8086] = "ConstructorExcludes"; // 'do' and 'while' statements are not block scopes. We track that the subtree is contained // within an IterationStatement to indicate whether the embedded statement is an // IterationStatementBlock. @@ -72095,19 +72024,17 @@ var ts; HierarchyFacts[HierarchyFacts["BlockExcludes"] = 3904] = "BlockExcludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes"; HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 4032] = "IterationStatementBlockExcludes"; - // Computed property names track subtree flags differently than their containing members. - HierarchyFacts[HierarchyFacts["ComputedPropertyNameIncludes"] = 8192] = "ComputedPropertyNameIncludes"; - HierarchyFacts[HierarchyFacts["ComputedPropertyNameExcludes"] = 0] = "ComputedPropertyNameExcludes"; // // Subtree facts // - HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget"; - HierarchyFacts[HierarchyFacts["NewTargetInComputedPropertyName"] = 32768] = "NewTargetInComputedPropertyName"; + HierarchyFacts[HierarchyFacts["NewTarget"] = 8192] = "NewTarget"; + HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 16384] = "CapturedLexicalThis"; // // Subtree masks // - HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask"; - HierarchyFacts[HierarchyFacts["PropagateNewTargetMask"] = 49152] = "PropagateNewTargetMask"; + HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -8192] = "SubtreeFactsMask"; + HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes"; + HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 24576] = "FunctionSubtreeExcludes"; })(HierarchyFacts || (HierarchyFacts = {})); function transformES2015(context) { var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; @@ -72156,7 +72083,7 @@ var ts; */ function enterSubtree(excludeFacts, includeFacts) { var ancestorFacts = hierarchyFacts; - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 8191 /* AncestorFactsMask */; return ancestorFacts; } /** @@ -72167,7 +72094,7 @@ var ts; * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated. */ function exitSubtree(ancestorFacts, excludeFacts, includeFacts) { - hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts; + hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -8192 /* SubtreeFactsMask */ | ancestorFacts; } function isReturnVoidStatementInConstructorWithCapturedSuper(node) { return (hierarchyFacts & 4096 /* ConstructorWithCapturedSuper */) !== 0 @@ -72189,12 +72116,6 @@ var ts; return node; } } - function functionBodyVisitor(node) { - if (shouldVisitNode(node)) { - return visitBlock(node, /*isFunctionBody*/ true); - } - return node; - } function callExpressionVisitor(node) { if (node.kind === 98 /* SuperKeyword */) { return visitSuperKeyword(/*isExpressionOfCall*/ true); @@ -72301,18 +72222,19 @@ var ts; } function visitSourceFile(node) { var ancestorFacts = enterSubtree(3968 /* SourceFileExcludes */, 64 /* SourceFileIncludes */); + var prologue = []; var statements = []; startLexicalEnvironment(); - var statementOffset = ts.addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false); - addCaptureThisForNodeIfNeeded(statements, node); - statementOffset = ts.addCustomPrologue(statements, node.statements, statementOffset, visitor); + var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); if (taggedTemplateStringDeclarations) { statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))); } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureThisForNodeIfNeeded(prologue, node); exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); + return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements)); } function visitSwitchStatement(node) { if (convertedLoopState !== undefined) { @@ -72352,6 +72274,9 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitThisKeyword(node) { + if (hierarchyFacts & 2 /* ArrowFunction */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; + } if (convertedLoopState) { if (hierarchyFacts & 2 /* ArrowFunction */) { // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword. @@ -72565,7 +72490,7 @@ var ts; statement.pos = closingBraceLocation.pos; ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */); statements.push(statement); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true); ts.setEmitFlags(block, 1536 /* NoComments */); return block; @@ -72593,7 +72518,7 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); + var ancestorFacts = enterSubtree(8086 /* ConstructorExcludes */, 73 /* ConstructorIncludes */); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); var constructorFunction = ts.createFunctionDeclaration( @@ -72607,7 +72532,7 @@ var ts; ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */); } statements.push(constructorFunction); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; } /** @@ -72626,6 +72551,24 @@ var ts; return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context) || []; } + function createDefaultConstructorBody(node, isDerivedClass) { + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + var statements = []; + resumeLexicalEnvironment(); + ts.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + if (isDerivedClass) { + // return _super !== null && _super.apply(this, arguments) || this; + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + } + var statementsArray = ts.createNodeArray(statements); + ts.setTextRange(statementsArray, node.members); + var block = ts.createBlock(statementsArray, /*multiLine*/ true); + ts.setTextRange(block, node); + ts.setEmitFlags(block, 1536 /* NoComments */); + return block; + } /** * Transforms the body of a constructor declaration of a class. * @@ -72636,59 +72579,137 @@ var ts; * synthesized `super` call. */ function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { - var statements = []; - resumeLexicalEnvironment(); - var statementOffset = -1; - if (hasSynthesizedSuper) { - // If a super call has already been synthesized, - // we're going to assume that we should just transform everything after that. - // The assumption is that no prior step in the pipeline has added any prologue directives. - statementOffset = 0; - } - else if (constructor) { - statementOffset = ts.addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false); - } - if (constructor) { - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); - if (!hasSynthesizedSuper) { - // If no super call has been synthesized, emit custom prologue directives. - statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); - } - ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); - } // determine whether the class is known syntactically to be a derived class (e.g. a // class that extends a value that is not syntactically known to be `null`). var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 96 /* NullKeyword */; - var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, isDerivedClass, hasSynthesizedSuper, statementOffset); - // The last statement expression was replaced. Skip it. - if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { - statementOffset++; + // When the subclass does not have a constructor, we synthesize a *default* constructor using the following + // representation: + // + // ``` + // // es2015 (source) + // class C extends Base { } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.apply(this, arguments) || this; + // } + // return C; + // })(Base); + // ``` + if (!constructor) + return createDefaultConstructorBody(node, isDerivedClass); + // The prologue will contain all leading standard and custom prologue statements added by this transform + var prologue = []; + var statements = []; + resumeLexicalEnvironment(); + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + var statementOffset = 0; + if (!hasSynthesizedSuper) + statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false); + addDefaultValueAssignmentsIfNeeded(statements, constructor); + addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + if (!hasSynthesizedSuper) + statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor); + // If the first statement is a call to `super()`, visit the statement directly + var superCallExpression; + if (hasSynthesizedSuper) { + superCallExpression = createDefaultSuperCallOrThis(); } - if (constructor) { - if (superCaptureStatus === 1 /* ReplaceSuperCapture */) { - hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + else if (isDerivedClass && statementOffset < constructor.body.statements.length) { + var firstStatement = constructor.body.statements[statementOffset]; + if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) { + superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); } - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); } - // Return `_this` unless we're sure enough that it would be pointless to add a return statement. - // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. - if (isDerivedClass - && superCaptureStatus !== 2 /* ReplaceWithReturn */ - && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { - statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + if (superCallExpression) { + hierarchyFacts |= 4096 /* ConstructorWithCapturedSuper */; + statementOffset++; // skip this statement, we will add it after visiting the rest of the body. } - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); - if (constructor) { - prependCaptureNewTargetIfNeeded(statements, constructor, /*copyOnWrite*/ false); + // visit the remaining statements + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); + if (isDerivedClass) { + if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 2048 /* ContainsLexicalThis */)) { + // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the + // following representation: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // return _super.call(this, "foo") || this; + // } + // return C; + // })(Base); + // ``` + var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); + var returnStatement = ts.createReturn(superCallExpression); + ts.setCommentRange(returnStatement, ts.getCommentRange(superCall)); + ts.setEmitFlags(superCall, 1536 /* NoComments */); + statements.push(returnStatement); + } + else { + // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor: + // + // ``` + // // es2015 (source) + // class C extends Base { + // constructor() { + // super("foo"); + // this.x = 1; + // } + // } + // + // // es5 (transformed) + // var C = (function (_super) { + // function C() { + // var _this = _super.call(this, "foo") || this; + // _this.x = 1; + // return _this; + // } + // return C; + // })(Base); + // ``` + // Since the `super()` call was the first statement, we insert the `this` capturing call to + // `super()` at the top of the list of `statements` (after any pre-existing custom prologues). + insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); + if (!isSufficientlyCoveredByReturnStatements(constructor.body)) { + statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this"))); + } + } } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), - /*location*/ constructor ? constructor.body.statements : node.members), + else { + // If a class is not derived from a base class or does not have a call to `super()`, `this` is only + // captured when necessitated by an arrow function capturing the lexical `this`: + // + // ``` + // // es2015 + // class C {} + // + // // es5 + // var C = (function () { + // function C() { + // } + // return C; + // })(); + // ``` + insertCaptureThisForNodeIfNeeded(prologue, constructor); + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), + /*location*/ constructor.body.statements), /*multiLine*/ true); - ts.setTextRange(block, constructor ? constructor.body : node); - if (!constructor) { - ts.setEmitFlags(block, 1536 /* NoComments */); - } + ts.setTextRange(block, constructor.body); return block; } /** @@ -72718,83 +72739,6 @@ var ts; } return false; } - /** - * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. - * - * @returns The new statement offset into the `statements` array. - */ - function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, isDerivedClass, hasSynthesizedSuper, statementOffset) { - // If this isn't a derived class, just capture 'this' for arrow functions if necessary. - if (!isDerivedClass) { - if (ctor) { - addCaptureThisForNodeIfNeeded(statements, ctor); - } - return 0 /* NoReplacement */; - } - // We must be here because the user didn't write a constructor - // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. - // If that's the case we can just immediately return the result of a 'super()' call. - if (!ctor) { - statements.push(ts.createReturn(createDefaultSuperCallOrThis())); - return 2 /* ReplaceWithReturn */; - } - // The constructor exists, but it and the 'super()' call it contains were generated - // for something like property initializers. - // Create a captured '_this' variable and assume it will subsequently be used. - if (hasSynthesizedSuper) { - captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); - enableSubstitutionsForCapturedThis(); - return 1 /* ReplaceSuperCapture */; - } - // Most of the time, a 'super' call will be the first real statement in a constructor body. - // In these cases, we'd like to transform these into a *single* statement instead of a declaration - // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, - // we'd get: - // - // var _this; - // _this = _super.call(...) || this; - // - // instead of - // - // var _this = _super.call(...) || this; - // - // Additionally, if the 'super()' call is the last statement, we should just avoid capturing - // entirely and immediately return the result like so: - // - // return _super.call(...) || this; - // - var firstStatement; - var superCallExpression; - var ctorStatements = ctor.body.statements; - if (statementOffset < ctorStatements.length) { - firstStatement = ctorStatements[statementOffset]; - if (firstStatement.kind === 221 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { - superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); - } - } - // Return the result if we have an immediate super() call on the last statement, - // but only if the constructor itself doesn't use 'this' elsewhere. - if (superCallExpression - && statementOffset === ctorStatements.length - 1 - && !(ctor.transformFlags & (8192 /* ContainsLexicalThis */ | 16384 /* ContainsCapturedLexicalThis */))) { - var returnStatement = ts.createReturn(superCallExpression); - if (superCallExpression.kind !== 204 /* BinaryExpression */ - || superCallExpression.left.kind !== 191 /* CallExpression */) { - ts.Debug.fail("Assumed generated super call would have form 'super.call(...) || this'."); - } - // Shift comments from the original super call to the return statement. - ts.setCommentRange(returnStatement, ts.getCommentRange(ts.setEmitFlags(superCallExpression.left, 1536 /* NoComments */))); - statements.push(returnStatement); - return 2 /* ReplaceWithReturn */; - } - // Perform the capture. - captureThisForNode(statements, ctor, superCallExpression || createActualThis()); - // If we're actually replacing the original statement, we need to signal this to the caller. - if (superCallExpression) { - return 1 /* ReplaceSuperCapture */; - } - return 0 /* NoReplacement */; - } function createActualThis() { return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */); } @@ -72840,14 +72784,9 @@ var ts; return node; } } - /** - * Gets a value indicating whether we need to add default value assignments for a - * function-like node. - * - * @param node A function-like node. - */ - function shouldAddDefaultValueAssignments(node) { - return (node.transformFlags & 65536 /* ContainsDefaultValueAssignments */) !== 0; + function hasDefaultValueOrBindingPattern(node) { + return node.initializer !== undefined + || ts.isBindingPattern(node.name); } /** * Adds statements to the body of a function-like node if it contains parameters with @@ -72857,9 +72796,10 @@ var ts; * @param node A function-like node. */ function addDefaultValueAssignmentsIfNeeded(statements, node) { - if (!shouldAddDefaultValueAssignments(node)) { - return; + if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) { + return false; } + var added = false; for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; @@ -72869,12 +72809,14 @@ var ts; continue; } if (ts.isBindingPattern(name)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer); + added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added; } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer); + added = true; } } + return added; } /** * Adds statements to the body of a function-like node for parameters with binding patterns @@ -72884,18 +72826,20 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { - var temp = ts.getGeneratedNameForNode(parameter); + function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { // In cases where a binding pattern is simply '[]' or '{}', // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { - statements.push(ts.setEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */)); + return true; } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); + return true; } + return false; } /** * Adds statements to the body of a function-like node for parameters with initializers. @@ -72905,7 +72849,7 @@ var ts; * @param name The name of the parameter. * @param initializer The initializer for the parameter. */ - function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { + function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([ ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */)) @@ -72913,7 +72857,7 @@ var ts; ts.startOnNewLine(statement); ts.setTextRange(statement, parameter); ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); - statements.push(statement); + ts.insertStatementAfterCustomPrologue(statements, statement); } /** * Gets a value indicating whether we need to add statements to handle a rest parameter. @@ -72936,9 +72880,10 @@ var ts; * synthesized call to `super` */ function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { + var prologueStatements = []; var parameter = ts.lastOrUndefined(node.parameters); if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { - return; + return false; } // `declarationName` is the name of the local declaration for the parameter. var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -72948,7 +72893,7 @@ var ts; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) @@ -72967,25 +72912,30 @@ var ts; ])); ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); - statements.push(forStatement); + prologueStatements.push(forStatement); if (parameter.name.kind !== 72 /* Identifier */) { // do the actual destructuring of the rest parameter if necessary - statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */)); } + ts.insertStatementsAfterCustomPrologue(statements, prologueStatements); + return true; } /** * Adds a statement to capture the `this` of a function declaration if it is needed. + * NOTE: This must be executed *after* the subtree has been visited. * * @param statements The statements for the new function body. * @param node A node. */ - function addCaptureThisForNodeIfNeeded(statements, node) { - if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { - captureThisForNode(statements, node, ts.createThis()); + function insertCaptureThisForNodeIfNeeded(statements, node) { + if (hierarchyFacts & 16384 /* CapturedLexicalThis */ && node.kind !== 197 /* ArrowFunction */) { + insertCaptureThisForNode(statements, node, ts.createThis()); + return true; } + return false; } - function captureThisForNode(statements, node, initializer) { + function insertCaptureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ @@ -72994,10 +72944,10 @@ var ts; ])); ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); ts.setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + ts.insertStatementAfterCustomPrologue(statements, captureThisStatement); } - function prependCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { - if (hierarchyFacts & 16384 /* NewTarget */) { + function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) { + if (hierarchyFacts & 8192 /* NewTarget */) { var newTarget = void 0; switch (node.kind) { case 197 /* ArrowFunction */: @@ -73028,10 +72978,11 @@ var ts; ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), /*type*/ undefined, newTarget) ])); + ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); if (copyOnWrite) { - return [captureNewTargetStatement].concat(statements); + statements = statements.slice(); } - statements.unshift(captureNewTargetStatement); + ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); } return statements; } @@ -73083,7 +73034,6 @@ var ts; * @param member The MethodDeclaration node. */ function transformClassMethodDeclarationToStatement(receiver, member, container) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var commentRange = ts.getCommentRange(member); var sourceMapRange = ts.getSourceMapRange(member); var memberName = ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name); @@ -73098,7 +73048,6 @@ var ts; // No source map should be emitted for this statement to align with the // old emitter. ts.setEmitFlags(statement, 48 /* NoSourceMap */); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return statement; } /** @@ -73124,7 +73073,6 @@ var ts; */ function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); // To align with source maps in the old emitter, the receiver and property name // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); @@ -73160,7 +73108,6 @@ var ts; if (startsOnNewLine) { ts.startOnNewLine(call); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return call; } /** @@ -73169,12 +73116,12 @@ var ts; * @param node An ArrowFunction node. */ function visitArrowFunction(node) { - if (node.transformFlags & 8192 /* ContainsLexicalThis */) { - enableSubstitutionsForCapturedThis(); + if (node.transformFlags & 2048 /* ContainsLexicalThis */) { + hierarchyFacts |= 16384 /* CapturedLexicalThis */; } var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16256 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); + var ancestorFacts = enterSubtree(8064 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */); var func = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -73184,7 +73131,11 @@ var ts; ts.setTextRange(func, node); ts.setOriginalNode(func, node); ts.setEmitFlags(func, 8 /* CapturesThis */); - exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */); + if (hierarchyFacts & 16384 /* CapturedLexicalThis */) { + enableSubstitutionsForCapturedThis(); + } + // If an arrow function contains + exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return func; } @@ -73195,18 +73146,16 @@ var ts; */ function visitFunctionExpression(node) { var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ - ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8086 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionExpression(node, /*modifiers*/ undefined, node.asteriskToken, name, @@ -73221,15 +73170,13 @@ var ts; function visitFunctionDeclaration(node) { var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & 64 /* ES2015 */ - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); - var name = hierarchyFacts & 16384 /* NewTarget */ + var body = transformFunctionBody(node); + var name = hierarchyFacts & 8192 /* NewTarget */ ? ts.getLocalName(node) : node.name; - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.updateFunctionDeclaration(node, /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, @@ -73247,14 +73194,14 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */) - ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) - : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + ? enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */) + : enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var parameters = ts.visitParameterList(node.parameters, visitor, context); var body = transformFunctionBody(node); - if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { + if (hierarchyFacts & 8192 /* NewTarget */ && !name && (node.kind === 239 /* FunctionDeclaration */ || node.kind === 196 /* FunctionExpression */)) { name = ts.getGeneratedNameForNode(node); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression( /*modifiers*/ undefined, node.asteriskToken, name, @@ -73272,7 +73219,7 @@ var ts; var singleLine = false; // indicates whether the block *may* be emitted as a single line var statementsLocation; var closeBraceLocation; - var leadingStatements = []; + var prologue = []; var statements = []; var body = node.body; var statementOffset; @@ -73280,14 +73227,13 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = ts.addStandardPrologue(leadingStatements, body.statements, /*ensureUseStrict*/ false); + statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false); } - addCaptureThisForNodeIfNeeded(leadingStatements, node); - addDefaultValueAssignmentsIfNeeded(leadingStatements, node); - addRestParameterIfNeeded(leadingStatements, node, /*inConstructorWithSynthesizedSuper*/ false); + multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine; + multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine; if (ts.isBlock(body)) { // addCustomPrologue puts already-existing directives at the beginning of the target statement-array - statementOffset = ts.addCustomPrologue(leadingStatements, body.statements, statementOffset, visitor); + statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor); statementsLocation = body.statements; ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset)); // If the original body was a multi-line block, this must be a multi-line block. @@ -73321,14 +73267,19 @@ var ts; // source map location for the close brace. closeBraceLocation = body; } - var lexicalEnvironment = context.endLexicalEnvironment(); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); - prependCaptureNewTargetIfNeeded(statements, node, /*copyOnWrite*/ false); + ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); + insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false); + insertCaptureThisForNodeIfNeeded(prologue, node); // If we added any final generated statements, this must be a multi-line block - if (ts.some(leadingStatements) || ts.some(lexicalEnvironment)) { + if (ts.some(prologue)) { multiLine = true; } - var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(leadingStatements.concat(statements)), statementsLocation), multiLine); + statements.unshift.apply(statements, prologue); + if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) { + // no changes were made, preserve the tree + return body; + } + var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine); ts.setTextRange(block, node.body); if (!multiLine && singleLine) { ts.setEmitFlags(block, 1 /* SingleLine */); @@ -73339,11 +73290,6 @@ var ts; ts.setOriginalNode(block, node.body); return block; } - function visitFunctionBodyDownLevel(node) { - var updated = ts.visitFunctionBody(node.body, functionBodyVisitor, context); - return ts.updateBlock(updated, ts.setTextRange(ts.createNodeArray(prependCaptureNewTargetIfNeeded(updated.statements, node, /*copyOnWrite*/ true)), - /*location*/ updated.statements)); - } function visitBlock(node, isFunctionBody) { if (isFunctionBody) { // A function body is not a block scope. @@ -73448,7 +73394,7 @@ var ts; * @param node A VariableDeclarationList node. */ function visitVariableDeclarationList(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 65536 /* ContainsBindingPattern */) { if (node.flags & 3 /* BlockScoped */) { enableSubstitutionsForBlockScopedBindings(); } @@ -73461,7 +73407,7 @@ var ts; ts.setCommentRange(declarationList, node); // If the first or last declaration is a binding pattern, we need to modify // the source map range for the declaration list. - if (node.transformFlags & 2097152 /* ContainsBindingPattern */ + if (node.transformFlags & 65536 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) { ts.setSourceMapRange(declarationList, getRangeUnion(declarations)); } @@ -73783,7 +73729,7 @@ var ts; var numInitialPropertiesWithoutYield = numProperties; for (var i = 0; i < numProperties; i++) { var property = properties[i]; - if ((property.transformFlags & 4194304 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) + if ((property.transformFlags & 131072 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */) && i < numInitialPropertiesWithoutYield) { numInitialPropertiesWithoutYield = i; } @@ -74059,7 +74005,7 @@ var ts; */ function createFunctionForInitializerOfForStatement(node, currentState) { var functionName = ts.createUniqueName("_loop_init"); - var containsYield = (node.initializer.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.initializer.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0 /* None */; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -74164,11 +74110,11 @@ var ts; statements.push(statement); } copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements); - ts.addStatementsAfterPrologue(statements, lexicalEnvironment); + ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment); var loopBody = ts.createBlock(statements, /*multiLine*/ true); if (ts.isBlock(statement)) ts.setOriginalNode(loopBody, statement); - var containsYield = (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; + var containsYield = (node.statement.transformFlags & 131072 /* ContainsYield */) !== 0; var emitFlags = 0; if (currentState.containsLexicalThis) emitFlags |= 8 /* CapturesThis */; @@ -74400,13 +74346,11 @@ var ts; * @param receiver The receiver for the assignment. */ function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) { - var ancestorFacts = enterSubtree(0 /* None */, 0 /* None */); var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container)); ts.setTextRange(expression, method); if (startsOnNewLine) { ts.startOnNewLine(expression); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 16384 /* NewTarget */ : 0 /* None */); return expression; } function visitCatchClause(node) { @@ -74458,19 +74402,17 @@ var ts; ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, 65 /* FunctionIncludes */); var updated; var parameters = ts.visitParameterList(node.parameters, visitor, context); - var body = node.transformFlags & (16384 /* ContainsCapturedLexicalThis */ | 128 /* ContainsES2015 */) - ? transformFunctionBody(node) - : visitFunctionBodyDownLevel(node); + var body = transformFunctionBody(node); if (node.kind === 158 /* GetAccessor */) { updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); } else { updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); } - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); + exitSubtree(ancestorFacts, 24576 /* FunctionSubtreeExcludes */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return updated; } @@ -74484,10 +74426,7 @@ var ts; /*location*/ node); } function visitComputedPropertyName(node) { - var ancestorFacts = enterSubtree(0 /* ComputedPropertyNameExcludes */, 8192 /* ComputedPropertyNameIncludes */); - var updated = ts.visitEachChild(node, visitor, context); - exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, hierarchyFacts & 49152 /* PropagateNewTargetMask */ ? 32768 /* NewTargetInComputedPropertyName */ : 0 /* None */); - return updated; + return ts.visitEachChild(node, visitor, context); } /** * Visits a YieldExpression node. @@ -74504,7 +74443,7 @@ var ts; * @param node An ArrayLiteralExpression node. */ function visitArrayLiteralExpression(node) { - if (node.transformFlags & 64 /* ES2015 */) { + if (ts.some(node.elements, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma); } @@ -74519,7 +74458,10 @@ var ts; if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) { return visitTypeScriptClassWrapper(node); } - if (node.transformFlags & 64 /* ES2015 */) { + var expression = ts.skipOuterExpressions(node.expression); + if (expression.kind === 98 /* SuperKeyword */ || + ts.isSuperProperty(expression) || + ts.some(node.arguments, ts.isSpreadElement)) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); } return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), @@ -74640,7 +74582,7 @@ var ts; function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. - if (node.transformFlags & 131072 /* ContainsRestOrSpread */ || + if (node.transformFlags & 4096 /* ContainsRestOrSpread */ || node.expression.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; @@ -74648,7 +74590,7 @@ var ts; ts.setEmitFlags(thisArg, 4 /* NoSubstitution */); } var resultingCall = void 0; - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (node.transformFlags & 4096 /* ContainsRestOrSpread */) { // [source] // f(...a, b) // x.m(...a, b) @@ -74662,7 +74604,7 @@ var ts; // _super.apply(this, a.concat([b])) // _super.m.apply(this, a.concat([b])) // _super.prototype.m.apply(this, a.concat([b])) - resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); } else { // [source] @@ -74674,13 +74616,11 @@ var ts; // _super.call(this, a) // _super.m.call(this, a) // _super.prototype.m.call(this, a) - resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 98 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } if (node.expression.kind === 98 /* SuperKeyword */) { - var actualThis = ts.createThis(); - ts.setEmitFlags(actualThis, 4 /* NoSubstitution */); - var initializer = ts.createLogicalOr(resultingCall, actualThis); + var initializer = ts.createLogicalOr(resultingCall, createActualThis()); resultingCall = assignToCapturedThis ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer) : initializer; @@ -74695,7 +74635,7 @@ var ts; * @param node A NewExpression node. */ function visitNewExpression(node) { - if (node.transformFlags & 131072 /* ContainsRestOrSpread */) { + if (ts.some(node.arguments, ts.isSpreadElement)) { // We are here because we contain a SpreadElementExpression. // [source] // new C(...a) @@ -74958,12 +74898,7 @@ var ts; } function visitMetaProperty(node) { if (node.keywordToken === 95 /* NewKeyword */ && node.name.escapedText === "target") { - if (hierarchyFacts & 8192 /* ComputedPropertyName */) { - hierarchyFacts |= 32768 /* NewTargetInComputedPropertyName */; - } - else { - hierarchyFacts |= 16384 /* NewTarget */; - } + hierarchyFacts |= 8192 /* NewTarget */; return ts.createFileLevelUniqueName("_newTarget"); } return node; @@ -74978,7 +74913,7 @@ var ts; function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. - var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ + var ancestorFacts = enterSubtree(8094 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */ ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */ : 65 /* FunctionIncludes */); previousOnEmitNode(hint, node, emitCallback); @@ -75526,7 +75461,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 256 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -75546,10 +75481,10 @@ var ts; else if (inGeneratorFunctionBody) { return visitJavaScriptInGeneratorFunctionBody(node); } - else if (transformFlags & 256 /* Generator */) { + else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 512 /* ContainsGenerator */) { + else if (transformFlags & 256 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -75602,10 +75537,10 @@ var ts; case 230 /* ReturnStatement */: return visitReturnStatement(node); default: - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (512 /* ContainsGenerator */ | 8388608 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (256 /* ContainsGenerator */ | 262144 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -75781,7 +75716,7 @@ var ts; var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor); transformAndEmitStatements(body.statements, statementOffset); var buildResult = build(); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); statements.push(ts.createReturn(buildResult)); // Restore previous generator state inGeneratorFunctionBody = savedInGeneratorFunctionBody; @@ -75808,7 +75743,7 @@ var ts; * @param node The node to visit. */ function visitVariableStatement(node) { - if (node.transformFlags & 4194304 /* ContainsYield */) { + if (node.transformFlags & 131072 /* ContainsYield */) { transformAndEmitVariableDeclarationList(node.declarationList); return undefined; } @@ -76866,7 +76801,7 @@ var ts; } } function containsYield(node) { - return !!node && (node.transformFlags & 4194304 /* ContainsYield */) !== 0; + return !!node && (node.transformFlags & 131072 /* ContainsYield */) !== 0; } function countInitialNodesWithoutYield(nodes) { var numNodes = nodes.length; @@ -77985,7 +77920,7 @@ var ts; function transformSourceFile(node) { if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || - node.transformFlags & 16777216 /* ContainsDynamicImport */ || + node.transformFlags & 524288 /* ContainsDynamicImport */ || (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } @@ -78022,7 +77957,7 @@ var ts; ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -78248,7 +78183,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); // End the lexical environment for the module body // and merge any new lexical declarations. - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var body = ts.createBlock(statements, /*multiLine*/ true); if (currentModuleInfo.hasExportStarsToExportValues && !compilerOptions.importHelpers) { // If we have any `export * from ...` declarations @@ -78322,13 +78257,13 @@ var ts; function moduleExpressionElementVisitor(node) { // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment, // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & 16777216 /* ContainsDynamicImport */) && !(node.transformFlags & 2048 /* ContainsDestructuringAssignment */)) { + if (!(node.transformFlags & 524288 /* ContainsDynamicImport */) && !(node.transformFlags & 512 /* ContainsDestructuringAssignment */)) { return node; } if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if (node.transformFlags & 1024 /* DestructuringAssignment */ && ts.isBinaryExpression(node)) { + else if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else { @@ -78389,7 +78324,7 @@ var ts; } function visitImportCallExpression(node) { var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor); - var containsLexicalThis = !!(node.transformFlags & 8192 /* ContainsLexicalThis */); + var containsLexicalThis = !!(node.transformFlags & 2048 /* ContainsLexicalThis */); switch (compilerOptions.module) { case ts.ModuleKind.AMD: return createImportCallExpressionAMD(argument, containsLexicalThis); @@ -79354,7 +79289,7 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { - if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 524288 /* ContainsDynamicImport */)) { return node; } var id = ts.getOriginalNodeId(node); @@ -79520,7 +79455,7 @@ var ts; // We emit hoisted variables early to align roughly with our previous emit output. // Two key differences in this approach are: // - Temporary variables will appear at the top rather than at the bottom of the file - ts.addStatementsAfterPrologue(statements, endLexicalEnvironment()); + ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment()); var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217 var moduleObject = ts.createObjectLiteral([ ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)), @@ -80432,14 +80367,13 @@ var ts; * @param node The node to visit. */ function destructuringAndImportCallVisitor(node) { - if (node.transformFlags & 1024 /* DestructuringAssignment */ - && node.kind === 204 /* BinaryExpression */) { + if (ts.isDestructuringAssignment(node)) { return visitDestructuringAssignment(node); } else if (ts.isImportCall(node)) { return visitImportCallExpression(node); } - else if ((node.transformFlags & 2048 /* ContainsDestructuringAssignment */) || (node.transformFlags & 16777216 /* ContainsDynamicImport */)) { + else if ((node.transformFlags & 512 /* ContainsDestructuringAssignment */) || (node.transformFlags & 524288 /* ContainsDynamicImport */)) { return ts.visitEachChild(node, destructuringAndImportCallVisitor, context); } else { @@ -92682,22 +92616,18 @@ var ts; var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics()); - var reportSemanticDiagnostics = false; // If we didn't have any syntactic errors, then also try getting the global and // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics()); ts.addRange(diagnostics, program.getGlobalDiagnostics()); if (diagnostics.length === configFileParsingDiagnosticsLength) { - reportSemanticDiagnostics = true; + ts.addRange(diagnostics, program.getSemanticDiagnostics()); } } // Emit and report any errors we ran into. var _a = program.emit(/*targetSourceFile*/ undefined, writeFile), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; ts.addRange(diagnostics, emitDiagnostics); - if (reportSemanticDiagnostics) { - ts.addRange(diagnostics, program.getSemanticDiagnostics()); - } ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); if (writeFileName) { var currentDir_1 = program.getCurrentDirectory(); @@ -92818,6 +92748,22 @@ var ts; } } ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; + function setCreateSourceFileAsHashVersioned(compilerHost, host) { + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + ts.setCreateSourceFileAsHashVersioned = setCreateSourceFileAsHashVersioned; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -92892,6 +92838,23 @@ var ts; return host; } ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; + function readBuilderProgram(compilerOptions, readFile) { + if (compilerOptions.out || compilerOptions.outFile) + return undefined; + var buildInfoPath = ts.getOutputPathForBuildInfo(compilerOptions); + if (!buildInfoPath) + return undefined; + var content = readFile(buildInfoPath); + if (!content) + return undefined; + var buildInfo = ts.getBuildInfo(content); + if (buildInfo.version !== ts.version) + return undefined; + if (!buildInfo.program) + return undefined; + return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + } + ts.readBuilderProgram = readBuilderProgram; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -92903,7 +92866,6 @@ var ts; } } ts.createWatchCompilerHost = createWatchCompilerHost; - var initialVersion = 1; function createWatchProgram(host) { var builderProgram; var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc @@ -92944,10 +92906,12 @@ var ts; var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); + var configFileWatcher; if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); + configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); } var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); // Members for CompilerHost var getNewSourceFile = compilerHost.getSourceFile; compilerHost.getSourceFile = function (fileName) { @@ -92988,21 +92952,43 @@ var ts; (function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }) : (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); }); var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + builderProgram = ts.readBuilderProgram(compilerOptions, function (path) { return compilerHost.readFile(path); }); synchronizeProgram(); // Update the wild card directory watch watchConfigFileWildCardDirectories(); return configFileName ? - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : - { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, close: close } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames, close: close }; + function close() { + resolutionCache.clear(); + ts.clearMap(sourceFilesCache, function (value) { + if (value && value.fileWatcher) { + value.fileWatcher.close(); + value.fileWatcher = undefined; + } + }); + if (configFileWatcher) { + configFileWatcher.close(); + configFileWatcher = undefined; + } + if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + watchedWildcardDirectories = undefined; + } + if (missingFilesMap) { + ts.clearMap(missingFilesMap, ts.closeFileWatcher); + missingFilesMap = undefined; + } + } function getCurrentBuilderProgram() { return builderProgram; } function getCurrentProgram() { - return builderProgram && builderProgram.getProgram(); + return builderProgram && builderProgram.getProgramOrUndefined(); } function synchronizeProgram() { writeLog("Synchronizing program"); - var program = getCurrentProgram(); + var program = getCurrentBuilderProgram(); if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { @@ -93018,19 +93004,19 @@ var ts; } } else { - createNewProgram(program, hasInvalidatedResolution); + createNewProgram(hasInvalidatedResolution); } if (host.afterProgramCreate) { host.afterProgramCreate(builderProgram); } return builderProgram; } - function createNewProgram(program, hasInvalidatedResolution) { + function createNewProgram(hasInvalidatedResolution) { // Compile the program writeLog("CreatingProgramWith::"); writeLog(" roots: " + JSON.stringify(rootFileNames)); writeLog(" options: " + JSON.stringify(compilerOptions)); - var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); @@ -93070,10 +93056,10 @@ var ts; return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function isFileMissingOnHost(hostSourceFile) { - return typeof hostSourceFile === "number"; + return typeof hostSourceFile === "boolean"; } - function isFilePresentOnHost(hostSourceFile) { - return !!hostSourceFile.sourceFile; + function isFilePresenceUnknownOnHost(hostSourceFile) { + return typeof hostSourceFile.version === "boolean"; } function fileExists(fileName) { var path = toPath(fileName); @@ -93091,36 +93077,32 @@ var ts; return undefined; } // Create new source file if requested or the versions dont match - if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) { var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { - if (shouldCreateNewSourceFile) { - hostSourceFile.version++; - } if (sourceFile) { // Set the source file and create file watcher now that file was present on the disk hostSourceFile.sourceFile = sourceFile; - sourceFile.version = hostSourceFile.version.toString(); + hostSourceFile.version = sourceFile.version; if (!hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); } } else { // There is no source file on host any more, close the watch, missing file paths will track it - if (isFilePresentOnHost(hostSourceFile)) { + if (hostSourceFile.fileWatcher) { hostSourceFile.fileWatcher.close(); } - sourceFilesCache.set(path, hostSourceFile.version); + sourceFilesCache.set(path, false); } } else { if (sourceFile) { - sourceFile.version = initialVersion.toString(); var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); - sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher }); } else { - sourceFilesCache.set(path, initialVersion); + sourceFilesCache.set(path, false); } } return sourceFile; @@ -93132,16 +93114,16 @@ var ts; if (hostSourceFile !== undefined) { if (isFileMissingOnHost(hostSourceFile)) { // The next version, lets set it as presence unknown file - sourceFilesCache.set(path, { version: Number(hostSourceFile) + 1 }); + sourceFilesCache.set(path, { version: false }); } else { - hostSourceFile.version++; + hostSourceFile.version = false; } } } function getSourceVersion(path) { var hostSourceFile = sourceFilesCache.get(path); - return !hostSourceFile || isFileMissingOnHost(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version; } function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) { var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath); @@ -93149,7 +93131,7 @@ var ts; // remove the cached entry. // Note we arent deleting entry if file became missing in new program or // there was version update and new source file was created. - if (hostSourceFileInfo) { + if (hostSourceFileInfo !== undefined) { // record the missing file paths so they can be removed later if watchers arent tracking them if (isFileMissingOnHost(hostSourceFileInfo)) { (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); @@ -93238,7 +93220,7 @@ var ts; function onSourceFileChange(fileName, eventKind, path) { updateCachedSystemWithFile(fileName, path, eventKind); // Update the source file cache - if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { + if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) { resolutionCache.invalidateResolutionOfFile(path); } resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); @@ -93516,19 +93498,7 @@ var ts; var readFileWithCache = function (f) { return host.readFile(f); }; var projectCompilerOptions = baseCompilerOptions; var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); - var originalGetSourceFile = compilerHost.getSourceFile; - var computeHash = host.createHash || ts.generateDjb2Hash; - compilerHost.getSourceFile = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); - if (result) { - result.version = computeHash.call(host, result.text); - } - return result; - }; + ts.setCreateSourceFileAsHashVersioned(compilerHost, host); var buildInfoChecked = createFileMap(toPath); // Watch state var builderPrograms = createFileMap(toPath); @@ -94195,16 +94165,7 @@ var ts; var value = builderPrograms.getValue(proj); if (value) return value; - var buildInfoPath = ts.getOutputPathForBuildInfo(parsed.options); - if (!buildInfoPath) - return undefined; - var content = readFileWithCache(buildInfoPath); - if (!content) - return undefined; - var buildInfo = ts.getBuildInfo(content); - if (buildInfo.version !== ts.version) - return undefined; - return buildInfo.program && ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); + return ts.readBuilderProgram(parsed.options, readFileWithCache); } function updateBundle(proj) { if (options.dry) { From f8ec54c22330b991aa744d1dca1308f2a792d2ae Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 8 Mar 2019 16:52:07 -0800 Subject: [PATCH 7/7] Rename setGetSourceFileAsHashVersioned --- src/compiler/tsbuild.ts | 2 +- src/compiler/watch.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 20e7101fcd8..7afa7eb9730 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -451,7 +451,7 @@ namespace ts { let readFileWithCache = (f: string) => host.readFile(f); let projectCompilerOptions = baseCompilerOptions; const compilerHost = createCompilerHostFromProgramHost(host, () => projectCompilerOptions); - setCreateSourceFileAsHashVersioned(compilerHost, host); + setGetSourceFileAsHashVersioned(compilerHost, host); const buildInfoChecked = createFileMap(toPath); diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index c01174f685b..1ad73c19382 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -275,7 +275,7 @@ namespace ts { } } - export function setCreateSourceFileAsHashVersioned(compilerHost: CompilerHost, host: ProgramHost) { + export function setGetSourceFileAsHashVersioned(compilerHost: CompilerHost, host: ProgramHost) { const originalGetSourceFile = compilerHost.getSourceFile; const computeHash = host.createHash || generateDjb2Hash; compilerHost.getSourceFile = (...args) => { @@ -619,7 +619,7 @@ namespace ts { } const compilerHost = createCompilerHostFromProgramHost(host, () => compilerOptions, directoryStructureHost) as CompilerHost & ResolutionCacheHost; - setCreateSourceFileAsHashVersioned(compilerHost, host); + setGetSourceFileAsHashVersioned(compilerHost, host); // Members for CompilerHost const getNewSourceFile = compilerHost.getSourceFile; compilerHost.getSourceFile = (fileName, ...args) => getVersionedSourceFileByPath(fileName, toPath(fileName), ...args);