Merge remote-tracking branch 'origin/main' into fix/spread-expr-iife-return-assigned-to-pattern

This commit is contained in:
Mateusz Burzyński
2022-07-16 09:34:33 +02:00
407 changed files with 12902 additions and 5311 deletions
+4
View File
@@ -148,6 +148,10 @@ The files in `lib/` are used to bootstrap compilation and usually **should not**
The files `src/lib/dom.generated.d.ts` and `src/lib/webworker.generated.d.ts` both represent type declarations for the DOM and are auto-generated. To make any modifications to them, you will have to direct changes to https://github.com/Microsoft/TSJS-lib-generator
## Documentation on TypeScript Compiler
If you need a head start understanding how the compiler works, or how the code in different parts of the compiler works, there is a separate repo: [TypeScript Compiler Notes](https://github.com/microsoft/TypeScript-Compiler-Notes). As the name implies, it contains notes understood by different engineers about different parts of the compiler.
## Running the Tests
To run all tests, invoke the `runtests-parallel` target using gulp:
+49 -49
View File
@@ -173,33 +173,33 @@
}
},
"@octokit/auth-token": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.5.0.tgz",
"integrity": "sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g==",
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-3.0.0.tgz",
"integrity": "sha512-MDNFUBcJIptB9At7HiV7VCvU3NcL4GnfCQaP8C5lrxWrRPMJBnemYtehaKSOlaM7AYxeRyj9etenu8LVpSpVaQ==",
"dev": true,
"requires": {
"@octokit/types": "^6.0.3"
}
},
"@octokit/core": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.6.0.tgz",
"integrity": "sha512-7RKRKuA4xTjMhY+eG3jthb3hlZCsOwg3rztWh75Xc+ShDWOfDDATWbeZpAHBNRpm4Tv9WgBMOy1zEJYXG6NJ7Q==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/@octokit/core/-/core-4.0.4.tgz",
"integrity": "sha512-sUpR/hc4Gc7K34o60bWC7WUH6Q7T6ftZ2dUmepSyJr9PRF76/qqkWjE2SOEzCqLA5W83SaISymwKtxks+96hPQ==",
"dev": true,
"requires": {
"@octokit/auth-token": "^2.4.4",
"@octokit/graphql": "^4.5.8",
"@octokit/request": "^5.6.3",
"@octokit/request-error": "^2.0.5",
"@octokit/auth-token": "^3.0.0",
"@octokit/graphql": "^5.0.0",
"@octokit/request": "^6.0.0",
"@octokit/request-error": "^3.0.0",
"@octokit/types": "^6.0.3",
"before-after-hook": "^2.2.0",
"universal-user-agent": "^6.0.0"
}
},
"@octokit/endpoint": {
"version": "6.0.12",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.12.tgz",
"integrity": "sha512-lF3puPwkQWGfkMClXb4k/eUT/nZKQfxinRWJrdZaJO85Dqwo/G0yOC434Jr2ojwafWJMYqFGFa5ms4jJUgujdA==",
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-7.0.0.tgz",
"integrity": "sha512-Kz/mIkOTjs9rV50hf/JK9pIDl4aGwAtT8pry6Rpy+hVXkAPhXanNQRxMoq6AeRgDCZR6t/A1zKniY2V1YhrzlQ==",
"dev": true,
"requires": {
"@octokit/types": "^6.0.3",
@@ -208,29 +208,29 @@
}
},
"@octokit/graphql": {
"version": "4.8.0",
"resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.8.0.tgz",
"integrity": "sha512-0gv+qLSBLKF0z8TKaSKTsS39scVKF9dbMxJpj3U0vC7wjNWFuIpL/z76Qe2fiuCbDRcJSavkXsVtMS6/dtQQsg==",
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-5.0.0.tgz",
"integrity": "sha512-1ZZ8tX4lUEcLPvHagfIVu5S2xpHYXAmgN0+95eAOPoaVPzCfUXJtA5vASafcpWcO86ze0Pzn30TAx72aB2aguQ==",
"dev": true,
"requires": {
"@octokit/request": "^5.6.0",
"@octokit/request": "^6.0.0",
"@octokit/types": "^6.0.3",
"universal-user-agent": "^6.0.0"
}
},
"@octokit/openapi-types": {
"version": "12.4.0",
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.4.0.tgz",
"integrity": "sha512-Npcb7Pv30b33U04jvcD7l75yLU0mxhuX2Xqrn51YyZ5WTkF04bpbxLaZ6GcaTqu03WZQHoO/Gbfp95NGRueDUA==",
"version": "12.10.0",
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.10.0.tgz",
"integrity": "sha512-xsgA7LKuQ/2QReMZQXNlBP68ferPlqw66Jmx5/J399Cn5EgIDaHXou6Rgn1GkpDNjkPji67fTlC2rz6ABaVFKw==",
"dev": true
},
"@octokit/plugin-paginate-rest": {
"version": "2.19.0",
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.19.0.tgz",
"integrity": "sha512-hQ4Qysg2hNmEMuZeJkvyzM4eSZiTifOKqYAMsW8FnxFKowhuwWICSgBQ9Gn9GpUmgKB7qaf1hFvMjYaTAg5jQA==",
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-3.0.0.tgz",
"integrity": "sha512-fvw0Q5IXnn60D32sKeLIxgXCEZ7BTSAjJd8cFAE6QU5qUp0xo7LjFUjjX1J5D7HgN355CN4EXE4+Q1/96JaNUA==",
"dev": true,
"requires": {
"@octokit/types": "^6.36.0"
"@octokit/types": "^6.39.0"
}
},
"@octokit/plugin-request-log": {
@@ -240,23 +240,23 @@
"dev": true
},
"@octokit/plugin-rest-endpoint-methods": {
"version": "5.15.0",
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.15.0.tgz",
"integrity": "sha512-Gsw9+Xm56jVhfbJoy4pt6eOOyf8/3K6CAnx1Sl7U2GhZWcg8MR6YgXWnpfdF69S2ViMXLA7nfvTDAsZpFlkLRw==",
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-6.1.0.tgz",
"integrity": "sha512-gP/yHUY0k/uKkEqXF6tZGRhCFqZNjQ0qdh9/gVo74AJ2pc3cr1rjnW/KRw1uXUKB/H9Y0rRBCBxsLXJmQjPv3A==",
"dev": true,
"requires": {
"@octokit/types": "^6.36.0",
"@octokit/types": "^6.40.0",
"deprecation": "^2.3.1"
}
},
"@octokit/request": {
"version": "5.6.3",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.6.3.tgz",
"integrity": "sha512-bFJl0I1KVc9jYTe9tdGGpAMPy32dLBXXo1dS/YwSCTL/2nd9XeHsY616RE3HPXDVk+a+dBuzyz5YdlXwcDTr2A==",
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-6.2.0.tgz",
"integrity": "sha512-7IAmHnaezZrgUqtRShMlByJK33MT9ZDnMRgZjnRrRV9a/jzzFwKGz0vxhFU6i7VMLraYcQ1qmcAOin37Kryq+Q==",
"dev": true,
"requires": {
"@octokit/endpoint": "^6.0.1",
"@octokit/request-error": "^2.1.0",
"@octokit/endpoint": "^7.0.0",
"@octokit/request-error": "^3.0.0",
"@octokit/types": "^6.16.1",
"is-plain-object": "^5.0.0",
"node-fetch": "^2.6.7",
@@ -264,9 +264,9 @@
}
},
"@octokit/request-error": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.1.0.tgz",
"integrity": "sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg==",
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-3.0.0.tgz",
"integrity": "sha512-WBtpzm9lR8z4IHIMtOqr6XwfkGvMOOILNLxsWvDwtzm/n7f5AWuqJTXQXdDtOvPfTDrH4TPhEvW2qMlR4JFA2w==",
"dev": true,
"requires": {
"@octokit/types": "^6.0.3",
@@ -275,24 +275,24 @@
}
},
"@octokit/rest": {
"version": "18.12.0",
"resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-18.12.0.tgz",
"integrity": "sha512-gDPiOHlyGavxr72y0guQEhLsemgVjwRePayJ+FcKc2SJqKUbxbkvf5kAZEWA/MKvsfYlQAMVzNJE3ezQcxMJ2Q==",
"version": "19.0.3",
"resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-19.0.3.tgz",
"integrity": "sha512-5arkTsnnRT7/sbI4fqgSJ35KiFaN7zQm0uQiQtivNQLI8RQx8EHwJCajcTUwmaCMNDg7tdCvqAnc7uvHHPxrtQ==",
"dev": true,
"requires": {
"@octokit/core": "^3.5.1",
"@octokit/plugin-paginate-rest": "^2.16.8",
"@octokit/core": "^4.0.0",
"@octokit/plugin-paginate-rest": "^3.0.0",
"@octokit/plugin-request-log": "^1.0.4",
"@octokit/plugin-rest-endpoint-methods": "^5.12.0"
"@octokit/plugin-rest-endpoint-methods": "^6.0.0"
}
},
"@octokit/types": {
"version": "6.37.0",
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.37.0.tgz",
"integrity": "sha512-BXWQhFKRkjX4dVW5L2oYa0hzWOAqsEsujXsQLSdepPoDZfYdubrD1KDGpyNldGXtR8QM/WezDcxcIN1UKJMGPA==",
"version": "6.40.0",
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.40.0.tgz",
"integrity": "sha512-MFZOU5r8SwgJWDMhrLUSvyJPtVsqA6VnbVI3TNbsmw+Jnvrktzvq2fYES/6RiJA/5Ykdwq4mJmtlYUfW7CGjmw==",
"dev": true,
"requires": {
"@octokit/openapi-types": "^12.4.0"
"@octokit/openapi-types": "^12.10.0"
}
},
"@types/chai": {
@@ -452,9 +452,9 @@
"dev": true
},
"@types/node": {
"version": "18.0.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz",
"integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==",
"version": "18.0.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.5.tgz",
"integrity": "sha512-En7tneq+j0qAiVwysBD79y86MT3ModuoIJbe7JXp+sb5UAjInSShmK3nXXMioBzfF7rXC12hv12d4IyCVwN4dA==",
"dev": true
},
"@types/node-fetch": {
-35
View File
@@ -2040,41 +2040,6 @@ namespace ts {
}
function bindObjectLiteralExpression(node: ObjectLiteralExpression) {
const enum ElementKind {
Property = 1,
Accessor = 2
}
if (inStrictMode && !isAssignmentTarget(node)) {
const seen = new Map<__String, ElementKind>();
for (const prop of node.properties) {
if (prop.kind === SyntaxKind.SpreadAssignment || prop.name.kind !== SyntaxKind.Identifier) {
continue;
}
const identifier = prop.name;
// ECMA-262 11.1.5 Object Initializer
// If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
// a.This production is contained in strict code and IsDataDescriptor(previous) is true and
// IsDataDescriptor(propId.descriptor) is true.
// b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
// c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
// d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
// and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
const currentKind = prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment || prop.kind === SyntaxKind.MethodDeclaration
? ElementKind.Property
: ElementKind.Accessor;
const existingKind = seen.get(identifier.escapedText);
if (!existingKind) {
seen.set(identifier.escapedText, currentKind);
continue;
}
}
}
return bindAnonymousDeclaration(node, SymbolFlags.ObjectLiteral, InternalSymbolName.Object);
}
+136 -47
View File
@@ -62,9 +62,9 @@ namespace ts {
*/
outSignature?: string;
/**
* Time when d.ts was modified
* Name of the file whose dts was the latest to change
*/
dtsChangeTime: number | undefined;
latestChangedDtsFile: string | undefined;
}
export const enum BuilderFileEmit {
@@ -112,7 +112,7 @@ namespace ts {
/**
* Records if change in dts emit was detected
*/
hasChangedEmitSignature?: boolean;
hasChangedEmitSignature?: boolean;
/**
* Files pending to be emitted
*/
@@ -141,7 +141,7 @@ namespace ts {
"programEmitComplete" |
"emitSignatures" |
"outSignature" |
"dtsChangeTime" |
"latestChangedDtsFile" |
"hasChangedEmitSignature"
> & { changedFilesSet: BuilderProgramState["changedFilesSet"] | undefined };
@@ -167,7 +167,7 @@ namespace ts {
state.outSignature = oldState?.outSignature;
}
state.changedFilesSet = new Set();
state.dtsChangeTime = compilerOptions.composite ? oldState?.dtsChangeTime : undefined;
state.latestChangedDtsFile = compilerOptions.composite ? oldState?.latestChangedDtsFile : undefined;
const useOldState = BuilderState.canReuseOldState(state.referencedMap, oldState);
const oldCompilerOptions = useOldState ? oldState!.compilerOptions : undefined;
@@ -301,7 +301,7 @@ namespace ts {
programEmitComplete: state.programEmitComplete,
emitSignatures: state.emitSignatures && new Map(state.emitSignatures),
outSignature: state.outSignature,
dtsChangeTime: state.dtsChangeTime,
latestChangedDtsFile: state.latestChangedDtsFile,
hasChangedEmitSignature: state.hasChangedEmitSignature,
changedFilesSet: outFilePath ? new Set(state.changedFilesSet) : undefined,
};
@@ -315,7 +315,7 @@ namespace ts {
state.programEmitComplete = savedEmitState.programEmitComplete;
state.emitSignatures = savedEmitState.emitSignatures;
state.outSignature = savedEmitState.outSignature;
state.dtsChangeTime = savedEmitState.dtsChangeTime;
state.latestChangedDtsFile = savedEmitState.latestChangedDtsFile;
state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature;
if (savedEmitState.changedFilesSet) state.changedFilesSet = savedEmitState.changedFilesSet;
}
@@ -333,7 +333,13 @@ namespace ts {
* This is to allow the callers to be able to actually remove affected file only when the operation is complete
* eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
*/
function getNextAffectedFile(state: BuilderProgramState, cancellationToken: CancellationToken | undefined, computeHash: BuilderState.ComputeHash, host: BuilderProgramHost): SourceFile | Program | undefined {
function getNextAffectedFile(
state: BuilderProgramState,
cancellationToken: CancellationToken | undefined,
computeHash: BuilderState.ComputeHash,
getCanonicalFileName: GetCanonicalFileName,
host: BuilderProgramHost
): SourceFile | Program | undefined {
while (true) {
const { affectedFiles } = state;
if (affectedFiles) {
@@ -344,7 +350,14 @@ namespace ts {
if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
// Set the next affected file as seen and remove the cached semantic diagnostics
state.affectedFilesIndex = affectedFilesIndex;
handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host);
handleDtsMayChangeOfAffectedFile(
state,
affectedFile,
cancellationToken,
computeHash,
getCanonicalFileName,
host
);
return affectedFile;
}
affectedFilesIndex++;
@@ -376,7 +389,14 @@ namespace ts {
}
// Get next batch of affected files
state.affectedFiles = BuilderState.getFilesAffectedByWithOldState(state, program, nextKey.value, cancellationToken, computeHash);
state.affectedFiles = BuilderState.getFilesAffectedByWithOldState(
state,
program,
nextKey.value,
cancellationToken,
computeHash,
getCanonicalFileName,
);
state.currentChangedFilePath = nextKey.value;
state.affectedFilesIndex = 0;
if (!state.seenAffectedFiles) state.seenAffectedFiles = new Set();
@@ -435,6 +455,7 @@ namespace ts {
affectedFile: SourceFile,
cancellationToken: CancellationToken | undefined,
computeHash: BuilderState.ComputeHash,
getCanonicalFileName: GetCanonicalFileName,
host: BuilderProgramHost,
) {
removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
@@ -451,11 +472,19 @@ namespace ts {
affectedFile,
cancellationToken,
computeHash,
getCanonicalFileName,
);
return;
}
if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return;
handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, computeHash, host);
handleDtsMayChangeOfReferencingExportOfAffectedFile(
state,
affectedFile,
cancellationToken,
computeHash,
getCanonicalFileName,
host,
);
}
/**
@@ -467,6 +496,7 @@ namespace ts {
path: Path,
cancellationToken: CancellationToken | undefined,
computeHash: BuilderState.ComputeHash,
getCanonicalFileName: GetCanonicalFileName,
host: BuilderProgramHost
): void {
removeSemanticDiagnosticsOf(state, path);
@@ -486,6 +516,7 @@ namespace ts {
sourceFile,
cancellationToken,
computeHash,
getCanonicalFileName,
!host.disableUseFileVersionAsSignature
);
// If not dts emit, nothing more to do
@@ -520,6 +551,7 @@ namespace ts {
filePath: Path,
cancellationToken: CancellationToken | undefined,
computeHash: BuilderState.ComputeHash,
getCanonicalFileName: GetCanonicalFileName,
host: BuilderProgramHost,
): boolean {
if (!state.fileInfos.get(filePath)?.affectsGlobalScope) return false;
@@ -530,6 +562,7 @@ namespace ts {
file.resolvedPath,
cancellationToken,
computeHash,
getCanonicalFileName,
host,
));
removeDiagnosticsOfLibraryFiles(state);
@@ -544,6 +577,7 @@ namespace ts {
affectedFile: SourceFile,
cancellationToken: CancellationToken | undefined,
computeHash: BuilderState.ComputeHash,
getCanonicalFileName: GetCanonicalFileName,
host: BuilderProgramHost
) {
// If there was change in signature (dts output) for the changed file,
@@ -561,8 +595,8 @@ namespace ts {
const currentPath = queue.pop()!;
if (!seenFileNamesMap.has(currentPath)) {
seenFileNamesMap.set(currentPath, true);
if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, host)) return;
handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, host);
if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host)) return;
handleDtsMayChangeOf(state, currentPath, cancellationToken, computeHash, getCanonicalFileName, host);
if (isChangedSignature(state, currentPath)) {
const currentSourceFile = Debug.checkDefined(state.program).getSourceFileByPath(currentPath)!;
queue.push(...BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
@@ -575,7 +609,7 @@ namespace ts {
// Go through exported modules from cache first
// If exported modules has path, all files referencing file exported from are affected
state.exportedModulesMap.getKeys(affectedFile.resolvedPath)?.forEach(exportedFromPath => {
if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, host)) return true;
if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, computeHash, getCanonicalFileName, host)) return true;
const references = state.referencedMap!.getKeys(exportedFromPath);
return references && forEachKey(references, filePath =>
handleDtsMayChangeOfFileAndExportsOfFile(
@@ -584,6 +618,7 @@ namespace ts {
seenFileAndExportsOfFile,
cancellationToken,
computeHash,
getCanonicalFileName,
host,
)
);
@@ -600,12 +635,13 @@ namespace ts {
seenFileAndExportsOfFile: Set<string>,
cancellationToken: CancellationToken | undefined,
computeHash: BuilderState.ComputeHash,
getCanonicalFileName: GetCanonicalFileName,
host: BuilderProgramHost,
): boolean | undefined {
if (!tryAddToSet(seenFileAndExportsOfFile, filePath)) return undefined;
if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, host)) return true;
handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, host);
if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host)) return true;
handleDtsMayChangeOf(state, filePath, cancellationToken, computeHash, getCanonicalFileName, host);
// If exported modules has path, all files referencing file exported from are affected
state.exportedModulesMap!.getKeys(filePath)?.forEach(exportedFromPath =>
@@ -615,6 +651,7 @@ namespace ts {
seenFileAndExportsOfFile,
cancellationToken,
computeHash,
getCanonicalFileName,
host,
)
);
@@ -627,6 +664,7 @@ namespace ts {
referencingFilePath,
cancellationToken,
computeHash,
getCanonicalFileName,
host,
)
);
@@ -757,7 +795,8 @@ namespace ts {
affectedFilesPendingEmit?: ProgramBuilderInfoFilePendingEmit[];
changeFileSet?: readonly ProgramBuildInfoFileId[];
emitSignatures?: readonly ProgramBuildInfoEmitSignature[];
dtsChangeTime?: number;
// Because this is only output file in the program, we dont need fileId to deduplicate name
latestChangedDtsFile?: string;
}
export interface ProgramBundleEmitBuildInfo {
@@ -765,7 +804,7 @@ namespace ts {
fileInfos: readonly string[];
options: CompilerOptions | undefined;
outSignature?: string;
dtsChangeTime?: number;
latestChangedDtsFile?: string;
}
export type ProgramBuildInfo = ProgramMultiFileEmitBuildInfo | ProgramBundleEmitBuildInfo;
@@ -777,13 +816,13 @@ namespace ts {
/**
* Gets the program information to be emitted in buildInfo so that we can use it to create new program
*/
function getProgramBuildInfo(state: BuilderProgramState, getCanonicalFileName: GetCanonicalFileName, host: BuilderProgramHost): ProgramBuildInfo | undefined {
function getProgramBuildInfo(state: BuilderProgramState, getCanonicalFileName: GetCanonicalFileName): ProgramBuildInfo | undefined {
const outFilePath = outFile(state.compilerOptions);
if (outFilePath && !state.compilerOptions.composite) return;
const currentDirectory = Debug.checkDefined(state.program).getCurrentDirectory();
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions)!, currentDirectory));
// Update the dtsChange time in buildInfo
state.dtsChangeTime = state.hasChangedEmitSignature ? getCurrentTime(host).getTime() : state.dtsChangeTime;
// Convert the file name to Path here if we set the fileName instead to optimize multiple d.ts file emits and having to compute Canonical path
const latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : undefined;
if (outFilePath) {
const fileNames: string[] = [];
const fileInfos: string[] = [];
@@ -798,7 +837,7 @@ namespace ts {
fileInfos,
options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions, "affectsBundleEmitBuildInfo"),
outSignature: state.outSignature,
dtsChangeTime: state.dtsChangeTime,
latestChangedDtsFile,
};
return result;
}
@@ -901,7 +940,7 @@ namespace ts {
affectedFilesPendingEmit,
changeFileSet,
emitSignatures,
dtsChangeTime: state.dtsChangeTime,
latestChangedDtsFile,
};
return result;
@@ -1038,8 +1077,45 @@ namespace ts {
return { host, newProgram, oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || emptyArray };
}
export function computeSignature(text: string, data: WriteFileCallbackData | undefined, computeHash: BuilderState.ComputeHash | undefined) {
return BuilderState.computeSignature(data?.sourceMapUrlPos !== undefined ? text.substring(0, data.sourceMapUrlPos) : text, computeHash);
function getTextHandlingSourceMapForSignature(text: string, data: WriteFileCallbackData | undefined) {
return data?.sourceMapUrlPos !== undefined ? text.substring(0, data.sourceMapUrlPos) : text;
}
export function computeSignatureWithDiagnostics(
sourceFile: SourceFile,
text: string,
computeHash: BuilderState.ComputeHash | undefined,
getCanonicalFileName: GetCanonicalFileName,
data: WriteFileCallbackData | undefined
) {
text = getTextHandlingSourceMapForSignature(text, data);
let sourceFileDirectory: string | undefined;
if (data?.diagnostics?.length) {
text += data.diagnostics.map(diagnostic =>
`${locationInfo(diagnostic)}${DiagnosticCategory[diagnostic.category]}${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText)}`
).join("\n");
}
return (computeHash ?? generateDjb2Hash)(text);
function flattenDiagnosticMessageText(diagnostic: string | DiagnosticMessageChain | undefined): string {
return isString(diagnostic) ?
diagnostic :
diagnostic === undefined ?
"" :
!diagnostic.next ?
diagnostic.messageText :
diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText).join("\n");
}
function locationInfo(diagnostic: DiagnosticWithLocation) {
if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) return `(${diagnostic.start},${diagnostic.length})`;
if (sourceFileDirectory === undefined) sourceFileDirectory = getDirectoryPath(sourceFile.resolvedPath);
return `${ensurePathIsNonModuleName(getRelativePathFromDirectory(sourceFileDirectory, diagnostic.file.resolvedPath, getCanonicalFileName))}(${diagnostic.start},${diagnostic.length})`;
}
}
export function computeSignature(text: string, computeHash: BuilderState.ComputeHash | undefined, data?: WriteFileCallbackData) {
return (computeHash ?? generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data));
}
export function createBuilderProgram(kind: BuilderProgramKind.SemanticDiagnosticsBuilderProgram, builderCreationParameters: BuilderCreationParameters): SemanticDiagnosticsBuilderProgram;
@@ -1062,7 +1138,7 @@ namespace ts {
*/
const computeHash = maybeBind(host, host.createHash);
const state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState, host.disableUseFileVersionAsSignature);
newProgram.getProgramBuildInfo = () => getProgramBuildInfo(state, getCanonicalFileName, host);
newProgram.getProgramBuildInfo = () => getProgramBuildInfo(state, getCanonicalFileName);
// To ensure that we arent storing any references to old program or new program without state
newProgram = undefined!; // TODO: GH#18217
@@ -1074,6 +1150,7 @@ namespace ts {
builderProgram.getState = getState;
builderProgram.saveEmitState = () => backupBuilderProgramEmitState(state);
builderProgram.restoreEmitState = (saved) => restoreBuilderProgramEmitState(state, saved);
builderProgram.hasChangedEmitSignature = () => !!state.hasChangedEmitSignature;
builderProgram.getAllDependencies = sourceFile => BuilderState.getAllDependencies(state, Debug.checkDefined(state.program), sourceFile);
builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
builderProgram.emit = emit;
@@ -1108,7 +1185,7 @@ namespace ts {
* in that order would be used to write the files
*/
function emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult<EmitResult> {
let affected = getNextAffectedFile(state, cancellationToken, computeHash, host);
let affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host);
let emitKind = BuilderFileEmit.Full;
let isPendingEmitFile = false;
if (!affected) {
@@ -1165,24 +1242,32 @@ namespace ts {
if (isDeclarationFileName(fileName)) {
if (!outFile(state.compilerOptions)) {
Debug.assert(sourceFiles?.length === 1);
let newSignature;
let emitSignature;
if (!customTransformers) {
const file = sourceFiles[0];
const info = state.fileInfos.get(file.resolvedPath)!;
if (info.signature === file.version) {
newSignature = computeSignature(text, data, computeHash);
if (newSignature !== file.version) { // Update it
if (host.storeFilesChangingSignatureDuringEmit) (state.filesChangingSignature ||= new Set()).add(file.resolvedPath);
const signature = computeSignatureWithDiagnostics(
file,
text,
computeHash,
getCanonicalFileName,
data,
);
// With d.ts diagnostics they are also part of the signature so emitSignature will be different from it since its just hash of d.ts
if (!data?.diagnostics?.length) emitSignature = signature;
if (signature !== file.version) { // Update it
if (host.storeFilesChangingSignatureDuringEmit) (state.filesChangingSignature ??= new Set()).add(file.resolvedPath);
if (state.exportedModulesMap) BuilderState.updateExportedModules(state, file, file.exportedModulesFromDeclarationEmit);
if (state.affectedFiles) {
// Keep old signature so we know what to undo if cancellation happens
const existing = state.oldSignatures?.get(file.resolvedPath);
if (existing === undefined) (state.oldSignatures ||= new Map()).set(file.resolvedPath, info.signature || false);
info.signature = newSignature;
if (existing === undefined) (state.oldSignatures ??= new Map()).set(file.resolvedPath, info.signature || false);
info.signature = signature;
}
else {
// These are directly commited
info.signature = newSignature;
info.signature = signature;
state.oldExportedModulesMap?.clear();
}
}
@@ -1195,19 +1280,21 @@ namespace ts {
if (state.compilerOptions.composite) {
const filePath = sourceFiles[0].resolvedPath;
const oldSignature = state.emitSignatures?.get(filePath);
newSignature ||= computeSignature(text, data, computeHash);
if (newSignature !== oldSignature) {
(state.emitSignatures ||= new Map()).set(filePath, newSignature);
state.hasChangedEmitSignature = true;
}
emitSignature ??= computeSignature(text, computeHash, data);
// Dont write dts files if they didn't change
if (emitSignature === oldSignature) return;
(state.emitSignatures ??= new Map()).set(filePath, emitSignature);
state.hasChangedEmitSignature = true;
state.latestChangedDtsFile = fileName;
}
}
else if (state.compilerOptions.composite) {
const newSignature = computeSignature(text, data, computeHash);
if (newSignature !== state.outSignature) {
state.outSignature = newSignature;
state.hasChangedEmitSignature = true;
}
const newSignature = computeSignature(text, computeHash, data);
// Dont write dts files if they didn't change
if (newSignature === state.outSignature) return;
state.outSignature = newSignature;
state.hasChangedEmitSignature = true;
state.latestChangedDtsFile = fileName;
}
}
if (writeFile) writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data);
@@ -1287,7 +1374,7 @@ namespace ts {
*/
function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult<readonly Diagnostic[]> {
while (true) {
const affected = getNextAffectedFile(state, cancellationToken, computeHash, host);
const affected = getNextAffectedFile(state, cancellationToken, computeHash, getCanonicalFileName, host);
if (!affected) {
// Done
return undefined;
@@ -1389,11 +1476,12 @@ namespace ts {
let state: ReusableBuilderProgramState;
let filePaths: Path[] | undefined;
let filePathsSetList: Set<Path>[] | undefined;
const latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : undefined;
if (isProgramBundleEmitBuildInfo(program)) {
state = {
fileInfos: new Map(),
compilerOptions: program.options ? convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {},
dtsChangeTime: program.dtsChangeTime,
latestChangedDtsFile,
outSignature: program.outSignature,
};
}
@@ -1423,7 +1511,7 @@ namespace ts {
affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && arrayToMap(program.affectedFilesPendingEmit, value => toFilePath(value[0]), value => value[1]),
affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0,
changedFilesSet: new Set(map(program.changeFileSet, toFilePath)),
dtsChangeTime: program.dtsChangeTime,
latestChangedDtsFile,
emitSignatures: emitSignatures?.size ? emitSignatures : undefined,
};
}
@@ -1451,6 +1539,7 @@ namespace ts {
getSemanticDiagnosticsOfNextAffectedFile: notImplemented,
emitBuildInfo: notImplemented,
close: noop,
hasChangedEmitSignature: returnFalse,
};
function toPath(path: string) {
+2
View File
@@ -42,6 +42,8 @@ namespace ts {
saveEmitState(): SavedBuildProgramEmitState;
/*@internal*/
restoreEmitState(saved: SavedBuildProgramEmitState): void;
/*@internal*/
hasChangedEmitSignature?(): boolean;
/**
* Returns current program
*/
+61 -25
View File
@@ -3,8 +3,8 @@ namespace ts {
export function getFileEmitOutput(program: Program, sourceFile: SourceFile, emitOnlyDtsFiles: boolean,
cancellationToken?: CancellationToken, customTransformers?: CustomTransformers, forceDtsEmit?: boolean): EmitOutput {
const outputFiles: OutputFile[] = [];
const { emitSkipped, diagnostics, exportedModulesFromDeclarationEmit } = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit);
return { outputFiles, emitSkipped, diagnostics, exportedModulesFromDeclarationEmit };
const { emitSkipped, diagnostics } = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit);
return { outputFiles, emitSkipped, diagnostics };
function writeFile(fileName: string, text: string, writeByteOrderMark: boolean) {
outputFiles.push({ name: fileName, writeByteOrderMark, text });
@@ -321,24 +321,45 @@ namespace ts {
/**
* Gets the files affected by the path from the program
*/
export function getFilesAffectedBy(state: BuilderState, programOfThisState: Program, path: Path, cancellationToken: CancellationToken | undefined, computeHash: ComputeHash): readonly SourceFile[] {
const result = getFilesAffectedByWithOldState(state, programOfThisState, path, cancellationToken, computeHash);
export function getFilesAffectedBy(
state: BuilderState,
programOfThisState: Program,
path: Path,
cancellationToken: CancellationToken | undefined,
computeHash: ComputeHash,
getCanonicalFileName: GetCanonicalFileName,
): readonly SourceFile[] {
const result = getFilesAffectedByWithOldState(
state,
programOfThisState,
path,
cancellationToken,
computeHash,
getCanonicalFileName,
);
state.oldSignatures?.clear();
state.oldExportedModulesMap?.clear();
return result;
}
export function getFilesAffectedByWithOldState(state: BuilderState, programOfThisState: Program, path: Path, cancellationToken: CancellationToken | undefined, computeHash: ComputeHash): readonly SourceFile[] {
export function getFilesAffectedByWithOldState(
state: BuilderState,
programOfThisState: Program,
path: Path,
cancellationToken: CancellationToken | undefined,
computeHash: ComputeHash,
getCanonicalFileName: GetCanonicalFileName,
): readonly SourceFile[] {
const sourceFile = programOfThisState.getSourceFileByPath(path);
if (!sourceFile) {
return emptyArray;
}
if (!updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash)) {
if (!updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName)) {
return [sourceFile];
}
return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, computeHash);
return (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, cancellationToken, computeHash, getCanonicalFileName);
}
export function updateSignatureOfFile(state: BuilderState, signature: string | undefined, path: Path) {
@@ -349,7 +370,15 @@ namespace ts {
/**
* Returns if the shape of the signature has changed since last emit
*/
export function updateShapeSignature(state: BuilderState, programOfThisState: Program, sourceFile: SourceFile, cancellationToken: CancellationToken | undefined, computeHash: ComputeHash, useFileVersionAsSignature = state.useFileVersionAsSignature) {
export function updateShapeSignature(
state: BuilderState,
programOfThisState: Program,
sourceFile: SourceFile,
cancellationToken: CancellationToken | undefined,
computeHash: ComputeHash,
getCanonicalFileName: GetCanonicalFileName,
useFileVersionAsSignature = state.useFileVersionAsSignature
) {
// If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
if (state.hasCalledUpdateShapeSignature?.has(sourceFile.resolvedPath)) return false;
@@ -357,22 +386,26 @@ namespace ts {
const prevSignature = info.signature;
let latestSignature: string | undefined;
if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) {
const emitOutput = getFileEmitOutput(
programOfThisState,
programOfThisState.emit(
sourceFile,
/*emitOnlyDtsFiles*/ true,
(fileName, text, _writeByteOrderMark, _onError, sourceFiles, data) => {
Debug.assert(isDeclarationFileName(fileName), `File extension for signature expected to be dts: Got:: ${fileName}`);
latestSignature = computeSignatureWithDiagnostics(
sourceFile,
text,
computeHash,
getCanonicalFileName,
data,
);
if (latestSignature !== prevSignature) {
updateExportedModules(state, sourceFile, sourceFiles![0].exportedModulesFromDeclarationEmit);
}
},
cancellationToken,
/*emitOnlyDtsFiles*/ true,
/*customTransformers*/ undefined,
/*forceDtsEmit*/ true
);
const firstDts = firstOrUndefined(emitOutput.outputFiles);
if (firstDts) {
Debug.assert(isDeclarationFileName(firstDts.name), "File extension for signature expected to be dts", () => `Found: ${getAnyExtensionFromPath(firstDts.name)} for ${firstDts.name}:: All output files: ${JSON.stringify(emitOutput.outputFiles.map(f => f.name))}`);
latestSignature = computeSignature(firstDts.text, computeHash);
if (latestSignature !== prevSignature) {
updateExportedModules(state, sourceFile, emitOutput.exportedModulesFromDeclarationEmit);
}
}
}
// Default is to use file version as signature
if (latestSignature === undefined) {
@@ -395,10 +428,6 @@ namespace ts {
return latestSignature !== prevSignature;
}
export function computeSignature(text: string, computeHash: ComputeHash | undefined) {
return (computeHash || generateDjb2Hash)(text);
}
/**
* Coverts the declaration emit result into exported modules map
*/
@@ -556,7 +585,14 @@ namespace ts {
/**
* When program emits modular code, gets the files affected by the sourceFile whose shape has changed
*/
function getFilesAffectedByUpdatedShapeWhenModuleEmit(state: BuilderState, programOfThisState: Program, sourceFileWithUpdatedShape: SourceFile, cancellationToken: CancellationToken | undefined, computeHash: ComputeHash) {
function getFilesAffectedByUpdatedShapeWhenModuleEmit(
state: BuilderState,
programOfThisState: Program,
sourceFileWithUpdatedShape: SourceFile,
cancellationToken: CancellationToken | undefined,
computeHash: ComputeHash,
getCanonicalFileName: GetCanonicalFileName,
) {
if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
}
@@ -579,7 +615,7 @@ namespace ts {
if (!seenFileNamesMap.has(currentPath)) {
const currentSourceFile = programOfThisState.getSourceFileByPath(currentPath)!;
seenFileNamesMap.set(currentPath, currentSourceFile);
if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cancellationToken, computeHash)) {
if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cancellationToken, computeHash, getCanonicalFileName)) {
queue.push(...getReferencedByPaths(state, currentSourceFile.resolvedPath));
}
}
-1
View File
@@ -3,7 +3,6 @@ namespace ts {
outputFiles: OutputFile[];
emitSkipped: boolean;
/* @internal */ diagnostics: readonly Diagnostic[];
/* @internal */ exportedModulesFromDeclarationEmit?: ExportedModulesFromDeclarationEmit;
}
export interface OutputFile {
+454 -294
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -2105,7 +2105,7 @@ namespace ts {
* and 1 insertion/deletion at 3 characters)
*/
export function getSpellingSuggestion<T>(name: string, candidates: T[], getName: (candidate: T) => string | undefined): T | undefined {
const maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
const maximumLengthDifference = Math.max(2, Math.floor(name.length * 0.34));
let bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result is worse than this, don't bother.
let bestCandidate: T | undefined;
for (const candidate of candidates) {
+64
View File
@@ -394,6 +394,22 @@ namespace ts {
return formatEnum(flags, (ts as any).FlowFlags, /*isFlags*/ true);
}
export function formatRelationComparisonResult(result: RelationComparisonResult | undefined): string {
return formatEnum(result, (ts as any).RelationComparisonResult, /*isFlags*/ true);
}
export function formatCheckMode(mode: CheckMode | undefined): string {
return formatEnum(mode, (ts as any).CheckMode, /*isFlags*/ true);
}
export function formatSignatureCheckMode(mode: SignatureCheckMode | undefined): string {
return formatEnum(mode, (ts as any).SignatureCheckMode, /*isFlags*/ true);
}
export function formatTypeFacts(facts: TypeFacts | undefined): string {
return formatEnum(facts, (ts as any).TypeFacts, /*isFlags*/ true);
}
let isDebugInfoEnabled = false;
interface ExtendedDebugModule {
@@ -748,5 +764,53 @@ namespace ts {
const deprecation = createDeprecation(options?.name ?? getFunctionName(func), options);
return wrapFunction(deprecation, func);
}
export function formatVariance(varianceFlags: VarianceFlags) {
const variance = varianceFlags & VarianceFlags.VarianceMask;
let result =
variance === VarianceFlags.Invariant ? "in out" :
variance === VarianceFlags.Bivariant ? "[bivariant]" :
variance === VarianceFlags.Contravariant ? "in" :
variance === VarianceFlags.Covariant ? "out" :
variance === VarianceFlags.Independent ? "[independent]" : "";
if (varianceFlags & VarianceFlags.Unmeasurable) {
result += " (unmeasurable)";
}
else if (varianceFlags & VarianceFlags.Unreliable) {
result += " (unreliable)";
}
return result;
}
export type DebugType = Type & { __debugTypeToString(): string }; // eslint-disable-line @typescript-eslint/naming-convention
export class DebugTypeMapper {
declare kind: TypeMapKind;
__debugToString(): string { // eslint-disable-line @typescript-eslint/naming-convention
type<TypeMapper>(this);
switch (this.kind) {
case TypeMapKind.Function: return this.debugInfo?.() || "(function mapper)";
case TypeMapKind.Simple: return `${(this.source as DebugType).__debugTypeToString()} -> ${(this.target as DebugType).__debugTypeToString()}`;
case TypeMapKind.Array: return zipWith<DebugType, DebugType | string, unknown>(
this.sources as readonly DebugType[],
this.targets as readonly DebugType[] || map(this.sources, () => "any"),
(s, t) => `${s.__debugTypeToString()} -> ${typeof t === "string" ? t : t.__debugTypeToString()}`).join(", ");
case TypeMapKind.Deferred: return zipWith(
this.sources,
this.targets,
(s, t) => `${(s as DebugType).__debugTypeToString()} -> ${(t() as DebugType).__debugTypeToString()}`).join(", ");
case TypeMapKind.Merged:
case TypeMapKind.Composite: return `m1: ${(this.mapper1 as unknown as DebugTypeMapper).__debugToString().split("\n").join("\n ")}
m2: ${(this.mapper2 as unknown as DebugTypeMapper).__debugToString().split("\n").join("\n ")}`;
default: return assertNever(this);
}
}
}
export function attachDebugPrototypeIfDebug(mapper: TypeMapper): TypeMapper {
if (isDebugging) {
return Object.setPrototypeOf(mapper, DebugTypeMapper.prototype);
}
return mapper;
}
}
}
+8
View File
@@ -1493,6 +1493,10 @@
"category": "Message",
"code": 1476
},
"An instantiation expression cannot be followed by a property access.": {
"category": "Error",
"code": 1477
},
"The types of '{0}' are incompatible between these types.": {
"category": "Error",
@@ -3503,6 +3507,10 @@
"category": "Error",
"code": 2843
},
"Type of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor.": {
"category": "Error",
"code": 2844
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
+15 -22
View File
@@ -288,7 +288,6 @@ namespace ts {
const { enter, exit } = performance.createTimer("printTime", "beforePrint", "afterPrint");
let bundleBuildInfo: BundleBuildInfo | undefined;
let emitSkipped = false;
let exportedModulesFromDeclarationEmit: ExportedModulesFromDeclarationEmit | undefined;
// Emit each output file
enter();
@@ -308,7 +307,6 @@ namespace ts {
diagnostics: emitterDiagnostics.getDiagnostics(),
emittedFiles: emittedFilesList,
sourceMaps: sourceMapDataList,
exportedModulesFromDeclarationEmit
};
function emitSourceFileOrBundle({ jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath }: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle | undefined) {
@@ -381,7 +379,7 @@ namespace ts {
}
// Make sure not to write js file and source map file if any of them cannot be written
if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit) {
emitSkipped = true;
return;
}
@@ -414,7 +412,7 @@ namespace ts {
});
Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, compilerOptions);
// Clean up emit nodes on parse tree
transform.dispose();
@@ -453,7 +451,7 @@ namespace ts {
noEmitHelpers: true,
module: compilerOptions.module,
target: compilerOptions.target,
sourceMap: compilerOptions.sourceMap,
sourceMap: !forceDtsEmit && compilerOptions.declarationMap,
inlineSourceMap: compilerOptions.inlineSourceMap,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
onlyPrintJsDocStyle: true,
@@ -478,20 +476,16 @@ namespace ts {
printSourceFileOrBundle(
declarationFilePath,
declarationMapPath,
declarationTransform.transformed[0],
declarationTransform,
declarationPrinter,
{
sourceMap: !forceDtsEmit && compilerOptions.declarationMap,
sourceMap: printerOptions.sourceMap,
sourceRoot: compilerOptions.sourceRoot,
mapRoot: compilerOptions.mapRoot,
extendedDiagnostics: compilerOptions.extendedDiagnostics,
// Explicitly do not passthru either `inline` option
}
);
if (forceDtsEmit && declarationTransform.transformed[0].kind === SyntaxKind.SourceFile) {
const sourceFile = declarationTransform.transformed[0];
exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
}
}
declarationTransform.dispose();
if (bundleBuildInfo) bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
@@ -511,7 +505,8 @@ namespace ts {
forEachChild(node, collectLinkedAliases);
}
function printSourceFileOrBundle(jsFilePath: string, sourceMapFilePath: string | undefined, sourceFileOrBundle: SourceFile | Bundle, printer: Printer, mapOptions: SourceMapOptions) {
function printSourceFileOrBundle(jsFilePath: string, sourceMapFilePath: string | undefined, transform: TransformationResult<SourceFile | Bundle>, printer: Printer, mapOptions: SourceMapOptions) {
const sourceFileOrBundle = transform.transformed[0];
const bundle = sourceFileOrBundle.kind === SyntaxKind.Bundle ? sourceFileOrBundle : undefined;
const sourceFile = sourceFileOrBundle.kind === SyntaxKind.SourceFile ? sourceFileOrBundle : undefined;
const sourceFiles = bundle ? bundle.sourceFiles : [sourceFile!];
@@ -559,7 +554,7 @@ namespace ts {
if (sourceMapFilePath) {
const sourceMap = sourceMapGenerator.toString();
writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
if (printer.bundleFileInfo) printer.bundleFileInfo.mapHash = BuilderState.computeSignature(sourceMap, maybeBind(host, host.createHash));
if (printer.bundleFileInfo) printer.bundleFileInfo.mapHash = computeSignature(sourceMap, maybeBind(host, host.createHash));
}
}
else {
@@ -568,10 +563,10 @@ namespace ts {
// Write the output file
const text = writer.getText();
writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos });
writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos, diagnostics: transform.diagnostics });
// We store the hash of the text written in the buildinfo to ensure that text of the referenced d.ts file is same as whats in the buildinfo
// This is needed because incremental can be toggled between two runs and we might use stale file text to do text manipulation in prepend mode
if (printer.bundleFileInfo) printer.bundleFileInfo.hash = BuilderState.computeSignature(text, maybeBind(host, host.createHash));
if (printer.bundleFileInfo) printer.bundleFileInfo.hash = computeSignature(text, maybeBind(host, host.createHash));
// Reset state
writer.clear();
@@ -717,7 +712,6 @@ namespace ts {
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
createHash?(data: string): string;
now?(): Date;
getBuildInfo?(fileName: string, configFilePath: string | undefined): BuildInfo | undefined;
}
@@ -774,20 +768,20 @@ namespace ts {
const jsFileText = host.readFile(Debug.checkDefined(jsFilePath));
if (!jsFileText) return jsFilePath!;
// If the jsFileText is not same has what it was created with, tsbuildinfo is stale so dont use it
if (BuilderState.computeSignature(jsFileText, createHash) !== buildInfo.bundle.js.hash) return jsFilePath!;
if (computeSignature(jsFileText, createHash) !== buildInfo.bundle.js.hash) return jsFilePath!;
const sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
// error if no source map or for now if inline sourcemap
if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap) return sourceMapFilePath || "inline sourcemap decoding";
if (sourceMapFilePath && BuilderState.computeSignature(sourceMapText!, createHash) !== buildInfo.bundle.js.mapHash) return sourceMapFilePath;
if (sourceMapFilePath && computeSignature(sourceMapText!, createHash) !== buildInfo.bundle.js.mapHash) return sourceMapFilePath;
// read declaration text
const declarationText = declarationFilePath && host.readFile(declarationFilePath);
if (declarationFilePath && !declarationText) return declarationFilePath;
if (declarationFilePath && BuilderState.computeSignature(declarationText!, createHash) !== buildInfo.bundle.dts!.hash) return declarationFilePath;
if (declarationFilePath && computeSignature(declarationText!, createHash) !== buildInfo.bundle.dts!.hash) return declarationFilePath;
const declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
// error if no source map or for now if inline sourcemap
if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap) return declarationMapPath || "inline sourcemap decoding";
if (declarationMapPath && BuilderState.computeSignature(declarationMapText!, createHash) !== buildInfo.bundle.dts!.mapHash) return declarationMapPath;
if (declarationMapPath && computeSignature(declarationMapText!, createHash) !== buildInfo.bundle.dts!.mapHash) return declarationMapPath;
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath!, host.getCurrentDirectory()));
const ownPrependInput = createInputFiles(
@@ -836,8 +830,7 @@ namespace ts {
newBuildInfo.program = buildInfo.program;
if (newBuildInfo.program && changedDtsText !== undefined && config.options.composite) {
// Update the output signature
(newBuildInfo.program as ProgramBundleEmitBuildInfo).outSignature = computeSignature(changedDtsText, changedDtsData, createHash);
newBuildInfo.program.dtsChangeTime = getCurrentTime(host).getTime();
(newBuildInfo.program as ProgramBundleEmitBuildInfo).outSignature = computeSignature(changedDtsText, createHash, changedDtsData);
}
// Update sourceFileInfo
const { js, dts, sourceFiles } = buildInfo.bundle!;
+3 -2
View File
@@ -2092,10 +2092,11 @@ namespace ts {
}
/**
* @internal
* From https://github.com/nodejs/node/blob/8f39f51cbbd3b2de14b9ee896e26421cc5b20121/lib/internal/modules/esm/resolve.js#L722 -
* "longest" has some nuance as to what "longest" means in the presence of pattern trailers
*/
function comparePatternKeys(a: string, b: string) {
export function comparePatternKeys(a: string, b: string) {
const aPatternIndex = a.indexOf("*");
const bPatternIndex = b.indexOf("*");
const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
@@ -2361,7 +2362,7 @@ namespace ts {
}
/* @internal */
export function isApplicableVersionedTypesKey(conditions: string[], key: string) {
export function isApplicableVersionedTypesKey(conditions: readonly string[], key: string) {
if (conditions.indexOf("types") === -1) return false; // only apply versioned types conditions if the types condition is applied
if (!startsWith(key, "types@")) return false;
const range = VersionRange.tryParse(key.substring("types@".length));
+32 -27
View File
@@ -2449,7 +2449,7 @@ namespace ts {
return parseElement();
}
function currentNode(parsingContext: ParsingContext): Node | undefined {
function currentNode(parsingContext: ParsingContext, pos?: number): Node | undefined {
// If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
//
// If there is an outstanding parse error that we've encountered, but not attached to
@@ -2463,7 +2463,7 @@ namespace ts {
return undefined;
}
const node = syntaxCursor.currentNode(scanner.getStartPos());
const node = syntaxCursor.currentNode(pos ?? scanner.getStartPos());
// Can't reuse a missing node.
// Can't reuse a node that intersected the change range.
@@ -3631,11 +3631,11 @@ namespace ts {
const hasJSDoc = hasPrecedingJSDocComment();
const modifiers = parseModifiers();
if (parseContextualModifier(SyntaxKind.GetKeyword)) {
return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, SyntaxKind.GetAccessor);
return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, SyntaxKind.GetAccessor, SignatureFlags.Type);
}
if (parseContextualModifier(SyntaxKind.SetKeyword)) {
return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, SyntaxKind.SetAccessor);
return parseAccessorDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers, SyntaxKind.SetAccessor, SignatureFlags.Type);
}
if (isIndexSignature()) {
@@ -5646,6 +5646,11 @@ namespace ts {
if (isOptionalChain && isPrivateIdentifier(propertyAccess.name)) {
parseErrorAtRange(propertyAccess.name, Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
}
if (isExpressionWithTypeArguments(expression) && expression.typeArguments) {
const pos = expression.typeArguments.pos - 1;
const end = skipTrivia(sourceText, expression.typeArguments.end) + 1;
parseErrorAt(pos, end, Diagnostics.An_instantiation_expression_cannot_be_followed_by_a_property_access);
}
return finishNode(propertyAccess, pos);
}
@@ -5923,10 +5928,10 @@ namespace ts {
const modifiers = parseModifiers();
if (parseContextualModifier(SyntaxKind.GetKeyword)) {
return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, SyntaxKind.GetAccessor);
return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, SyntaxKind.GetAccessor, SignatureFlags.None);
}
if (parseContextualModifier(SyntaxKind.SetKeyword)) {
return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, SyntaxKind.SetAccessor);
return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, SyntaxKind.SetAccessor, SignatureFlags.None);
}
const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken);
@@ -6610,25 +6615,20 @@ namespace ts {
}
function parseDeclaration(): Statement {
// TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner
// if we can't reuse the declaration, so that we don't do this work twice?
//
// `parseListElement` attempted to get the reused node at this position,
// but the ambient context flag was not yet set, so the node appeared
// not reusable in that context.
const isAmbient = some(lookAhead(() => (parseDecorators(), parseModifiers())), isDeclareModifier);
if (isAmbient) {
const node = tryReuseAmbientDeclaration();
if (node) {
return node;
}
}
const pos = getNodePos();
const hasJSDoc = hasPrecedingJSDocComment();
const decorators = parseDecorators();
const modifiers = parseModifiers();
const isAmbient = some(modifiers, isDeclareModifier);
if (isAmbient) {
const node = tryReuseAmbientDeclaration(pos);
if (node) {
return node;
}
for (const m of modifiers!) {
(m as Mutable<Node>).flags |= NodeFlags.Ambient;
}
@@ -6639,9 +6639,9 @@ namespace ts {
}
}
function tryReuseAmbientDeclaration(): Statement | undefined {
function tryReuseAmbientDeclaration(pos: number): Statement | undefined {
return doInsideOfContext(NodeFlags.Ambient, () => {
const node = currentNode(parsingContext);
const node = currentNode(parsingContext, pos);
if (node) {
return consumeNode(node) as Statement;
}
@@ -6701,11 +6701,16 @@ namespace ts {
}
function parseFunctionBlockOrSemicolon(flags: SignatureFlags, diagnosticMessage?: DiagnosticMessage): Block | undefined {
if (token() !== SyntaxKind.OpenBraceToken && canParseSemicolon()) {
parseSemicolon();
return;
if (token() !== SyntaxKind.OpenBraceToken) {
if (flags & SignatureFlags.Type) {
parseTypeMemberSemicolon();
return;
}
if (canParseSemicolon()) {
parseSemicolon();
return;
}
}
return parseFunctionBlock(flags, diagnosticMessage);
}
@@ -6972,12 +6977,12 @@ namespace ts {
return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken);
}
function parseAccessorDeclaration(pos: number, hasJSDoc: boolean, decorators: NodeArray<Decorator> | undefined, modifiers: NodeArray<Modifier> | undefined, kind: AccessorDeclaration["kind"]): AccessorDeclaration {
function parseAccessorDeclaration(pos: number, hasJSDoc: boolean, decorators: NodeArray<Decorator> | undefined, modifiers: NodeArray<Modifier> | undefined, kind: AccessorDeclaration["kind"], flags: SignatureFlags): AccessorDeclaration {
const name = parsePropertyName();
const typeParameters = parseTypeParameters();
const parameters = parseParameters(SignatureFlags.None);
const type = parseReturnType(SyntaxKind.ColonToken, /*isType*/ false);
const body = parseFunctionBlockOrSemicolon(SignatureFlags.None);
const body = parseFunctionBlockOrSemicolon(flags);
const node = kind === SyntaxKind.GetAccessor
? factory.createGetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, type, body)
: factory.createSetAccessorDeclaration(combineDecoratorsAndModifiers(decorators, modifiers), name, parameters, body);
@@ -7188,11 +7193,11 @@ namespace ts {
}
if (parseContextualModifier(SyntaxKind.GetKeyword)) {
return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, SyntaxKind.GetAccessor);
return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, SyntaxKind.GetAccessor, SignatureFlags.None);
}
if (parseContextualModifier(SyntaxKind.SetKeyword)) {
return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, SyntaxKind.SetAccessor);
return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, SyntaxKind.SetAccessor, SignatureFlags.None);
}
if (token() === SyntaxKind.ConstructorKeyword || token() === SyntaxKind.StringLiteral) {
+1 -1
View File
@@ -3118,7 +3118,7 @@ namespace ts {
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined,
reason: FileIncludeReason
): void {
tracing?.push(tracing.Phase.Program, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined });
tracing?.push(tracing.Phase.Program, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined });
processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason);
tracing?.pop();
}
+5 -4
View File
@@ -131,9 +131,9 @@ namespace ts { // eslint-disable-line one-namespace-per-file
}
eventStack.push({ phase, name, args, time: 1000 * timestamp(), separateBeginAndEnd });
}
export function pop() {
export function pop(results?: Args) {
Debug.assert(eventStack.length > 0);
writeStackEvent(eventStack.length - 1, 1000 * timestamp());
writeStackEvent(eventStack.length - 1, 1000 * timestamp(), results);
eventStack.length--;
}
export function popAll() {
@@ -145,14 +145,15 @@ namespace ts { // eslint-disable-line one-namespace-per-file
}
// sample every 10ms
const sampleInterval = 1000 * 10;
function writeStackEvent(index: number, endTime: number) {
function writeStackEvent(index: number, endTime: number, results?: Args) {
const { phase, name, args, time, separateBeginAndEnd } = eventStack[index];
if (separateBeginAndEnd) {
Debug.assert(!results, "`results` are not supported for events with `separateBeginAndEnd`");
writeEvent("E", phase, name, args, /*extras*/ undefined, endTime);
}
// test if [time,endTime) straddles a sampling point
else if (sampleInterval - (time % sampleInterval) <= endTime - time) {
writeEvent("X", phase, name, args, `"dur":${endTime - time}`, time);
writeEvent("X", phase, name, { ...args, results }, `"dur":${endTime - time}`, time);
}
}
-1
View File
@@ -72,7 +72,6 @@ namespace ts {
type: UpToDateStatusType.UpToDate | UpToDateStatusType.UpToDateWithUpstreamTypes | UpToDateStatusType.UpToDateWithInputFileText;
newestInputFileTime?: Date;
newestInputFileName?: string;
newestDeclarationFileContentChangedTime: Date | undefined;
oldestOutputFileName: string;
}
+33 -27
View File
@@ -224,6 +224,7 @@ namespace ts {
path: Path;
buildInfo: BuildInfo | false;
modifiedTime: Date;
latestChangedDtsTime?: Date | false;
}
interface SolutionBuilderState<T extends BuilderProgram = BuilderProgram> extends WatchFactory<WatchType, ResolvedConfigFileName> {
@@ -980,8 +981,7 @@ namespace ts {
// Actual Emit
const { host, compilerHost } = state;
let resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
const existingBuildInfo = state.buildInfoCache.get(projectPath)?.buildInfo || undefined;
const resultFlags = program.hasChangedEmitSignature?.() ? BuildResultFlags.None : BuildResultFlags.DeclarationOutputUnchanged;
const emitterDiagnostics = createDiagnosticCollection();
const emittedOutputs = new Map<Path, string>();
const options = program.getCompilerOptions();
@@ -991,13 +991,7 @@ namespace ts {
outputFiles.forEach(({ name, text, writeByteOrderMark, buildInfo }) => {
const path = toPath(state, name);
emittedOutputs.set(toPath(state, name), name);
if (buildInfo) {
setBuildInfo(state, buildInfo, projectPath, options);
// Buildinfo has information on when last dts change time
if (buildInfo.program?.dtsChangeTime !== existingBuildInfo?.program?.dtsChangeTime) {
resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
}
}
if (buildInfo) setBuildInfo(state, buildInfo, projectPath, options, resultFlags);
writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
if (!isIncremental && state.watch) {
(outputTimeStampMap ||= getOutputTimeStampMap(state, projectPath)!).set(path, now ||= getCurrentTime(state.host));
@@ -1017,7 +1011,7 @@ namespace ts {
Debug.assertIsDefined(program);
Debug.assert(step === BuildStep.EmitBuildInfo);
const emitResult = program.emitBuildInfo((name, text, writeByteOrderMark, onError, sourceFiles, data) => {
if (data?.buildInfo) setBuildInfo(state, data.buildInfo, projectPath, program!.getCompilerOptions());
if (data?.buildInfo) setBuildInfo(state, data.buildInfo, projectPath, program!.getCompilerOptions(), BuildResultFlags.DeclarationOutputUnchanged);
if (writeFileCallback) writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data);
else state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data);
}, cancellationToken);
@@ -1064,7 +1058,6 @@ namespace ts {
state.diagnostics.delete(projectPath);
state.projectStatus.set(projectPath, {
type: UpToDateStatusType.UpToDate,
newestDeclarationFileContentChangedTime: getDtsChangeTime(state, config.options, projectPath)!,
oldestOutputFileName
});
afterProgramDone(state, program, config);
@@ -1120,10 +1113,10 @@ namespace ts {
outputFiles.forEach(({ name, text, writeByteOrderMark, buildInfo }) => {
emittedOutputs.set(toPath(state, name), name);
if (buildInfo) {
setBuildInfo(state, buildInfo, projectPath, config.options);
if (buildInfo.program?.dtsChangeTime !== existingBuildInfo.program?.dtsChangeTime) {
if ((buildInfo.program as ProgramBundleEmitBuildInfo)?.outSignature !== (existingBuildInfo.program as ProgramBundleEmitBuildInfo)?.outSignature) {
resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
}
setBuildInfo(state, buildInfo, projectPath, config.options, resultFlags);
}
writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
});
@@ -1365,7 +1358,7 @@ namespace ts {
config: ParsedCommandLine
) {
if (program) {
if (program && state.write) listFiles(program, state.write);
if (state.write) listFiles(program, state.write);
if (state.host.afterProgramEmitAndDiagnostics) {
state.host.afterProgramEmitAndDiagnostics(program);
}
@@ -1464,15 +1457,28 @@ namespace ts {
return result;
}
function setBuildInfo(state: SolutionBuilderState, buildInfo: BuildInfo, resolvedConfigPath: ResolvedConfigFilePath, options: CompilerOptions) {
function setBuildInfo(
state: SolutionBuilderState,
buildInfo: BuildInfo,
resolvedConfigPath: ResolvedConfigFilePath,
options: CompilerOptions,
resultFlags: BuildResultFlags,
) {
const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options)!;
const existing = getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath);
const modifiedTime = getCurrentTime(state.host);
if (existing) {
existing.buildInfo = buildInfo;
existing.modifiedTime = getCurrentTime(state.host);
existing.modifiedTime = modifiedTime;
if (!(resultFlags & BuildResultFlags.DeclarationOutputUnchanged)) existing.latestChangedDtsTime = modifiedTime;
}
else {
state.buildInfoCache.set(resolvedConfigPath, { path: toPath(state, buildInfoPath), buildInfo, modifiedTime: getCurrentTime(state.host) });
state.buildInfoCache.set(resolvedConfigPath, {
path: toPath(state, buildInfoPath),
buildInfo,
modifiedTime,
latestChangedDtsTime: resultFlags & BuildResultFlags.DeclarationOutputUnchanged ? undefined : modifiedTime,
});
}
}
@@ -1563,7 +1569,6 @@ namespace ts {
let buildInfoTime: Date | undefined;
let buildInfoProgram: ProgramBuildInfo | undefined;
let buildInfoVersionMap: ESMap<Path, string> | undefined;
let newestDeclarationFileContentChangedTime;
if (buildInfoPath) {
const buildInfoCacheEntry = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath);
buildInfoTime = buildInfoCacheEntry?.modifiedTime || ts.getModifiedTime(host, buildInfoPath);
@@ -1603,8 +1608,6 @@ namespace ts {
oldestOutputFileTime = buildInfoTime;
oldestOutputFileName = buildInfoPath;
// Get the last dtsChange time from build info
newestDeclarationFileContentChangedTime = buildInfo.program?.dtsChangeTime ? new Date(buildInfo.program.dtsChangeTime) : undefined;
}
// Check input files
@@ -1718,7 +1721,8 @@ namespace ts {
// If the upstream project has only change .d.ts files, and we've built
// *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
const newestDeclarationFileContentChangedTime = getLatestChangedDtsTime(state, resolvedConfig.options, resolvedRefPath);
if (newestDeclarationFileContentChangedTime && newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
pseudoUpToDate = true;
upstreamChangedProject = ref.path;
continue;
@@ -1764,7 +1768,6 @@ namespace ts {
pseudoInputUpToDate ?
UpToDateStatusType.UpToDateWithInputFileText :
UpToDateStatusType.UpToDate,
newestDeclarationFileContentChangedTime,
newestInputFileTime,
newestInputFileName,
oldestOutputFileName: oldestOutputFileName!
@@ -1854,11 +1857,15 @@ namespace ts {
});
}
function getDtsChangeTime(state: SolutionBuilderState, options: CompilerOptions, resolvedConfigPath: ResolvedConfigFilePath) {
function getLatestChangedDtsTime(state: SolutionBuilderState, options: CompilerOptions, resolvedConfigPath: ResolvedConfigFilePath) {
if (!options.composite) return undefined;
const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options)!;
const buildInfo = getBuildInfo(state, buildInfoPath, resolvedConfigPath, /*modifiedTime*/ undefined);
return buildInfo?.program?.dtsChangeTime ? new Date(buildInfo.program.dtsChangeTime) : undefined;
const entry = Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath));
if (entry.latestChangedDtsTime !== undefined) return entry.latestChangedDtsTime || undefined;
const latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ?
state.host.getModifiedTime(getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, getDirectoryPath(entry.path))) :
undefined;
entry.latestChangedDtsTime = latestChangedDtsTime || false;
return latestChangedDtsTime;
}
function updateOutputTimestamps(state: SolutionBuilderState, proj: ParsedCommandLine, resolvedPath: ResolvedConfigFilePath) {
@@ -1868,7 +1875,6 @@ namespace ts {
updateOutputTimestampsWorker(state, proj, resolvedPath, Diagnostics.Updating_output_timestamps_of_project_0);
state.projectStatus.set(resolvedPath, {
type: UpToDateStatusType.UpToDate,
newestDeclarationFileContentChangedTime: getDtsChangeTime(state, proj.options, resolvedPath),
oldestOutputFileName: getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
});
}
+14 -5
View File
@@ -3791,6 +3791,12 @@ namespace ts {
* It is _public_ so that (pre)transformers can set this field,
* since it switches the builtin `node` module transform. Generally speaking, if unset,
* the field is treated as though it is `ModuleKind.CommonJS`.
*
* Note that this field is only set by the module resolution process when
* `moduleResolution` is `Node16` or `NodeNext`, which is implied by the `module` setting
* of `Node16` or `NodeNext`, respectively, but may be overriden (eg, by a `moduleResolution`
* of `node`). If so, this field will be unset and source files will be considered to be
* CommonJS-output-format by the node module transformer and type checker, regardless of extension or context.
*/
impliedNodeFormat?: ModuleKind.ESNext | ModuleKind.CommonJS;
@@ -4026,6 +4032,7 @@ namespace ts {
export interface WriteFileCallbackData {
/*@internal*/ sourceMapUrlPos?: number;
/*@internal*/ buildInfo?: BuildInfo;
/*@internal*/ diagnostics?: readonly DiagnosticWithLocation[];
}
export type WriteFileCallback = (
fileName: string,
@@ -4335,7 +4342,6 @@ namespace ts {
diagnostics: readonly Diagnostic[];
emittedFiles?: string[]; // Array of files the compiler wrote to disk
/* @internal */ sourceMaps?: SourceMapEmitResult[]; // Array of sourceMapData if compiler emitted sourcemaps
/* @internal */ exportedModulesFromDeclarationEmit?: ExportedModulesFromDeclarationEmit;
}
/* @internal */
@@ -4664,10 +4670,11 @@ namespace ts {
UseAliasDefinedOutsideCurrentScope = 1 << 14, // Allow non-visible aliases
UseSingleQuotesForStringLiteralType = 1 << 28, // Use single quotes for string literal type
NoTypeReduction = 1 << 29, // Don't call getReducedType
OmitThisParameter = 1 << 25,
// Error handling
AllowThisInObjectLiteral = 1 << 15,
AllowQualifiedNameInPlaceOfIdentifier = 1 << 16,
AllowQualifiedNameInPlaceOfIdentifier = 1 << 16,
/** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */
AllowQualifedNameInPlaceOfIdentifier = AllowQualifiedNameInPlaceOfIdentifier,
AllowAnonymousIdentifier = 1 << 17,
@@ -4709,6 +4716,7 @@ namespace ts {
UseAliasDefinedOutsideCurrentScope = 1 << 14, // For a `type T = ... ` defined in a different file, write `T` instead of its value, even though `T` can't be accessed in the current scope.
UseSingleQuotesForStringLiteralType = 1 << 28, // Use single quotes for string literal type
NoTypeReduction = 1 << 29, // Don't call getReducedType
OmitThisParameter = 1 << 25,
// Error Handling
AllowUniqueESSymbolType = 1 << 20, // This is bit 20 to align with the same bit in `NodeBuilderFlags`
@@ -4728,7 +4736,7 @@ namespace ts {
NodeBuilderFlagsMask = NoTruncation | WriteArrayAsGenericType | UseStructuralFallback | WriteTypeArgumentsOfSignature |
UseFullyQualifiedType | SuppressAnyReturnType | MultilineObjectLiterals | WriteClassExpressionAsTypeLiteral |
UseTypeOfFunction | OmitParameterModifiers | UseAliasDefinedOutsideCurrentScope | AllowUniqueESSymbolType | InTypeAlias |
UseSingleQuotesForStringLiteralType | NoTypeReduction,
UseSingleQuotesForStringLiteralType | NoTypeReduction | OmitThisParameter
}
export const enum SymbolFormatFlags {
@@ -6025,6 +6033,7 @@ namespace ts {
export const enum TypeMapKind {
Simple,
Array,
Deferred,
Function,
Composite,
Merged,
@@ -6034,7 +6043,8 @@ namespace ts {
export type TypeMapper =
| { kind: TypeMapKind.Simple, source: Type, target: Type }
| { kind: TypeMapKind.Array, sources: readonly Type[], targets: readonly Type[] | undefined }
| { kind: TypeMapKind.Function, func: (t: Type) => Type }
| { kind: TypeMapKind.Deferred, sources: readonly Type[], targets: (() => Type)[] }
| { kind: TypeMapKind.Function, func: (t: Type) => Type, debugInfo?: () => string }
| { kind: TypeMapKind.Composite | TypeMapKind.Merged, mapper1: TypeMapper, mapper2: TypeMapper };
export const enum InferencePriority {
@@ -6981,7 +6991,6 @@ namespace ts {
// For testing:
/*@internal*/ disableUseFileVersionAsSignature?: boolean;
/*@internal*/ storeFilesChangingSignatureDuringEmit?: boolean;
/*@internal*/ now?(): Date;
}
/** true if --out otherwise source file name */
+4 -6
View File
@@ -5565,7 +5565,8 @@ namespace ts {
export function getDeclarationModifierFlagsFromSymbol(s: Symbol, isWrite = false): ModifierFlags {
if (s.valueDeclaration) {
const declaration = (isWrite && s.declarations && find(s.declarations, d => d.kind === SyntaxKind.SetAccessor)) || s.valueDeclaration;
const declaration = (isWrite && s.declarations && find(s.declarations, isSetAccessorDeclaration))
|| (s.flags & SymbolFlags.GetAccessor && find(s.declarations, isGetAccessorDeclaration)) || s.valueDeclaration;
const flags = getCombinedModifierFlags(declaration);
return s.parent && s.parent.flags & SymbolFlags.Class ? flags : flags & ~ModifierFlags.AccessibilityModifier;
}
@@ -6319,7 +6320,7 @@ namespace ts {
// Excludes declaration files - they still require an explicit `export {}` or the like
// for back compat purposes. The only non-declaration files _not_ forced to be a module are `.js` files
// that aren't esm-mode (meaning not in a `type: module` scope).
return (file.impliedNodeFormat === ModuleKind.ESNext || (fileExtensionIsOneOf(file.fileName, [Extension.Cjs, Extension.Cts]))) && !file.isDeclarationFile ? true : undefined;
return (file.impliedNodeFormat === ModuleKind.ESNext || (fileExtensionIsOneOf(file.fileName, [Extension.Cjs, Extension.Cts, Extension.Mjs, Extension.Mts]))) && !file.isDeclarationFile ? true : undefined;
}
export function getSetExternalModuleIndicator(options: CompilerOptions): (file: SourceFile) => void {
@@ -6343,10 +6344,7 @@ namespace ts {
if (options.jsx === JsxEmit.ReactJSX || options.jsx === JsxEmit.ReactJSXDev) {
checks.push(isFileModuleFromUsingJSXTag);
}
const moduleKind = getEmitModuleKind(options);
if (moduleKind === ModuleKind.Node16 || moduleKind === ModuleKind.NodeNext) {
checks.push(isFileForcedToBeModuleByFormat);
}
checks.push(isFileForcedToBeModuleByFormat);
const combined = or(...checks);
const callback = (file: SourceFile) => void (file.externalModuleIndicator = combined(file));
return callback;
-1
View File
@@ -596,7 +596,6 @@ namespace ts {
readDirectory: maybeBind(host, host.readDirectory),
disableUseFileVersionAsSignature: host.disableUseFileVersionAsSignature,
storeFilesChangingSignatureDuringEmit: host.storeFilesChangingSignatureDuringEmit,
now: maybeBind(host, host.now),
};
function writeFile(fileName: string, text: string, writeByteOrderMark: boolean, onError: (message: string) => void) {
+2 -5
View File
@@ -30,7 +30,6 @@ namespace ts {
host.createHash = maybeBind(system, system.createHash);
host.disableUseFileVersionAsSignature = system.disableUseFileVersionAsSignature;
host.storeFilesChangingSignatureDuringEmit = system.storeFilesChangingSignatureDuringEmit;
host.now = maybeBind(system, system.now);
setGetSourceFileAsHashVersioned(host, system);
changeCompilerHostLikeToUseCache(host, fileName => toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName));
return host;
@@ -284,7 +283,6 @@ namespace ts {
let parsedConfigs: ESMap<Path, ParsedConfig> | undefined; // Parsed commandline and watching cached for referenced projects
let sharedExtendedConfigFileWatchers: ESMap<Path, SharedExtendedConfigFileWatcher<Path>>; // Map of file watchers for extended files, shared between different referenced projects
let extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation
let changesAffectResolution = false; // Flag for indicating non-config changes affect module resolution
let reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created
const sourceFilesCache = new Map<string, HostFileInfo>(); // Cache that stores the source file and version info
@@ -435,13 +433,13 @@ namespace ts {
const program = getCurrentBuilderProgram();
if (hasChangedCompilerOptions) {
newLine = updateNewLine();
if (program && (changesAffectResolution || changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions))) {
if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
resolutionCache.clear();
}
}
// All resolutions are invalid if user provided resolutions
const hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution);
const hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) {
if (hasChangedConfigFileParsingErrors) {
if (reportFileChangeDetectedOnCreateProgram) {
@@ -458,7 +456,6 @@ namespace ts {
createNewProgram(hasInvalidatedResolution);
}
changesAffectResolution = false; // reset for next sync
reportFileChangeDetectedOnCreateProgram = false;
if (host.afterProgramCreate && program !== builderProgram) {
+62 -1
View File
@@ -1,16 +1,36 @@
interface Map<K, V> {
clear(): void;
/**
* @returns true if an element in the Map existed and has been removed, or false if the element does not exist.
*/
delete(key: K): boolean;
/**
* Executes a provided function once per each key/value pair in the Map, in insertion order.
*/
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
/**
* Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
* @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.
*/
get(key: K): V | undefined;
/**
* @returns boolean indicating whether an element with the specified key exists or not.
*/
has(key: K): boolean;
/**
* Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.
*/
set(key: K, value: V): this;
/**
* @returns the number of elements in the Map.
*/
readonly size: number;
}
interface MapConstructor {
new(): Map<any, any>;
new<K, V>(entries?: readonly (readonly [K, V])[] | null): Map<K, V>;
new <K, V>(entries?: readonly (readonly [K, V])[] | null): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
@@ -23,9 +43,23 @@ interface ReadonlyMap<K, V> {
}
interface WeakMap<K extends object, V> {
/**
* Removes the specified element from the WeakMap.
* @returns true if the element was successfully removed, or false if it was not present.
*/
delete(key: K): boolean;
/**
* @returns a specified element.
*/
get(key: K): V | undefined;
/**
* @returns a boolean indicating whether an element with the specified key exists or not.
*/
has(key: K): boolean;
/**
* Adds a new element with a specified key and value.
* @param key Must be an object.
*/
set(key: K, value: V): this;
}
@@ -36,11 +70,28 @@ interface WeakMapConstructor {
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
/**
* Appends a new element with a specified value to the end of the Set.
*/
add(value: T): this;
clear(): void;
/**
* Removes a specified value from the Set.
* @returns Returns true if an element in the Set existed and has been removed, or false if the element does not exist.
*/
delete(value: T): boolean;
/**
* Executes a provided function once per each value in the Set object, in insertion order.
*/
forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void;
/**
* @returns a boolean indicating whether an element with the specified value exists in the Set or not.
*/
has(value: T): boolean;
/**
* @returns the number of (unique) elements in Set.
*/
readonly size: number;
}
@@ -57,8 +108,18 @@ interface ReadonlySet<T> {
}
interface WeakSet<T extends object> {
/**
* Appends a new object to the end of the WeakSet.
*/
add(value: T): this;
/**
* Removes the specified element from the WeakSet.
* @returns Returns true if the element existed and has been removed, or false if the element does not exist.
*/
delete(value: T): boolean;
/**
* @returns a boolean indicating whether an object exists in the WeakSet or not.
*/
has(value: T): boolean;
}
+2 -2
View File
@@ -1,9 +1,9 @@
interface ErrorOptions {
cause?: Error;
cause?: unknown;
}
interface Error {
cause?: Error;
cause?: unknown;
}
interface ErrorConstructor {
+2 -1
View File
@@ -709,7 +709,8 @@ namespace ts.server {
this.program!,
scriptInfo.path,
this.cancellationToken,
maybeBind(this.projectService.host, this.projectService.host.createHash)
maybeBind(this.projectService.host, this.projectService.host.createHash),
this.getCanonicalFileName,
),
sourceFile => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined
);
@@ -51,7 +51,7 @@ namespace ts.codefix {
if (!newConstraint) return;
const newConstraintText = newConstraint[1];
changes.insertText(related.file!, related.start! + related.length!, ` extends ${newConstraintText}`);
changes.insertText(related.file!, decl.name.end, ` extends ${newConstraintText}`);
}
function findAncestorMatchingSpan(sourceFile: SourceFile, span: TextSpan): Node {
+52 -78
View File
@@ -507,87 +507,61 @@ namespace ts.Completions {
}
const entries = createSortedArray<CompletionEntry>();
if (isUncheckedFile(sourceFile, compilerOptions)) {
const uniqueNames = getCompletionEntriesFromSymbols(
symbols,
entries,
/*replacementToken*/ undefined,
contextToken,
location,
sourceFile,
host,
program,
getEmitScriptTarget(compilerOptions),
log,
completionKind,
preferences,
compilerOptions,
formatContext,
isTypeOnlyLocation,
propertyAccessToConvert,
isJsxIdentifierExpected,
isJsxInitializer,
importCompletionNode,
recommendedCompletion,
symbolToOriginInfoMap,
symbolToSortTextMap,
isJsxIdentifierExpected,
isRightOfOpenTag,
);
getJSCompletionEntries(sourceFile, location.pos, uniqueNames, getEmitScriptTarget(compilerOptions), entries);
}
else {
if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === KeywordCompletionFilters.None) {
return undefined;
}
getCompletionEntriesFromSymbols(
symbols,
entries,
/*replacementToken*/ undefined,
contextToken,
location,
sourceFile,
host,
program,
getEmitScriptTarget(compilerOptions),
log,
completionKind,
preferences,
compilerOptions,
formatContext,
isTypeOnlyLocation,
propertyAccessToConvert,
isJsxIdentifierExpected,
isJsxInitializer,
importCompletionNode,
recommendedCompletion,
symbolToOriginInfoMap,
symbolToSortTextMap,
isJsxIdentifierExpected,
isRightOfOpenTag,
);
const isChecked = isCheckedFile(sourceFile, compilerOptions);
if (isChecked && !isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === KeywordCompletionFilters.None) {
return undefined;
}
const uniqueNames = getCompletionEntriesFromSymbols(
symbols,
entries,
/*replacementToken*/ undefined,
contextToken,
location,
sourceFile,
host,
program,
getEmitScriptTarget(compilerOptions),
log,
completionKind,
preferences,
compilerOptions,
formatContext,
isTypeOnlyLocation,
propertyAccessToConvert,
isJsxIdentifierExpected,
isJsxInitializer,
importCompletionNode,
recommendedCompletion,
symbolToOriginInfoMap,
symbolToSortTextMap,
isJsxIdentifierExpected,
isRightOfOpenTag,
);
if (keywordFilters !== KeywordCompletionFilters.None) {
const entryNames = new Set(entries.map(e => e.name));
for (const keywordEntry of getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && isSourceFileJS(sourceFile))) {
if (isTypeOnlyLocation && isTypeKeyword(stringToToken(keywordEntry.name)!) || !entryNames.has(keywordEntry.name)) {
if (isTypeOnlyLocation && isTypeKeyword(stringToToken(keywordEntry.name)!) || !uniqueNames.has(keywordEntry.name)) {
uniqueNames.add(keywordEntry.name);
insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true);
}
}
}
const entryNames = new Set(entries.map(e => e.name));
for (const keywordEntry of getContextualKeywords(contextToken, position)) {
if (!entryNames.has(keywordEntry.name)) {
if (!uniqueNames.has(keywordEntry.name)) {
uniqueNames.add(keywordEntry.name);
insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true);
}
}
for (const literal of literals) {
insertSorted(entries, createCompletionEntryForLiteral(sourceFile, preferences, literal), compareCompletionEntries, /*allowDuplicates*/ true);
const literalEntry = createCompletionEntryForLiteral(sourceFile, preferences, literal);
uniqueNames.add(literalEntry.name);
insertSorted(entries, literalEntry, compareCompletionEntries, /*allowDuplicates*/ true);
}
if (!isChecked) {
getJSCompletionEntries(sourceFile, location.pos, uniqueNames, getEmitScriptTarget(compilerOptions), entries);
}
return {
@@ -601,8 +575,8 @@ namespace ts.Completions {
};
}
function isUncheckedFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean {
return isSourceFileJS(sourceFile) && !isCheckJsEnabledForFile(sourceFile, compilerOptions);
function isCheckedFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean {
return !isSourceFileJS(sourceFile) || !!isCheckJsEnabledForFile(sourceFile, compilerOptions);
}
function isMemberCompletionKind(kind: CompletionKind): boolean {
@@ -1152,7 +1126,7 @@ namespace ts.Completions {
const name = getSynthesizedDeepClone(getNameOfDeclaration(declaration), /*includeTrivia*/ false) as PropertyName;
const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration));
const quotePreference = getQuotePreference(sourceFile, preferences);
const builderFlags = quotePreference === QuotePreference.Single ? NodeBuilderFlags.UseSingleQuotesForStringLiteralType : undefined;
const builderFlags = NodeBuilderFlags.OmitThisParameter | (quotePreference === QuotePreference.Single ? NodeBuilderFlags.UseSingleQuotesForStringLiteralType : NodeBuilderFlags.None);
switch (declaration.kind) {
case SyntaxKind.PropertySignature:
@@ -1942,7 +1916,7 @@ namespace ts.Completions {
cancellationToken?: CancellationToken,
): CompletionData | Request | undefined {
const typeChecker = program.getTypeChecker();
const inUncheckedFile = isUncheckedFile(sourceFile, compilerOptions);
const inCheckedFile = isCheckedFile(sourceFile, compilerOptions);
let start = timestamp();
let currentToken = getTokenAtPosition(sourceFile, position); // TODO: GH#15853
// We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.)
@@ -2396,7 +2370,14 @@ namespace ts.Completions {
}
const propertyAccess = node.kind === SyntaxKind.ImportType ? node as ImportTypeNode : node.parent as PropertyAccessExpression | QualifiedName;
if (inUncheckedFile) {
if (inCheckedFile) {
for (const symbol of type.getApparentProperties()) {
if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) {
addPropertySymbol(symbol, /* insertAwait */ false, insertQuestionDot);
}
}
}
else {
// In javascript files, for union types, we don't just get the members that
// the individual types have in common, we also include all the members that
// each individual type has. This is because we're going to add all identifiers
@@ -2404,13 +2385,6 @@ namespace ts.Completions {
// of the individual types to a higher status since we know what they are.
symbols.push(...filter(getPropertiesForCompletion(type, typeChecker), s => typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, s)));
}
else {
for (const symbol of type.getApparentProperties()) {
if (typeChecker.isValidPropertyAccessForCompletions(propertyAccess, type, symbol)) {
addPropertySymbol(symbol, /* insertAwait */ false, insertQuestionDot);
}
}
}
if (insertAwait && preferences.includeCompletionsWithInsertText) {
const promiseType = typeChecker.getPromisedTypeOfPromise(type);
+28 -15
View File
@@ -343,20 +343,25 @@ namespace ts {
}
getContextualDocumentationComment(context: Node | undefined, checker: TypeChecker | undefined): SymbolDisplayPart[] {
switch (context?.kind) {
case SyntaxKind.GetAccessor:
if (context) {
if (isGetAccessor(context)) {
if (!this.contextualGetAccessorDocumentationComment) {
this.contextualGetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isGetAccessor), checker);
}
return this.contextualGetAccessorDocumentationComment;
case SyntaxKind.SetAccessor:
if (length(this.contextualGetAccessorDocumentationComment)) {
return this.contextualGetAccessorDocumentationComment;
}
}
if (isSetAccessor(context)) {
if (!this.contextualSetAccessorDocumentationComment) {
this.contextualSetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isSetAccessor), checker);
}
return this.contextualSetAccessorDocumentationComment;
default:
return this.getDocumentationComment(checker);
if (length(this.contextualSetAccessorDocumentationComment)) {
return this.contextualSetAccessorDocumentationComment;
}
}
}
return this.getDocumentationComment(checker);
}
getJsDocTags(checker?: TypeChecker): JSDocTagInfo[] {
@@ -368,20 +373,25 @@ namespace ts {
}
getContextualJsDocTags(context: Node | undefined, checker: TypeChecker | undefined): JSDocTagInfo[] {
switch (context?.kind) {
case SyntaxKind.GetAccessor:
if (context) {
if (isGetAccessor(context)) {
if (!this.contextualGetAccessorTags) {
this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isGetAccessor), checker);
}
return this.contextualGetAccessorTags;
case SyntaxKind.SetAccessor:
if (length(this.contextualGetAccessorTags)) {
return this.contextualGetAccessorTags;
}
}
if (isSetAccessor(context)) {
if (!this.contextualSetAccessorTags) {
this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isSetAccessor), checker);
}
return this.contextualSetAccessorTags;
default:
return this.getJsDocTags(checker);
if (length(this.contextualSetAccessorTags)) {
return this.contextualSetAccessorTags;
}
}
}
return this.getJsDocTags(checker);
}
}
@@ -1283,7 +1293,10 @@ namespace ts {
lastTypesRootVersion = typeRootsVersion;
}
const rootFileNames = host.getScriptFileNames();
// This array is retained by the program and will be used to determine if the program is up to date,
// so we need to make a copy in case the host mutates the underlying array - otherwise it would look
// like every program always has the host's current list of root files.
const rootFileNames = host.getScriptFileNames().slice();
// Get a fresh cache of the host information
const newSettings = host.getCompilationSettings() || getDefaultCompilerOptions();
+16 -2
View File
@@ -52,13 +52,24 @@ namespace ts.SmartSelectionRange {
// selected from open to close, including whitespace but not including the braces/etc. themselves.
const isBetweenMultiLineBookends = isSyntaxList(node) && isListOpener(prevNode) && isListCloser(nextNode)
&& !positionsAreOnSameLine(prevNode.getStart(), nextNode.getStart(), sourceFile);
const start = isBetweenMultiLineBookends ? prevNode.getEnd() : node.getStart();
let start = isBetweenMultiLineBookends ? prevNode.getEnd() : node.getStart();
const end = isBetweenMultiLineBookends ? nextNode.getStart() : getEndPos(sourceFile, node);
if (hasJSDocNodes(node) && node.jsDoc?.length) {
pushSelectionRange(first(node.jsDoc).getStart(), end);
}
// (#39618 & #49807)
// When the node is a SyntaxList and its first child has a JSDoc comment, then the node's
// `start` (which usually is the result of calling `node.getStart()`) points to the first
// token after the JSDoc comment. So, we have to make sure we'd pushed the selection
// covering the JSDoc comment before diving further.
if (isSyntaxList(node)) {
const firstChild = node.getChildren()[0];
if (firstChild && hasJSDocNodes(firstChild) && firstChild.jsDoc?.length && firstChild.getStart() !== node.pos) {
start = Math.min(start, first(firstChild.jsDoc).getStart());
}
}
pushSelectionRange(start, end);
// String literals should have a stop both inside and outside their quotes.
@@ -184,7 +195,10 @@ namespace ts.SmartSelectionRange {
if (isPropertySignature(node)) {
const children = groupChildren(node.getChildren(), child =>
child === node.name || contains(node.modifiers, child));
return splitChildren(children, ({ kind }) => kind === SyntaxKind.ColonToken);
const firstJSDocChild = children[0]?.kind === SyntaxKind.JSDoc ? children[0] : undefined;
const withJSDocSeparated = firstJSDocChild? children.slice(1) : children;
const splittedChildren = splitChildren(withJSDocSeparated, ({ kind }) => kind === SyntaxKind.ColonToken);
return firstJSDocChild? [firstJSDocChild, createSyntaxList(splittedChildren)] : splittedChildren;
}
// Group the parameter name with its `...`, then that group with its `?`, then pivot on `=`.
+190 -103
View File
@@ -1,5 +1,30 @@
/* @internal */
namespace ts.Completions.StringCompletions {
interface NameAndKindSet {
add(value: NameAndKind): void;
has(name: string): boolean;
values(): Iterator<NameAndKind>;
}
const kindPrecedence = {
[ScriptElementKind.directory]: 0,
[ScriptElementKind.scriptElement]: 1,
[ScriptElementKind.externalModuleName]: 2,
};
function createNameAndKindSet(): NameAndKindSet {
const map = new Map<string, NameAndKind>();
function add(value: NameAndKind) {
const existing = map.get(value.name);
if (!existing || kindPrecedence[existing.kind] < kindPrecedence[value.kind]) {
map.set(value.name, value);
}
}
return {
add,
has: map.has.bind(map),
values: map.values.bind(map),
};
}
export function getStringLiteralCompletions(
sourceFile: SourceFile,
position: number,
@@ -343,13 +368,14 @@ namespace ts.Completions.StringCompletions {
function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker, preferences: UserPreferences): readonly NameAndKind[] {
const literalValue = normalizeSlashes(node.text);
const mode = isStringLiteralLike(node) ? getModeForUsageLocation(sourceFile, node) : undefined;
const scriptPath = sourceFile.path;
const scriptDirectory = getDirectoryPath(scriptPath);
return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && (isRootedDiskPath(literalValue) || isUrl(literalValue))
? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, getIncludeExtensionOption())
: getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, compilerOptions, host, typeChecker);
: getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, compilerOptions, host, getIncludeExtensionOption(), typeChecker);
function getIncludeExtensionOption() {
const mode = isStringLiteralLike(node) ? getModeForUsageLocation(sourceFile, node) : undefined;
@@ -371,7 +397,7 @@ namespace ts.Completions.StringCompletions {
compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, compilerOptions, host, scriptPath);
}
else {
return getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath);
return arrayFrom(getCompletionEntriesForDirectoryFragment(literalValue, scriptDirectory, extensionOptions, host, scriptPath).values());
}
}
@@ -416,7 +442,7 @@ namespace ts.Completions.StringCompletions {
const basePath = compilerOptions.project || host.getCurrentDirectory();
const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames());
const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase);
return flatMap(baseDirectories, baseDirectory => getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude));
return flatMap(baseDirectories, baseDirectory => arrayFrom(getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, host, exclude).values()));
}
const enum IncludeExtensionsOption {
@@ -427,7 +453,14 @@ namespace ts.Completions.StringCompletions {
/**
* Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename.
*/
function getCompletionEntriesForDirectoryFragment(fragment: string, scriptPath: string, { extensions, includeExtensionsOption }: ExtensionOptions, host: LanguageServiceHost, exclude?: string, result: NameAndKind[] = []): NameAndKind[] {
function getCompletionEntriesForDirectoryFragment(
fragment: string,
scriptPath: string,
extensionOptions: ExtensionOptions,
host: LanguageServiceHost,
exclude?: string,
result = createNameAndKindSet()
): NameAndKindSet {
if (fragment === undefined) {
fragment = "";
}
@@ -461,7 +494,7 @@ namespace ts.Completions.StringCompletions {
if (versionPaths) {
const packageDirectory = getDirectoryPath(packageJsonPath);
const pathInPackage = absolutePath.slice(ensureTrailingDirectorySeparator(packageDirectory).length);
if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensions, versionPaths, host)) {
if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, host, versionPaths)) {
// A true result means one of the `versionPaths` was matched, which will block relative resolution
// to files and folders from here. All reachable paths given the pattern match are already added.
return result;
@@ -474,41 +507,18 @@ namespace ts.Completions.StringCompletions {
if (!tryDirectoryExists(host, baseDirectory)) return result;
// Enumerate the available files if possible
const files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]);
const files = tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, /*include*/ ["./*"]);
if (files) {
/**
* Multiple file entries might map to the same truncated name once we remove extensions
* (happens iff includeExtensionsOption === includeExtensionsOption.Exclude) so we use a set-like data structure. Eg:
*
* both foo.ts and foo.tsx become foo
*/
const foundFiles = new Map<string, Extension | undefined>(); // maps file to its extension
for (let filePath of files) {
filePath = normalizePath(filePath);
if (exclude && comparePaths(filePath, exclude, scriptPath, ignoreCase) === Comparison.EqualTo) {
continue;
}
let foundFileName: string;
const outputExtension = moduleSpecifiers.tryGetJSExtensionForFile(filePath, host.getCompilationSettings());
if (includeExtensionsOption === IncludeExtensionsOption.Exclude && !fileExtensionIsOneOf(filePath, [Extension.Json, Extension.Mts, Extension.Cts, Extension.Dmts, Extension.Dcts, Extension.Mjs, Extension.Cjs])) {
foundFileName = removeFileExtension(getBaseFileName(filePath));
foundFiles.set(foundFileName, tryGetExtensionFromPath(filePath));
}
else if ((fileExtensionIsOneOf(filePath, [Extension.Mts, Extension.Cts, Extension.Dmts, Extension.Dcts, Extension.Mjs, Extension.Cjs]) || includeExtensionsOption === IncludeExtensionsOption.ModuleSpecifierCompletion) && outputExtension) {
foundFileName = changeExtension(getBaseFileName(filePath), outputExtension);
foundFiles.set(foundFileName, outputExtension);
}
else {
foundFileName = getBaseFileName(filePath);
foundFiles.set(foundFileName, tryGetExtensionFromPath(filePath));
}
const { name, extension } = getFilenameWithExtensionOption(getBaseFileName(filePath), host.getCompilationSettings(), extensionOptions.includeExtensionsOption);
result.add(nameAndKind(name, ScriptElementKind.scriptElement, extension));
}
foundFiles.forEach((ext, foundFile) => {
result.push(nameAndKind(foundFile, ScriptElementKind.scriptElement, ext));
});
}
// If possible, get folder completion as well
@@ -518,7 +528,7 @@ namespace ts.Completions.StringCompletions {
for (const directory of directories) {
const directoryName = getBaseFileName(normalizePath(directory));
if (directoryName !== "@types") {
result.push(directoryResult(directoryName));
result.add(directoryResult(directoryName));
}
}
}
@@ -526,18 +536,61 @@ namespace ts.Completions.StringCompletions {
return result;
}
function getFilenameWithExtensionOption(name: string, compilerOptions: CompilerOptions, includeExtensionsOption: IncludeExtensionsOption): { name: string, extension: Extension | undefined } {
const outputExtension = moduleSpecifiers.tryGetJSExtensionForFile(name, compilerOptions);
if (includeExtensionsOption === IncludeExtensionsOption.Exclude && !fileExtensionIsOneOf(name, [Extension.Json, Extension.Mts, Extension.Cts, Extension.Dmts, Extension.Dcts, Extension.Mjs, Extension.Cjs])) {
return { name: removeFileExtension(name), extension: tryGetExtensionFromPath(name) };
}
else if ((fileExtensionIsOneOf(name, [Extension.Mts, Extension.Cts, Extension.Dmts, Extension.Dcts, Extension.Mjs, Extension.Cjs]) || includeExtensionsOption === IncludeExtensionsOption.ModuleSpecifierCompletion) && outputExtension) {
return { name: changeExtension(name, outputExtension), extension: outputExtension };
}
else {
return { name, extension: tryGetExtensionFromPath(name) };
}
}
/** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */
function addCompletionEntriesFromPaths(result: NameAndKind[], fragment: string, baseDirectory: string, fileExtensions: readonly string[], paths: MapLike<string[]>, host: LanguageServiceHost) {
function addCompletionEntriesFromPaths(
result: NameAndKindSet,
fragment: string,
baseDirectory: string,
extensionOptions: ExtensionOptions,
host: LanguageServiceHost,
paths: MapLike<string[]>
) {
const getPatternsForKey = (key: string) => paths[key];
const comparePaths = (a: string, b: string): Comparison => {
const patternA = tryParsePattern(a);
const patternB = tryParsePattern(b);
const lengthA = typeof patternA === "object" ? patternA.prefix.length : a.length;
const lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length;
return compareValues(lengthB, lengthA);
};
return addCompletionEntriesFromPathsOrExports(result, fragment, baseDirectory, extensionOptions, host, getOwnKeys(paths), getPatternsForKey, comparePaths);
}
/** @returns whether `fragment` was a match for any `paths` (which should indicate whether any other path completions should be offered) */
function addCompletionEntriesFromPathsOrExports(
result: NameAndKindSet,
fragment: string,
baseDirectory: string,
extensionOptions: ExtensionOptions,
host: LanguageServiceHost,
keys: readonly string[],
getPatternsForKey: (key: string) => string[] | undefined,
comparePaths: (a: string, b: string) => Comparison,
) {
let pathResults: { results: NameAndKind[], matchedPattern: boolean }[] = [];
let matchedPathPrefixLength = -1;
for (const path in paths) {
if (!hasProperty(paths, path)) continue;
const patterns = paths[path];
let matchedPath: string | undefined;
for (const key of keys) {
if (key === ".") continue;
const keyWithoutLeadingDotSlash = key.replace(/^\.\//, ""); // remove leading "./"
const patterns = getPatternsForKey(key);
if (patterns) {
const pathPattern = tryParsePattern(path);
const pathPattern = tryParsePattern(keyWithoutLeadingDotSlash);
if (!pathPattern) continue;
const isMatch = typeof pathPattern === "object" && isPatternMatch(pathPattern, fragment);
const isLongestMatch = isMatch && (matchedPathPrefixLength === undefined || pathPattern.prefix.length > matchedPathPrefixLength);
const isLongestMatch = isMatch && (matchedPath === undefined || comparePaths(key, matchedPath) === Comparison.LessThan);
if (isLongestMatch) {
// If this is a higher priority match than anything we've seen so far, previous results from matches are invalid, e.g.
// for `import {} from "some-package/|"` with a typesVersions:
@@ -550,24 +603,21 @@ namespace ts.Completions.StringCompletions {
// added by the '*' match, after typing `"some-package/foo/|"` we would get file results from both
// ./dist/foo and ./foo, when only the latter will actually be resolvable.
// See pathCompletionsTypesVersionsWildcard6.ts.
matchedPathPrefixLength = pathPattern.prefix.length;
matchedPath = key;
pathResults = pathResults.filter(r => !r.matchedPattern);
}
if (typeof pathPattern === "string" || matchedPathPrefixLength === undefined || pathPattern.prefix.length >= matchedPathPrefixLength) {
if (typeof pathPattern === "string" || matchedPath === undefined || comparePaths(key, matchedPath) !== Comparison.GreaterThan) {
pathResults.push({
matchedPattern: isMatch,
results: getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host)
results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, host)
.map(({ name, kind, extension }) => nameAndKind(name, kind, extension)),
});
}
}
}
const equatePaths = host.useCaseSensitiveFileNames?.() ? equateStringsCaseSensitive : equateStringsCaseInsensitive;
const equateResults: EqualityComparer<NameAndKind> = (a, b) => equatePaths(a.name, b.name);
pathResults.forEach(pathResult => pathResult.results.forEach(pathResult => pushIfUnique(result, pathResult, equateResults)));
return matchedPathPrefixLength > -1;
pathResults.forEach(pathResult => pathResult.results.forEach(r => result.add(r)));
return matchedPath !== undefined;
}
/**
@@ -577,24 +627,31 @@ namespace ts.Completions.StringCompletions {
* Modules from node_modules (i.e. those listed in package.json)
* This includes all files that are found in node_modules/moduleName/ with acceptable file extensions
*/
function getCompletionEntriesForNonRelativeModules(fragment: string, scriptPath: string, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker): readonly NameAndKind[] {
function getCompletionEntriesForNonRelativeModules(
fragment: string,
scriptPath: string,
mode: SourceFile["impliedNodeFormat"],
compilerOptions: CompilerOptions,
host: LanguageServiceHost,
includeExtensionsOption: IncludeExtensionsOption,
typeChecker: TypeChecker,
): readonly NameAndKind[] {
const { baseUrl, paths } = compilerOptions;
const result: NameAndKind[] = [];
const extensionOptions = getExtensionOptions(compilerOptions);
const result = createNameAndKindSet();
const extensionOptions = getExtensionOptions(compilerOptions, includeExtensionsOption);
if (baseUrl) {
const projectDir = compilerOptions.project || host.getCurrentDirectory();
const absolute = normalizePath(combinePaths(projectDir, baseUrl));
getCompletionEntriesForDirectoryFragment(fragment, absolute, extensionOptions, host, /*exclude*/ undefined, result);
if (paths) {
addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions.extensions, paths, host);
addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, host, paths);
}
}
const fragmentDirectory = getFragmentDirectory(fragment);
for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker)) {
result.push(nameAndKind(ambientName, ScriptElementKind.externalModuleName, /*extension*/ undefined));
result.add(nameAndKind(ambientName, ScriptElementKind.externalModuleName, /*extension*/ undefined));
}
getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result);
@@ -605,9 +662,10 @@ namespace ts.Completions.StringCompletions {
let foundGlobal = false;
if (fragmentDirectory === undefined) {
for (const moduleName of enumerateNodeModulesVisibleToScript(host, scriptPath)) {
if (!result.some(entry => entry.name === moduleName)) {
const moduleResult = nameAndKind(moduleName, ScriptElementKind.externalModuleName, /*extension*/ undefined);
if (!result.has(moduleResult.name)) {
foundGlobal = true;
result.push(nameAndKind(moduleName, ScriptElementKind.externalModuleName, /*extension*/ undefined));
result.add(moduleResult);
}
}
}
@@ -634,36 +692,27 @@ namespace ts.Completions.StringCompletions {
}
packagePath = combinePaths(packagePath, subName);
}
const packageFile = combinePaths(ancestor, "node_modules", packagePath, "package.json");
const packageDirectory = combinePaths(ancestor, "node_modules", packagePath);
const packageFile = combinePaths(packageDirectory, "package.json");
if (tryFileExists(host, packageFile)) {
const packageJson = readJson(packageFile, host as { readFile: (filename: string) => string | undefined });
const packageJson = readJson(packageFile, host);
const exports = (packageJson as any).exports;
if (exports) {
if (typeof exports !== "object" || exports === null) { // eslint-disable-line no-null/no-null
return; // null exports or entrypoint only, no sub-modules available
}
const keys = getOwnKeys(exports);
const fragmentSubpath = components.join("/");
const processedKeys = mapDefined(keys, k => {
if (k === ".") return undefined;
if (!startsWith(k, "./")) return undefined;
const subpath = k.substring(2);
if (!startsWith(subpath, fragmentSubpath)) return undefined;
// subpath is a valid export (barring conditions, which we don't currently check here)
if (!stringContains(subpath, "*")) {
return subpath;
}
// pattern export - only return everything up to the `*`, so the user can autocomplete, then
// keep filling in the pattern (we could speculatively return a list of options by hitting disk,
// but conditions will make that somewhat awkward, as each condition may have a different set of possible
// options for the `*`.
return subpath.slice(0, subpath.indexOf("*"));
});
forEach(processedKeys, k => {
if (k) {
result.push(nameAndKind(k, ScriptElementKind.externalModuleName, /*extension*/ undefined));
}
});
const fragmentSubpath = components.join("/") + (components.length && hasTrailingDirectorySeparator(fragment) ? "/" : "");
const conditions = mode === ModuleKind.ESNext ? ["node", "import", "types"] : ["node", "require", "types"];
addCompletionEntriesFromPathsOrExports(
result,
fragmentSubpath,
packageDirectory,
extensionOptions,
host,
keys,
key => singleElementArray(getPatternFromFirstMatchingCondition(exports[key], conditions)),
comparePatternKeys);
return;
}
}
@@ -674,7 +723,21 @@ namespace ts.Completions.StringCompletions {
}
}
return result;
return arrayFrom(result.values());
}
function getPatternFromFirstMatchingCondition(target: unknown, conditions: readonly string[]): string | undefined {
if (typeof target === "string") {
return target;
}
if (target && typeof target === "object" && !isArray(target)) {
for (const condition in target) {
if (condition === "default" || conditions.indexOf(condition) > -1 || isApplicableVersionedTypesKey(conditions, condition)) {
const pattern = (target as MapLike<unknown>)[condition];
return getPatternFromFirstMatchingCondition(pattern, conditions);
}
}
}
}
function getFragmentDirectory(fragment: string): string | undefined {
@@ -682,28 +745,39 @@ namespace ts.Completions.StringCompletions {
}
function getCompletionsForPathMapping(
path: string, patterns: readonly string[], fragment: string, baseUrl: string, fileExtensions: readonly string[], host: LanguageServiceHost,
path: string,
patterns: readonly string[],
fragment: string,
packageDirectory: string,
extensionOptions: ExtensionOptions,
host: LanguageServiceHost,
): readonly NameAndKind[] {
if (!endsWith(path, "*")) {
// For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion.
return !stringContains(path, "*") ? justPathMappingName(path) : emptyArray;
return !stringContains(path, "*") ? justPathMappingName(path, ScriptElementKind.scriptElement) : emptyArray;
}
const pathPrefix = path.slice(0, path.length - 1);
const remainingFragment = tryRemovePrefix(fragment, pathPrefix);
if (remainingFragment === undefined) {
const starIsFullPathComponent = path[path.length - 2] === "/";
return starIsFullPathComponent ? justPathMappingName(pathPrefix) : flatMap(patterns, pattern =>
getModulesForPathsPattern("", baseUrl, pattern, fileExtensions, host)?.map(({ name, ...rest }) => ({ name: pathPrefix + name, ...rest })));
return starIsFullPathComponent ? justPathMappingName(pathPrefix, ScriptElementKind.directory) : flatMap(patterns, pattern =>
getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, host)?.map(({ name, ...rest }) => ({ name: pathPrefix + name, ...rest })));
}
return flatMap(patterns, pattern => getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host));
return flatMap(patterns, pattern => getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, host));
function justPathMappingName(name: string): readonly NameAndKind[] {
return startsWith(name, fragment) ? [directoryResult(removeTrailingDirectorySeparator(name))] : emptyArray;
function justPathMappingName(name: string, kind: ScriptElementKind.directory | ScriptElementKind.scriptElement): readonly NameAndKind[] {
return startsWith(name, fragment) ? [{ name: removeTrailingDirectorySeparator(name), kind, extension: undefined }] : emptyArray;
}
}
function getModulesForPathsPattern(fragment: string, baseUrl: string, pattern: string, fileExtensions: readonly string[], host: LanguageServiceHost): readonly NameAndKind[] | undefined {
function getModulesForPathsPattern(
fragment: string,
packageDirectory: string,
pattern: string,
extensionOptions: ExtensionOptions,
host: LanguageServiceHost,
): readonly NameAndKind[] | undefined {
if (!host.readDirectory) {
return undefined;
}
@@ -727,23 +801,36 @@ namespace ts.Completions.StringCompletions {
const normalizedSuffix = normalizePath(parsed.suffix);
// Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b".
const baseDirectory = normalizePath(combinePaths(baseUrl, expandedPrefixDirectory));
const baseDirectory = normalizePath(combinePaths(packageDirectory, expandedPrefixDirectory));
const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase;
// If we have a suffix, then we need to read the directory all the way down. We could create a glob
// that encodes the suffix, but we would have to escape the character "?" which readDirectory
// doesn't support. For now, this is safer but slower
const includeGlob = normalizedSuffix ? "**/*" : "./*";
// If we have a suffix, then we read the directory all the way down to avoid returning completions for
// directories that don't contain files that would match the suffix. A previous comment here was concerned
// about the case where `normalizedSuffix` includes a `?` character, which should be interpreted literally,
// but will match any single character as part of the `include` pattern in `tryReadDirectory`. This is not
// a problem, because (in the extremely unusual circumstance where the suffix has a `?` in it) a `?`
// interpreted as "any character" can only return *too many* results as compared to the literal
// interpretation, so we can filter those superfluous results out via `trimPrefixAndSuffix` as we've always
// done.
const includeGlob = normalizedSuffix ? "**/*" + normalizedSuffix : "./*";
const matches = mapDefined(tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]), match => {
const extension = tryGetExtensionFromPath(match);
const name = trimPrefixAndSuffix(match);
return name === undefined ? undefined : nameAndKind(removeFileExtension(name), ScriptElementKind.scriptElement, extension);
});
const directories = mapDefined(tryGetDirectories(host, baseDirectory).map(d => combinePaths(baseDirectory, d)), dir => {
const name = trimPrefixAndSuffix(dir);
return name === undefined ? undefined : directoryResult(name);
const matches = mapDefined(tryReadDirectory(host, baseDirectory, extensionOptions.extensions, /*exclude*/ undefined, [includeGlob]), match => {
const trimmedWithPattern = trimPrefixAndSuffix(match);
if (trimmedWithPattern) {
if (containsSlash(trimmedWithPattern)) {
return directoryResult(getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]);
}
const { name, extension } = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions.includeExtensionsOption);
return nameAndKind(name, ScriptElementKind.scriptElement, extension);
}
});
// If we had a suffix, we already recursively searched for all possible files that could match
// it and returned the directories leading to those files. Otherwise, assume any directory could
// have something valid to import.
const directories = normalizedSuffix
? emptyArray
: mapDefined(tryGetDirectories(host, baseDirectory), dir => dir === "node_modules" ? undefined : directoryResult(dir));
return [...matches, ...directories];
function trimPrefixAndSuffix(path: string): string | undefined {
@@ -793,10 +880,10 @@ namespace ts.Completions.StringCompletions {
const names = kind === "path" ? getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, getExtensionOptions(compilerOptions, IncludeExtensionsOption.Include), host, sourceFile.path)
: kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions))
: Debug.fail();
return addReplacementSpans(toComplete, range.pos + prefix.length, names);
return addReplacementSpans(toComplete, range.pos + prefix.length, arrayFrom(names.values()));
}
function getCompletionEntriesFromTypings(host: LanguageServiceHost, options: CompilerOptions, scriptPath: string, fragmentDirectory: string | undefined, extensionOptions: ExtensionOptions, result: NameAndKind[] = []): readonly NameAndKind[] {
function getCompletionEntriesFromTypings(host: LanguageServiceHost, options: CompilerOptions, scriptPath: string, fragmentDirectory: string | undefined, extensionOptions: ExtensionOptions, result = createNameAndKindSet()): NameAndKindSet {
// Check for typings specified in compiler options
const seen = new Map<string, true>();
@@ -823,7 +910,7 @@ namespace ts.Completions.StringCompletions {
if (fragmentDirectory === undefined) {
if (!seen.has(packageName)) {
result.push(nameAndKind(packageName, ScriptElementKind.externalModuleName, /*extension*/ undefined));
result.add(nameAndKind(packageName, ScriptElementKind.externalModuleName, /*extension*/ undefined));
seen.set(packageName, true);
}
}
+14 -4
View File
@@ -1147,13 +1147,20 @@ namespace ts {
// position and whose end is greater than the position.
// There are more sophisticated end tests later, but this one is very fast
// and allows us to skip a bunch of work
const end = children[middle].getEnd();
if (end < position) {
return Comparison.LessThan;
}
const start = allowPositionInLeadingTrivia ? children[middle].getFullStart() : children[middle].getStart(sourceFile, /*includeJsDoc*/ true);
if (start > position) {
return Comparison.GreaterThan;
}
// first element whose start position is before the input and whose end position is after or equal to the input
if (nodeContainsPosition(children[middle])) {
if (nodeContainsPosition(children[middle], start, end)) {
if (children[middle - 1]) {
// we want the _first_ element that contains the position, so left-recur if the prior node also contains the position
if (nodeContainsPosition(children[middle - 1])) {
@@ -1181,13 +1188,16 @@ namespace ts {
return current;
}
function nodeContainsPosition(node: Node) {
const start = allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true);
function nodeContainsPosition(node: Node, start?: number, end?: number) {
end ??= node.getEnd();
if (end < position) {
return false;
}
start ??= allowPositionInLeadingTrivia ? node.getFullStart() : node.getStart(sourceFile, /*includeJsDoc*/ true);
if (start > position) {
// If this child begins after position, then all subsequent children will as well.
return false;
}
const end = node.getEnd();
if (position < end || (position === end && (node.kind === SyntaxKind.EndOfFileToken || includeEndPosition))) {
return true;
}
+6 -34
View File
@@ -18,7 +18,7 @@ namespace Harness {
abstract class ExternalCompileRunnerBase extends RunnerBase {
abstract testDir: string;
abstract report(result: ExecResult, cwd: string): string | null;
abstract report(result: ExecResult): string | null;
enumerateTestFiles() {
return IO.getDirectories(this.testDir);
}
@@ -91,7 +91,7 @@ namespace Harness {
}
}
args.push("--noEmit");
Baseline.runBaseline(`${cls.kind()}/${directoryName}.log`, cls.report(cp.spawnSync(`node`, args, { cwd, timeout, shell: true }), cwd));
Baseline.runBaseline(`${cls.kind()}/${directoryName}.log`, cls.report(cp.spawnSync(`node`, args, { cwd, timeout, shell: true })));
function exec(command: string, args: string[], options: { cwd: string, timeout?: number, stdio?: import("child_process").StdioOptions }): string | undefined {
const res = cp.spawnSync(isWorker ? `${command} 2>&1` : command, args, { shell: true, stdio, ...options });
@@ -281,46 +281,18 @@ ${sanitizeDockerfileOutput(result.stderr.toString())}`;
kind(): TestRunnerKind {
return "dt";
}
report(result: ExecResult, cwd: string) {
const stdout = removeExpectedErrors(result.stdout.toString(), cwd);
const stderr = result.stderr.toString();
report(result: ExecResult) {
// eslint-disable-next-line no-null/no-null
return !stdout.length && !stderr.length ? null : `Exit Code: ${result.status}
return !result.stdout.length && !result.stderr.length ? null : `Exit Code: ${result.status}
Standard output:
${stdout.replace(/\r\n/g, "\n")}
${result.stdout.toString().replace(/\r\n/g, "\n")}
Standard error:
${stderr.replace(/\r\n/g, "\n")}`;
${result.stderr.toString().replace(/\r\n/g, "\n")}`;
}
}
function removeExpectedErrors(errors: string, cwd: string): string {
return ts.flatten(splitBy(errors.split("\n"), s => /^\S+/.test(s)).filter(isUnexpectedError(cwd))).join("\n");
}
/**
* Returns true if the line that caused the error contains '$ExpectError',
* or if the line before that one contains '$ExpectError'.
* '$ExpectError' is a marker used in Definitely Typed tests,
* meaning that the error should not contribute toward our error baslines.
*/
function isUnexpectedError(cwd: string) {
return (error: string[]) => {
ts.Debug.assertGreaterThanOrEqual(error.length, 1);
const match = error[0].match(/(.+\.tsx?)\((\d+),\d+\): error TS/);
if (!match) {
return true;
}
const [, errorFile, lineNumberString] = match;
const lines = fs.readFileSync(path.join(cwd, errorFile), { encoding: "utf8" }).split("\n");
const lineNumber = parseInt(lineNumberString) - 1;
ts.Debug.assertGreaterThanOrEqual(lineNumber, 0);
ts.Debug.assertLessThan(lineNumber, lines.length);
const previousLine = lineNumber - 1 > 0 ? lines[lineNumber - 1] : "";
return !ts.stringContains(lines[lineNumber], "$ExpectError") && !ts.stringContains(previousLine, "$ExpectError");
};
}
/**
* Split an array into multiple arrays whenever `isStart` returns true.
* @example
@@ -62,7 +62,6 @@ export function Component(x: Config): any;`
emitSkipped: true,
diagnostics: emptyArray,
outputFiles: emptyArray,
exportedModulesFromDeclarationEmit: undefined
}
);
@@ -80,7 +79,6 @@ export function Component(x: Config): any;`
text: "export {};\r\n",
writeByteOrderMark: false
}],
exportedModulesFromDeclarationEmit: undefined
}
);
});
@@ -485,5 +485,19 @@ export { a as alias };
export * as alias from './file';`, {
noSetFileName: true
});
transpilesCorrectly("Elides import equals referenced only by export type",
`import IFoo = Namespace.IFoo;` +
`export type { IFoo };`, {
options: { compilerOptions: { module: ModuleKind.CommonJS } }
}
);
transpilesCorrectly("Elides import equals referenced only by type only export specifier",
`import IFoo = Namespace.IFoo;` +
`export { type IFoo };`, {
options: { compilerOptions: { module: ModuleKind.CommonJS } }
}
);
});
}
+2 -2
View File
@@ -263,7 +263,7 @@ interface Symbol {
toFileName(s) :
[toFileName(s[0]), s[1]]
),
dtsChangeTime: buildInfo.program.dtsChangeTime,
latestChangedDtsFile: buildInfo.program.latestChangedDtsFile,
};
}
const version = buildInfo.version === ts.version ? fakes.version : buildInfo.version;
@@ -544,7 +544,7 @@ interface Symbol {
options: { ...readableBuildInfo.program.options, noEmit: undefined },
exportedModulesMap: undefined,
affectedFilesPendingEmit: undefined,
dtsChangeTime: readableBuildInfo.program.dtsChangeTime ? "FakeTime" : undefined,
latestChangedDtsFile: readableBuildInfo.program.latestChangedDtsFile ? "FakeFileName" : undefined,
},
size: undefined, // Size doesnt need to be equal
}, /*replacer*/ undefined, 2),
+43 -2
View File
@@ -125,8 +125,8 @@ const a: string = 10;`, "utf-8"),
function verifyNoEmitChanges(compilerOptions: CompilerOptions) {
const discrepancyExplanation = () => [
...noChangeWithExportsDiscrepancyRun.discrepancyExplanation!(),
"Clean build will not have dtsChangeTime as there was no emit and emitSignatures as undefined for files",
"Incremental will store the past dtsChangeTime and emitSignatures",
"Clean build will not have latestChangedDtsFile as there was no emit and emitSignatures as undefined for files",
"Incremental will store the past latestChangedDtsFile and emitSignatures",
];
const discrepancyIfNoDtsEmit = getEmitDeclarations(compilerOptions) ?
undefined :
@@ -524,5 +524,46 @@ console.log(a);`,
modifyFs: fs => fs.writeFileSync("/src/project/constants.ts", "export default 2;"),
}],
});
function verifyModifierChange(declaration: boolean) {
verifyTscWithEdits({
scenario: "incremental",
subScenario: `change to modifier of class expression field${declaration ? " with declaration emit enabled" : ""}`,
commandLineArgs: ["-p", "src/project", "--incremental"],
fs: () => loadProjectFromFiles({
"/src/project/tsconfig.json": JSON.stringify({ compilerOptions: { declaration } }),
"/src/project/main.ts": Utils.dedent`
import MessageablePerson from './MessageablePerson.js';
function logMessage( person: MessageablePerson ) {
console.log( person.message );
}`,
"/src/project/MessageablePerson.ts": Utils.dedent`
const Messageable = () => {
return class MessageableClass {
public message = 'hello';
}
};
const wrapper = () => Messageable();
type MessageablePerson = InstanceType<ReturnType<typeof wrapper>>;
export default MessageablePerson;`,
}),
modifyFs: fs => appendText(fs, "/lib/lib.d.ts", Utils.dedent`
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any;`
),
edits: [
{
subScenario: "modify public to protected",
modifyFs: fs => replaceText(fs, "/src/project/MessageablePerson.ts", "public", "protected"),
},
{
subScenario: "modify protected to public",
modifyFs: fs => replaceText(fs, "/src/project/MessageablePerson.ts", "protected", "public"),
},
],
});
}
verifyModifierChange(/*declaration*/ false);
verifyModifierChange(/*declaration*/ true);
});
}
@@ -29,7 +29,7 @@ namespace ts.tscWatch {
},
// not ideal, but currently because of d.ts but no new file is written
// There will be timeout queued even though file contents are same
timeouts: checkSingleTimeoutQueueLengthAndRun
timeouts: sys => sys.checkTimeoutQueueLength(0),
},
{
caption: "non local edit in logic ts, and build logic",
@@ -139,7 +139,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path }
}).response as EmitOutput;
@@ -175,7 +175,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -218,7 +218,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path }
}).response as EmitOutput;
@@ -261,7 +261,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -315,7 +315,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path }
}).response as EmitOutput;
@@ -369,7 +369,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -412,7 +412,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path }
}).response as EmitOutput;
@@ -455,7 +455,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -509,7 +509,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path }
}).response as EmitOutput;
@@ -563,7 +563,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -597,7 +597,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path }
}).response as EmitOutput;
@@ -628,7 +628,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -666,7 +666,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path }
}).response as EmitOutput;
@@ -704,7 +704,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -753,7 +753,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path }
}).response as EmitOutput;
@@ -802,7 +802,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -840,7 +840,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path }
}).response as EmitOutput;
@@ -878,7 +878,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -927,7 +927,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path }
}).response as EmitOutput;
@@ -976,7 +976,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -1017,7 +1017,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path }
}).response as EmitOutput;
@@ -1053,7 +1053,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -1107,7 +1107,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path }
}).response as EmitOutput;
@@ -1161,7 +1161,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -1215,7 +1215,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path }
}).response as EmitOutput;
@@ -1269,7 +1269,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -1323,7 +1323,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path }
}).response as EmitOutput;
@@ -1377,7 +1377,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -1431,7 +1431,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path }
}).response as EmitOutput;
@@ -1485,7 +1485,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: usageTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -1519,7 +1519,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -1568,7 +1568,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -1617,7 +1617,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -1666,7 +1666,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -1715,7 +1715,7 @@ ${appendDts}`
assert.equal(host.writtenFiles.size, 0);
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: usageConfig.path }
}).response as EmitOutput;
@@ -1755,7 +1755,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path }
}).response as EmitOutput;
@@ -1791,7 +1791,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }
}).response as EmitOutput;
@@ -1846,7 +1846,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path }
}).response as EmitOutput;
@@ -1900,7 +1900,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }
}).response as EmitOutput;
@@ -1955,7 +1955,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path }
}).response as EmitOutput;
@@ -2009,7 +2009,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }
}).response as EmitOutput;
@@ -2064,7 +2064,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path }
}).response as EmitOutput;
@@ -2118,7 +2118,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }
}).response as EmitOutput;
@@ -2173,7 +2173,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path }
}).response as EmitOutput;
@@ -2227,7 +2227,7 @@ ${appendDts}`
}
// Verify EmitOutput
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
const actualEmitOutput = session.executeCommandSeq<protocol.EmitOutputRequest>({
command: protocol.CommandTypes.EmitOutput,
arguments: { file: dependencyTs.path, projectFileName: dependencyConfig.path }
}).response as EmitOutput;
@@ -1,6 +1,6 @@
tests/cases/compiler/DateTimeFormatAndNumberFormatES2021.ts(1,29): error TS2339: Property 'formatRange' does not exist on type 'NumberFormat'.
tests/cases/compiler/DateTimeFormatAndNumberFormatES2021.ts(4,25): error TS2339: Property 'formatRange' does not exist on type 'NumberFormat'.
tests/cases/compiler/DateTimeFormatAndNumberFormatES2021.ts(5,25): error TS2339: Property 'formatRangeToParts' does not exist on type 'NumberFormat'.
tests/cases/compiler/DateTimeFormatAndNumberFormatES2021.ts(5,25): error TS2551: Property 'formatRangeToParts' does not exist on type 'NumberFormat'. Did you mean 'formatToParts'?
==== tests/cases/compiler/DateTimeFormatAndNumberFormatES2021.ts (3 errors) ====
@@ -14,6 +14,7 @@ tests/cases/compiler/DateTimeFormatAndNumberFormatES2021.ts(5,25): error TS2339:
!!! error TS2339: Property 'formatRange' does not exist on type 'NumberFormat'.
new Intl.NumberFormat().formatRangeToParts
~~~~~~~~~~~~~~~~~~
!!! error TS2339: Property 'formatRangeToParts' does not exist on type 'NumberFormat'.
!!! error TS2551: Property 'formatRangeToParts' does not exist on type 'NumberFormat'. Did you mean 'formatToParts'?
!!! related TS2728 /.ts/lib.es2018.intl.d.ts:71:9: 'formatToParts' is declared here.
new Intl.DateTimeFormat().formatRange
new Intl.DateTimeFormat().formatRangeToParts
@@ -0,0 +1,61 @@
//// [accessorDeclarationOrder.ts]
class C1 {
#name: string;
public get name() {
return this.#name;
}
private set name(name: string) {
this.#name = name;
}
}
class C2 {
#name: string;
private set name(name: string) {
this.#name = name;
}
public get name() {
return this.#name;
}
}
const c1 = new C1();
const c2 = new C2();
// no error
c1.name;
// no error
c2.name;
//// [accessorDeclarationOrder.js]
class C1 {
#name;
get name() {
return this.#name;
}
set name(name) {
this.#name = name;
}
}
class C2 {
#name;
set name(name) {
this.#name = name;
}
get name() {
return this.#name;
}
}
const c1 = new C1();
const c2 = new C2();
// no error
c1.name;
// no error
c2.name;
@@ -0,0 +1,72 @@
=== tests/cases/compiler/accessorDeclarationOrder.ts ===
class C1 {
>C1 : Symbol(C1, Decl(accessorDeclarationOrder.ts, 0, 0))
#name: string;
>#name : Symbol(C1.#name, Decl(accessorDeclarationOrder.ts, 0, 10))
public get name() {
>name : Symbol(C1.name, Decl(accessorDeclarationOrder.ts, 1, 18), Decl(accessorDeclarationOrder.ts, 5, 5))
return this.#name;
>this.#name : Symbol(C1.#name, Decl(accessorDeclarationOrder.ts, 0, 10))
>this : Symbol(C1, Decl(accessorDeclarationOrder.ts, 0, 0))
}
private set name(name: string) {
>name : Symbol(C1.name, Decl(accessorDeclarationOrder.ts, 1, 18), Decl(accessorDeclarationOrder.ts, 5, 5))
>name : Symbol(name, Decl(accessorDeclarationOrder.ts, 7, 21))
this.#name = name;
>this.#name : Symbol(C1.#name, Decl(accessorDeclarationOrder.ts, 0, 10))
>this : Symbol(C1, Decl(accessorDeclarationOrder.ts, 0, 0))
>name : Symbol(name, Decl(accessorDeclarationOrder.ts, 7, 21))
}
}
class C2 {
>C2 : Symbol(C2, Decl(accessorDeclarationOrder.ts, 10, 1))
#name: string;
>#name : Symbol(C2.#name, Decl(accessorDeclarationOrder.ts, 12, 10))
private set name(name: string) {
>name : Symbol(C2.name, Decl(accessorDeclarationOrder.ts, 13, 18), Decl(accessorDeclarationOrder.ts, 17, 5))
>name : Symbol(name, Decl(accessorDeclarationOrder.ts, 15, 21))
this.#name = name;
>this.#name : Symbol(C2.#name, Decl(accessorDeclarationOrder.ts, 12, 10))
>this : Symbol(C2, Decl(accessorDeclarationOrder.ts, 10, 1))
>name : Symbol(name, Decl(accessorDeclarationOrder.ts, 15, 21))
}
public get name() {
>name : Symbol(C2.name, Decl(accessorDeclarationOrder.ts, 13, 18), Decl(accessorDeclarationOrder.ts, 17, 5))
return this.#name;
>this.#name : Symbol(C2.#name, Decl(accessorDeclarationOrder.ts, 12, 10))
>this : Symbol(C2, Decl(accessorDeclarationOrder.ts, 10, 1))
}
}
const c1 = new C1();
>c1 : Symbol(c1, Decl(accessorDeclarationOrder.ts, 24, 5))
>C1 : Symbol(C1, Decl(accessorDeclarationOrder.ts, 0, 0))
const c2 = new C2();
>c2 : Symbol(c2, Decl(accessorDeclarationOrder.ts, 25, 5))
>C2 : Symbol(C2, Decl(accessorDeclarationOrder.ts, 10, 1))
// no error
c1.name;
>c1.name : Symbol(C1.name, Decl(accessorDeclarationOrder.ts, 1, 18), Decl(accessorDeclarationOrder.ts, 5, 5))
>c1 : Symbol(c1, Decl(accessorDeclarationOrder.ts, 24, 5))
>name : Symbol(C1.name, Decl(accessorDeclarationOrder.ts, 1, 18), Decl(accessorDeclarationOrder.ts, 5, 5))
// no error
c2.name;
>c2.name : Symbol(C2.name, Decl(accessorDeclarationOrder.ts, 13, 18), Decl(accessorDeclarationOrder.ts, 17, 5))
>c2 : Symbol(c2, Decl(accessorDeclarationOrder.ts, 25, 5))
>name : Symbol(C2.name, Decl(accessorDeclarationOrder.ts, 13, 18), Decl(accessorDeclarationOrder.ts, 17, 5))
@@ -0,0 +1,76 @@
=== tests/cases/compiler/accessorDeclarationOrder.ts ===
class C1 {
>C1 : C1
#name: string;
>#name : string
public get name() {
>name : string
return this.#name;
>this.#name : string
>this : this
}
private set name(name: string) {
>name : string
>name : string
this.#name = name;
>this.#name = name : string
>this.#name : string
>this : this
>name : string
}
}
class C2 {
>C2 : C2
#name: string;
>#name : string
private set name(name: string) {
>name : string
>name : string
this.#name = name;
>this.#name = name : string
>this.#name : string
>this : this
>name : string
}
public get name() {
>name : string
return this.#name;
>this.#name : string
>this : this
}
}
const c1 = new C1();
>c1 : C1
>new C1() : C1
>C1 : typeof C1
const c2 = new C2();
>c2 : C2
>new C2() : C2
>C2 : typeof C2
// no error
c1.name;
>c1.name : string
>c1 : C1
>name : string
// no error
c2.name;
>c2.name : string
>c2 : C2
>name : string
@@ -14,5 +14,5 @@ tests/cases/conformance/classes/propertyMemberDeclarations/accessorsOverrideProp
}
const obj = new Derived(); // nothing printed
console.log(obj.x); // 1
console.log(obj.x); // number
@@ -9,7 +9,7 @@ class Derived extends Base {
}
const obj = new Derived(); // nothing printed
console.log(obj.x); // 1
console.log(obj.x); // number
//// [accessorsOverrideProperty2.js]
@@ -21,4 +21,4 @@ class Derived extends Base {
set x(value) { console.log(`x was set to ${value}`); }
}
const obj = new Derived(); // nothing printed
console.log(obj.x); // 1
console.log(obj.x); // number
@@ -26,7 +26,7 @@ const obj = new Derived(); // nothing printed
>obj : Symbol(obj, Decl(accessorsOverrideProperty2.ts, 9, 5))
>Derived : Symbol(Derived, Decl(accessorsOverrideProperty2.ts, 2, 1))
console.log(obj.x); // 1
console.log(obj.x); // number
>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --))
>console : Symbol(console, Decl(lib.dom.d.ts, --, --))
>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --))
@@ -31,7 +31,7 @@ const obj = new Derived(); // nothing printed
>new Derived() : Derived
>Derived : typeof Derived
console.log(obj.x); // 1
console.log(obj.x); // number
>console.log(obj.x) : void
>console.log : (...data: any[]) => void
>console : Console
+9 -1
View File
@@ -2096,6 +2096,12 @@ declare namespace ts {
* It is _public_ so that (pre)transformers can set this field,
* since it switches the builtin `node` module transform. Generally speaking, if unset,
* the field is treated as though it is `ModuleKind.CommonJS`.
*
* Note that this field is only set by the module resolution process when
* `moduleResolution` is `Node16` or `NodeNext`, which is implied by the `module` setting
* of `Node16` or `NodeNext`, respectively, but may be overriden (eg, by a `moduleResolution`
* of `node`). If so, this field will be unset and source files will be considered to be
* CommonJS-output-format by the node module transformer and type checker, regardless of extension or context.
*/
impliedNodeFormat?: ModuleKind.ESNext | ModuleKind.CommonJS;
}
@@ -2420,6 +2426,7 @@ declare namespace ts {
UseAliasDefinedOutsideCurrentScope = 16384,
UseSingleQuotesForStringLiteralType = 268435456,
NoTypeReduction = 536870912,
OmitThisParameter = 33554432,
AllowThisInObjectLiteral = 32768,
AllowQualifiedNameInPlaceOfIdentifier = 65536,
/** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */
@@ -2450,6 +2457,7 @@ declare namespace ts {
UseAliasDefinedOutsideCurrentScope = 16384,
UseSingleQuotesForStringLiteralType = 268435456,
NoTypeReduction = 536870912,
OmitThisParameter = 33554432,
AllowUniqueESSymbolType = 1048576,
AddUndefined = 131072,
WriteArrowStyleSignature = 262144,
@@ -2458,7 +2466,7 @@ declare namespace ts {
InFirstTypeArgument = 4194304,
InTypeAlias = 8388608,
/** @deprecated */ WriteOwnNameForAnyLike = 0,
NodeBuilderFlagsMask = 814775659
NodeBuilderFlagsMask = 848330091
}
export enum SymbolFormatFlags {
None = 0,
+9 -1
View File
@@ -2096,6 +2096,12 @@ declare namespace ts {
* It is _public_ so that (pre)transformers can set this field,
* since it switches the builtin `node` module transform. Generally speaking, if unset,
* the field is treated as though it is `ModuleKind.CommonJS`.
*
* Note that this field is only set by the module resolution process when
* `moduleResolution` is `Node16` or `NodeNext`, which is implied by the `module` setting
* of `Node16` or `NodeNext`, respectively, but may be overriden (eg, by a `moduleResolution`
* of `node`). If so, this field will be unset and source files will be considered to be
* CommonJS-output-format by the node module transformer and type checker, regardless of extension or context.
*/
impliedNodeFormat?: ModuleKind.ESNext | ModuleKind.CommonJS;
}
@@ -2420,6 +2426,7 @@ declare namespace ts {
UseAliasDefinedOutsideCurrentScope = 16384,
UseSingleQuotesForStringLiteralType = 268435456,
NoTypeReduction = 536870912,
OmitThisParameter = 33554432,
AllowThisInObjectLiteral = 32768,
AllowQualifiedNameInPlaceOfIdentifier = 65536,
/** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */
@@ -2450,6 +2457,7 @@ declare namespace ts {
UseAliasDefinedOutsideCurrentScope = 16384,
UseSingleQuotesForStringLiteralType = 268435456,
NoTypeReduction = 536870912,
OmitThisParameter = 33554432,
AllowUniqueESSymbolType = 1048576,
AddUndefined = 131072,
WriteArrowStyleSignature = 262144,
@@ -2458,7 +2466,7 @@ declare namespace ts {
InFirstTypeArgument = 4194304,
InTypeAlias = 8388608,
/** @deprecated */ WriteOwnNameForAnyLike = 0,
NodeBuilderFlagsMask = 814775659
NodeBuilderFlagsMask = 848330091
}
export enum SymbolFormatFlags {
None = 0,
@@ -1,4 +1,4 @@
tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts(3,11): error TS2304: Cannot find name 'await'.
tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts(3,11): error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts (1 errors) ====
@@ -6,6 +6,6 @@ tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2
// Legal to use 'await' in a type context.
var v: await;
~~~~~
!!! error TS2304: Cannot find name 'await'.
!!! error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
}
@@ -1,4 +1,4 @@
tests/cases/conformance/async/es5/asyncArrowFunction/asyncArrowFunction10_es5.ts(3,11): error TS2304: Cannot find name 'await'.
tests/cases/conformance/async/es5/asyncArrowFunction/asyncArrowFunction10_es5.ts(3,11): error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
==== tests/cases/conformance/async/es5/asyncArrowFunction/asyncArrowFunction10_es5.ts (1 errors) ====
@@ -6,6 +6,6 @@ tests/cases/conformance/async/es5/asyncArrowFunction/asyncArrowFunction10_es5.ts
// Legal to use 'await' in a type context.
var v: await;
~~~~~
!!! error TS2304: Cannot find name 'await'.
!!! error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
}
@@ -1,4 +1,4 @@
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction10_es6.ts(3,11): error TS2304: Cannot find name 'await'.
tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction10_es6.ts(3,11): error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
==== tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction10_es6.ts (1 errors) ====
@@ -6,6 +6,6 @@ tests/cases/conformance/async/es6/asyncArrowFunction/asyncArrowFunction10_es6.ts
// Legal to use 'await' in a type context.
var v: await;
~~~~~
!!! error TS2304: Cannot find name 'await'.
!!! error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
}
@@ -1,4 +1,4 @@
tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts(3,11): error TS2304: Cannot find name 'await'.
tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts(3,11): error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts (1 errors) ====
@@ -6,6 +6,6 @@ tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclarati
// Legal to use 'await' in a type context.
var v: await;
~~~~~
!!! error TS2304: Cannot find name 'await'.
!!! error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
}
@@ -1,4 +1,4 @@
tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration13_es5.ts(3,11): error TS2304: Cannot find name 'await'.
tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration13_es5.ts(3,11): error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
==== tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration13_es5.ts (1 errors) ====
@@ -6,6 +6,6 @@ tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration1
// Legal to use 'await' in a type context.
var v: await;
~~~~~
!!! error TS2304: Cannot find name 'await'.
!!! error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
}
@@ -1,4 +1,4 @@
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration13_es6.ts(3,11): error TS2304: Cannot find name 'await'.
tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration13_es6.ts(3,11): error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
==== tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration13_es6.ts (1 errors) ====
@@ -6,6 +6,6 @@ tests/cases/conformance/async/es6/functionDeclarations/asyncFunctionDeclaration1
// Legal to use 'await' in a type context.
var v: await;
~~~~~
!!! error TS2304: Cannot find name 'await'.
!!! error TS2552: Cannot find name 'await'. Did you mean 'Awaited'?
}
@@ -0,0 +1,17 @@
=== tests/cases/conformance/generators/asyncGeneratorGenericNonWrappedReturn.ts ===
// #48966
export async function* test<T>(a: T): AsyncGenerator<T, T, T> {
>test : Symbol(test, Decl(asyncGeneratorGenericNonWrappedReturn.ts, 0, 0))
>T : Symbol(T, Decl(asyncGeneratorGenericNonWrappedReturn.ts, 2, 28))
>a : Symbol(a, Decl(asyncGeneratorGenericNonWrappedReturn.ts, 2, 31))
>T : Symbol(T, Decl(asyncGeneratorGenericNonWrappedReturn.ts, 2, 28))
>AsyncGenerator : Symbol(AsyncGenerator, Decl(lib.es2018.asyncgenerator.d.ts, --, --))
>T : Symbol(T, Decl(asyncGeneratorGenericNonWrappedReturn.ts, 2, 28))
>T : Symbol(T, Decl(asyncGeneratorGenericNonWrappedReturn.ts, 2, 28))
>T : Symbol(T, Decl(asyncGeneratorGenericNonWrappedReturn.ts, 2, 28))
return a // `T` should be allowed here even though the generator's `returnType` is `Awaited<T>`
>a : Symbol(a, Decl(asyncGeneratorGenericNonWrappedReturn.ts, 2, 31))
}
@@ -0,0 +1,11 @@
=== tests/cases/conformance/generators/asyncGeneratorGenericNonWrappedReturn.ts ===
// #48966
export async function* test<T>(a: T): AsyncGenerator<T, T, T> {
>test : <T>(a: T) => AsyncGenerator<T, T, T>
>a : T
return a // `T` should be allowed here even though the generator's `returnType` is `Awaited<T>`
>a : T
}
@@ -168,4 +168,13 @@ tests/cases/compiler/awaitedType.ts(22,12): error TS2589: Type instantiation is
// helps with tests where '.types' just prints out the type alias name
type _Expect<TActual extends TExpected, TExpected> = TActual;
// https://github.com/microsoft/TypeScript/issues/48320
async function f17<T extends (...args: any[]) => Promise<any>>(fn: T) {
const ret: Awaited<ReturnType<T>> = await fn(1, 2, 3);
return ret;
}
async function f17_usage() {
const x = await f17(async () => 123 as const);
return { x };
}
+19 -1
View File
@@ -160,7 +160,16 @@ async function f16<T extends number & { then(): void }>(x: T) {
// helps with tests where '.types' just prints out the type alias name
type _Expect<TActual extends TExpected, TExpected> = TActual;
// https://github.com/microsoft/TypeScript/issues/48320
async function f17<T extends (...args: any[]) => Promise<any>>(fn: T) {
const ret: Awaited<ReturnType<T>> = await fn(1, 2, 3);
return ret;
}
async function f17_usage() {
const x = await f17(async () => 123 as const);
return { x };
}
//// [awaitedType.js]
async function main() {
@@ -263,3 +272,12 @@ async function f16(x) {
// y: T
const y = await x;
}
// https://github.com/microsoft/TypeScript/issues/48320
async function f17(fn) {
const ret = await fn(1, 2, 3);
return ret;
}
async function f17_usage() {
const x = await f17(async () => 123);
return { x };
}
@@ -403,3 +403,33 @@ type _Expect<TActual extends TExpected, TExpected> = TActual;
>TExpected : Symbol(TExpected, Decl(awaitedType.ts, 160, 39))
>TActual : Symbol(TActual, Decl(awaitedType.ts, 160, 13))
// https://github.com/microsoft/TypeScript/issues/48320
async function f17<T extends (...args: any[]) => Promise<any>>(fn: T) {
>f17 : Symbol(f17, Decl(awaitedType.ts, 160, 61))
>T : Symbol(T, Decl(awaitedType.ts, 163, 19))
>args : Symbol(args, Decl(awaitedType.ts, 163, 30))
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --))
>fn : Symbol(fn, Decl(awaitedType.ts, 163, 63))
>T : Symbol(T, Decl(awaitedType.ts, 163, 19))
const ret: Awaited<ReturnType<T>> = await fn(1, 2, 3);
>ret : Symbol(ret, Decl(awaitedType.ts, 164, 9))
>Awaited : Symbol(Awaited, Decl(lib.es5.d.ts, --, --))
>ReturnType : Symbol(ReturnType, Decl(lib.es5.d.ts, --, --))
>T : Symbol(T, Decl(awaitedType.ts, 163, 19))
>fn : Symbol(fn, Decl(awaitedType.ts, 163, 63))
return ret;
>ret : Symbol(ret, Decl(awaitedType.ts, 164, 9))
}
async function f17_usage() {
>f17_usage : Symbol(f17_usage, Decl(awaitedType.ts, 166, 1))
const x = await f17(async () => 123 as const);
>x : Symbol(x, Decl(awaitedType.ts, 168, 9))
>f17 : Symbol(f17, Decl(awaitedType.ts, 160, 61))
>const : Symbol(const)
return { x };
>x : Symbol(x, Decl(awaitedType.ts, 169, 12))
}
+36 -2
View File
@@ -278,8 +278,8 @@ async function f11<T extends { then(onfulfilled: (value: unknown) => void): void
// y: Awaited<T>
const y = await x;
>y : unknown
>await x : unknown
>y : Awaited<T>
>await x : Awaited<T>
>x : T
}
@@ -358,3 +358,37 @@ async function f16<T extends number & { then(): void }>(x: T) {
type _Expect<TActual extends TExpected, TExpected> = TActual;
>_Expect : TActual
// https://github.com/microsoft/TypeScript/issues/48320
async function f17<T extends (...args: any[]) => Promise<any>>(fn: T) {
>f17 : <T extends (...args: any[]) => Promise<any>>(fn: T) => Promise<ReturnType<T>>
>args : any[]
>fn : T
const ret: Awaited<ReturnType<T>> = await fn(1, 2, 3);
>ret : Awaited<ReturnType<T>>
>await fn(1, 2, 3) : any
>fn(1, 2, 3) : Promise<any>
>fn : T
>1 : 1
>2 : 2
>3 : 3
return ret;
>ret : Awaited<ReturnType<T>>
}
async function f17_usage() {
>f17_usage : () => Promise<{ x: 123; }>
const x = await f17(async () => 123 as const);
>x : 123
>await f17(async () => 123 as const) : 123
>f17(async () => 123 as const) : Promise<Promise<123>>
>f17 : <T extends (...args: any[]) => Promise<any>>(fn: T) => Promise<ReturnType<T>>
>async () => 123 as const : () => Promise<123>
>123 as const : 123
>123 : 123
return { x };
>{ x } : { x: 123; }
>x : 123
}
@@ -11,13 +11,13 @@ tests/cases/compiler/bigintWithoutLib.ts(13,38): error TS2554: Expected 0 argume
tests/cases/compiler/bigintWithoutLib.ts(14,38): error TS2554: Expected 0 arguments, but got 2.
tests/cases/compiler/bigintWithoutLib.ts(15,38): error TS2554: Expected 0 arguments, but got 2.
tests/cases/compiler/bigintWithoutLib.ts(18,18): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
tests/cases/compiler/bigintWithoutLib.ts(18,38): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'?
tests/cases/compiler/bigintWithoutLib.ts(19,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'?
tests/cases/compiler/bigintWithoutLib.ts(20,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'?
tests/cases/compiler/bigintWithoutLib.ts(18,38): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
tests/cases/compiler/bigintWithoutLib.ts(19,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
tests/cases/compiler/bigintWithoutLib.ts(20,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
tests/cases/compiler/bigintWithoutLib.ts(20,34): error TS2737: BigInt literals are not available when targeting lower than ES2020.
tests/cases/compiler/bigintWithoutLib.ts(20,38): error TS2737: BigInt literals are not available when targeting lower than ES2020.
tests/cases/compiler/bigintWithoutLib.ts(20,42): error TS2737: BigInt literals are not available when targeting lower than ES2020.
tests/cases/compiler/bigintWithoutLib.ts(21,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'?
tests/cases/compiler/bigintWithoutLib.ts(21,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
tests/cases/compiler/bigintWithoutLib.ts(22,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
tests/cases/compiler/bigintWithoutLib.ts(23,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
tests/cases/compiler/bigintWithoutLib.ts(24,19): error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
@@ -97,16 +97,13 @@ tests/cases/compiler/bigintWithoutLib.ts(56,36): error TS2345: Argument of type
~~~~~~~~~~~~~
!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
~~~~~~~~~~~~~
!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'?
!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:18:5: 'bigIntArray' is declared here.
!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
bigIntArray = new BigInt64Array(10);
~~~~~~~~~~~~~
!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'?
!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:18:5: 'bigIntArray' is declared here.
!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
bigIntArray = new BigInt64Array([1n, 2n, 3n]);
~~~~~~~~~~~~~
!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'?
!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:18:5: 'bigIntArray' is declared here.
!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
~~
!!! error TS2737: BigInt literals are not available when targeting lower than ES2020.
~~
@@ -115,8 +112,7 @@ tests/cases/compiler/bigintWithoutLib.ts(56,36): error TS2345: Argument of type
!!! error TS2737: BigInt literals are not available when targeting lower than ES2020.
bigIntArray = new BigInt64Array([1, 2, 3]);
~~~~~~~~~~~~~
!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'?
!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:18:5: 'bigIntArray' is declared here.
!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
bigIntArray = new BigInt64Array(new ArrayBuffer(80));
~~~~~~~~~~~~~
!!! error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
@@ -1,4 +1,4 @@
tests/cases/compiler/weird.js(1,1): error TS2304: Cannot find name 'someFunction'.
tests/cases/compiler/weird.js(1,1): error TS2552: Cannot find name 'someFunction'. Did you mean 'Function'?
tests/cases/compiler/weird.js(1,23): error TS7006: Parameter 'BaseClass' implicitly has an 'any' type.
tests/cases/compiler/weird.js(9,17): error TS7006: Parameter 'error' implicitly has an 'any' type.
@@ -6,7 +6,8 @@ tests/cases/compiler/weird.js(9,17): error TS7006: Parameter 'error' implicitly
==== tests/cases/compiler/weird.js (3 errors) ====
someFunction(function(BaseClass) {
~~~~~~~~~~~~
!!! error TS2304: Cannot find name 'someFunction'.
!!! error TS2552: Cannot find name 'someFunction'. Did you mean 'Function'?
!!! related TS2728 /.ts/lib.es5.d.ts:324:13: 'Function' is declared here.
~~~~~~~~~
!!! error TS7006: Parameter 'BaseClass' implicitly has an 'any' type.
'use strict';
@@ -0,0 +1,41 @@
=== tests/cases/compiler/classPropInitializationInferenceWithElementAccess.ts ===
// repro #49339
export class Cls {
>Cls : Symbol(Cls, Decl(classPropInitializationInferenceWithElementAccess.ts, 0, 0))
x;
>x : Symbol(Cls.x, Decl(classPropInitializationInferenceWithElementAccess.ts, 1, 18))
y;
>y : Symbol(Cls.y, Decl(classPropInitializationInferenceWithElementAccess.ts, 2, 6))
z;
>z : Symbol(Cls.z, Decl(classPropInitializationInferenceWithElementAccess.ts, 3, 6))
0;
>0 : Symbol(Cls[0], Decl(classPropInitializationInferenceWithElementAccess.ts, 4, 6))
constructor(seed: number) {
>seed : Symbol(seed, Decl(classPropInitializationInferenceWithElementAccess.ts, 8, 16))
this['x'] = [seed];
>this : Symbol(Cls, Decl(classPropInitializationInferenceWithElementAccess.ts, 0, 0))
>'x' : Symbol(Cls.x, Decl(classPropInitializationInferenceWithElementAccess.ts, 1, 18))
>seed : Symbol(seed, Decl(classPropInitializationInferenceWithElementAccess.ts, 8, 16))
this['y'] = { seed };
>this : Symbol(Cls, Decl(classPropInitializationInferenceWithElementAccess.ts, 0, 0))
>'y' : Symbol(Cls.y, Decl(classPropInitializationInferenceWithElementAccess.ts, 2, 6))
>seed : Symbol(seed, Decl(classPropInitializationInferenceWithElementAccess.ts, 10, 21))
this['z'] = `${seed}`;
>this : Symbol(Cls, Decl(classPropInitializationInferenceWithElementAccess.ts, 0, 0))
>'z' : Symbol(Cls.z, Decl(classPropInitializationInferenceWithElementAccess.ts, 3, 6))
>seed : Symbol(seed, Decl(classPropInitializationInferenceWithElementAccess.ts, 8, 16))
this[0] = [seed];
>this : Symbol(Cls, Decl(classPropInitializationInferenceWithElementAccess.ts, 0, 0))
>0 : Symbol(Cls[0], Decl(classPropInitializationInferenceWithElementAccess.ts, 4, 6))
>seed : Symbol(seed, Decl(classPropInitializationInferenceWithElementAccess.ts, 8, 16))
}
}
@@ -0,0 +1,53 @@
=== tests/cases/compiler/classPropInitializationInferenceWithElementAccess.ts ===
// repro #49339
export class Cls {
>Cls : Cls
x;
>x : number[]
y;
>y : { seed: number; }
z;
>z : string
0;
>0 : number[]
constructor(seed: number) {
>seed : number
this['x'] = [seed];
>this['x'] = [seed] : number[]
>this['x'] : number[]
>this : this
>'x' : "x"
>[seed] : number[]
>seed : number
this['y'] = { seed };
>this['y'] = { seed } : { seed: number; }
>this['y'] : { seed: number; }
>this : this
>'y' : "y"
>{ seed } : { seed: number; }
>seed : number
this['z'] = `${seed}`;
>this['z'] = `${seed}` : string
>this['z'] : string
>this : this
>'z' : "z"
>`${seed}` : string
>seed : number
this[0] = [seed];
>this[0] = [seed] : number[]
>this[0] : number[]
>this : this
>0 : 0
>[seed] : number[]
>seed : number
}
}
@@ -39,7 +39,7 @@ tests/cases/compiler/commonMissingSemicolons.ts(26,18): error TS1003: Identifier
tests/cases/compiler/commonMissingSemicolons.ts(27,1): error TS2304: Cannot find name 'functionMyFunction'.
tests/cases/compiler/commonMissingSemicolons.ts(30,1): error TS1435: Unknown keyword or identifier. Did you mean 'interface'?
tests/cases/compiler/commonMissingSemicolons.ts(30,1): error TS2304: Cannot find name 'interfaced'.
tests/cases/compiler/commonMissingSemicolons.ts(30,12): error TS1434: Unexpected keyword or identifier.
tests/cases/compiler/commonMissingSemicolons.ts(30,12): error TS1435: Unknown keyword or identifier. Did you mean 'interface'?
tests/cases/compiler/commonMissingSemicolons.ts(30,12): error TS2304: Cannot find name 'myInterface2'.
tests/cases/compiler/commonMissingSemicolons.ts(32,1): error TS2693: 'interface' only refers to a type, but is being used as a value here.
tests/cases/compiler/commonMissingSemicolons.ts(32,11): error TS1438: Interface must be given a name.
@@ -193,7 +193,7 @@ tests/cases/compiler/commonMissingSemicolons.ts(78,1): error TS1128: Declaration
~~~~~~~~~~
!!! error TS2304: Cannot find name 'interfaced'.
~~~~~~~~~~~~
!!! error TS1434: Unexpected keyword or identifier.
!!! error TS1435: Unknown keyword or identifier. Did you mean 'interface'?
~~~~~~~~~~~~
!!! error TS2304: Cannot find name 'myInterface2'.
interface interface { }
@@ -0,0 +1,16 @@
//// [computedPropertyNameAndTypeParameterConflict.ts]
declare const O: unique symbol;
declare class Bar<O> {
[O]: number;
}
//// [computedPropertyNameAndTypeParameterConflict.js]
//// [computedPropertyNameAndTypeParameterConflict.d.ts]
declare const O: unique symbol;
declare class Bar<O> {
[O]: number;
}
@@ -0,0 +1,14 @@
=== tests/cases/compiler/computedPropertyNameAndTypeParameterConflict.ts ===
declare const O: unique symbol;
>O : Symbol(O, Decl(computedPropertyNameAndTypeParameterConflict.ts, 0, 13))
declare class Bar<O> {
>Bar : Symbol(Bar, Decl(computedPropertyNameAndTypeParameterConflict.ts, 0, 31))
>O : Symbol(O, Decl(computedPropertyNameAndTypeParameterConflict.ts, 1, 18))
[O]: number;
>[O] : Symbol(Bar[O], Decl(computedPropertyNameAndTypeParameterConflict.ts, 1, 22))
>O : Symbol(O, Decl(computedPropertyNameAndTypeParameterConflict.ts, 0, 13))
}
@@ -0,0 +1,13 @@
=== tests/cases/compiler/computedPropertyNameAndTypeParameterConflict.ts ===
declare const O: unique symbol;
>O : unique symbol
declare class Bar<O> {
>Bar : Bar<O>
[O]: number;
>[O] : number
>O : unique symbol
}
@@ -1,22 +1,22 @@
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(2,17): error TS2304: Cannot find name 'x'.
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(3,22): error TS2304: Cannot find name 'x'.
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(4,23): error TS2304: Cannot find name 'x'.
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(10,17): error TS2304: Cannot find name 'x'.
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(11,22): error TS2304: Cannot find name 'x'.
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(12,23): error TS2304: Cannot find name 'x'.
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(2,17): error TS2301: Initializer of instance member variable 'a' cannot reference identifier 'x' declared in the constructor.
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(3,22): error TS2301: Initializer of instance member variable 'b' cannot reference identifier 'x' declared in the constructor.
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(4,23): error TS2301: Initializer of instance member variable 'c' cannot reference identifier 'x' declared in the constructor.
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(10,17): error TS2301: Initializer of instance member variable 'a' cannot reference identifier 'x' declared in the constructor.
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(11,22): error TS2301: Initializer of instance member variable 'b' cannot reference identifier 'x' declared in the constructor.
tests/cases/compiler/constructorParametersInVariableDeclarations.ts(12,23): error TS2301: Initializer of instance member variable 'c' cannot reference identifier 'x' declared in the constructor.
==== tests/cases/compiler/constructorParametersInVariableDeclarations.ts (6 errors) ====
class A {
private a = x;
~
!!! error TS2304: Cannot find name 'x'.
!!! error TS2301: Initializer of instance member variable 'a' cannot reference identifier 'x' declared in the constructor.
private b = { p: x };
~
!!! error TS2304: Cannot find name 'x'.
!!! error TS2301: Initializer of instance member variable 'b' cannot reference identifier 'x' declared in the constructor.
private c = () => x;
~
!!! error TS2304: Cannot find name 'x'.
!!! error TS2301: Initializer of instance member variable 'c' cannot reference identifier 'x' declared in the constructor.
constructor(x: number) {
}
}
@@ -24,13 +24,13 @@ tests/cases/compiler/constructorParametersInVariableDeclarations.ts(12,23): erro
class B {
private a = x;
~
!!! error TS2304: Cannot find name 'x'.
!!! error TS2301: Initializer of instance member variable 'a' cannot reference identifier 'x' declared in the constructor.
private b = { p: x };
~
!!! error TS2304: Cannot find name 'x'.
!!! error TS2301: Initializer of instance member variable 'b' cannot reference identifier 'x' declared in the constructor.
private c = () => x;
~
!!! error TS2304: Cannot find name 'x'.
!!! error TS2301: Initializer of instance member variable 'c' cannot reference identifier 'x' declared in the constructor.
constructor() {
var x = 1;
}
@@ -0,0 +1,32 @@
//// [index.tsx]
interface Elements {
foo: { callback?: (value: number) => void };
bar: { callback?: (value: string) => void };
}
type Props<C extends keyof Elements> = { as?: C } & Elements[C];
declare function Test<C extends keyof Elements>(props: Props<C>): null;
<Test
as="bar"
callback={(value) => {}}
/>;
Test({
as: "bar",
callback: (value) => {},
});
<Test<'bar'>
as="bar"
callback={(value) => {}}
/>;
//// [index.jsx]
<Test as="bar" callback={function (value) { }}/>;
Test({
as: "bar",
callback: function (value) { }
});
<Test as="bar" callback={function (value) { }}/>;
@@ -0,0 +1,68 @@
=== tests/cases/compiler/index.tsx ===
interface Elements {
>Elements : Symbol(Elements, Decl(index.tsx, 0, 0))
foo: { callback?: (value: number) => void };
>foo : Symbol(Elements.foo, Decl(index.tsx, 0, 20))
>callback : Symbol(callback, Decl(index.tsx, 1, 8))
>value : Symbol(value, Decl(index.tsx, 1, 21))
bar: { callback?: (value: string) => void };
>bar : Symbol(Elements.bar, Decl(index.tsx, 1, 46))
>callback : Symbol(callback, Decl(index.tsx, 2, 8))
>value : Symbol(value, Decl(index.tsx, 2, 21))
}
type Props<C extends keyof Elements> = { as?: C } & Elements[C];
>Props : Symbol(Props, Decl(index.tsx, 3, 1))
>C : Symbol(C, Decl(index.tsx, 5, 11))
>Elements : Symbol(Elements, Decl(index.tsx, 0, 0))
>as : Symbol(as, Decl(index.tsx, 5, 40))
>C : Symbol(C, Decl(index.tsx, 5, 11))
>Elements : Symbol(Elements, Decl(index.tsx, 0, 0))
>C : Symbol(C, Decl(index.tsx, 5, 11))
declare function Test<C extends keyof Elements>(props: Props<C>): null;
>Test : Symbol(Test, Decl(index.tsx, 5, 64))
>C : Symbol(C, Decl(index.tsx, 6, 22))
>Elements : Symbol(Elements, Decl(index.tsx, 0, 0))
>props : Symbol(props, Decl(index.tsx, 6, 48))
>Props : Symbol(Props, Decl(index.tsx, 3, 1))
>C : Symbol(C, Decl(index.tsx, 6, 22))
<Test
>Test : Symbol(Test, Decl(index.tsx, 5, 64))
as="bar"
>as : Symbol(as, Decl(index.tsx, 8, 5))
callback={(value) => {}}
>callback : Symbol(callback, Decl(index.tsx, 9, 10))
>value : Symbol(value, Decl(index.tsx, 10, 13))
/>;
Test({
>Test : Symbol(Test, Decl(index.tsx, 5, 64))
as: "bar",
>as : Symbol(as, Decl(index.tsx, 13, 6))
callback: (value) => {},
>callback : Symbol(callback, Decl(index.tsx, 14, 12))
>value : Symbol(value, Decl(index.tsx, 15, 13))
});
<Test<'bar'>
>Test : Symbol(Test, Decl(index.tsx, 5, 64))
as="bar"
>as : Symbol(as, Decl(index.tsx, 18, 12))
callback={(value) => {}}
>callback : Symbol(callback, Decl(index.tsx, 19, 10))
>value : Symbol(value, Decl(index.tsx, 20, 13))
/>;
@@ -0,0 +1,66 @@
=== tests/cases/compiler/index.tsx ===
interface Elements {
foo: { callback?: (value: number) => void };
>foo : { callback?: (value: number) => void; }
>callback : (value: number) => void
>value : number
bar: { callback?: (value: string) => void };
>bar : { callback?: (value: string) => void; }
>callback : (value: string) => void
>value : string
}
type Props<C extends keyof Elements> = { as?: C } & Elements[C];
>Props : Props<C>
>as : C
declare function Test<C extends keyof Elements>(props: Props<C>): null;
>Test : <C extends keyof Elements>(props: Props<C>) => null
>props : Props<C>
>null : null
<Test
><Test as="bar" callback={(value) => {}}/> : error
>Test : <C extends keyof Elements>(props: Props<C>) => null
as="bar"
>as : "bar"
callback={(value) => {}}
>callback : (value: string) => void
>(value) => {} : (value: string) => void
>value : string
/>;
Test({
>Test({ as: "bar", callback: (value) => {},}) : null
>Test : <C extends keyof Elements>(props: Props<C>) => null
>{ as: "bar", callback: (value) => {},} : { as: "bar"; callback: (value: string) => void; }
as: "bar",
>as : "bar"
>"bar" : "bar"
callback: (value) => {},
>callback : (value: string) => void
>(value) => {} : (value: string) => void
>value : string
});
<Test<'bar'>
><Test<'bar'> as="bar" callback={(value) => {}}/> : error
>Test : <C extends keyof Elements>(props: Props<C>) => null
as="bar"
>as : "bar"
callback={(value) => {}}
>callback : (value: string) => void
>(value) => {} : (value: string) => void
>value : string
/>;
@@ -1768,9 +1768,9 @@ function f30(o: Thing | undefined) {
>foo : string | number | undefined
o.foo;
>o.foo : string | number
>o.foo : NonNullable<string | number | undefined>
>o : Thing
>foo : string | number
>foo : NonNullable<string | number | undefined>
}
}
@@ -0,0 +1,18 @@
//// [declarationEmitDistributiveConditionalWithInfer.ts]
// This function's type is changed on declaration
export const fun = (
subFun: <Collection, Field extends keyof Collection>()
=> FlatArray<Collection[Field], 0>[]) => { };
//// [declarationEmitDistributiveConditionalWithInfer.js]
"use strict";
exports.__esModule = true;
exports.fun = void 0;
// This function's type is changed on declaration
var fun = function (subFun) { };
exports.fun = fun;
//// [declarationEmitDistributiveConditionalWithInfer.d.ts]
export declare const fun: (subFun: <Collection, Field extends keyof Collection>() => (Collection[Field] extends infer T ? T extends Collection[Field] ? T extends readonly (infer InnerArr)[] ? InnerArr : T : never : never)[]) => void;
@@ -0,0 +1,16 @@
=== tests/cases/compiler/declarationEmitDistributiveConditionalWithInfer.ts ===
// This function's type is changed on declaration
export const fun = (
>fun : Symbol(fun, Decl(declarationEmitDistributiveConditionalWithInfer.ts, 1, 12))
subFun: <Collection, Field extends keyof Collection>()
>subFun : Symbol(subFun, Decl(declarationEmitDistributiveConditionalWithInfer.ts, 1, 20))
>Collection : Symbol(Collection, Decl(declarationEmitDistributiveConditionalWithInfer.ts, 2, 13))
>Field : Symbol(Field, Decl(declarationEmitDistributiveConditionalWithInfer.ts, 2, 24))
>Collection : Symbol(Collection, Decl(declarationEmitDistributiveConditionalWithInfer.ts, 2, 13))
=> FlatArray<Collection[Field], 0>[]) => { };
>FlatArray : Symbol(FlatArray, Decl(lib.es2019.array.d.ts, --, --))
>Collection : Symbol(Collection, Decl(declarationEmitDistributiveConditionalWithInfer.ts, 2, 13))
>Field : Symbol(Field, Decl(declarationEmitDistributiveConditionalWithInfer.ts, 2, 24))
@@ -0,0 +1,11 @@
=== tests/cases/compiler/declarationEmitDistributiveConditionalWithInfer.ts ===
// This function's type is changed on declaration
export const fun = (
>fun : (subFun: <Collection, Field extends keyof Collection>() => (Collection[Field] extends readonly (infer InnerArr)[] ? InnerArr : Collection[Field])[]) => void
>( subFun: <Collection, Field extends keyof Collection>() => FlatArray<Collection[Field], 0>[]) => { } : (subFun: <Collection, Field extends keyof Collection>() => (Collection[Field] extends readonly (infer InnerArr)[] ? InnerArr : Collection[Field])[]) => void
subFun: <Collection, Field extends keyof Collection>()
>subFun : <Collection, Field extends keyof Collection>() => (Collection[Field] extends readonly (infer InnerArr)[] ? InnerArr : Collection[Field])[]
=> FlatArray<Collection[Field], 0>[]) => { };
@@ -1,15 +0,0 @@
/b.ts(2,30): error TS4021: 'extends' clause of exported class has or is using private name 'Foo'.
==== /b.ts (1 errors) ====
const { Foo } = require("./a");
export default class extends Foo {}
~~~
!!! error TS4021: 'extends' clause of exported class has or is using private name 'Foo'.
==== /node_modules/@types/node/index.d.ts (0 errors) ====
declare const require: any;
==== /a.js (0 errors) ====
export class Foo {}
@@ -3,14 +3,25 @@
//// [index.d.ts]
declare const require: any;
//// [a.js]
//// [a.ts]
export class Foo {}
//// [b.ts]
const { Foo } = require("./a");
import * as A from "./a";
const { Foo } = A;
export default class extends Foo {}
//// [a.js]
"use strict";
exports.__esModule = true;
exports.Foo = void 0;
var Foo = /** @class */ (function () {
function Foo() {
}
return Foo;
}());
exports.Foo = Foo;
//// [b.js]
"use strict";
var __extends = (this && this.__extends) || (function () {
@@ -29,7 +40,8 @@ var __extends = (this && this.__extends) || (function () {
};
})();
exports.__esModule = true;
var Foo = require("./a").Foo;
var A = require("./a");
var Foo = A.Foo;
var default_1 = /** @class */ (function (_super) {
__extends(default_1, _super);
function default_1() {
@@ -38,3 +50,14 @@ var default_1 = /** @class */ (function (_super) {
return default_1;
}(Foo));
exports["default"] = default_1;
//// [a.d.ts]
export declare class Foo {
}
//// [b.d.ts]
import * as A from "./a";
declare const Foo: typeof A.Foo;
export default class extends Foo {
}
export {};
@@ -1,12 +1,19 @@
=== /b.ts ===
const { Foo } = require("./a");
>Foo : Symbol(Foo, Decl(b.ts, 0, 7))
>require : Symbol(require, Decl(index.d.ts, 0, 13))
export default class extends Foo {}
>Foo : Symbol(Foo, Decl(b.ts, 0, 7))
=== /node_modules/@types/node/index.d.ts ===
declare const require: any;
>require : Symbol(require, Decl(index.d.ts, 0, 13))
=== /a.ts ===
export class Foo {}
>Foo : Symbol(Foo, Decl(a.ts, 0, 0))
=== /b.ts ===
import * as A from "./a";
>A : Symbol(A, Decl(b.ts, 0, 6))
const { Foo } = A;
>Foo : Symbol(Foo, Decl(b.ts, 1, 7))
>A : Symbol(A, Decl(b.ts, 0, 6))
export default class extends Foo {}
>Foo : Symbol(Foo, Decl(b.ts, 1, 7))
@@ -1,14 +1,19 @@
=== /b.ts ===
const { Foo } = require("./a");
>Foo : any
>require("./a") : any
>require : any
>"./a" : "./a"
export default class extends Foo {}
>Foo : any
=== /node_modules/@types/node/index.d.ts ===
declare const require: any;
>require : any
=== /a.ts ===
export class Foo {}
>Foo : Foo
=== /b.ts ===
import * as A from "./a";
>A : typeof A
const { Foo } = A;
>Foo : typeof A.Foo
>A : typeof A
export default class extends Foo {}
>Foo : A.Foo
@@ -0,0 +1,61 @@
//// [tests/cases/compiler/declarationEmitMappedTypeDistributivityPreservesConstraints.ts] ////
//// [types.ts]
type Fns = Record<string, (...params: unknown[]) => unknown>
type Map<T extends Fns> = { [K in keyof T]: T[K]; };
type AllArg<T extends Fns> = { [K in keyof T]: Parameters<T[K]> };
function fn<T extends { x: Map<T['x']> }>(sliceIndex: T): AllArg<T['x']> {
return null!;
}
export default { fn };
//// [reexport.ts]
import test from "./types";
export default { test };
//// [types.js]
"use strict";
exports.__esModule = true;
function fn(sliceIndex) {
return null;
}
exports["default"] = { fn: fn };
//// [reexport.js]
"use strict";
exports.__esModule = true;
var types_1 = require("./types");
exports["default"] = { test: types_1["default"] };
//// [types.d.ts]
declare type Fns = Record<string, (...params: unknown[]) => unknown>;
declare type Map<T extends Fns> = {
[K in keyof T]: T[K];
};
declare type AllArg<T extends Fns> = {
[K in keyof T]: Parameters<T[K]>;
};
declare function fn<T extends {
x: Map<T['x']>;
}>(sliceIndex: T): AllArg<T['x']>;
declare const _default: {
fn: typeof fn;
};
export default _default;
//// [reexport.d.ts]
declare const _default: {
test: {
fn: <T_1 extends {
x: T_1["x"] extends infer T extends {
[x: string]: (...params: unknown[]) => unknown;
} ? { [K in keyof T]: T_1["x"][K]; } : never;
}>(sliceIndex: T_1) => T_1["x"] extends infer T_2 extends {
[x: string]: (...params: unknown[]) => unknown;
} ? { [K_1 in keyof T_2]: Parameters<T_1["x"][K_1]>; } : never;
};
};
export default _default;
@@ -0,0 +1,49 @@
=== tests/cases/compiler/types.ts ===
type Fns = Record<string, (...params: unknown[]) => unknown>
>Fns : Symbol(Fns, Decl(types.ts, 0, 0))
>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --))
>params : Symbol(params, Decl(types.ts, 0, 27))
type Map<T extends Fns> = { [K in keyof T]: T[K]; };
>Map : Symbol(Map, Decl(types.ts, 0, 60))
>T : Symbol(T, Decl(types.ts, 2, 9))
>Fns : Symbol(Fns, Decl(types.ts, 0, 0))
>K : Symbol(K, Decl(types.ts, 2, 29))
>T : Symbol(T, Decl(types.ts, 2, 9))
>T : Symbol(T, Decl(types.ts, 2, 9))
>K : Symbol(K, Decl(types.ts, 2, 29))
type AllArg<T extends Fns> = { [K in keyof T]: Parameters<T[K]> };
>AllArg : Symbol(AllArg, Decl(types.ts, 2, 52))
>T : Symbol(T, Decl(types.ts, 4, 12))
>Fns : Symbol(Fns, Decl(types.ts, 0, 0))
>K : Symbol(K, Decl(types.ts, 4, 32))
>T : Symbol(T, Decl(types.ts, 4, 12))
>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --))
>T : Symbol(T, Decl(types.ts, 4, 12))
>K : Symbol(K, Decl(types.ts, 4, 32))
function fn<T extends { x: Map<T['x']> }>(sliceIndex: T): AllArg<T['x']> {
>fn : Symbol(fn, Decl(types.ts, 4, 66))
>T : Symbol(T, Decl(types.ts, 6, 12))
>x : Symbol(x, Decl(types.ts, 6, 23))
>Map : Symbol(Map, Decl(types.ts, 0, 60))
>T : Symbol(T, Decl(types.ts, 6, 12))
>sliceIndex : Symbol(sliceIndex, Decl(types.ts, 6, 42))
>T : Symbol(T, Decl(types.ts, 6, 12))
>AllArg : Symbol(AllArg, Decl(types.ts, 2, 52))
>T : Symbol(T, Decl(types.ts, 6, 12))
return null!;
}
export default { fn };
>fn : Symbol(fn, Decl(types.ts, 10, 16))
=== tests/cases/compiler/reexport.ts ===
import test from "./types";
>test : Symbol(test, Decl(reexport.ts, 0, 6))
export default { test };
>test : Symbol(test, Decl(reexport.ts, 1, 16))
@@ -0,0 +1,33 @@
=== tests/cases/compiler/types.ts ===
type Fns = Record<string, (...params: unknown[]) => unknown>
>Fns : { [x: string]: (...params: unknown[]) => unknown; }
>params : unknown[]
type Map<T extends Fns> = { [K in keyof T]: T[K]; };
>Map : Map<T>
type AllArg<T extends Fns> = { [K in keyof T]: Parameters<T[K]> };
>AllArg : AllArg<T>
function fn<T extends { x: Map<T['x']> }>(sliceIndex: T): AllArg<T['x']> {
>fn : <T extends { x: Map<T['x']>; }>(sliceIndex: T) => AllArg<T['x']>
>x : Map<T["x"]>
>sliceIndex : T
return null!;
>null! : null
>null : null
}
export default { fn };
>{ fn } : { fn: <T extends { x: Map<T["x"]>; }>(sliceIndex: T) => AllArg<T["x"]>; }
>fn : <T extends { x: Map<T["x"]>; }>(sliceIndex: T) => AllArg<T["x"]>
=== tests/cases/compiler/reexport.ts ===
import test from "./types";
>test : { fn: <T extends { x: { [K in keyof T["x"]]: T["x"][K]; }; }>(sliceIndex: T) => { [K in keyof T["x"]]: Parameters<T["x"][K]>; }; }
export default { test };
>{ test } : { test: { fn: <T extends { x: { [K in keyof T["x"]]: T["x"][K]; }; }>(sliceIndex: T) => { [K in keyof T["x"]]: Parameters<T["x"][K]>; }; }; }
>test : { fn: <T extends { x: { [K in keyof T["x"]]: T["x"][K]; }; }>(sliceIndex: T) => { [K in keyof T["x"]]: Parameters<T["x"][K]>; }; }
@@ -0,0 +1,48 @@
//// [test.ts]
function getFoo() {
return { foo: { test: 42 } }
}
const { foo } = getFoo()
export type AliasType = typeof foo
const { foo: renamed } = getFoo()
export type AliasType2 = typeof renamed
function getNested() {
return { a: { b: { c: 'd' } } }
}
const { a: { b: { c } } } = getNested()
export type AliasType3 = typeof c
//// [test.js]
"use strict";
exports.__esModule = true;
function getFoo() {
return { foo: { test: 42 } };
}
var foo = getFoo().foo;
var renamed = getFoo().foo;
function getNested() {
return { a: { b: { c: 'd' } } };
}
var c = getNested().a.b.c;
//// [test.d.ts]
declare const foo: {
test: number;
};
export declare type AliasType = typeof foo;
declare const renamed: {
test: number;
};
export declare type AliasType2 = typeof renamed;
declare const c: string;
export declare type AliasType3 = typeof c;
export {};
@@ -0,0 +1,45 @@
=== tests/cases/compiler/test.ts ===
function getFoo() {
>getFoo : Symbol(getFoo, Decl(test.ts, 0, 0))
return { foo: { test: 42 } }
>foo : Symbol(foo, Decl(test.ts, 1, 10))
>test : Symbol(test, Decl(test.ts, 1, 17))
}
const { foo } = getFoo()
>foo : Symbol(foo, Decl(test.ts, 4, 7))
>getFoo : Symbol(getFoo, Decl(test.ts, 0, 0))
export type AliasType = typeof foo
>AliasType : Symbol(AliasType, Decl(test.ts, 4, 24))
>foo : Symbol(foo, Decl(test.ts, 4, 7))
const { foo: renamed } = getFoo()
>foo : Symbol(foo, Decl(test.ts, 1, 10))
>renamed : Symbol(renamed, Decl(test.ts, 8, 7))
>getFoo : Symbol(getFoo, Decl(test.ts, 0, 0))
export type AliasType2 = typeof renamed
>AliasType2 : Symbol(AliasType2, Decl(test.ts, 8, 33))
>renamed : Symbol(renamed, Decl(test.ts, 8, 7))
function getNested() {
>getNested : Symbol(getNested, Decl(test.ts, 10, 39))
return { a: { b: { c: 'd' } } }
>a : Symbol(a, Decl(test.ts, 13, 10))
>b : Symbol(b, Decl(test.ts, 13, 15))
>c : Symbol(c, Decl(test.ts, 13, 20))
}
const { a: { b: { c } } } = getNested()
>a : Symbol(a, Decl(test.ts, 13, 10))
>b : Symbol(b, Decl(test.ts, 13, 15))
>c : Symbol(c, Decl(test.ts, 16, 17))
>getNested : Symbol(getNested, Decl(test.ts, 10, 39))
export type AliasType3 = typeof c
>AliasType3 : Symbol(AliasType3, Decl(test.ts, 16, 39))
>c : Symbol(c, Decl(test.ts, 16, 17))
@@ -0,0 +1,55 @@
=== tests/cases/compiler/test.ts ===
function getFoo() {
>getFoo : () => { foo: { test: number; }; }
return { foo: { test: 42 } }
>{ foo: { test: 42 } } : { foo: { test: number; }; }
>foo : { test: number; }
>{ test: 42 } : { test: number; }
>test : number
>42 : 42
}
const { foo } = getFoo()
>foo : { test: number; }
>getFoo() : { foo: { test: number; }; }
>getFoo : () => { foo: { test: number; }; }
export type AliasType = typeof foo
>AliasType : { test: number; }
>foo : { test: number; }
const { foo: renamed } = getFoo()
>foo : any
>renamed : { test: number; }
>getFoo() : { foo: { test: number; }; }
>getFoo : () => { foo: { test: number; }; }
export type AliasType2 = typeof renamed
>AliasType2 : { test: number; }
>renamed : { test: number; }
function getNested() {
>getNested : () => { a: { b: { c: string; }; }; }
return { a: { b: { c: 'd' } } }
>{ a: { b: { c: 'd' } } } : { a: { b: { c: string; }; }; }
>a : { b: { c: string; }; }
>{ b: { c: 'd' } } : { b: { c: string; }; }
>b : { c: string; }
>{ c: 'd' } : { c: string; }
>c : string
>'d' : "d"
}
const { a: { b: { c } } } = getNested()
>a : any
>b : any
>c : string
>getNested() : { a: { b: { c: string; }; }; }
>getNested : () => { a: { b: { c: string; }; }; }
export type AliasType3 = typeof c
>AliasType3 : string
>c : string
@@ -331,4 +331,47 @@ tests/cases/conformance/controlFlow/dependentDestructuredVariables.ts(314,5): er
test8 = value1.test8,
test9 = value1.test9
}) {}
// Repro from #49772
function fa1(x: [true, number] | [false, string]) {
const [guard, value] = x;
if (guard) {
for (;;) {
value; // number
}
}
else {
while (!!true) {
value; // string
}
}
}
function fa2(x: { guard: true, value: number } | { guard: false, value: string }) {
const { guard, value } = x;
if (guard) {
for (;;) {
value; // number
}
}
else {
while (!!true) {
value; // string
}
}
}
const fa3: (...args: [true, number] | [false, string]) => void = (guard, value) => {
if (guard) {
for (;;) {
value; // number
}
}
else {
while (!!true) {
value; // string
}
}
}
@@ -323,6 +323,49 @@ function foo({
test8 = value1.test8,
test9 = value1.test9
}) {}
// Repro from #49772
function fa1(x: [true, number] | [false, string]) {
const [guard, value] = x;
if (guard) {
for (;;) {
value; // number
}
}
else {
while (!!true) {
value; // string
}
}
}
function fa2(x: { guard: true, value: number } | { guard: false, value: string }) {
const { guard, value } = x;
if (guard) {
for (;;) {
value; // number
}
}
else {
while (!!true) {
value; // string
}
}
}
const fa3: (...args: [true, number] | [false, string]) => void = (guard, value) => {
if (guard) {
for (;;) {
value; // number
}
}
else {
while (!!true) {
value; // string
}
}
}
//// [dependentDestructuredVariables.js]
@@ -567,6 +610,45 @@ const f60 = (kind, payload) => {
};
// Repro from #48902
function foo({ value1, test1 = value1.test1, test2 = value1.test2, test3 = value1.test3, test4 = value1.test4, test5 = value1.test5, test6 = value1.test6, test7 = value1.test7, test8 = value1.test8, test9 = value1.test9 }) { }
// Repro from #49772
function fa1(x) {
const [guard, value] = x;
if (guard) {
for (;;) {
value; // number
}
}
else {
while (!!true) {
value; // string
}
}
}
function fa2(x) {
const { guard, value } = x;
if (guard) {
for (;;) {
value; // number
}
}
else {
while (!!true) {
value; // string
}
}
}
const fa3 = (guard, value) => {
if (guard) {
for (;;) {
value; // number
}
}
else {
while (!!true) {
value; // string
}
}
};
//// [dependentDestructuredVariables.d.ts]
@@ -696,3 +778,12 @@ declare function foo({ value1, test1, test2, test3, test4, test5, test6, test7,
test8?: any;
test9?: any;
}): void;
declare function fa1(x: [true, number] | [false, string]): void;
declare function fa2(x: {
guard: true;
value: number;
} | {
guard: false;
value: string;
}): void;
declare const fa3: (...args: [true, number] | [false, string]) => void;
@@ -830,3 +830,81 @@ function foo({
}) {}
// Repro from #49772
function fa1(x: [true, number] | [false, string]) {
>fa1 : Symbol(fa1, Decl(dependentDestructuredVariables.ts, 323, 5))
>x : Symbol(x, Decl(dependentDestructuredVariables.ts, 327, 13))
const [guard, value] = x;
>guard : Symbol(guard, Decl(dependentDestructuredVariables.ts, 328, 11))
>value : Symbol(value, Decl(dependentDestructuredVariables.ts, 328, 17))
>x : Symbol(x, Decl(dependentDestructuredVariables.ts, 327, 13))
if (guard) {
>guard : Symbol(guard, Decl(dependentDestructuredVariables.ts, 328, 11))
for (;;) {
value; // number
>value : Symbol(value, Decl(dependentDestructuredVariables.ts, 328, 17))
}
}
else {
while (!!true) {
value; // string
>value : Symbol(value, Decl(dependentDestructuredVariables.ts, 328, 17))
}
}
}
function fa2(x: { guard: true, value: number } | { guard: false, value: string }) {
>fa2 : Symbol(fa2, Decl(dependentDestructuredVariables.ts, 339, 1))
>x : Symbol(x, Decl(dependentDestructuredVariables.ts, 341, 13))
>guard : Symbol(guard, Decl(dependentDestructuredVariables.ts, 341, 17))
>value : Symbol(value, Decl(dependentDestructuredVariables.ts, 341, 30))
>guard : Symbol(guard, Decl(dependentDestructuredVariables.ts, 341, 50))
>value : Symbol(value, Decl(dependentDestructuredVariables.ts, 341, 64))
const { guard, value } = x;
>guard : Symbol(guard, Decl(dependentDestructuredVariables.ts, 342, 11))
>value : Symbol(value, Decl(dependentDestructuredVariables.ts, 342, 18))
>x : Symbol(x, Decl(dependentDestructuredVariables.ts, 341, 13))
if (guard) {
>guard : Symbol(guard, Decl(dependentDestructuredVariables.ts, 342, 11))
for (;;) {
value; // number
>value : Symbol(value, Decl(dependentDestructuredVariables.ts, 342, 18))
}
}
else {
while (!!true) {
value; // string
>value : Symbol(value, Decl(dependentDestructuredVariables.ts, 342, 18))
}
}
}
const fa3: (...args: [true, number] | [false, string]) => void = (guard, value) => {
>fa3 : Symbol(fa3, Decl(dependentDestructuredVariables.ts, 355, 5))
>args : Symbol(args, Decl(dependentDestructuredVariables.ts, 355, 12))
>guard : Symbol(guard, Decl(dependentDestructuredVariables.ts, 355, 66))
>value : Symbol(value, Decl(dependentDestructuredVariables.ts, 355, 72))
if (guard) {
>guard : Symbol(guard, Decl(dependentDestructuredVariables.ts, 355, 66))
for (;;) {
value; // number
>value : Symbol(value, Decl(dependentDestructuredVariables.ts, 355, 72))
}
}
else {
while (!!true) {
value; // string
>value : Symbol(value, Decl(dependentDestructuredVariables.ts, 355, 72))
}
}
}
@@ -955,3 +955,100 @@ function foo({
}) {}
// Repro from #49772
function fa1(x: [true, number] | [false, string]) {
>fa1 : (x: [true, number] | [false, string]) => void
>x : [true, number] | [false, string]
>true : true
>false : false
const [guard, value] = x;
>guard : boolean
>value : string | number
>x : [true, number] | [false, string]
if (guard) {
>guard : boolean
for (;;) {
value; // number
>value : number
}
}
else {
while (!!true) {
>!!true : true
>!true : false
>true : true
value; // string
>value : string
}
}
}
function fa2(x: { guard: true, value: number } | { guard: false, value: string }) {
>fa2 : (x: { guard: true; value: number;} | { guard: false; value: string;}) => void
>x : { guard: true; value: number; } | { guard: false; value: string; }
>guard : true
>true : true
>value : number
>guard : false
>false : false
>value : string
const { guard, value } = x;
>guard : boolean
>value : string | number
>x : { guard: true; value: number; } | { guard: false; value: string; }
if (guard) {
>guard : boolean
for (;;) {
value; // number
>value : number
}
}
else {
while (!!true) {
>!!true : true
>!true : false
>true : true
value; // string
>value : string
}
}
}
const fa3: (...args: [true, number] | [false, string]) => void = (guard, value) => {
>fa3 : (...args: [true, number] | [false, string]) => void
>args : [true, number] | [false, string]
>true : true
>false : false
>(guard, value) => { if (guard) { for (;;) { value; // number } } else { while (!!true) { value; // string } }} : (guard: boolean, value: string | number) => void
>guard : boolean
>value : string | number
if (guard) {
>guard : boolean
for (;;) {
value; // number
>value : number
}
}
else {
while (!!true) {
>!!true : true
>!true : false
>true : true
value; // string
>value : string
}
}
}
@@ -1,24 +1,38 @@
tests/cases/compiler/errorCause.ts(1,28): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(2,5): error TS2550: Property 'cause' does not exist on type 'Error'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2022' or later.
tests/cases/compiler/errorCause.ts(4,22): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(5,23): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(6,27): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(7,24): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(3,28): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(4,5): error TS2550: Property 'cause' does not exist on type 'Error'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2022' or later.
tests/cases/compiler/errorCause.ts(5,35): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(6,12): error TS2550: Property 'cause' does not exist on type 'Error'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2022' or later.
tests/cases/compiler/errorCause.ts(8,22): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(9,21): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(10,31): error TS2554: Expected 1-2 arguments, but got 3.
tests/cases/compiler/errorCause.ts(9,22): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(10,23): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(11,27): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(12,24): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(13,22): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(14,21): error TS2554: Expected 0-1 arguments, but got 2.
tests/cases/compiler/errorCause.ts(15,31): error TS2554: Expected 1-2 arguments, but got 3.
==== tests/cases/compiler/errorCause.ts (9 errors) ====
==== tests/cases/compiler/errorCause.ts (12 errors) ====
declare const a: unknown;
let err = new Error("foo", { cause: new Error("bar") });
~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2554: Expected 0-1 arguments, but got 2.
err.cause;
~~~~~
!!! error TS2550: Property 'cause' does not exist on type 'Error'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2022' or later.
let anotherErr = new Error("foo", { cause: a });
~~~~~~~~~~~~
!!! error TS2554: Expected 0-1 arguments, but got 2.
anotherErr.cause;
~~~~~
!!! error TS2550: Property 'cause' does not exist on type 'Error'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2022' or later.
new EvalError("foo", { cause: new Error("bar") });
~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2554: Expected 0-1 arguments, but got 2.
new EvalError("foo", { cause: a });
~~~~~~~~~~~~
!!! error TS2554: Expected 0-1 arguments, but got 2.
new RangeError("foo", { cause: new Error("bar") });
~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1,8 +1,13 @@
//// [errorCause.ts]
declare const a: unknown;
let err = new Error("foo", { cause: new Error("bar") });
err.cause;
let anotherErr = new Error("foo", { cause: a });
anotherErr.cause;
new EvalError("foo", { cause: new Error("bar") });
new EvalError("foo", { cause: a });
new RangeError("foo", { cause: new Error("bar") });
new ReferenceError("foo", { cause: new Error("bar") });
new SyntaxError("foo", { cause: new Error("bar") });
@@ -14,7 +19,10 @@ new AggregateError([], "foo", { cause: new Error("bar") });
//// [errorCause.js]
let err = new Error("foo", { cause: new Error("bar") });
err.cause;
let anotherErr = new Error("foo", { cause: a });
anotherErr.cause;
new EvalError("foo", { cause: new Error("bar") });
new EvalError("foo", { cause: a });
new RangeError("foo", { cause: new Error("bar") });
new ReferenceError("foo", { cause: new Error("bar") });
new SyntaxError("foo", { cause: new Error("bar") });
@@ -1,45 +1,62 @@
=== tests/cases/compiler/errorCause.ts ===
declare const a: unknown;
>a : Symbol(a, Decl(errorCause.ts, 0, 13))
let err = new Error("foo", { cause: new Error("bar") });
>err : Symbol(err, Decl(errorCause.ts, 0, 3))
>err : Symbol(err, Decl(errorCause.ts, 2, 3))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 0, 28))
>cause : Symbol(cause, Decl(errorCause.ts, 2, 28))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
err.cause;
>err : Symbol(err, Decl(errorCause.ts, 0, 3))
>err : Symbol(err, Decl(errorCause.ts, 2, 3))
let anotherErr = new Error("foo", { cause: a });
>anotherErr : Symbol(anotherErr, Decl(errorCause.ts, 4, 3))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 4, 35))
>a : Symbol(a, Decl(errorCause.ts, 0, 13))
anotherErr.cause;
>anotherErr : Symbol(anotherErr, Decl(errorCause.ts, 4, 3))
new EvalError("foo", { cause: new Error("bar") });
>EvalError : Symbol(EvalError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 3, 22))
>cause : Symbol(cause, Decl(errorCause.ts, 7, 22))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
new EvalError("foo", { cause: a });
>EvalError : Symbol(EvalError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 8, 22))
>a : Symbol(a, Decl(errorCause.ts, 0, 13))
new RangeError("foo", { cause: new Error("bar") });
>RangeError : Symbol(RangeError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 4, 23))
>cause : Symbol(cause, Decl(errorCause.ts, 9, 23))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
new ReferenceError("foo", { cause: new Error("bar") });
>ReferenceError : Symbol(ReferenceError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 5, 27))
>cause : Symbol(cause, Decl(errorCause.ts, 10, 27))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
new SyntaxError("foo", { cause: new Error("bar") });
>SyntaxError : Symbol(SyntaxError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 6, 24))
>cause : Symbol(cause, Decl(errorCause.ts, 11, 24))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
new TypeError("foo", { cause: new Error("bar") });
>TypeError : Symbol(TypeError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 7, 22))
>cause : Symbol(cause, Decl(errorCause.ts, 12, 22))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
new URIError("foo", { cause: new Error("bar") });
>URIError : Symbol(URIError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 8, 21))
>cause : Symbol(cause, Decl(errorCause.ts, 13, 21))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
new AggregateError([], "foo", { cause: new Error("bar") });
>AggregateError : Symbol(AggregateError, Decl(lib.es2021.promise.d.ts, --, --), Decl(lib.es2021.promise.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 9, 31))
>cause : Symbol(cause, Decl(errorCause.ts, 14, 31))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
@@ -1,4 +1,7 @@
=== tests/cases/compiler/errorCause.ts ===
declare const a: unknown;
>a : unknown
let err = new Error("foo", { cause: new Error("bar") });
>err : Error
>new Error("foo", { cause: new Error("bar") }) : Error
@@ -15,6 +18,20 @@ err.cause;
>err : Error
>cause : any
let anotherErr = new Error("foo", { cause: a });
>anotherErr : Error
>new Error("foo", { cause: a }) : Error
>Error : ErrorConstructor
>"foo" : "foo"
>{ cause: a } : { cause: unknown; }
>cause : unknown
>a : unknown
anotherErr.cause;
>anotherErr.cause : any
>anotherErr : Error
>cause : any
new EvalError("foo", { cause: new Error("bar") });
>new EvalError("foo", { cause: new Error("bar") }) : EvalError & Error
>EvalError : EvalErrorConstructor
@@ -25,6 +42,14 @@ new EvalError("foo", { cause: new Error("bar") });
>Error : ErrorConstructor
>"bar" : "bar"
new EvalError("foo", { cause: a });
>new EvalError("foo", { cause: a }) : EvalError & Error
>EvalError : EvalErrorConstructor
>"foo" : "foo"
>{ cause: a } : { cause: unknown; }
>cause : unknown
>a : unknown
new RangeError("foo", { cause: new Error("bar") });
>new RangeError("foo", { cause: new Error("bar") }) : RangeError & Error
>RangeError : RangeErrorConstructor
@@ -1,8 +1,13 @@
//// [errorCause.ts]
declare const a: unknown;
let err = new Error("foo", { cause: new Error("bar") });
err.cause;
let anotherErr = new Error("foo", { cause: a });
anotherErr.cause;
new EvalError("foo", { cause: new Error("bar") });
new EvalError("foo", { cause: a });
new RangeError("foo", { cause: new Error("bar") });
new ReferenceError("foo", { cause: new Error("bar") });
new SyntaxError("foo", { cause: new Error("bar") });
@@ -14,7 +19,10 @@ new AggregateError([], "foo", { cause: new Error("bar") });
//// [errorCause.js]
let err = new Error("foo", { cause: new Error("bar") });
err.cause;
let anotherErr = new Error("foo", { cause: a });
anotherErr.cause;
new EvalError("foo", { cause: new Error("bar") });
new EvalError("foo", { cause: a });
new RangeError("foo", { cause: new Error("bar") });
new ReferenceError("foo", { cause: new Error("bar") });
new SyntaxError("foo", { cause: new Error("bar") });
@@ -1,47 +1,66 @@
=== tests/cases/compiler/errorCause.ts ===
declare const a: unknown;
>a : Symbol(a, Decl(errorCause.ts, 0, 13))
let err = new Error("foo", { cause: new Error("bar") });
>err : Symbol(err, Decl(errorCause.ts, 0, 3))
>err : Symbol(err, Decl(errorCause.ts, 2, 3))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 0, 28))
>cause : Symbol(cause, Decl(errorCause.ts, 2, 28))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
err.cause;
>err.cause : Symbol(Error.cause, Decl(lib.es2022.error.d.ts, --, --))
>err : Symbol(err, Decl(errorCause.ts, 0, 3))
>err : Symbol(err, Decl(errorCause.ts, 2, 3))
>cause : Symbol(Error.cause, Decl(lib.es2022.error.d.ts, --, --))
let anotherErr = new Error("foo", { cause: a });
>anotherErr : Symbol(anotherErr, Decl(errorCause.ts, 4, 3))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 4, 35))
>a : Symbol(a, Decl(errorCause.ts, 0, 13))
anotherErr.cause;
>anotherErr.cause : Symbol(Error.cause, Decl(lib.es2022.error.d.ts, --, --))
>anotherErr : Symbol(anotherErr, Decl(errorCause.ts, 4, 3))
>cause : Symbol(Error.cause, Decl(lib.es2022.error.d.ts, --, --))
new EvalError("foo", { cause: new Error("bar") });
>EvalError : Symbol(EvalError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 3, 22))
>cause : Symbol(cause, Decl(errorCause.ts, 7, 22))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new EvalError("foo", { cause: a });
>EvalError : Symbol(EvalError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 8, 22))
>a : Symbol(a, Decl(errorCause.ts, 0, 13))
new RangeError("foo", { cause: new Error("bar") });
>RangeError : Symbol(RangeError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 4, 23))
>cause : Symbol(cause, Decl(errorCause.ts, 9, 23))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new ReferenceError("foo", { cause: new Error("bar") });
>ReferenceError : Symbol(ReferenceError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 5, 27))
>cause : Symbol(cause, Decl(errorCause.ts, 10, 27))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new SyntaxError("foo", { cause: new Error("bar") });
>SyntaxError : Symbol(SyntaxError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 6, 24))
>cause : Symbol(cause, Decl(errorCause.ts, 11, 24))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new TypeError("foo", { cause: new Error("bar") });
>TypeError : Symbol(TypeError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 7, 22))
>cause : Symbol(cause, Decl(errorCause.ts, 12, 22))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new URIError("foo", { cause: new Error("bar") });
>URIError : Symbol(URIError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 8, 21))
>cause : Symbol(cause, Decl(errorCause.ts, 13, 21))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new AggregateError([], "foo", { cause: new Error("bar") });
>AggregateError : Symbol(AggregateError, Decl(lib.es2021.promise.d.ts, --, --), Decl(lib.es2021.promise.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 9, 31))
>cause : Symbol(cause, Decl(errorCause.ts, 14, 31))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
@@ -1,4 +1,7 @@
=== tests/cases/compiler/errorCause.ts ===
declare const a: unknown;
>a : unknown
let err = new Error("foo", { cause: new Error("bar") });
>err : Error
>new Error("foo", { cause: new Error("bar") }) : Error
@@ -11,9 +14,23 @@ let err = new Error("foo", { cause: new Error("bar") });
>"bar" : "bar"
err.cause;
>err.cause : Error
>err.cause : unknown
>err : Error
>cause : Error
>cause : unknown
let anotherErr = new Error("foo", { cause: a });
>anotherErr : Error
>new Error("foo", { cause: a }) : Error
>Error : ErrorConstructor
>"foo" : "foo"
>{ cause: a } : { cause: unknown; }
>cause : unknown
>a : unknown
anotherErr.cause;
>anotherErr.cause : unknown
>anotherErr : Error
>cause : unknown
new EvalError("foo", { cause: new Error("bar") });
>new EvalError("foo", { cause: new Error("bar") }) : EvalError
@@ -25,6 +42,14 @@ new EvalError("foo", { cause: new Error("bar") });
>Error : ErrorConstructor
>"bar" : "bar"
new EvalError("foo", { cause: a });
>new EvalError("foo", { cause: a }) : EvalError
>EvalError : EvalErrorConstructor
>"foo" : "foo"
>{ cause: a } : { cause: unknown; }
>cause : unknown
>a : unknown
new RangeError("foo", { cause: new Error("bar") });
>new RangeError("foo", { cause: new Error("bar") }) : RangeError
>RangeError : RangeErrorConstructor
@@ -1,8 +1,13 @@
//// [errorCause.ts]
declare const a: unknown;
let err = new Error("foo", { cause: new Error("bar") });
err.cause;
let anotherErr = new Error("foo", { cause: a });
anotherErr.cause;
new EvalError("foo", { cause: new Error("bar") });
new EvalError("foo", { cause: a });
new RangeError("foo", { cause: new Error("bar") });
new ReferenceError("foo", { cause: new Error("bar") });
new SyntaxError("foo", { cause: new Error("bar") });
@@ -14,7 +19,10 @@ new AggregateError([], "foo", { cause: new Error("bar") });
//// [errorCause.js]
let err = new Error("foo", { cause: new Error("bar") });
err.cause;
let anotherErr = new Error("foo", { cause: a });
anotherErr.cause;
new EvalError("foo", { cause: new Error("bar") });
new EvalError("foo", { cause: a });
new RangeError("foo", { cause: new Error("bar") });
new ReferenceError("foo", { cause: new Error("bar") });
new SyntaxError("foo", { cause: new Error("bar") });
@@ -1,47 +1,66 @@
=== tests/cases/compiler/errorCause.ts ===
declare const a: unknown;
>a : Symbol(a, Decl(errorCause.ts, 0, 13))
let err = new Error("foo", { cause: new Error("bar") });
>err : Symbol(err, Decl(errorCause.ts, 0, 3))
>err : Symbol(err, Decl(errorCause.ts, 2, 3))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 0, 28))
>cause : Symbol(cause, Decl(errorCause.ts, 2, 28))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
err.cause;
>err.cause : Symbol(Error.cause, Decl(lib.es2022.error.d.ts, --, --))
>err : Symbol(err, Decl(errorCause.ts, 0, 3))
>err : Symbol(err, Decl(errorCause.ts, 2, 3))
>cause : Symbol(Error.cause, Decl(lib.es2022.error.d.ts, --, --))
let anotherErr = new Error("foo", { cause: a });
>anotherErr : Symbol(anotherErr, Decl(errorCause.ts, 4, 3))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 4, 35))
>a : Symbol(a, Decl(errorCause.ts, 0, 13))
anotherErr.cause;
>anotherErr.cause : Symbol(Error.cause, Decl(lib.es2022.error.d.ts, --, --))
>anotherErr : Symbol(anotherErr, Decl(errorCause.ts, 4, 3))
>cause : Symbol(Error.cause, Decl(lib.es2022.error.d.ts, --, --))
new EvalError("foo", { cause: new Error("bar") });
>EvalError : Symbol(EvalError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 3, 22))
>cause : Symbol(cause, Decl(errorCause.ts, 7, 22))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new EvalError("foo", { cause: a });
>EvalError : Symbol(EvalError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 8, 22))
>a : Symbol(a, Decl(errorCause.ts, 0, 13))
new RangeError("foo", { cause: new Error("bar") });
>RangeError : Symbol(RangeError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 4, 23))
>cause : Symbol(cause, Decl(errorCause.ts, 9, 23))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new ReferenceError("foo", { cause: new Error("bar") });
>ReferenceError : Symbol(ReferenceError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 5, 27))
>cause : Symbol(cause, Decl(errorCause.ts, 10, 27))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new SyntaxError("foo", { cause: new Error("bar") });
>SyntaxError : Symbol(SyntaxError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 6, 24))
>cause : Symbol(cause, Decl(errorCause.ts, 11, 24))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new TypeError("foo", { cause: new Error("bar") });
>TypeError : Symbol(TypeError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 7, 22))
>cause : Symbol(cause, Decl(errorCause.ts, 12, 22))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new URIError("foo", { cause: new Error("bar") });
>URIError : Symbol(URIError, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 8, 21))
>cause : Symbol(cause, Decl(errorCause.ts, 13, 21))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
new AggregateError([], "foo", { cause: new Error("bar") });
>AggregateError : Symbol(AggregateError, Decl(lib.es2021.promise.d.ts, --, --), Decl(lib.es2021.promise.d.ts, --, --))
>cause : Symbol(cause, Decl(errorCause.ts, 9, 31))
>cause : Symbol(cause, Decl(errorCause.ts, 14, 31))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --))
@@ -1,4 +1,7 @@
=== tests/cases/compiler/errorCause.ts ===
declare const a: unknown;
>a : unknown
let err = new Error("foo", { cause: new Error("bar") });
>err : Error
>new Error("foo", { cause: new Error("bar") }) : Error
@@ -11,9 +14,23 @@ let err = new Error("foo", { cause: new Error("bar") });
>"bar" : "bar"
err.cause;
>err.cause : Error
>err.cause : unknown
>err : Error
>cause : Error
>cause : unknown
let anotherErr = new Error("foo", { cause: a });
>anotherErr : Error
>new Error("foo", { cause: a }) : Error
>Error : ErrorConstructor
>"foo" : "foo"
>{ cause: a } : { cause: unknown; }
>cause : unknown
>a : unknown
anotherErr.cause;
>anotherErr.cause : unknown
>anotherErr : Error
>cause : unknown
new EvalError("foo", { cause: new Error("bar") });
>new EvalError("foo", { cause: new Error("bar") }) : EvalError
@@ -25,6 +42,14 @@ new EvalError("foo", { cause: new Error("bar") });
>Error : ErrorConstructor
>"bar" : "bar"
new EvalError("foo", { cause: a });
>new EvalError("foo", { cause: a }) : EvalError
>EvalError : EvalErrorConstructor
>"foo" : "foo"
>{ cause: a } : { cause: unknown; }
>cause : unknown
>a : unknown
new RangeError("foo", { cause: new Error("bar") });
>new RangeError("foo", { cause: new Error("bar") }) : RangeError
>RangeError : RangeErrorConstructor

Some files were not shown because too many files have changed in this diff Show More