Merge branch 'master' into release-2.9

This commit is contained in:
Mohamed Hegazy
2018-05-21 12:40:47 -07:00
75 changed files with 1832 additions and 9911 deletions
+2 -1
View File
@@ -1,6 +1,6 @@
built
doc
Gulpfile.ts
Gulpfile.js
internal
jenkins.sh
lib/README.md
@@ -23,3 +23,4 @@ test.config
package-lock.json
yarn.lock
.github/
CONTRIBUTING.md
-1
View File
@@ -1 +0,0 @@
{"version":3,"sources":["cancellationToken.ts"],"names":[],"mappings":";AAEA,uBAA0B;AAQ1B,oBAAoB,IAAY;IAC5B,IAAI;QACA,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAClB,OAAO,IAAI,CAAC;KACf;IACD,OAAO,CAAC,EAAE;QACN,OAAO,KAAK,CAAC;KAChB;AACL,CAAC;AAED,iCAAiC,IAAc;IAC3C,IAAI,oBAA4B,CAAC;IACjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;QACtC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,wBAAwB,EAAE;YACtC,oBAAoB,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YACnC,MAAM;SACT;KACJ;IACD,IAAI,CAAC,oBAAoB,EAAE;QACvB,OAAO;YACH,uBAAuB,EAAE,cAAM,OAAA,KAAK,EAAL,CAAK;YACpC,UAAU,EAAE,UAAC,UAAkB,IAAW,OAAA,KAAK,CAAC,EAAN,CAAM;YAChD,YAAY,EAAE,UAAC,UAAkB,IAAW,OAAA,KAAK,CAAC,EAAN,CAAM;SACrD,CAAC;KACL;IAMD,IAAI,oBAAoB,CAAC,MAAM,CAAC,oBAAoB,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,EAAE;QACtE,IAAM,YAAU,GAAG,oBAAoB,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACrD,IAAI,YAAU,CAAC,MAAM,KAAK,CAAC,IAAI,YAAU,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;YACzD,MAAM,IAAI,KAAK,CAAC,wHAAwH,CAAC,CAAC;SAC7I;QACD,IAAI,oBAA0B,CAAC;QAC/B,IAAI,kBAAwB,CAAC;QAC7B,OAAO;YACH,uBAAuB,EAAE,cAAM,OAAA,oBAAkB,KAAK,SAAS,IAAI,UAAU,CAAC,oBAAkB,CAAC,EAAlE,CAAkE;YACjG,UAAU,YAAC,SAAiB;gBACxB,kBAAgB,GAAG,SAAS,CAAC;gBAC7B,oBAAkB,GAAG,YAAU,GAAG,SAAS,CAAC;YAChD,CAAC;YACD,YAAY,YAAC,SAAiB;gBAC1B,IAAI,kBAAgB,KAAK,SAAS,EAAE;oBAChC,MAAM,IAAI,KAAK,CAAC,qCAAmC,kBAAgB,iBAAY,SAAW,CAAC,CAAC;iBAC/F;gBACD,oBAAkB,GAAG,SAAS,CAAC;YACnC,CAAC;SACJ,CAAC;KACL;SACI;QACD,OAAO;YACH,uBAAuB,EAAE,cAAM,OAAA,UAAU,CAAC,oBAAoB,CAAC,EAAhC,CAAgC;YAC/D,UAAU,EAAE,UAAC,UAAkB,IAAW,OAAA,KAAK,CAAC,EAAN,CAAM;YAChD,YAAY,EAAE,UAAC,UAAkB,IAAW,OAAA,KAAK,CAAC,EAAN,CAAM;SACrD,CAAC;KACL;AACL,CAAC;AACD,iBAAS,uBAAuB,CAAC","file":"cancellationToken.js","sourcesContent":["/// <reference types=\"node\"/>\r\n\r\nimport fs = require(\"fs\");\r\n\r\ninterface ServerCancellationToken {\r\n isCancellationRequested(): boolean;\r\n setRequest(requestId: number): void;\r\n resetRequest(requestId: number): void;\r\n}\r\n\r\nfunction pipeExists(name: string): boolean {\r\n try {\r\n fs.statSync(name);\r\n return true;\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n\r\nfunction createCancellationToken(args: string[]): ServerCancellationToken {\r\n let cancellationPipeName: string;\r\n for (let i = 0; i < args.length - 1; i++) {\r\n if (args[i] === \"--cancellationPipeName\") {\r\n cancellationPipeName = args[i + 1];\r\n break;\r\n }\r\n }\r\n if (!cancellationPipeName) {\r\n return {\r\n isCancellationRequested: () => false,\r\n setRequest: (_requestId: number): void => void 0,\r\n resetRequest: (_requestId: number): void => void 0\r\n };\r\n }\r\n // cancellationPipeName is a string without '*' inside that can optionally end with '*'\r\n // when client wants to signal cancellation it should create a named pipe with name=<cancellationPipeName>\r\n // server will synchronously check the presence of the pipe and treat its existance as indicator that current request should be canceled.\r\n // in case if client prefers to use more fine-grained schema than one name for all request it can add '*' to the end of cancelellationPipeName.\r\n // in this case pipe name will be build dynamically as <cancellationPipeName><request_seq>.\r\n if (cancellationPipeName.charAt(cancellationPipeName.length - 1) === \"*\") {\r\n const namePrefix = cancellationPipeName.slice(0, -1);\r\n if (namePrefix.length === 0 || namePrefix.indexOf(\"*\") >= 0) {\r\n throw new Error(\"Invalid name for template cancellation pipe: it should have length greater than 2 characters and contain only one '*'.\");\r\n }\r\n let perRequestPipeName: string;\r\n let currentRequestId: number;\r\n return {\r\n isCancellationRequested: () => perRequestPipeName !== undefined && pipeExists(perRequestPipeName),\r\n setRequest(requestId: number) {\r\n currentRequestId = requestId;\r\n perRequestPipeName = namePrefix + requestId;\r\n },\r\n resetRequest(requestId: number) {\r\n if (currentRequestId !== requestId) {\r\n throw new Error(`Mismatched request id, expected ${currentRequestId}, actual ${requestId}`);\r\n }\r\n perRequestPipeName = undefined;\r\n }\r\n };\r\n }\r\n else {\r\n return {\r\n isCancellationRequested: () => pipeExists(cancellationPipeName),\r\n setRequest: (_requestId: number): void => void 0,\r\n resetRequest: (_requestId: number): void => void 0\r\n };\r\n }\r\n}\r\nexport = createCancellationToken;\r\n"]}
File diff suppressed because it is too large Load Diff
+13 -1
View File
@@ -653,7 +653,7 @@
</Item>
<Item ItemId=";Add_missing_typeof_95052" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Add missing typeof]]></Val>
<Val><![CDATA[Add missing 'typeof']]></Val>
</Str>
<Disp Icon="Str" />
</Item>
@@ -4269,6 +4269,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_all_unused_labels_95054" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove all unused labels]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_declaration_for_Colon_0_90004" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove declaration for: '{0}']]></Val>
@@ -4293,6 +4299,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_unused_label_95053" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove unused label]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Replace_import_with_0_95015" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Replace import with '{0}'.]]></Val>
+3
View File
@@ -106,6 +106,7 @@
"Add_initializer_to_property_0_95019": "Agregar inicializador a la propiedad \"{0}\"",
"Add_initializers_to_all_uninitialized_properties_95027": "Agregar inicializadores a todas las propiedades sin inicializar",
"Add_missing_super_call_90001": "Agregar la llamada a \"super()\" que falta",
"Add_missing_typeof_95052": "Agregar el objeto typeof que falta",
"Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Agregar un calificador a todas las variables no resueltas que coincidan con un nombre de miembro",
"Add_to_all_uncalled_decorators_95044": "Agregar \"()\" a todos los elementos Decorator a los que no se llama",
"Add_ts_ignore_to_all_error_messages_95042": "Agregar \"@ts-ignore\" a todos los mensajes de error",
@@ -708,10 +709,12 @@
"Redirect_output_structure_to_the_directory_6006": "Redirija la estructura de salida al directorio.",
"Referenced_project_0_must_have_setting_composite_Colon_true_6306": "El proyecto \"{0}\" al que se hace referencia debe tener el valor \"composite\": true.",
"Remove_all_unreachable_code_95051": "Quitar todo el código inaccesible",
"Remove_all_unused_labels_95054": "Remove all unused labels",
"Remove_declaration_for_Colon_0_90004": "Quitar declaración de: \"{0}\"",
"Remove_destructuring_90009": "Quitar la desestructuración",
"Remove_import_from_0_90005": "Quitar importación de \"{0}\"",
"Remove_unreachable_code_95050": "Quitar el código inaccesible",
"Remove_unused_label_95053": "Remove unused label",
"Replace_import_with_0_95015": "Reemplazar importación por \"{0}\".",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Notificar un error cuando no todas las rutas de acceso de código en funcionamiento devuelven un valor.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Notificar errores de los casos de fallthrough en la instrucción switch.",
+1
View File
@@ -106,6 +106,7 @@
"Add_initializer_to_property_0_95019": "Ajouter un initialiseur à la propriété '{0}'",
"Add_initializers_to_all_uninitialized_properties_95027": "Ajouter des initialiseurs à toutes les propriétés non initialisées",
"Add_missing_super_call_90001": "Ajouter l'appel manquant à 'super()'",
"Add_missing_typeof_95052": "Ajouter un typeof manquant",
"Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Ajouter un qualificateur à toutes les variables non résolues correspondant à un nom de membre",
"Add_to_all_uncalled_decorators_95044": "Ajouter '()' à tous les décorateurs non appelés",
"Add_ts_ignore_to_all_error_messages_95042": "Ajouter '@ts-ignore' à tous les messages d'erreur",
+5
View File
@@ -16305,6 +16305,11 @@ declare var WScript: {
Sleep(intTime: number): void;
};
/**
* WSH is an alias for WScript under Windows Script Host
*/
declare var WSH: typeof WScript;
/**
* Represents an Automation SAFEARRAY
*/
+8
View File
@@ -28,4 +28,12 @@ interface RegExpExecArray {
groups?: {
[key: string]: string
}
}
interface RegExp {
/**
* Returns a Boolean value indicating the state of the dotAll flag (s) used with a regular expression.
* Default is false. Read-only.
*/
readonly dotAll: boolean;
}
@@ -106,6 +106,7 @@
"Add_initializer_to_property_0_95019": "Adicionar inicializador à propriedade '{0}'",
"Add_initializers_to_all_uninitialized_properties_95027": "Adicionar inicializadores a todas as propriedades não inicializadas",
"Add_missing_super_call_90001": "Adicionar chamada 'super()' ausente",
"Add_missing_typeof_95052": "Adicionar typeof ausente",
"Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "Adicionar um qualificador a todas as variáveis não resolvidas correspondentes a um nome de membro",
"Add_to_all_uncalled_decorators_95044": "Adicionar '()' a todos os decoradores não chamados",
"Add_ts_ignore_to_all_error_messages_95042": "Adicionar '@ts-ignore' a todas as mensagens de erro",
-3436
View File
File diff suppressed because it is too large Load Diff
+32 -24
View File
@@ -174,7 +174,7 @@ var ts;
var ts;
(function (ts) {
ts.versionMajorMinor = "2.9";
ts.version = ts.versionMajorMinor + ".1";
ts.version = ts.versionMajorMinor + ".0-dev";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -4700,7 +4700,9 @@ var ts;
Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing typeof"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
};
})(ts || (ts = {}));
var ts;
@@ -8032,10 +8034,7 @@ var ts;
}
ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
function getJSDocHost(node) {
var comment = ts.findAncestor(node.parent, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152) ? "quit" : node.kind === 285; });
if (comment) {
return comment.parent;
}
return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
}
ts.getJSDocHost = getJSDocHost;
function getTypeParameterFromJsDoc(node) {
@@ -9031,8 +9030,9 @@ var ts;
}
ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
function getJSDocTypeParameterDeclarations(node) {
var tags = ts.filter(ts.getJSDocTags(node), ts.isJSDocTemplateTag);
var tag = ts.find(tags, function (tag) { return !(tag.parent.kind === 285 && ts.find(tag.parent.tags, isJSDocTypeAlias)); });
var tag = ts.find(ts.getJSDocTags(node), function (tag) {
return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 && tag.parent.tags.some(isJSDocTypeAlias));
});
return (tag && tag.typeParameters) || ts.emptyArray;
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
@@ -21598,7 +21598,7 @@ var ts;
checkSourceFile(file);
var diagnostics = [];
ts.Debug.assert(!!(getNodeLinks(file).flags & 1));
checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) {
if (!unusedIsError(kind)) {
diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
}
@@ -21703,8 +21703,6 @@ var ts;
var deferredGlobalExtractSymbol;
var deferredNodes;
var allPotentiallyUnusedIdentifiers = ts.createMap();
var potentiallyUnusedIdentifiers;
var seenPotentiallyUnusedIdentifiers = ts.createMap();
var flowLoopStart = 0;
var flowLoopCount = 0;
var sharedFlowCount = 0;
@@ -22993,8 +22991,7 @@ var ts;
return;
}
var host = ts.getJSDocHost(node);
if (host &&
ts.isExpressionStatement(host) &&
if (ts.isExpressionStatement(host) &&
ts.isBinaryExpression(host.expression) &&
ts.getSpecialPropertyAssignmentKind(host.expression) === 3) {
var symbol = getSymbolOfNode(host.expression.left);
@@ -30151,9 +30148,12 @@ var ts;
return result;
}
}
else if (result = isRelatedTo(constraint, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
else {
var instantiated = getTypeWithThisArgument(constraint, source);
if (result = isRelatedTo(instantiated, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
}
}
}
else if (source.flags & 524288) {
@@ -38877,7 +38877,13 @@ var ts;
}
}
function registerForUnusedIdentifiersCheck(node) {
if (potentiallyUnusedIdentifiers) {
if (produceDiagnostics) {
var sourceFile = ts.getSourceFileOfNode(node);
var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
potentiallyUnusedIdentifiers = [];
allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
}
potentiallyUnusedIdentifiers.push(node);
}
}
@@ -41182,6 +41188,9 @@ var ts;
return ts.Debug.assertNever(kind);
}
}
function getPotentiallyUnusedIdentifiers(sourceFile) {
return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
}
function checkSourceFileWorker(node) {
var links = getNodeLinks(node);
if (!(links.flags & 1)) {
@@ -41192,25 +41201,19 @@ var ts;
ts.clear(potentialThisCollisions);
ts.clear(potentialNewTargetCollisions);
deferredNodes = [];
if (produceDiagnostics) {
ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName));
allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []);
}
ts.forEach(node.statements, checkSourceElement);
checkDeferredNodes();
if (ts.isExternalOrCommonJsModule(node)) {
registerForUnusedIdentifiersCheck(node);
}
if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) {
if (unusedIsError(kind)) {
diagnostics.add(diag);
}
});
}
deferredNodes = undefined;
seenPotentiallyUnusedIdentifiers.clear();
potentiallyUnusedIdentifiers = undefined;
if (ts.isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
}
@@ -65355,6 +65358,7 @@ var ts;
startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
resolveModuleNames: resolveModuleNames,
getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
removeResolutionsOfFile: removeResolutionsOfFile,
invalidateResolutionOfFile: invalidateResolutionOfFile,
@@ -65513,6 +65517,10 @@ var ts;
function resolveModuleNames(moduleNames, containingFile, reusedNames) {
return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule);
}
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
return cache && cache.get(moduleName);
}
function isNodeModulesDirectory(dirPath) {
return ts.endsWith(dirPath, "/node_modules");
}
-1
View File
File diff suppressed because one or more lines are too long
+126 -40
View File
@@ -1387,7 +1387,7 @@ var ts;
var ts;
(function (ts) {
ts.versionMajorMinor = "2.9";
ts.version = ts.versionMajorMinor + ".1";
ts.version = ts.versionMajorMinor + ".0-dev";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -5932,7 +5932,9 @@ var ts;
Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing typeof"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
};
})(ts || (ts = {}));
var ts;
@@ -9264,10 +9266,7 @@ var ts;
}
ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
function getJSDocHost(node) {
var comment = ts.findAncestor(node.parent, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152) ? "quit" : node.kind === 285; });
if (comment) {
return comment.parent;
}
return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
}
ts.getJSDocHost = getJSDocHost;
function getTypeParameterFromJsDoc(node) {
@@ -10282,8 +10281,9 @@ var ts;
}
ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
function getJSDocTypeParameterDeclarations(node) {
var tags = ts.filter(ts.getJSDocTags(node), ts.isJSDocTemplateTag);
var tag = ts.find(tags, function (tag) { return !(tag.parent.kind === 285 && ts.find(tag.parent.tags, isJSDocTypeAlias)); });
var tag = ts.find(ts.getJSDocTags(node), function (tag) {
return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 && tag.parent.tags.some(isJSDocTypeAlias));
});
return (tag && tag.typeParameters) || ts.emptyArray;
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
@@ -22937,7 +22937,7 @@ var ts;
checkSourceFile(file);
var diagnostics = [];
ts.Debug.assert(!!(getNodeLinks(file).flags & 1));
checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) {
if (!unusedIsError(kind)) {
diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
}
@@ -23042,8 +23042,6 @@ var ts;
var deferredGlobalExtractSymbol;
var deferredNodes;
var allPotentiallyUnusedIdentifiers = ts.createMap();
var potentiallyUnusedIdentifiers;
var seenPotentiallyUnusedIdentifiers = ts.createMap();
var flowLoopStart = 0;
var flowLoopCount = 0;
var sharedFlowCount = 0;
@@ -24436,8 +24434,7 @@ var ts;
return;
}
var host = ts.getJSDocHost(node);
if (host &&
ts.isExpressionStatement(host) &&
if (ts.isExpressionStatement(host) &&
ts.isBinaryExpression(host.expression) &&
ts.getSpecialPropertyAssignmentKind(host.expression) === 3) {
var symbol = getSymbolOfNode(host.expression.left);
@@ -31594,9 +31591,12 @@ var ts;
return result;
}
}
else if (result = isRelatedTo(constraint, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
else {
var instantiated = getTypeWithThisArgument(constraint, source);
if (result = isRelatedTo(instantiated, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
}
}
}
else if (source.flags & 524288) {
@@ -40334,7 +40334,13 @@ var ts;
}
}
function registerForUnusedIdentifiersCheck(node) {
if (potentiallyUnusedIdentifiers) {
if (produceDiagnostics) {
var sourceFile = ts.getSourceFileOfNode(node);
var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
potentiallyUnusedIdentifiers = [];
allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
}
potentiallyUnusedIdentifiers.push(node);
}
}
@@ -42639,6 +42645,9 @@ var ts;
return ts.Debug.assertNever(kind);
}
}
function getPotentiallyUnusedIdentifiers(sourceFile) {
return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
}
function checkSourceFileWorker(node) {
var links = getNodeLinks(node);
if (!(links.flags & 1)) {
@@ -42649,25 +42658,19 @@ var ts;
ts.clear(potentialThisCollisions);
ts.clear(potentialNewTargetCollisions);
deferredNodes = [];
if (produceDiagnostics) {
ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName));
allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []);
}
ts.forEach(node.statements, checkSourceElement);
checkDeferredNodes();
if (ts.isExternalOrCommonJsModule(node)) {
registerForUnusedIdentifiersCheck(node);
}
if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) {
if (unusedIsError(kind)) {
diagnostics.add(diag);
}
});
}
deferredNodes = undefined;
seenPotentiallyUnusedIdentifiers.clear();
potentiallyUnusedIdentifiers = undefined;
if (ts.isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
}
@@ -67005,6 +67008,7 @@ var ts;
startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
resolveModuleNames: resolveModuleNames,
getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
removeResolutionsOfFile: removeResolutionsOfFile,
invalidateResolutionOfFile: invalidateResolutionOfFile,
@@ -67163,6 +67167,10 @@ var ts;
function resolveModuleNames(moduleNames, containingFile, reusedNames) {
return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule);
}
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
return cache && cache.get(moduleName);
}
function isNodeModulesDirectory(dirPath) {
return ts.endsWith(dirPath, "/node_modules");
}
@@ -77793,16 +77801,21 @@ var ts;
(function (OrganizeImports) {
function organizeImports(sourceFile, formatContext, host, program, _preferences) {
var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); };
var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
organizeImportsWorker(topLevelImportDecls);
organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration);
organizeImportsWorker(topLevelExportDecls, coalesceExports);
for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
var ambientModule = _a[_i];
var ambientModuleBody = getModuleBlock(ambientModule);
var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
organizeImportsWorker(ambientModuleImportDecls);
organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration);
organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
}
return changeTracker.getChanges();
function organizeImportsWorker(oldImportDecls) {
function organizeImportsWorker(oldImportDecls, coalesce) {
if (ts.length(oldImportDecls) === 0) {
return;
}
@@ -77811,7 +77824,7 @@ var ts;
var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
return getExternalModuleName(importGroup[0].moduleSpecifier)
? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
? coalesce(importGroup)
: importGroup;
});
if (newImportDecls.length === 0) {
@@ -77878,7 +77891,9 @@ var ts;
}
}
function getExternalModuleName(specifier) {
return ts.isStringLiteralLike(specifier) ? specifier.text : undefined;
return specifier !== undefined && ts.isStringLiteralLike(specifier)
? specifier.text
: undefined;
}
function coalesceImports(importGroup) {
if (importGroup.length === 0) {
@@ -77916,10 +77931,7 @@ var ts;
}
}
newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; }));
var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
var importDecl = defaultImports.length > 0
? defaultImports[0]
: namedImports[0];
@@ -77963,14 +77975,54 @@ var ts;
namedImports: namedImports,
};
}
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseInsensitive(s1.text, s2.text);
}
}
OrganizeImports.coalesceImports = coalesceImports;
function coalesceExports(exportGroup) {
if (exportGroup.length === 0) {
return exportGroup;
}
var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports;
var coalescedExports = [];
if (exportWithoutClause) {
coalescedExports.push(exportWithoutClause);
}
if (namedExports.length === 0) {
return coalescedExports;
}
var newExportSpecifiers = [];
newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; }));
var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
var exportDecl = namedExports[0];
coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier));
return coalescedExports;
function getCategorizedExports(exportGroup) {
var exportWithoutClause;
var namedExports = [];
for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) {
var exportDeclaration = exportGroup_1[_i];
if (exportDeclaration.exportClause === undefined) {
exportWithoutClause = exportWithoutClause || exportDeclaration;
}
else {
namedExports.push(exportDeclaration);
}
}
return {
exportWithoutClause: exportWithoutClause,
namedExports: namedExports,
};
}
}
OrganizeImports.coalesceExports = coalesceExports;
function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier);
}
function sortSpecifiers(specifiers) {
return ts.stableSort(specifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
}
function compareModuleSpecifiers(m1, m2) {
var name1 = getExternalModuleName(m1);
var name2 = getExternalModuleName(m2);
@@ -77979,6 +78031,9 @@ var ts;
ts.compareStringsCaseInsensitive(name1, name2);
}
OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers;
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseInsensitive(s1.text, s2.text);
}
})(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {}));
})(ts || (ts = {}));
var ts;
@@ -77987,7 +78042,7 @@ var ts;
var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host);
return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) {
updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath);
for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath); _i < _a.length; _i++) {
for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) {
var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate;
var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text);
if (newPath !== undefined) {
@@ -78008,7 +78063,7 @@ var ts;
function isRef(toUpdate) {
return "fileName" in toUpdate;
}
function getImportsToUpdate(program, oldFilePath) {
function getImportsToUpdate(program, oldFilePath, host) {
var checker = program.getTypeChecker();
var result = [];
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
@@ -78023,7 +78078,9 @@ var ts;
var importStringLiteral = _e[_d];
if (checker.getSymbolAtLocation(importStringLiteral))
continue;
var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
var resolved = host.resolveModuleNames
? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName)
: program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) {
result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral });
}
@@ -85149,6 +85206,32 @@ var ts;
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
var ts;
(function (ts) {
var codefix;
(function (codefix) {
var fixId = "fixUnusedLabel";
var errorCodes = [ts.Diagnostics.Unused_label.code];
codefix.registerCodeFix({
errorCodes: errorCodes,
getCodeActions: function (context) {
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)];
},
fixIds: [fixId],
getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); },
});
function doChange(changes, sourceFile, start) {
var token = ts.getTokenAtPosition(sourceFile, start, false);
var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
var pos = token.getStart(sourceFile);
var statementPos = labeledStatement.statement.getStart(sourceFile);
var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
: ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56, sourceFile).end, true);
changes.deleteRange(sourceFile, { pos: pos, end: end });
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
var ts;
(function (ts) {
var codefix;
(function (codefix) {
@@ -88020,7 +88103,7 @@ var ts;
case 242:
return !ts.hasModifier(node, 1);
case 213:
return node.declarationList.declarations.every(function (d) { return ts.isRequireCall(d.initializer, true); });
return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, true); });
default:
return false;
}
@@ -92711,6 +92794,9 @@ var ts;
Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) {
return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames);
};
Project.prototype.getResolvedModuleWithFailedLookupLocationsFromCache = function (moduleName, containingFile) {
return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile);
};
Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile);
};
File diff suppressed because one or more lines are too long
+2
View File
@@ -4477,6 +4477,7 @@ declare namespace ts {
fileExists?(path: string): boolean;
getTypeRootsVersion?(): number;
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getDirectories?(directoryName: string): string[];
/**
@@ -7864,6 +7865,7 @@ declare namespace ts.server {
readFile(fileName: string): string | undefined;
fileExists(file: string): boolean;
resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[];
getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
directoryExists(path: string): boolean;
getDirectories(path: string): string[];
+140 -40
View File
@@ -1635,7 +1635,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "2.9";
/** The version of the TypeScript compiler release */
ts.version = ts.versionMajorMinor + ".1";
ts.version = ts.versionMajorMinor + ".0-dev";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -6776,7 +6776,9 @@ var ts;
Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing typeof"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
};
})(ts || (ts = {}));
var ts;
@@ -10504,10 +10506,7 @@ var ts;
}
ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
function getJSDocHost(node) {
var comment = ts.findAncestor(node.parent, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : node.kind === 285 /* JSDocComment */; });
if (comment) {
return comment.parent;
}
return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
}
ts.getJSDocHost = getJSDocHost;
function getTypeParameterFromJsDoc(node) {
@@ -11609,9 +11608,10 @@ var ts;
}
ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
function getJSDocTypeParameterDeclarations(node) {
var tags = ts.filter(ts.getJSDocTags(node), ts.isJSDocTemplateTag);
// template tags are only available when a typedef isn't already using them
var tag = ts.find(tags, function (tag) { return !(tag.parent.kind === 285 /* JSDocComment */ && ts.find(tag.parent.tags, isJSDocTypeAlias)); });
var tag = ts.find(ts.getJSDocTags(node), function (tag) {
return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
});
return (tag && tag.typeParameters) || ts.emptyArray;
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
@@ -26732,7 +26732,7 @@ var ts;
checkSourceFile(file);
var diagnostics = [];
ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) {
if (!unusedIsError(kind)) {
diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
}
@@ -26847,8 +26847,6 @@ var ts;
var deferredGlobalExtractSymbol;
var deferredNodes;
var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
var potentiallyUnusedIdentifiers; // Potentially unused identifiers in the source file currently being checked.
var seenPotentiallyUnusedIdentifiers = ts.createMap(); // For assertion that we don't defer the same identifier twice
var flowLoopStart = 0;
var flowLoopCount = 0;
var sharedFlowCount = 0;
@@ -28458,8 +28456,7 @@ var ts;
return;
}
var host = ts.getJSDocHost(node);
if (host &&
ts.isExpressionStatement(host) &&
if (ts.isExpressionStatement(host) &&
ts.isBinaryExpression(host.expression) &&
ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) {
var symbol = getSymbolOfNode(host.expression.left);
@@ -36563,9 +36560,12 @@ var ts;
return result;
}
}
else if (result = isRelatedTo(constraint, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
else {
var instantiated = getTypeWithThisArgument(constraint, source);
if (result = isRelatedTo(instantiated, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
}
}
}
else if (source.flags & 524288 /* Index */) {
@@ -47139,7 +47139,13 @@ var ts;
}
function registerForUnusedIdentifiersCheck(node) {
// May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
if (potentiallyUnusedIdentifiers) {
if (produceDiagnostics) {
var sourceFile = ts.getSourceFileOfNode(node);
var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
potentiallyUnusedIdentifiers = [];
allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
}
// TODO: GH#22580
// Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
potentiallyUnusedIdentifiers.push(node);
@@ -49846,6 +49852,9 @@ var ts;
return ts.Debug.assertNever(kind);
}
}
function getPotentiallyUnusedIdentifiers(sourceFile) {
return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
}
// Fully type check a source file and collect the relevant diagnostics.
function checkSourceFileWorker(node) {
var links = getNodeLinks(node);
@@ -49861,25 +49870,19 @@ var ts;
ts.clear(potentialThisCollisions);
ts.clear(potentialNewTargetCollisions);
deferredNodes = [];
if (produceDiagnostics) {
ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName));
allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []);
}
ts.forEach(node.statements, checkSourceElement);
checkDeferredNodes();
if (ts.isExternalOrCommonJsModule(node)) {
registerForUnusedIdentifiersCheck(node);
}
if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) {
if (unusedIsError(kind)) {
diagnostics.add(diag);
}
});
}
deferredNodes = undefined;
seenPotentiallyUnusedIdentifiers.clear();
potentiallyUnusedIdentifiers = undefined;
if (ts.isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
}
@@ -80914,6 +80917,7 @@ var ts;
startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
resolveModuleNames: resolveModuleNames,
getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
removeResolutionsOfFile: removeResolutionsOfFile,
invalidateResolutionOfFile: invalidateResolutionOfFile,
@@ -81086,6 +81090,10 @@ var ts;
function resolveModuleNames(moduleNames, containingFile, reusedNames) {
return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule);
}
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
return cache && cache.get(moduleName);
}
function isNodeModulesDirectory(dirPath) {
return ts.endsWith(dirPath, "/node_modules");
}
@@ -93484,17 +93492,23 @@ var ts;
*/
function organizeImports(sourceFile, formatContext, host, program, _preferences) {
var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); };
// All of the old ImportDeclarations in the file, in syntactic order.
var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
organizeImportsWorker(topLevelImportDecls);
organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
// All of the old ExportDeclarations in the file, in syntactic order.
var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration);
organizeImportsWorker(topLevelExportDecls, coalesceExports);
for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
var ambientModule = _a[_i];
var ambientModuleBody = getModuleBlock(ambientModule);
var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
organizeImportsWorker(ambientModuleImportDecls);
organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration);
organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
}
return changeTracker.getChanges();
function organizeImportsWorker(oldImportDecls) {
function organizeImportsWorker(oldImportDecls, coalesce) {
if (ts.length(oldImportDecls) === 0) {
return;
}
@@ -93508,7 +93522,7 @@ var ts;
var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
return getExternalModuleName(importGroup[0].moduleSpecifier)
? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
? coalesce(importGroup)
: importGroup;
});
// Delete or replace the first import.
@@ -93583,7 +93597,9 @@ var ts;
}
}
function getExternalModuleName(specifier) {
return ts.isStringLiteralLike(specifier) ? specifier.text : undefined;
return specifier !== undefined && ts.isStringLiteralLike(specifier)
? specifier.text
: undefined;
}
/* @internal */ // Internal for testing
/**
@@ -93629,10 +93645,7 @@ var ts;
}
}
newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; }));
var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
var importDecl = defaultImports.length > 0
? defaultImports[0]
: namedImports[0];
@@ -93685,14 +93698,65 @@ var ts;
namedImports: namedImports,
};
}
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseInsensitive(s1.text, s2.text);
}
}
OrganizeImports.coalesceImports = coalesceImports;
/* @internal */ // Internal for testing
/**
* @param exportGroup a list of ExportDeclarations, all with the same module name.
*/
function coalesceExports(exportGroup) {
if (exportGroup.length === 0) {
return exportGroup;
}
var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports;
var coalescedExports = [];
if (exportWithoutClause) {
coalescedExports.push(exportWithoutClause);
}
if (namedExports.length === 0) {
return coalescedExports;
}
var newExportSpecifiers = [];
newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; }));
var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
var exportDecl = namedExports[0];
coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier));
return coalescedExports;
/*
* Returns entire export declarations because they may already have been rewritten and
* may lack parent pointers. The desired parts can easily be recovered based on the
* categorization.
*/
function getCategorizedExports(exportGroup) {
var exportWithoutClause;
var namedExports = [];
for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) {
var exportDeclaration = exportGroup_1[_i];
if (exportDeclaration.exportClause === undefined) {
// Only the first such export is interesting - the others are redundant.
// Note: Unfortunately, we will lose trivia that was on this node.
exportWithoutClause = exportWithoutClause || exportDeclaration;
}
else {
namedExports.push(exportDeclaration);
}
}
return {
exportWithoutClause: exportWithoutClause,
namedExports: namedExports,
};
}
}
OrganizeImports.coalesceExports = coalesceExports;
function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier);
}
function sortSpecifiers(specifiers) {
return ts.stableSort(specifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
}
/* internal */ // Exported for testing
function compareModuleSpecifiers(m1, m2) {
var name1 = getExternalModuleName(m1);
@@ -93702,6 +93766,9 @@ var ts;
ts.compareStringsCaseInsensitive(name1, name2);
}
OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers;
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseInsensitive(s1.text, s2.text);
}
})(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {}));
})(ts || (ts = {}));
/* @internal */
@@ -93711,7 +93778,7 @@ var ts;
var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host);
return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) {
updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath);
for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath); _i < _a.length; _i++) {
for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) {
var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate;
var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text);
if (newPath !== undefined) {
@@ -93732,7 +93799,7 @@ var ts;
function isRef(toUpdate) {
return "fileName" in toUpdate;
}
function getImportsToUpdate(program, oldFilePath) {
function getImportsToUpdate(program, oldFilePath, host) {
var checker = program.getTypeChecker();
var result = [];
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
@@ -93748,7 +93815,9 @@ var ts;
// If it resolved to something already, ignore.
if (checker.getSymbolAtLocation(importStringLiteral))
continue;
var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
var resolved = host.resolveModuleNames
? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName)
: program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) {
result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral });
}
@@ -101980,6 +102049,34 @@ var ts;
})(ts || (ts = {}));
/* @internal */
var ts;
(function (ts) {
var codefix;
(function (codefix) {
var fixId = "fixUnusedLabel";
var errorCodes = [ts.Diagnostics.Unused_label.code];
codefix.registerCodeFix({
errorCodes: errorCodes,
getCodeActions: function (context) {
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)];
},
fixIds: [fixId],
getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); },
});
function doChange(changes, sourceFile, start) {
var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
var pos = token.getStart(sourceFile);
var statementPos = labeledStatement.statement.getStart(sourceFile);
// If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement.
var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
: ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true);
changes.deleteRange(sourceFile, { pos: pos, end: end });
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
var ts;
(function (ts) {
var codefix;
(function (codefix) {
@@ -105250,7 +105347,7 @@ var ts;
case 242 /* ImportEqualsDeclaration */:
return !ts.hasModifier(node, 1 /* Export */);
case 213 /* VariableStatement */:
return node.declarationList.declarations.every(function (d) { return ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
default:
return false;
}
@@ -110622,6 +110719,9 @@ var ts;
Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) {
return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames);
};
Project.prototype.getResolvedModuleWithFailedLookupLocationsFromCache = function (moduleName, containingFile) {
return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile);
};
Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) {
return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile);
};
File diff suppressed because one or more lines are too long
+1
View File
@@ -4477,6 +4477,7 @@ declare namespace ts {
fileExists?(path: string): boolean;
getTypeRootsVersion?(): number;
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getDirectories?(directoryName: string): string[];
/**
+137 -40
View File
@@ -1635,7 +1635,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "2.9";
/** The version of the TypeScript compiler release */
ts.version = ts.versionMajorMinor + ".1";
ts.version = ts.versionMajorMinor + ".0-dev";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -6776,7 +6776,9 @@ var ts;
Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing typeof"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
};
})(ts || (ts = {}));
var ts;
@@ -10504,10 +10506,7 @@ var ts;
}
ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
function getJSDocHost(node) {
var comment = ts.findAncestor(node.parent, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : node.kind === 285 /* JSDocComment */; });
if (comment) {
return comment.parent;
}
return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
}
ts.getJSDocHost = getJSDocHost;
function getTypeParameterFromJsDoc(node) {
@@ -11609,9 +11608,10 @@ var ts;
}
ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
function getJSDocTypeParameterDeclarations(node) {
var tags = ts.filter(ts.getJSDocTags(node), ts.isJSDocTemplateTag);
// template tags are only available when a typedef isn't already using them
var tag = ts.find(tags, function (tag) { return !(tag.parent.kind === 285 /* JSDocComment */ && ts.find(tag.parent.tags, isJSDocTypeAlias)); });
var tag = ts.find(ts.getJSDocTags(node), function (tag) {
return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
});
return (tag && tag.typeParameters) || ts.emptyArray;
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
@@ -26732,7 +26732,7 @@ var ts;
checkSourceFile(file);
var diagnostics = [];
ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) {
if (!unusedIsError(kind)) {
diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
}
@@ -26847,8 +26847,6 @@ var ts;
var deferredGlobalExtractSymbol;
var deferredNodes;
var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
var potentiallyUnusedIdentifiers; // Potentially unused identifiers in the source file currently being checked.
var seenPotentiallyUnusedIdentifiers = ts.createMap(); // For assertion that we don't defer the same identifier twice
var flowLoopStart = 0;
var flowLoopCount = 0;
var sharedFlowCount = 0;
@@ -28458,8 +28456,7 @@ var ts;
return;
}
var host = ts.getJSDocHost(node);
if (host &&
ts.isExpressionStatement(host) &&
if (ts.isExpressionStatement(host) &&
ts.isBinaryExpression(host.expression) &&
ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) {
var symbol = getSymbolOfNode(host.expression.left);
@@ -36563,9 +36560,12 @@ var ts;
return result;
}
}
else if (result = isRelatedTo(constraint, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
else {
var instantiated = getTypeWithThisArgument(constraint, source);
if (result = isRelatedTo(instantiated, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
}
}
}
else if (source.flags & 524288 /* Index */) {
@@ -47139,7 +47139,13 @@ var ts;
}
function registerForUnusedIdentifiersCheck(node) {
// May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
if (potentiallyUnusedIdentifiers) {
if (produceDiagnostics) {
var sourceFile = ts.getSourceFileOfNode(node);
var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
potentiallyUnusedIdentifiers = [];
allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
}
// TODO: GH#22580
// Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
potentiallyUnusedIdentifiers.push(node);
@@ -49846,6 +49852,9 @@ var ts;
return ts.Debug.assertNever(kind);
}
}
function getPotentiallyUnusedIdentifiers(sourceFile) {
return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
}
// Fully type check a source file and collect the relevant diagnostics.
function checkSourceFileWorker(node) {
var links = getNodeLinks(node);
@@ -49861,25 +49870,19 @@ var ts;
ts.clear(potentialThisCollisions);
ts.clear(potentialNewTargetCollisions);
deferredNodes = [];
if (produceDiagnostics) {
ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName));
allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []);
}
ts.forEach(node.statements, checkSourceElement);
checkDeferredNodes();
if (ts.isExternalOrCommonJsModule(node)) {
registerForUnusedIdentifiersCheck(node);
}
if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) {
if (unusedIsError(kind)) {
diagnostics.add(diag);
}
});
}
deferredNodes = undefined;
seenPotentiallyUnusedIdentifiers.clear();
potentiallyUnusedIdentifiers = undefined;
if (ts.isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
}
@@ -80914,6 +80917,7 @@ var ts;
startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
resolveModuleNames: resolveModuleNames,
getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
removeResolutionsOfFile: removeResolutionsOfFile,
invalidateResolutionOfFile: invalidateResolutionOfFile,
@@ -81086,6 +81090,10 @@ var ts;
function resolveModuleNames(moduleNames, containingFile, reusedNames) {
return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule);
}
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
return cache && cache.get(moduleName);
}
function isNodeModulesDirectory(dirPath) {
return ts.endsWith(dirPath, "/node_modules");
}
@@ -93484,17 +93492,23 @@ var ts;
*/
function organizeImports(sourceFile, formatContext, host, program, _preferences) {
var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); };
// All of the old ImportDeclarations in the file, in syntactic order.
var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
organizeImportsWorker(topLevelImportDecls);
organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
// All of the old ExportDeclarations in the file, in syntactic order.
var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration);
organizeImportsWorker(topLevelExportDecls, coalesceExports);
for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
var ambientModule = _a[_i];
var ambientModuleBody = getModuleBlock(ambientModule);
var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
organizeImportsWorker(ambientModuleImportDecls);
organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration);
organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
}
return changeTracker.getChanges();
function organizeImportsWorker(oldImportDecls) {
function organizeImportsWorker(oldImportDecls, coalesce) {
if (ts.length(oldImportDecls) === 0) {
return;
}
@@ -93508,7 +93522,7 @@ var ts;
var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
return getExternalModuleName(importGroup[0].moduleSpecifier)
? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
? coalesce(importGroup)
: importGroup;
});
// Delete or replace the first import.
@@ -93583,7 +93597,9 @@ var ts;
}
}
function getExternalModuleName(specifier) {
return ts.isStringLiteralLike(specifier) ? specifier.text : undefined;
return specifier !== undefined && ts.isStringLiteralLike(specifier)
? specifier.text
: undefined;
}
/* @internal */ // Internal for testing
/**
@@ -93629,10 +93645,7 @@ var ts;
}
}
newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; }));
var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
var importDecl = defaultImports.length > 0
? defaultImports[0]
: namedImports[0];
@@ -93685,14 +93698,65 @@ var ts;
namedImports: namedImports,
};
}
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseInsensitive(s1.text, s2.text);
}
}
OrganizeImports.coalesceImports = coalesceImports;
/* @internal */ // Internal for testing
/**
* @param exportGroup a list of ExportDeclarations, all with the same module name.
*/
function coalesceExports(exportGroup) {
if (exportGroup.length === 0) {
return exportGroup;
}
var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports;
var coalescedExports = [];
if (exportWithoutClause) {
coalescedExports.push(exportWithoutClause);
}
if (namedExports.length === 0) {
return coalescedExports;
}
var newExportSpecifiers = [];
newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; }));
var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
var exportDecl = namedExports[0];
coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier));
return coalescedExports;
/*
* Returns entire export declarations because they may already have been rewritten and
* may lack parent pointers. The desired parts can easily be recovered based on the
* categorization.
*/
function getCategorizedExports(exportGroup) {
var exportWithoutClause;
var namedExports = [];
for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) {
var exportDeclaration = exportGroup_1[_i];
if (exportDeclaration.exportClause === undefined) {
// Only the first such export is interesting - the others are redundant.
// Note: Unfortunately, we will lose trivia that was on this node.
exportWithoutClause = exportWithoutClause || exportDeclaration;
}
else {
namedExports.push(exportDeclaration);
}
}
return {
exportWithoutClause: exportWithoutClause,
namedExports: namedExports,
};
}
}
OrganizeImports.coalesceExports = coalesceExports;
function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier);
}
function sortSpecifiers(specifiers) {
return ts.stableSort(specifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
}
/* internal */ // Exported for testing
function compareModuleSpecifiers(m1, m2) {
var name1 = getExternalModuleName(m1);
@@ -93702,6 +93766,9 @@ var ts;
ts.compareStringsCaseInsensitive(name1, name2);
}
OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers;
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseInsensitive(s1.text, s2.text);
}
})(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {}));
})(ts || (ts = {}));
/* @internal */
@@ -93711,7 +93778,7 @@ var ts;
var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host);
return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) {
updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath);
for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath); _i < _a.length; _i++) {
for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) {
var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate;
var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text);
if (newPath !== undefined) {
@@ -93732,7 +93799,7 @@ var ts;
function isRef(toUpdate) {
return "fileName" in toUpdate;
}
function getImportsToUpdate(program, oldFilePath) {
function getImportsToUpdate(program, oldFilePath, host) {
var checker = program.getTypeChecker();
var result = [];
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
@@ -93748,7 +93815,9 @@ var ts;
// If it resolved to something already, ignore.
if (checker.getSymbolAtLocation(importStringLiteral))
continue;
var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
var resolved = host.resolveModuleNames
? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName)
: program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) {
result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral });
}
@@ -101980,6 +102049,34 @@ var ts;
})(ts || (ts = {}));
/* @internal */
var ts;
(function (ts) {
var codefix;
(function (codefix) {
var fixId = "fixUnusedLabel";
var errorCodes = [ts.Diagnostics.Unused_label.code];
codefix.registerCodeFix({
errorCodes: errorCodes,
getCodeActions: function (context) {
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)];
},
fixIds: [fixId],
getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); },
});
function doChange(changes, sourceFile, start) {
var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
var pos = token.getStart(sourceFile);
var statementPos = labeledStatement.statement.getStart(sourceFile);
// If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement.
var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
: ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true);
changes.deleteRange(sourceFile, { pos: pos, end: end });
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
var ts;
(function (ts) {
var codefix;
(function (codefix) {
@@ -105250,7 +105347,7 @@ var ts;
case 242 /* ImportEqualsDeclaration */:
return !ts.hasModifier(node, 1 /* Export */);
case 213 /* VariableStatement */:
return node.declarationList.declarations.every(function (d) { return ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
default:
return false;
}
+1
View File
@@ -4477,6 +4477,7 @@ declare namespace ts {
fileExists?(path: string): boolean;
getTypeRootsVersion?(): number;
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getDirectories?(directoryName: string): string[];
/**
+137 -40
View File
@@ -1635,7 +1635,7 @@ var ts;
// If changing the text in this section, be sure to test `configureNightly` too.
ts.versionMajorMinor = "2.9";
/** The version of the TypeScript compiler release */
ts.version = ts.versionMajorMinor + ".1";
ts.version = ts.versionMajorMinor + ".0-dev";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -6776,7 +6776,9 @@ var ts;
Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing typeof"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
};
})(ts || (ts = {}));
var ts;
@@ -10504,10 +10506,7 @@ var ts;
}
ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
function getJSDocHost(node) {
var comment = ts.findAncestor(node.parent, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152 /* JSDoc */) ? "quit" : node.kind === 285 /* JSDocComment */; });
if (comment) {
return comment.parent;
}
return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
}
ts.getJSDocHost = getJSDocHost;
function getTypeParameterFromJsDoc(node) {
@@ -11609,9 +11608,10 @@ var ts;
}
ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
function getJSDocTypeParameterDeclarations(node) {
var tags = ts.filter(ts.getJSDocTags(node), ts.isJSDocTemplateTag);
// template tags are only available when a typedef isn't already using them
var tag = ts.find(tags, function (tag) { return !(tag.parent.kind === 285 /* JSDocComment */ && ts.find(tag.parent.tags, isJSDocTypeAlias)); });
var tag = ts.find(ts.getJSDocTags(node), function (tag) {
return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
});
return (tag && tag.typeParameters) || ts.emptyArray;
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
@@ -26732,7 +26732,7 @@ var ts;
checkSourceFile(file);
var diagnostics = [];
ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName), function (kind, diag) {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (kind, diag) {
if (!unusedIsError(kind)) {
diagnostics.push(__assign({}, diag, { category: ts.DiagnosticCategory.Suggestion }));
}
@@ -26847,8 +26847,6 @@ var ts;
var deferredGlobalExtractSymbol;
var deferredNodes;
var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
var potentiallyUnusedIdentifiers; // Potentially unused identifiers in the source file currently being checked.
var seenPotentiallyUnusedIdentifiers = ts.createMap(); // For assertion that we don't defer the same identifier twice
var flowLoopStart = 0;
var flowLoopCount = 0;
var sharedFlowCount = 0;
@@ -28458,8 +28456,7 @@ var ts;
return;
}
var host = ts.getJSDocHost(node);
if (host &&
ts.isExpressionStatement(host) &&
if (ts.isExpressionStatement(host) &&
ts.isBinaryExpression(host.expression) &&
ts.getSpecialPropertyAssignmentKind(host.expression) === 3 /* PrototypeProperty */) {
var symbol = getSymbolOfNode(host.expression.left);
@@ -36563,9 +36560,12 @@ var ts;
return result;
}
}
else if (result = isRelatedTo(constraint, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
else {
var instantiated = getTypeWithThisArgument(constraint, source);
if (result = isRelatedTo(instantiated, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
}
}
}
else if (source.flags & 524288 /* Index */) {
@@ -47139,7 +47139,13 @@ var ts;
}
function registerForUnusedIdentifiersCheck(node) {
// May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
if (potentiallyUnusedIdentifiers) {
if (produceDiagnostics) {
var sourceFile = ts.getSourceFileOfNode(node);
var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
potentiallyUnusedIdentifiers = [];
allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
}
// TODO: GH#22580
// Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
potentiallyUnusedIdentifiers.push(node);
@@ -49846,6 +49852,9 @@ var ts;
return ts.Debug.assertNever(kind);
}
}
function getPotentiallyUnusedIdentifiers(sourceFile) {
return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
}
// Fully type check a source file and collect the relevant diagnostics.
function checkSourceFileWorker(node) {
var links = getNodeLinks(node);
@@ -49861,25 +49870,19 @@ var ts;
ts.clear(potentialThisCollisions);
ts.clear(potentialNewTargetCollisions);
deferredNodes = [];
if (produceDiagnostics) {
ts.Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName));
allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []);
}
ts.forEach(node.statements, checkSourceElement);
checkDeferredNodes();
if (ts.isExternalOrCommonJsModule(node)) {
registerForUnusedIdentifiersCheck(node);
}
if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
checkUnusedIdentifiers(potentiallyUnusedIdentifiers, function (kind, diag) {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (kind, diag) {
if (unusedIsError(kind)) {
diagnostics.add(diag);
}
});
}
deferredNodes = undefined;
seenPotentiallyUnusedIdentifiers.clear();
potentiallyUnusedIdentifiers = undefined;
if (ts.isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
}
@@ -80914,6 +80917,7 @@ var ts;
startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
resolveModuleNames: resolveModuleNames,
getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
removeResolutionsOfFile: removeResolutionsOfFile,
invalidateResolutionOfFile: invalidateResolutionOfFile,
@@ -81086,6 +81090,10 @@ var ts;
function resolveModuleNames(moduleNames, containingFile, reusedNames) {
return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule);
}
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
return cache && cache.get(moduleName);
}
function isNodeModulesDirectory(dirPath) {
return ts.endsWith(dirPath, "/node_modules");
}
@@ -93484,17 +93492,23 @@ var ts;
*/
function organizeImports(sourceFile, formatContext, host, program, _preferences) {
var changeTracker = ts.textChanges.ChangeTracker.fromContext({ host: host, formatContext: formatContext });
var coalesceAndOrganizeImports = function (importGroup) { return coalesceImports(removeUnusedImports(importGroup, sourceFile, program)); };
// All of the old ImportDeclarations in the file, in syntactic order.
var topLevelImportDecls = sourceFile.statements.filter(ts.isImportDeclaration);
organizeImportsWorker(topLevelImportDecls);
organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
// All of the old ExportDeclarations in the file, in syntactic order.
var topLevelExportDecls = sourceFile.statements.filter(ts.isExportDeclaration);
organizeImportsWorker(topLevelExportDecls, coalesceExports);
for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) {
var ambientModule = _a[_i];
var ambientModuleBody = getModuleBlock(ambientModule);
var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration);
organizeImportsWorker(ambientModuleImportDecls);
organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration);
organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
}
return changeTracker.getChanges();
function organizeImportsWorker(oldImportDecls) {
function organizeImportsWorker(oldImportDecls, coalesce) {
if (ts.length(oldImportDecls) === 0) {
return;
}
@@ -93508,7 +93522,7 @@ var ts;
var sortedImportGroups = ts.stableSort(oldImportGroups, function (group1, group2) { return compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier); });
var newImportDecls = ts.flatMap(sortedImportGroups, function (importGroup) {
return getExternalModuleName(importGroup[0].moduleSpecifier)
? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
? coalesce(importGroup)
: importGroup;
});
// Delete or replace the first import.
@@ -93583,7 +93597,9 @@ var ts;
}
}
function getExternalModuleName(specifier) {
return ts.isStringLiteralLike(specifier) ? specifier.text : undefined;
return specifier !== undefined && ts.isStringLiteralLike(specifier)
? specifier.text
: undefined;
}
/* @internal */ // Internal for testing
/**
@@ -93629,10 +93645,7 @@ var ts;
}
}
newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; }));
var sortedImportSpecifiers = ts.stableSort(newImportSpecifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
var importDecl = defaultImports.length > 0
? defaultImports[0]
: namedImports[0];
@@ -93685,14 +93698,65 @@ var ts;
namedImports: namedImports,
};
}
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseInsensitive(s1.text, s2.text);
}
}
OrganizeImports.coalesceImports = coalesceImports;
/* @internal */ // Internal for testing
/**
* @param exportGroup a list of ExportDeclarations, all with the same module name.
*/
function coalesceExports(exportGroup) {
if (exportGroup.length === 0) {
return exportGroup;
}
var _a = getCategorizedExports(exportGroup), exportWithoutClause = _a.exportWithoutClause, namedExports = _a.namedExports;
var coalescedExports = [];
if (exportWithoutClause) {
coalescedExports.push(exportWithoutClause);
}
if (namedExports.length === 0) {
return coalescedExports;
}
var newExportSpecifiers = [];
newExportSpecifiers.push.apply(newExportSpecifiers, ts.flatMap(namedExports, function (i) { return (i.exportClause).elements; }));
var sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
var exportDecl = namedExports[0];
coalescedExports.push(ts.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, ts.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers), exportDecl.moduleSpecifier));
return coalescedExports;
/*
* Returns entire export declarations because they may already have been rewritten and
* may lack parent pointers. The desired parts can easily be recovered based on the
* categorization.
*/
function getCategorizedExports(exportGroup) {
var exportWithoutClause;
var namedExports = [];
for (var _i = 0, exportGroup_1 = exportGroup; _i < exportGroup_1.length; _i++) {
var exportDeclaration = exportGroup_1[_i];
if (exportDeclaration.exportClause === undefined) {
// Only the first such export is interesting - the others are redundant.
// Note: Unfortunately, we will lose trivia that was on this node.
exportWithoutClause = exportWithoutClause || exportDeclaration;
}
else {
namedExports.push(exportDeclaration);
}
}
return {
exportWithoutClause: exportWithoutClause,
namedExports: namedExports,
};
}
}
OrganizeImports.coalesceExports = coalesceExports;
function updateImportDeclarationAndClause(importDeclaration, name, namedBindings) {
return ts.updateImportDeclaration(importDeclaration, importDeclaration.decorators, importDeclaration.modifiers, ts.updateImportClause(importDeclaration.importClause, name, namedBindings), importDeclaration.moduleSpecifier);
}
function sortSpecifiers(specifiers) {
return ts.stableSort(specifiers, function (s1, s2) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name);
});
}
/* internal */ // Exported for testing
function compareModuleSpecifiers(m1, m2) {
var name1 = getExternalModuleName(m1);
@@ -93702,6 +93766,9 @@ var ts;
ts.compareStringsCaseInsensitive(name1, name2);
}
OrganizeImports.compareModuleSpecifiers = compareModuleSpecifiers;
function compareIdentifiers(s1, s2) {
return ts.compareStringsCaseInsensitive(s1.text, s2.text);
}
})(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {}));
})(ts || (ts = {}));
/* @internal */
@@ -93711,7 +93778,7 @@ var ts;
var pathUpdater = getPathUpdater(oldFilePath, newFilePath, host);
return ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext }, function (changeTracker) {
updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath);
for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath); _i < _a.length; _i++) {
for (var _i = 0, _a = getImportsToUpdate(program, oldFilePath, host); _i < _a.length; _i++) {
var _b = _a[_i], sourceFile = _b.sourceFile, toUpdate = _b.toUpdate;
var newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text);
if (newPath !== undefined) {
@@ -93732,7 +93799,7 @@ var ts;
function isRef(toUpdate) {
return "fileName" in toUpdate;
}
function getImportsToUpdate(program, oldFilePath) {
function getImportsToUpdate(program, oldFilePath, host) {
var checker = program.getTypeChecker();
var result = [];
for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {
@@ -93748,7 +93815,9 @@ var ts;
// If it resolved to something already, ignore.
if (checker.getSymbolAtLocation(importStringLiteral))
continue;
var resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
var resolved = host.resolveModuleNames
? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName)
: program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
if (resolved && ts.contains(resolved.failedLookupLocations, oldFilePath)) {
result.push({ sourceFile: sourceFile, toUpdate: importStringLiteral });
}
@@ -101980,6 +102049,34 @@ var ts;
})(ts || (ts = {}));
/* @internal */
var ts;
(function (ts) {
var codefix;
(function (codefix) {
var fixId = "fixUnusedLabel";
var errorCodes = [ts.Diagnostics.Unused_label.code];
codefix.registerCodeFix({
errorCodes: errorCodes,
getCodeActions: function (context) {
var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start); });
return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unused_label, fixId, ts.Diagnostics.Remove_all_unused_labels)];
},
fixIds: [fixId],
getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return doChange(changes, diag.file, diag.start); }); },
});
function doChange(changes, sourceFile, start) {
var token = ts.getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
var labeledStatement = ts.cast(token.parent, ts.isLabeledStatement);
var pos = token.getStart(sourceFile);
var statementPos = labeledStatement.statement.getStart(sourceFile);
// If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement.
var end = ts.positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
: ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, 56 /* ColonToken */, sourceFile).end, /*stopAfterLineBreak*/ true);
changes.deleteRange(sourceFile, { pos: pos, end: end });
}
})(codefix = ts.codefix || (ts.codefix = {}));
})(ts || (ts = {}));
/* @internal */
var ts;
(function (ts) {
var codefix;
(function (codefix) {
@@ -105250,7 +105347,7 @@ var ts;
case 242 /* ImportEqualsDeclaration */:
return !ts.hasModifier(node, 1 /* Export */);
case 213 /* VariableStatement */:
return node.declarationList.declarations.every(function (d) { return ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
return node.declarationList.declarations.every(function (d) { return d.initializer && ts.isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true); });
default:
return false;
}
File diff suppressed because one or more lines are too long
-5171
View File
File diff suppressed because it is too large Load Diff
+8 -8
View File
@@ -180,7 +180,7 @@ var ts;
var ts;
(function (ts) {
ts.versionMajorMinor = "2.9";
ts.version = ts.versionMajorMinor + ".1";
ts.version = ts.versionMajorMinor + ".0-dev";
})(ts || (ts = {}));
(function (ts) {
function isExternalModuleNameRelative(moduleName) {
@@ -4706,7 +4706,9 @@ var ts;
Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing typeof"),
Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
};
})(ts || (ts = {}));
var ts;
@@ -6345,10 +6347,7 @@ var ts;
}
ts.getHostSignatureFromJSDocHost = getHostSignatureFromJSDocHost;
function getJSDocHost(node) {
var comment = ts.findAncestor(node.parent, function (node) { return !(ts.isJSDocNode(node) || node.flags & 2097152) ? "quit" : node.kind === 285; });
if (comment) {
return comment.parent;
}
return ts.Debug.assertDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
}
ts.getJSDocHost = getJSDocHost;
function getTypeParameterFromJsDoc(node) {
@@ -7344,8 +7343,9 @@ var ts;
}
ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
function getJSDocTypeParameterDeclarations(node) {
var tags = ts.filter(ts.getJSDocTags(node), ts.isJSDocTemplateTag);
var tag = ts.find(tags, function (tag) { return !(tag.parent.kind === 285 && ts.find(tag.parent.tags, isJSDocTypeAlias)); });
var tag = ts.find(ts.getJSDocTags(node), function (tag) {
return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 285 && tag.parent.tags.some(isJSDocTypeAlias));
});
return (tag && tag.typeParameters) || ts.emptyArray;
}
ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
File diff suppressed because one or more lines are too long
+21 -18
View File
@@ -319,7 +319,7 @@ namespace ts {
checkSourceFile(file);
const diagnostics: Diagnostic[] = [];
Debug.assert(!!(getNodeLinks(file).flags & NodeCheckFlags.TypeChecked));
checkUnusedIdentifiers(allPotentiallyUnusedIdentifiers.get(file.fileName)!, (kind, diag) => {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), (kind, diag) => {
if (!unusedIsError(kind)) {
diagnostics.push({ ...diag, category: DiagnosticCategory.Suggestion });
}
@@ -450,9 +450,7 @@ namespace ts {
let deferredGlobalExtractSymbol: Symbol;
let deferredNodes: Node[];
const allPotentiallyUnusedIdentifiers = createMap<ReadonlyArray<PotentiallyUnusedIdentifier>>(); // key is file name
let potentiallyUnusedIdentifiers: PotentiallyUnusedIdentifier[]; // Potentially unused identifiers in the source file currently being checked.
const seenPotentiallyUnusedIdentifiers = createMap<true>(); // For assertion that we don't defer the same identifier twice
const allPotentiallyUnusedIdentifiers = createMap<PotentiallyUnusedIdentifier[]>(); // key is file name
let flowLoopStart = 0;
let flowLoopCount = 0;
@@ -2172,8 +2170,7 @@ namespace ts {
return;
}
const host = getJSDocHost(node);
if (host &&
isExpressionStatement(host) &&
if (isExpressionStatement(host) &&
isBinaryExpression(host.expression) &&
getSpecialPropertyAssignmentKind(host.expression) === SpecialPropertyAssignmentKind.PrototypeProperty) {
const symbol = getSymbolOfNode(host.expression.left);
@@ -10957,9 +10954,12 @@ namespace ts {
return result;
}
}
else if (result = isRelatedTo(constraint, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
else {
const instantiated = getTypeWithThisArgument(constraint, source);
if (result = isRelatedTo(instantiated, target, reportErrors)) {
errorInfo = saveErrorInfo;
return result;
}
}
}
else if (source.flags & TypeFlags.Index) {
@@ -22554,7 +22554,13 @@ namespace ts {
function registerForUnusedIdentifiersCheck(node: PotentiallyUnusedIdentifier): void {
// May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
if (potentiallyUnusedIdentifiers) {
if (produceDiagnostics) {
const sourceFile = getSourceFileOfNode(node);
let potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
if (!potentiallyUnusedIdentifiers) {
potentiallyUnusedIdentifiers = [];
allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
}
// TODO: GH#22580
// Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
potentiallyUnusedIdentifiers.push(node);
@@ -25536,6 +25542,10 @@ namespace ts {
}
}
function getPotentiallyUnusedIdentifiers(sourceFile: SourceFile): ReadonlyArray<PotentiallyUnusedIdentifier> {
return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || emptyArray;
}
// Fully type check a source file and collect the relevant diagnostics.
function checkSourceFileWorker(node: SourceFile) {
const links = getNodeLinks(node);
@@ -25554,11 +25564,6 @@ namespace ts {
clear(potentialNewTargetCollisions);
deferredNodes = [];
if (produceDiagnostics) {
Debug.assert(!allPotentiallyUnusedIdentifiers.has(node.fileName));
allPotentiallyUnusedIdentifiers.set(node.fileName, potentiallyUnusedIdentifiers = []);
}
forEach(node.statements, checkSourceElement);
checkDeferredNodes();
@@ -25568,7 +25573,7 @@ namespace ts {
}
if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
checkUnusedIdentifiers(potentiallyUnusedIdentifiers, (kind, diag) => {
checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), (kind, diag) => {
if (unusedIsError(kind)) {
diagnostics.add(diag);
}
@@ -25576,8 +25581,6 @@ namespace ts {
}
deferredNodes = undefined;
seenPotentiallyUnusedIdentifiers.clear();
potentiallyUnusedIdentifiers = undefined;
if (isExternalOrCommonJsModule(node)) {
checkExternalModuleExports(node);
+9 -1
View File
@@ -4258,8 +4258,16 @@
"category": "Message",
"code": 95051
},
"Add missing typeof": {
"Add missing 'typeof'": {
"category": "Message",
"code": 95052
},
"Remove unused label": {
"category": "Message",
"code": 95053
},
"Remove all unused labels": {
"category": "Message",
"code": 95054
}
}
+10 -3
View File
@@ -6,6 +6,7 @@ namespace ts {
finishRecordingFilesWithChangedResolutions(): Path[];
resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined): ResolvedModuleFull[];
getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
invalidateResolutionOfFile(filePath: Path): void;
@@ -73,7 +74,7 @@ namespace ts {
export const maxNumberOfFilesToIterateForInvalidation = 256;
type GetResolutionWithResolvedFileName<T extends ResolutionWithFailedLookupLocations = ResolutionWithFailedLookupLocations, R extends ResolutionWithResolvedFileName = ResolutionWithResolvedFileName> =
(resolution: T) => R;
(resolution: T) => R | undefined;
export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootDirForResolution: string, logChangesWhenResolvingModule: boolean): ResolutionCache {
let filesWithChangedSetOfUnresolvedImports: Path[] | undefined;
@@ -124,6 +125,7 @@ namespace ts {
startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
finishCachingPerDirectoryResolution,
resolveModuleNames,
getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives,
removeResolutionsOfFile,
invalidateResolutionOfFile,
@@ -320,7 +322,7 @@ namespace ts {
}
function resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] {
return resolveNamesWithLocalCache(
return resolveNamesWithLocalCache<ResolvedTypeReferenceDirectiveWithFailedLookupLocations, ResolvedTypeReferenceDirective>(
typeDirectiveNames, containingFile,
resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives,
resolveTypeReferenceDirective, getResolvedTypeReferenceDirective,
@@ -329,7 +331,7 @@ namespace ts {
}
function resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined): ResolvedModuleFull[] {
return resolveNamesWithLocalCache(
return resolveNamesWithLocalCache<ResolvedModuleWithFailedLookupLocations, ResolvedModuleFull>(
moduleNames, containingFile,
resolvedModuleNames, perDirectoryResolvedModuleNames,
resolveModuleName, getResolvedModule,
@@ -337,6 +339,11 @@ namespace ts {
);
}
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined {
const cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
return cache && cache.get(moduleName);
}
function isNodeModulesDirectory(dirPath: Path) {
return endsWith(dirPath, "/node_modules");
}
+3 -7
View File
@@ -1927,11 +1927,7 @@ namespace ts {
}
export function getJSDocHost(node: Node): HasJSDoc {
const comment = findAncestor(node.parent,
node => !(isJSDocNode(node) || node.flags & NodeFlags.JSDoc) ? "quit" : node.kind === SyntaxKind.JSDocComment);
if (comment) {
return (comment as JSDoc).parent;
}
return Debug.assertDefined(findAncestor(node.parent, isJSDoc)).parent;
}
export function getTypeParameterFromJsDoc(node: TypeParameterDeclaration & { parent: JSDocTemplateTag }): TypeParameterDeclaration | undefined {
@@ -3118,9 +3114,9 @@ namespace ts {
}
export function getJSDocTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray<TypeParameterDeclaration> {
const tags = filter(getJSDocTags(node), isJSDocTemplateTag);
// template tags are only available when a typedef isn't already using them
const tag = find(tags, tag => !(tag.parent.kind === SyntaxKind.JSDocComment && find(tag.parent.tags, isJSDocTypeAlias)));
const tag = find(getJSDocTags(node), (tag): tag is JSDocTemplateTag =>
isJSDocTemplateTag(tag) && !(tag.parent.kind === SyntaxKind.JSDocComment && tag.parent.tags!.some(isJSDocTypeAlias)));
return (tag && tag.typeParameters) || emptyArray;
}
+1
View File
@@ -106,6 +106,7 @@
"../services/codefixes/fixForgottenThisPropertyAccess.ts",
"../services/codefixes/fixUnusedIdentifier.ts",
"../services/codefixes/fixUnreachableCode.ts",
"../services/codefixes/fixUnusedLabel.ts",
"../services/codefixes/fixJSDocTypes.ts",
"../services/codefixes/fixAwaitInSyncFunction.ts",
"../services/codefixes/disableJsDiagnostics.ts",
+244 -7
View File
@@ -44,13 +44,6 @@ namespace ts {
assert.isEmpty(OrganizeImports.coalesceImports([]));
});
it("Sort specifiers", () => {
const sortedImports = parseImports(`import { default as m, a as n, b, y, z as o } from "lib";`);
const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);
const expectedCoalescedImports = parseImports(`import { a as n, b, default as m, y, z as o } from "lib";`);
assertListEqual(actualCoalescedImports, expectedCoalescedImports);
});
it("Sort specifiers - case-insensitive", () => {
const sortedImports = parseImports(`import { default as M, a as n, B, y, Z as O } from "lib";`);
const actualCoalescedImports = OrganizeImports.coalesceImports(sortedImports);
@@ -181,6 +174,78 @@ namespace ts {
});
});
describe("Coalesce exports", () => {
it("No exports", () => {
assert.isEmpty(OrganizeImports.coalesceExports([]));
});
it("Sort specifiers - case-insensitive", () => {
const sortedExports = parseExports(`export { default as M, a as n, B, y, Z as O } from "lib";`);
const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);
const expectedCoalescedExports = parseExports(`export { a as n, B, default as M, y, Z as O } from "lib";`);
assertListEqual(actualCoalescedExports, expectedCoalescedExports);
});
it("Combine namespace re-exports", () => {
const sortedExports = parseExports(
`export * from "lib";`,
`export * from "lib";`);
const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);
const expectedCoalescedExports = parseExports(`export * from "lib";`);
assertListEqual(actualCoalescedExports, expectedCoalescedExports);
});
it("Combine property exports", () => {
const sortedExports = parseExports(
`export { x };`,
`export { y as z };`);
const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);
const expectedCoalescedExports = parseExports(`export { x, y as z };`);
assertListEqual(actualCoalescedExports, expectedCoalescedExports);
});
it("Combine property re-exports", () => {
const sortedExports = parseExports(
`export { x } from "lib";`,
`export { y as z } from "lib";`);
const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);
const expectedCoalescedExports = parseExports(`export { x, y as z } from "lib";`);
assertListEqual(actualCoalescedExports, expectedCoalescedExports);
});
it("Combine namespace re-export with property re-export", () => {
const sortedExports = parseExports(
`export * from "lib";`,
`export { y } from "lib";`);
const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);
const expectedCoalescedExports = sortedExports;
assertListEqual(actualCoalescedExports, expectedCoalescedExports);
});
it("Combine many exports", () => {
const sortedExports = parseExports(
`export { x };`,
`export { y as w, z as default };`,
`export { w as q };`);
const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);
const expectedCoalescedExports = parseExports(
`export { w as q, x, y as w, z as default };`);
assertListEqual(actualCoalescedExports, expectedCoalescedExports);
});
it("Combine many re-exports", () => {
const sortedExports = parseExports(
`export { x as a, y } from "lib";`,
`export * from "lib";`,
`export { z as b } from "lib";`);
const actualCoalescedExports = OrganizeImports.coalesceExports(sortedExports);
const expectedCoalescedExports = parseExports(
`export * from "lib";`,
`export { x as a, y, z as b } from "lib";`);
assertListEqual(actualCoalescedExports, expectedCoalescedExports);
});
});
describe("Baselines", () => {
const libFile = {
@@ -471,6 +536,154 @@ import { React, Other } from "react";
},
reactLibFile);
describe("Exports", () => {
testOrganizeExports("MoveToTop",
{
path: "/test.ts",
content: `
export { F1, F2 } from "lib";
1;
export * from "lib";
2;
`,
},
libFile);
// tslint:disable no-invalid-template-strings
testOrganizeExports("MoveToTop_Invalid",
{
path: "/test.ts",
content: `
export { F1, F2 } from "lib";
1;
export * from "lib";
2;
export { b } from ${"`${'lib'}`"};
export { a } from ${"`${'lib'}`"};
export { D } from "lib";
3;
`,
},
libFile);
// tslint:enable no-invalid-template-strings
testOrganizeExports("MoveToTop_WithImportsFirst",
{
path: "/test.ts",
content: `
import { F1, F2 } from "lib";
1;
export { F1, F2 } from "lib";
2;
import * as NS from "lib";
3;
export * from "lib";
4;
F1(); F2(); NS.F1();
`,
},
libFile);
testOrganizeExports("MoveToTop_WithExportsFirst",
{
path: "/test.ts",
content: `
export { F1, F2 } from "lib";
1;
import { F1, F2 } from "lib";
2;
export * from "lib";
3;
import * as NS from "lib";
4;
F1(); F2(); NS.F1();
`,
},
libFile);
testOrganizeExports("CoalesceMultipleModules",
{
path: "/test.ts",
content: `
export { d } from "lib1";
export { b } from "lib1";
export { c } from "lib2";
export { a } from "lib2";
`,
},
{ path: "/lib1.ts", content: "export const b = 1, d = 2;" },
{ path: "/lib2.ts", content: "export const a = 3, c = 4;" });
testOrganizeExports("CoalesceTrivia",
{
path: "/test.ts",
content: `
/*A*/export /*B*/ { /*C*/ F2 /*D*/ } /*E*/ from /*F*/ "lib" /*G*/;/*H*/ //I
/*J*/export /*K*/ { /*L*/ F1 /*M*/ } /*N*/ from /*O*/ "lib" /*P*/;/*Q*/ //R
`,
},
libFile);
testOrganizeExports("SortTrivia",
{
path: "/test.ts",
content: `
/*A*/export /*B*/ * /*C*/ from /*D*/ "lib2" /*E*/;/*F*/ //G
/*H*/export /*I*/ * /*J*/ from /*K*/ "lib1" /*L*/;/*M*/ //N
`,
},
{ path: "/lib1.ts", content: "" },
{ path: "/lib2.ts", content: "" });
testOrganizeExports("SortHeaderComment",
{
path: "/test.ts",
content: `
// Header
export * from "lib2";
export * from "lib1";
`,
},
{ path: "/lib1.ts", content: "" },
{ path: "/lib2.ts", content: "" });
testOrganizeExports("AmbientModule",
{
path: "/test.ts",
content: `
declare module "mod" {
export { F1 } from "lib";
export * from "lib";
export { F2 } from "lib";
}
`,
},
libFile);
testOrganizeExports("TopLevelAndAmbientModule",
{
path: "/test.ts",
content: `
export { D } from "lib";
declare module "mod" {
export { F1 } from "lib";
export * from "lib";
export { F2 } from "lib";
}
export { E } from "lib";
export * from "lib";
`,
},
libFile);
});
function testOrganizeExports(testName: string, testFile: TestFSWithWatch.File, ...otherFiles: TestFSWithWatch.File[]) {
testOrganizeImports(`${testName}.exports`, testFile, ...otherFiles);
}
function testOrganizeImports(testName: string, testFile: TestFSWithWatch.File, ...otherFiles: TestFSWithWatch.File[]) {
it(testName, () => runBaseline(`organizeImports/${testName}.ts`, testFile, ...otherFiles));
}
@@ -509,6 +722,13 @@ import { React, Other } from "react";
return imports;
}
function parseExports(...exportStrings: string[]): ReadonlyArray<ExportDeclaration> {
const sourceFile = createSourceFile("a.ts", exportStrings.join("\n"), ScriptTarget.ES2015, /*setParentNodes*/ true, ScriptKind.TS);
const exports = filter(sourceFile.statements, isExportDeclaration);
assert.equal(exports.length, exportStrings.length);
return exports;
}
function assertEqual(node1?: Node, node2?: Node) {
if (node1 === undefined) {
assert.isUndefined(node2);
@@ -550,6 +770,23 @@ import { React, Other } from "react";
assertEqual(is1.name, is2.name);
assertEqual(is1.propertyName, is2.propertyName);
break;
case SyntaxKind.ExportDeclaration:
const ed1 = node1 as ExportDeclaration;
const ed2 = node2 as ExportDeclaration;
assertEqual(ed1.exportClause, ed2.exportClause);
assertEqual(ed1.moduleSpecifier, ed2.moduleSpecifier);
break;
case SyntaxKind.NamedExports:
const ne1 = node1 as NamedExports;
const ne2 = node2 as NamedExports;
assertListEqual(ne1.elements, ne2.elements);
break;
case SyntaxKind.ExportSpecifier:
const es1 = node1 as ExportSpecifier;
const es2 = node2 as ExportSpecifier;
assertEqual(es1.name, es2.name);
assertEqual(es1.propertyName, es2.propertyName);
break;
case SyntaxKind.Identifier:
const id1 = node1 as Identifier;
const id2 = node2 as Identifier;
@@ -8383,4 +8383,35 @@ new C();`
verifyCompletionListWithNewFileInSubFolder(TestFSWithWatch.Tsc_WatchDirectory.DynamicPolling);
});
});
describe("tsserverProjectSystem getEditsForFileRename", () => {
it("works for host implementing 'resolveModuleNames' and 'getResolvedModuleWithFailedLookupLocationsFromCache'", () => {
const userTs: File = {
path: "/user.ts",
content: 'import { x } from "./old";',
};
const host = createServerHost([userTs]);
const projectService = createProjectService(host);
projectService.openClientFile(userTs.path);
const project = first(projectService.inferredProjects);
Debug.assert(!!project.resolveModuleNames);
const edits = project.getLanguageService().getEditsForFileRename("/old.ts", "/new.ts", testFormatOptions);
assert.deepEqual<ReadonlyArray<FileTextChanges>>(edits, [{
fileName: "/user.ts",
textChanges: [{
span: textSpanFromSubstring(userTs.content, "./old"),
newText: "./new",
}],
}]);
});
});
function textSpanFromSubstring(str: string, substring: string): TextSpan {
const start = str.indexOf(substring);
Debug.assert(start !== -1);
return createTextSpan(start, substring.length);
}
}
+8
View File
@@ -8,4 +8,12 @@ interface RegExpExecArray {
groups?: {
[key: string]: string
}
}
interface RegExp {
/**
* Returns a Boolean value indicating the state of the dotAll flag (s) used with a regular expression.
* Default is false. Read-only.
*/
readonly dotAll: boolean;
}
+1
View File
@@ -38,6 +38,7 @@
"es2015.full",
"es2016.full",
"es2017.full",
"es2018.full",
"esnext.full"
],
"paths": {
@@ -1017,6 +1017,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Add_missing_typeof_95052" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Add missing typeof]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Agregar el objeto typeof que falta]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Add qualifier to all unresolved variables matching a member name]]></Val>
@@ -6573,6 +6582,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_all_unused_labels_95054" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove all unused labels]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_declaration_for_Colon_0_90004" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove declaration for: '{0}']]></Val>
@@ -6612,6 +6627,12 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Remove_unused_label_95053" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Remove unused label]]></Val>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Replace_import_with_0_95015" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Replace import with '{0}'.]]></Val>
@@ -1017,6 +1017,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Add_missing_typeof_95052" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Add missing typeof]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Ajouter un typeof manquant]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Add qualifier to all unresolved variables matching a member name]]></Val>
@@ -998,6 +998,15 @@
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Add_missing_typeof_95052" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Add missing typeof]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Adicionar typeof ausente]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
</Item>
<Item ItemId=";Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037" ItemType="0" PsrId="306" Leaf="true">
<Str Cat="Text">
<Val><![CDATA[Add qualifier to all unresolved variables matching a member name]]></Val>
+4
View File
@@ -358,6 +358,10 @@ namespace ts.server {
return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames);
}
getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations {
return this.resolutionCache.getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile);
}
resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] {
return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile);
}
+1
View File
@@ -102,6 +102,7 @@
"../services/codefixes/fixForgottenThisPropertyAccess.ts",
"../services/codefixes/fixUnusedIdentifier.ts",
"../services/codefixes/fixUnreachableCode.ts",
"../services/codefixes/fixUnusedLabel.ts",
"../services/codefixes/fixJSDocTypes.ts",
"../services/codefixes/fixAwaitInSyncFunction.ts",
"../services/codefixes/disableJsDiagnostics.ts",
+1
View File
@@ -108,6 +108,7 @@
"../services/codefixes/fixForgottenThisPropertyAccess.ts",
"../services/codefixes/fixUnusedIdentifier.ts",
"../services/codefixes/fixUnreachableCode.ts",
"../services/codefixes/fixUnusedLabel.ts",
"../services/codefixes/fixJSDocTypes.ts",
"../services/codefixes/fixAwaitInSyncFunction.ts",
"../services/codefixes/disableJsDiagnostics.ts",
+25
View File
@@ -0,0 +1,25 @@
/* @internal */
namespace ts.codefix {
const fixId = "fixUnusedLabel";
const errorCodes = [Diagnostics.Unused_label.code];
registerCodeFix({
errorCodes,
getCodeActions(context) {
const changes = textChanges.ChangeTracker.with(context, t => doChange(t, context.sourceFile, context.span.start));
return [createCodeFixAction(fixId, changes, Diagnostics.Remove_unused_label, fixId, Diagnostics.Remove_all_unused_labels)];
},
fixIds: [fixId],
getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => doChange(changes, diag.file, diag.start)),
});
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, start: number): void {
const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false);
const labeledStatement = cast(token.parent, isLabeledStatement);
const pos = token.getStart(sourceFile);
const statementPos = labeledStatement.statement.getStart(sourceFile);
// If label is on a separate line, just delete the rest of that line, but not the indentation of the labeled statement.
const end = positionsAreOnSameLine(pos, statementPos, sourceFile) ? statementPos
: skipTrivia(sourceFile.text, findChildOfKind(labeledStatement, SyntaxKind.ColonToken, sourceFile)!.end, /*stopAfterLineBreak*/ true);
changes.deleteRange(sourceFile, { pos, end });
}
}
+1 -1
View File
@@ -498,7 +498,7 @@ namespace ts.codefix {
}
for (const sourceFile of allSourceFiles) {
if (isExternalOrCommonJsModule(sourceFile)) {
cb(sourceFile.symbol, sourceFile);
cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile);
}
}
}
+5 -3
View File
@@ -4,7 +4,7 @@ namespace ts {
const pathUpdater = getPathUpdater(oldFilePath, newFilePath, host);
return textChanges.ChangeTracker.with({ host, formatContext }, changeTracker => {
updateTsconfigFiles(program, changeTracker, oldFilePath, newFilePath);
for (const { sourceFile, toUpdate } of getImportsToUpdate(program, oldFilePath)) {
for (const { sourceFile, toUpdate } of getImportsToUpdate(program, oldFilePath, host)) {
const newPath = pathUpdater(isRef(toUpdate) ? toUpdate.fileName : toUpdate.text);
if (newPath !== undefined) {
const range = isRef(toUpdate) ? toUpdate : createStringRange(toUpdate, sourceFile);
@@ -30,7 +30,7 @@ namespace ts {
return "fileName" in toUpdate;
}
function getImportsToUpdate(program: Program, oldFilePath: string): ReadonlyArray<ToUpdate> {
function getImportsToUpdate(program: Program, oldFilePath: string, host: LanguageServiceHost): ReadonlyArray<ToUpdate> {
const checker = program.getTypeChecker();
const result: ToUpdate[] = [];
for (const sourceFile of program.getSourceFiles()) {
@@ -44,7 +44,9 @@ namespace ts {
// If it resolved to something already, ignore.
if (checker.getSymbolAtLocation(importStringLiteral)) continue;
const resolved = program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
const resolved = host.resolveModuleNames
? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName)
: program.getResolvedModuleWithFailedLookupLocationsFromCache(importStringLiteral.text, sourceFile.fileName);
if (resolved && contains(resolved.failedLookupLocations, oldFilePath)) {
result.push({ sourceFile, toUpdate: importStringLiteral });
}
+94 -11
View File
@@ -17,19 +17,32 @@ namespace ts.OrganizeImports {
const changeTracker = textChanges.ChangeTracker.fromContext({ host, formatContext });
const coalesceAndOrganizeImports = (importGroup: ReadonlyArray<ImportDeclaration>) => coalesceImports(removeUnusedImports(importGroup, sourceFile, program));
// All of the old ImportDeclarations in the file, in syntactic order.
const topLevelImportDecls = sourceFile.statements.filter(isImportDeclaration);
organizeImportsWorker(topLevelImportDecls);
organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
// All of the old ExportDeclarations in the file, in syntactic order.
const topLevelExportDecls = sourceFile.statements.filter(isExportDeclaration);
organizeImportsWorker(topLevelExportDecls, coalesceExports);
for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) {
const ambientModuleBody = getModuleBlock(ambientModule as ModuleDeclaration);
const ambientModuleImportDecls = ambientModuleBody.statements.filter(isImportDeclaration);
organizeImportsWorker(ambientModuleImportDecls);
organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
const ambientModuleExportDecls = ambientModuleBody.statements.filter(isExportDeclaration);
organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
}
return changeTracker.getChanges();
function organizeImportsWorker(oldImportDecls: ReadonlyArray<ImportDeclaration>) {
function organizeImportsWorker<T extends ImportDeclaration | ExportDeclaration>(
oldImportDecls: ReadonlyArray<T>,
coalesce: (group: ReadonlyArray<T>) => ReadonlyArray<T>) {
if (length(oldImportDecls) === 0) {
return;
}
@@ -45,7 +58,7 @@ namespace ts.OrganizeImports {
const sortedImportGroups = stableSort(oldImportGroups, (group1, group2) => compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier));
const newImportDecls = flatMap(sortedImportGroups, importGroup =>
getExternalModuleName(importGroup[0].moduleSpecifier)
? coalesceImports(removeUnusedImports(importGroup, sourceFile, program))
? coalesce(importGroup)
: importGroup);
// Delete or replace the first import.
@@ -131,7 +144,9 @@ namespace ts.OrganizeImports {
}
function getExternalModuleName(specifier: Expression) {
return isStringLiteralLike(specifier) ? specifier.text : undefined;
return specifier !== undefined && isStringLiteralLike(specifier)
? specifier.text
: undefined;
}
/* @internal */ // Internal for testing
@@ -189,9 +204,7 @@ namespace ts.OrganizeImports {
newImportSpecifiers.push(...flatMap(namedImports, i => (i.importClause.namedBindings as NamedImports).elements));
const sortedImportSpecifiers = stableSort(newImportSpecifiers, (s1, s2) =>
compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name));
const sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
const importDecl = defaultImports.length > 0
? defaultImports[0]
@@ -254,9 +267,69 @@ namespace ts.OrganizeImports {
namedImports,
};
}
}
function compareIdentifiers(s1: Identifier, s2: Identifier) {
return compareStringsCaseInsensitive(s1.text, s2.text);
/* @internal */ // Internal for testing
/**
* @param exportGroup a list of ExportDeclarations, all with the same module name.
*/
export function coalesceExports(exportGroup: ReadonlyArray<ExportDeclaration>) {
if (exportGroup.length === 0) {
return exportGroup;
}
const { exportWithoutClause, namedExports } = getCategorizedExports(exportGroup);
const coalescedExports: ExportDeclaration[] = [];
if (exportWithoutClause) {
coalescedExports.push(exportWithoutClause);
}
if (namedExports.length === 0) {
return coalescedExports;
}
const newExportSpecifiers: ExportSpecifier[] = [];
newExportSpecifiers.push(...flatMap(namedExports, i => (i.exportClause).elements));
const sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
const exportDecl = namedExports[0];
coalescedExports.push(
updateExportDeclaration(
exportDecl,
exportDecl.decorators,
exportDecl.modifiers,
updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers),
exportDecl.moduleSpecifier));
return coalescedExports;
/*
* Returns entire export declarations because they may already have been rewritten and
* may lack parent pointers. The desired parts can easily be recovered based on the
* categorization.
*/
function getCategorizedExports(exportGroup: ReadonlyArray<ExportDeclaration>) {
let exportWithoutClause: ExportDeclaration | undefined;
const namedExports: ExportDeclaration[] = [];
for (const exportDeclaration of exportGroup) {
if (exportDeclaration.exportClause === undefined) {
// Only the first such export is interesting - the others are redundant.
// Note: Unfortunately, we will lose trivia that was on this node.
exportWithoutClause = exportWithoutClause || exportDeclaration;
}
else {
namedExports.push(exportDeclaration);
}
}
return {
exportWithoutClause,
namedExports,
};
}
}
@@ -273,6 +346,12 @@ namespace ts.OrganizeImports {
importDeclaration.moduleSpecifier);
}
function sortSpecifiers<T extends ImportOrExportSpecifier>(specifiers: ReadonlyArray<T>) {
return stableSort(specifiers, (s1, s2) =>
compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) ||
compareIdentifiers(s1.name, s2.name));
}
/* internal */ // Exported for testing
export function compareModuleSpecifiers(m1: Expression, m2: Expression) {
const name1 = getExternalModuleName(m1);
@@ -281,4 +360,8 @@ namespace ts.OrganizeImports {
compareBooleans(isExternalModuleNameRelative(name1), isExternalModuleNameRelative(name2)) ||
compareStringsCaseInsensitive(name1, name2);
}
}
function compareIdentifiers(s1: Identifier, s2: Identifier) {
return compareStringsCaseInsensitive(s1.text, s2.text);
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ namespace ts.refactor {
case SyntaxKind.ImportEqualsDeclaration:
return !hasModifier(node, ModifierFlags.Export);
case SyntaxKind.VariableStatement:
return (node as VariableStatement).declarationList.declarations.every(d => isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true));
return (node as VariableStatement).declarationList.declarations.every(d => d.initializer && isRequireCall(d.initializer, /*checkArgumentIsStringLiteralLike*/ true));
default:
return false;
}
+1
View File
@@ -99,6 +99,7 @@
"codefixes/fixForgottenThisPropertyAccess.ts",
"codefixes/fixUnusedIdentifier.ts",
"codefixes/fixUnreachableCode.ts",
"codefixes/fixUnusedLabel.ts",
"codefixes/fixJSDocTypes.ts",
"codefixes/fixAwaitInSyncFunction.ts",
"codefixes/disableJsDiagnostics.ts",
+3
View File
@@ -207,8 +207,11 @@ namespace ts {
* LS host can optionally implement this method if it wants to be completely in charge of module name resolution.
* if implementation is omitted then language service will use built-in module resolution logic and get answers to
* host specific questions using 'getScriptSnapshot'.
*
* If this is implemented, `getResolvedModuleWithFailedLookupLocationsFromCache` should be too.
*/
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
/* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution;
/* @internal */ hasChangedAutomaticTypeDirectiveNames?: boolean;
+2
View File
@@ -4477,6 +4477,7 @@ declare namespace ts {
fileExists?(path: string): boolean;
getTypeRootsVersion?(): number;
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getDirectories?(directoryName: string): string[];
/**
@@ -7864,6 +7865,7 @@ declare namespace ts.server {
readFile(fileName: string): string | undefined;
fileExists(file: string): boolean;
resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModuleFull[];
getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
directoryExists(path: string): boolean;
getDirectories(path: string): string[];
+1
View File
@@ -4477,6 +4477,7 @@ declare namespace ts {
fileExists?(path: string): boolean;
getTypeRootsVersion?(): number;
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[];
getResolvedModuleWithFailedLookupLocationsFromCache?(modulename: string, containingFile: string): ResolvedModuleWithFailedLookupLocations;
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
getDirectories?(directoryName: string): string[];
/**
@@ -0,0 +1,67 @@
//// [collectionPatternNoError.ts]
interface MsgConstructor<T extends Message> {
new(data: Array<{}>): T;
}
class Message {
clone(): this {
return this;
}
}
interface MessageList<T extends Message> extends Message {
methodOnMessageList(): T[];
}
function fetchMsg<V extends Message>(protoCtor: MsgConstructor<V>): V {
return null!;
}
class DataProvider<T extends Message, U extends MessageList<T>> {
constructor(
private readonly message: MsgConstructor<T>,
private readonly messageList: MsgConstructor<U>,
) { }
fetch() {
const messageList = fetchMsg(this.messageList);
messageList.methodOnMessageList();
}
}
// The same bug as the above but using indexed accesses
// (won't surface directly unless unsound indexed access assignments are forbidden)
function f<
U extends {TType: MessageList<T>},
T extends Message
>(message: MsgConstructor<T>, messageList: MsgConstructor<U["TType"]>) {
fetchMsg(messageList).methodOnMessageList();
}
//// [collectionPatternNoError.js]
var Message = /** @class */ (function () {
function Message() {
}
Message.prototype.clone = function () {
return this;
};
return Message;
}());
function fetchMsg(protoCtor) {
return null;
}
var DataProvider = /** @class */ (function () {
function DataProvider(message, messageList) {
this.message = message;
this.messageList = messageList;
}
DataProvider.prototype.fetch = function () {
var messageList = fetchMsg(this.messageList);
messageList.methodOnMessageList();
};
return DataProvider;
}());
// The same bug as the above but using indexed accesses
// (won't surface directly unless unsound indexed access assignments are forbidden)
function f(message, messageList) {
fetchMsg(messageList).methodOnMessageList();
}
@@ -0,0 +1,112 @@
=== tests/cases/compiler/collectionPatternNoError.ts ===
interface MsgConstructor<T extends Message> {
>MsgConstructor : Symbol(MsgConstructor, Decl(collectionPatternNoError.ts, 0, 0))
>T : Symbol(T, Decl(collectionPatternNoError.ts, 0, 25))
>Message : Symbol(Message, Decl(collectionPatternNoError.ts, 2, 1))
new(data: Array<{}>): T;
>data : Symbol(data, Decl(collectionPatternNoError.ts, 1, 6))
>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>T : Symbol(T, Decl(collectionPatternNoError.ts, 0, 25))
}
class Message {
>Message : Symbol(Message, Decl(collectionPatternNoError.ts, 2, 1))
clone(): this {
>clone : Symbol(Message.clone, Decl(collectionPatternNoError.ts, 3, 15))
return this;
>this : Symbol(Message, Decl(collectionPatternNoError.ts, 2, 1))
}
}
interface MessageList<T extends Message> extends Message {
>MessageList : Symbol(MessageList, Decl(collectionPatternNoError.ts, 7, 1))
>T : Symbol(T, Decl(collectionPatternNoError.ts, 8, 22))
>Message : Symbol(Message, Decl(collectionPatternNoError.ts, 2, 1))
>Message : Symbol(Message, Decl(collectionPatternNoError.ts, 2, 1))
methodOnMessageList(): T[];
>methodOnMessageList : Symbol(MessageList.methodOnMessageList, Decl(collectionPatternNoError.ts, 8, 58))
>T : Symbol(T, Decl(collectionPatternNoError.ts, 8, 22))
}
function fetchMsg<V extends Message>(protoCtor: MsgConstructor<V>): V {
>fetchMsg : Symbol(fetchMsg, Decl(collectionPatternNoError.ts, 10, 1))
>V : Symbol(V, Decl(collectionPatternNoError.ts, 12, 18))
>Message : Symbol(Message, Decl(collectionPatternNoError.ts, 2, 1))
>protoCtor : Symbol(protoCtor, Decl(collectionPatternNoError.ts, 12, 37))
>MsgConstructor : Symbol(MsgConstructor, Decl(collectionPatternNoError.ts, 0, 0))
>V : Symbol(V, Decl(collectionPatternNoError.ts, 12, 18))
>V : Symbol(V, Decl(collectionPatternNoError.ts, 12, 18))
return null!;
}
class DataProvider<T extends Message, U extends MessageList<T>> {
>DataProvider : Symbol(DataProvider, Decl(collectionPatternNoError.ts, 14, 1))
>T : Symbol(T, Decl(collectionPatternNoError.ts, 16, 19))
>Message : Symbol(Message, Decl(collectionPatternNoError.ts, 2, 1))
>U : Symbol(U, Decl(collectionPatternNoError.ts, 16, 37))
>MessageList : Symbol(MessageList, Decl(collectionPatternNoError.ts, 7, 1))
>T : Symbol(T, Decl(collectionPatternNoError.ts, 16, 19))
constructor(
private readonly message: MsgConstructor<T>,
>message : Symbol(DataProvider.message, Decl(collectionPatternNoError.ts, 17, 14))
>MsgConstructor : Symbol(MsgConstructor, Decl(collectionPatternNoError.ts, 0, 0))
>T : Symbol(T, Decl(collectionPatternNoError.ts, 16, 19))
private readonly messageList: MsgConstructor<U>,
>messageList : Symbol(DataProvider.messageList, Decl(collectionPatternNoError.ts, 18, 48))
>MsgConstructor : Symbol(MsgConstructor, Decl(collectionPatternNoError.ts, 0, 0))
>U : Symbol(U, Decl(collectionPatternNoError.ts, 16, 37))
) { }
fetch() {
>fetch : Symbol(DataProvider.fetch, Decl(collectionPatternNoError.ts, 20, 7))
const messageList = fetchMsg(this.messageList);
>messageList : Symbol(messageList, Decl(collectionPatternNoError.ts, 23, 9))
>fetchMsg : Symbol(fetchMsg, Decl(collectionPatternNoError.ts, 10, 1))
>this.messageList : Symbol(DataProvider.messageList, Decl(collectionPatternNoError.ts, 18, 48))
>this : Symbol(DataProvider, Decl(collectionPatternNoError.ts, 14, 1))
>messageList : Symbol(DataProvider.messageList, Decl(collectionPatternNoError.ts, 18, 48))
messageList.methodOnMessageList();
>messageList.methodOnMessageList : Symbol(MessageList.methodOnMessageList, Decl(collectionPatternNoError.ts, 8, 58))
>messageList : Symbol(messageList, Decl(collectionPatternNoError.ts, 23, 9))
>methodOnMessageList : Symbol(MessageList.methodOnMessageList, Decl(collectionPatternNoError.ts, 8, 58))
}
}
// The same bug as the above but using indexed accesses
// (won't surface directly unless unsound indexed access assignments are forbidden)
function f<
>f : Symbol(f, Decl(collectionPatternNoError.ts, 26, 1))
U extends {TType: MessageList<T>},
>U : Symbol(U, Decl(collectionPatternNoError.ts, 30, 11))
>TType : Symbol(TType, Decl(collectionPatternNoError.ts, 31, 13))
>MessageList : Symbol(MessageList, Decl(collectionPatternNoError.ts, 7, 1))
>T : Symbol(T, Decl(collectionPatternNoError.ts, 31, 36))
T extends Message
>T : Symbol(T, Decl(collectionPatternNoError.ts, 31, 36))
>Message : Symbol(Message, Decl(collectionPatternNoError.ts, 2, 1))
>(message: MsgConstructor<T>, messageList: MsgConstructor<U["TType"]>) {
>message : Symbol(message, Decl(collectionPatternNoError.ts, 33, 2))
>MsgConstructor : Symbol(MsgConstructor, Decl(collectionPatternNoError.ts, 0, 0))
>T : Symbol(T, Decl(collectionPatternNoError.ts, 31, 36))
>messageList : Symbol(messageList, Decl(collectionPatternNoError.ts, 33, 29))
>MsgConstructor : Symbol(MsgConstructor, Decl(collectionPatternNoError.ts, 0, 0))
>U : Symbol(U, Decl(collectionPatternNoError.ts, 30, 11))
fetchMsg(messageList).methodOnMessageList();
>fetchMsg(messageList).methodOnMessageList : Symbol(MessageList.methodOnMessageList, Decl(collectionPatternNoError.ts, 8, 58))
>fetchMsg : Symbol(fetchMsg, Decl(collectionPatternNoError.ts, 10, 1))
>messageList : Symbol(messageList, Decl(collectionPatternNoError.ts, 33, 29))
>methodOnMessageList : Symbol(MessageList.methodOnMessageList, Decl(collectionPatternNoError.ts, 8, 58))
}
@@ -0,0 +1,118 @@
=== tests/cases/compiler/collectionPatternNoError.ts ===
interface MsgConstructor<T extends Message> {
>MsgConstructor : MsgConstructor<T>
>T : T
>Message : Message
new(data: Array<{}>): T;
>data : {}[]
>Array : T[]
>T : T
}
class Message {
>Message : Message
clone(): this {
>clone : () => this
return this;
>this : this
}
}
interface MessageList<T extends Message> extends Message {
>MessageList : MessageList<T>
>T : T
>Message : Message
>Message : Message
methodOnMessageList(): T[];
>methodOnMessageList : () => T[]
>T : T
}
function fetchMsg<V extends Message>(protoCtor: MsgConstructor<V>): V {
>fetchMsg : <V extends Message>(protoCtor: MsgConstructor<V>) => V
>V : V
>Message : Message
>protoCtor : MsgConstructor<V>
>MsgConstructor : MsgConstructor<T>
>V : V
>V : V
return null!;
>null! : null
>null : null
}
class DataProvider<T extends Message, U extends MessageList<T>> {
>DataProvider : DataProvider<T, U>
>T : T
>Message : Message
>U : U
>MessageList : MessageList<T>
>T : T
constructor(
private readonly message: MsgConstructor<T>,
>message : MsgConstructor<T>
>MsgConstructor : MsgConstructor<T>
>T : T
private readonly messageList: MsgConstructor<U>,
>messageList : MsgConstructor<U>
>MsgConstructor : MsgConstructor<T>
>U : U
) { }
fetch() {
>fetch : () => void
const messageList = fetchMsg(this.messageList);
>messageList : U
>fetchMsg(this.messageList) : U
>fetchMsg : <V extends Message>(protoCtor: MsgConstructor<V>) => V
>this.messageList : MsgConstructor<U>
>this : this
>messageList : MsgConstructor<U>
messageList.methodOnMessageList();
>messageList.methodOnMessageList() : T[]
>messageList.methodOnMessageList : () => T[]
>messageList : U
>methodOnMessageList : () => T[]
}
}
// The same bug as the above but using indexed accesses
// (won't surface directly unless unsound indexed access assignments are forbidden)
function f<
>f : <U extends { TType: MessageList<T>; }, T extends Message>(message: MsgConstructor<T>, messageList: MsgConstructor<U["TType"]>) => void
U extends {TType: MessageList<T>},
>U : U
>TType : MessageList<T>
>MessageList : MessageList<T>
>T : T
T extends Message
>T : T
>Message : Message
>(message: MsgConstructor<T>, messageList: MsgConstructor<U["TType"]>) {
>message : MsgConstructor<T>
>MsgConstructor : MsgConstructor<T>
>T : T
>messageList : MsgConstructor<U["TType"]>
>MsgConstructor : MsgConstructor<T>
>U : U
fetchMsg(messageList).methodOnMessageList();
>fetchMsg(messageList).methodOnMessageList() : T[]
>fetchMsg(messageList).methodOnMessageList : () => T[]
>fetchMsg(messageList) : U["TType"]
>fetchMsg : <V extends Message>(protoCtor: MsgConstructor<V>) => V
>messageList : MsgConstructor<U["TType"]>
>methodOnMessageList : () => T[]
}
@@ -4,7 +4,6 @@ tests/cases/compiler/fuzzy.ts(21,13): error TS2322: Type '{ anything: number; on
Types of property 'oneI' are incompatible.
Type 'this' is not assignable to type 'I'.
Type 'C' is not assignable to type 'I'.
Property 'alsoWorks' is missing in type 'C'.
tests/cases/compiler/fuzzy.ts(25,20): error TS2352: Type '{ oneI: this; }' cannot be converted to type 'R'.
Property 'anything' is missing in type '{ oneI: this; }'.
@@ -39,7 +38,6 @@ tests/cases/compiler/fuzzy.ts(25,20): error TS2352: Type '{ oneI: this; }' canno
!!! error TS2322: Types of property 'oneI' are incompatible.
!!! error TS2322: Type 'this' is not assignable to type 'I'.
!!! error TS2322: Type 'C' is not assignable to type 'I'.
!!! error TS2322: Property 'alsoWorks' is missing in type 'C'.
}
worksToo():R {
@@ -0,0 +1,15 @@
// ==ORIGINAL==
declare module "mod" {
export { F1 } from "lib";
export * from "lib";
export { F2 } from "lib";
}
// ==ORGANIZED==
declare module "mod" {
export * from "lib";
export { F1, F2 } from "lib";
}
@@ -0,0 +1,11 @@
// ==ORIGINAL==
export { d } from "lib1";
export { b } from "lib1";
export { c } from "lib2";
export { a } from "lib2";
// ==ORGANIZED==
export { b, d } from "lib1";
export { a, c } from "lib2";
@@ -0,0 +1,8 @@
// ==ORIGINAL==
/*A*/export /*B*/ { /*C*/ F2 /*D*/ } /*E*/ from /*F*/ "lib" /*G*/;/*H*/ //I
/*J*/export /*K*/ { /*L*/ F1 /*M*/ } /*N*/ from /*O*/ "lib" /*P*/;/*Q*/ //R
// ==ORGANIZED==
/*A*/export /*B*/ { /*L*/ F1 /*M*/, /*C*/ F2 /*D*/ } /*E*/ from /*F*/ "lib" /*G*/; /*H*/ //I
@@ -0,0 +1,13 @@
// ==ORIGINAL==
export { F1, F2 } from "lib";
1;
export * from "lib";
2;
// ==ORGANIZED==
export * from "lib";
export { F1, F2 } from "lib";
1;
2;
@@ -0,0 +1,20 @@
// ==ORIGINAL==
export { F1, F2 } from "lib";
1;
export * from "lib";
2;
export { b } from `${'lib'}`;
export { a } from `${'lib'}`;
export { D } from "lib";
3;
// ==ORGANIZED==
export * from "lib";
export { D, F1, F2 } from "lib";
export { b } from `${'lib'}`;
export { a } from `${'lib'}`;
1;
2;
3;
@@ -0,0 +1,23 @@
// ==ORIGINAL==
export { F1, F2 } from "lib";
1;
import { F1, F2 } from "lib";
2;
export * from "lib";
3;
import * as NS from "lib";
4;
F1(); F2(); NS.F1();
// ==ORGANIZED==
export * from "lib";
export { F1, F2 } from "lib";
1;
import * as NS from "lib";
import { F1, F2 } from "lib";
2;
3;
4;
F1(); F2(); NS.F1();
@@ -0,0 +1,23 @@
// ==ORIGINAL==
import { F1, F2 } from "lib";
1;
export { F1, F2 } from "lib";
2;
import * as NS from "lib";
3;
export * from "lib";
4;
F1(); F2(); NS.F1();
// ==ORGANIZED==
import * as NS from "lib";
import { F1, F2 } from "lib";
1;
export * from "lib";
export { F1, F2 } from "lib";
2;
3;
4;
F1(); F2(); NS.F1();
@@ -0,0 +1,11 @@
// ==ORIGINAL==
// Header
export * from "lib2";
export * from "lib1";
// ==ORGANIZED==
// Header
export * from "lib1";
export * from "lib2";
@@ -0,0 +1,9 @@
// ==ORIGINAL==
/*A*/export /*B*/ * /*C*/ from /*D*/ "lib2" /*E*/;/*F*/ //G
/*H*/export /*I*/ * /*J*/ from /*K*/ "lib1" /*L*/;/*M*/ //N
// ==ORGANIZED==
/*A*//*H*/ export /*I*/ * /*J*/ from /*K*/ "lib1" /*L*/; /*M*/ //N
export /*B*/ * /*C*/ from /*D*/ "lib2" /*E*/; /*F*/ //G
@@ -0,0 +1,23 @@
// ==ORIGINAL==
export { D } from "lib";
declare module "mod" {
export { F1 } from "lib";
export * from "lib";
export { F2 } from "lib";
}
export { E } from "lib";
export * from "lib";
// ==ORGANIZED==
export * from "lib";
export { D, E } from "lib";
declare module "mod" {
export * from "lib";
export { F1, F2 } from "lib";
}
@@ -0,0 +1,31 @@
//// [subclassWithPolymorphicThisIsAssignable.ts]
/* taken from mongoose.Document */
interface Document {
increment(): this;
}
/* our custom model extends the mongoose document */
interface CustomDocument extends Document { }
export class Example<Z extends CustomDocument> {
constructor() {
// types of increment not compatible??
this.test<Z>();
}
public test<Z extends Document>() { }
}
//// [subclassWithPolymorphicThisIsAssignable.js]
"use strict";
exports.__esModule = true;
var Example = /** @class */ (function () {
function Example() {
// types of increment not compatible??
this.test();
}
Example.prototype.test = function () { };
return Example;
}());
exports.Example = Example;
@@ -0,0 +1,34 @@
=== tests/cases/compiler/subclassWithPolymorphicThisIsAssignable.ts ===
/* taken from mongoose.Document */
interface Document {
>Document : Symbol(Document, Decl(subclassWithPolymorphicThisIsAssignable.ts, 0, 0))
increment(): this;
>increment : Symbol(Document.increment, Decl(subclassWithPolymorphicThisIsAssignable.ts, 1, 20))
}
/* our custom model extends the mongoose document */
interface CustomDocument extends Document { }
>CustomDocument : Symbol(CustomDocument, Decl(subclassWithPolymorphicThisIsAssignable.ts, 3, 1))
>Document : Symbol(Document, Decl(subclassWithPolymorphicThisIsAssignable.ts, 0, 0))
export class Example<Z extends CustomDocument> {
>Example : Symbol(Example, Decl(subclassWithPolymorphicThisIsAssignable.ts, 6, 45))
>Z : Symbol(Z, Decl(subclassWithPolymorphicThisIsAssignable.ts, 8, 21))
>CustomDocument : Symbol(CustomDocument, Decl(subclassWithPolymorphicThisIsAssignable.ts, 3, 1))
constructor() {
// types of increment not compatible??
this.test<Z>();
>this.test : Symbol(Example.test, Decl(subclassWithPolymorphicThisIsAssignable.ts, 12, 5))
>this : Symbol(Example, Decl(subclassWithPolymorphicThisIsAssignable.ts, 6, 45))
>test : Symbol(Example.test, Decl(subclassWithPolymorphicThisIsAssignable.ts, 12, 5))
>Z : Symbol(Z, Decl(subclassWithPolymorphicThisIsAssignable.ts, 8, 21))
}
public test<Z extends Document>() { }
>test : Symbol(Example.test, Decl(subclassWithPolymorphicThisIsAssignable.ts, 12, 5))
>Z : Symbol(Z, Decl(subclassWithPolymorphicThisIsAssignable.ts, 14, 16))
>Document : Symbol(Document, Decl(subclassWithPolymorphicThisIsAssignable.ts, 0, 0))
}
@@ -0,0 +1,35 @@
=== tests/cases/compiler/subclassWithPolymorphicThisIsAssignable.ts ===
/* taken from mongoose.Document */
interface Document {
>Document : Document
increment(): this;
>increment : () => this
}
/* our custom model extends the mongoose document */
interface CustomDocument extends Document { }
>CustomDocument : CustomDocument
>Document : Document
export class Example<Z extends CustomDocument> {
>Example : Example<Z>
>Z : Z
>CustomDocument : CustomDocument
constructor() {
// types of increment not compatible??
this.test<Z>();
>this.test<Z>() : void
>this.test : <Z extends Document>() => void
>this : this
>test : <Z extends Document>() => void
>Z : Z
}
public test<Z extends Document>() { }
>test : <Z extends Document>() => void
>Z : Z
>Document : Document
}
@@ -0,0 +1,36 @@
interface MsgConstructor<T extends Message> {
new(data: Array<{}>): T;
}
class Message {
clone(): this {
return this;
}
}
interface MessageList<T extends Message> extends Message {
methodOnMessageList(): T[];
}
function fetchMsg<V extends Message>(protoCtor: MsgConstructor<V>): V {
return null!;
}
class DataProvider<T extends Message, U extends MessageList<T>> {
constructor(
private readonly message: MsgConstructor<T>,
private readonly messageList: MsgConstructor<U>,
) { }
fetch() {
const messageList = fetchMsg(this.messageList);
messageList.methodOnMessageList();
}
}
// The same bug as the above but using indexed accesses
// (won't surface directly unless unsound indexed access assignments are forbidden)
function f<
U extends {TType: MessageList<T>},
T extends Message
>(message: MsgConstructor<T>, messageList: MsgConstructor<U["TType"]>) {
fetchMsg(messageList).methodOnMessageList();
}
@@ -0,0 +1,16 @@
/* taken from mongoose.Document */
interface Document {
increment(): this;
}
/* our custom model extends the mongoose document */
interface CustomDocument extends Document { }
export class Example<Z extends CustomDocument> {
constructor() {
// types of increment not compatible??
this.test<Z>();
}
public test<Z extends Document>() { }
}
@@ -7,7 +7,7 @@
//// const x: import("foo") = import("foo");
verify.codeFix({
description: "Add missing typeof",
description: "Add missing 'typeof'",
newFileContent: `declare module "foo" {
const a = "foo"
export = a
@@ -8,6 +8,6 @@
goTo.file("b.ts")
verify.codeFix({
description: "Add missing typeof",
description: "Add missing 'typeof'",
newFileContent: `const a: typeof import("./a") = import("./a")`
});
@@ -0,0 +1,11 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
/////* a */label/* b */:/* c */while (1) {}
verify.codeFix({
description: "Remove unused label",
newFileContent:
`/* a */while (1) {}`,
});
@@ -0,0 +1,21 @@
/// <reference path='fourslash.ts' />
// @noUnusedLocals: true
////label1: while (1) {}
////
////function f() {
////label2:
//// while (1) {}
////}
verify.codeFixAll({
fixId: "fixUnusedLabel",
fixAllDescription: "Remove all unused labels",
newFileContent:
`while (1) {}
function f() {
while (1) {}
}`,
});
@@ -0,0 +1,36 @@
/// <reference path="fourslash.ts" />
// @Filename: /a.ts
////export const foo = 0;
// @Filename: /bar.ts
////export {};
////declare module "./a" {
//// export const bar = 0;
////}
// @Filename: /user.ts
/////**/
verify.completions({
marker: "",
includes: [
{
name: "foo",
text: "const foo: 0",
source: "/a",
sourceDisplay: "./a",
hasAction: true,
},
{
name: "bar",
text: "const bar: 0",
source: "/a",
sourceDisplay: "./a",
hasAction: true,
},
],
preferences: {
includeCompletionsForModuleExports: true,
},
});
@@ -2,6 +2,7 @@
// @Filename: /a.ts
////[|import { a, b } from "m";
////let l;
////a;|]
////b;
@@ -10,8 +11,9 @@ verify.moveToNewFile({
"/a.ts":
`import { b } from "m";
b;`,
"/newFile.ts":
"/l.ts":
`import { a } from "m";
let l;
a;`,
}
});
@@ -0,0 +1,31 @@
/// <reference path='fourslash.ts' />
//@allowJs: true
// @Filename: /mymodule.js
////(function ([|root|], factory) {
//// module.exports = factory();
////}(this, function () {
//// var [|unusedVar|] = "something";
//// return {};
////}));
// @Filename: /app.js
//////@ts-check
////require("./mymodule");
const [range0, range1] = test.ranges();
goTo.file("/app.js");
verify.getSuggestionDiagnostics([]);
goTo.file("/mymodule.js");
verify.getSuggestionDiagnostics([{
message: "'root' is declared but its value is never read.",
code: 6133,
range: range0
}, {
message: "'unusedVar' is declared but its value is never read.",
code: 6133,
range: range1
}]);