diff --git a/Jakefile.js b/Jakefile.js index cdf8e30efe0..bd5074b43d6 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -113,7 +113,7 @@ var languageServiceLibrarySources = [ return path.join(serverDirectory, f); }).concat(servicesSources); -var harnessSources = [ +var harnessCoreSources = [ "harness.ts", "sourceMapRecorder.ts", "harnessLanguageService.ts", @@ -129,7 +129,9 @@ var harnessSources = [ "runner.ts" ].map(function (f) { return path.join(harnessDirectory, f); -}).concat([ +}); + +var harnessSources = harnessCoreSources.concat([ "incrementalParser.ts", "jsDocParsing.ts", "services/colorization.ts", @@ -730,12 +732,13 @@ task("update-sublime", ["local", serverFile], function() { // run this task automatically desc("Runs tslint on the compiler sources"); task("lint", [], function() { - for(var i in compilerSources) { - var f = compilerSources[i]; + function success(f) { return function() { console.log('SUCCESS: No linter errors in ' + f + '\n'); }}; + function failure(f) { return function() { console.log('FAILURE: Please fix linting errors in ' + f + '\n') }}; + + var lintTargets = compilerSources.concat(harnessCoreSources); + for(var i in lintTargets) { + var f = lintTargets[i]; var cmd = 'tslint -f ' + f; - exec(cmd, - function() { console.log('SUCCESS: No linter errors'); }, - function() { console.log('FAILURE: Please fix linting errors in ' + f + '\n'); - }); + exec(cmd, success(f), failure(f)); } }, { async: true }); diff --git a/bin/tsc.js b/bin/tsc.js index f5a780a390d..185aca1ef44 100644 --- a/bin/tsc.js +++ b/bin/tsc.js @@ -933,7 +933,14 @@ var ts; newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, write: function (s) { - _fs.writeSync(1, s); + var buffer = new Buffer(s, 'utf8'); + var offset = 0; + var toWrite = buffer.length; + var written = 0; + while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) { + offset += written; + toWrite -= written; + } }, readFile: readFile, writeFile: writeFile, @@ -1401,7 +1408,7 @@ var ts; Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes containing abstract methods must be marked abstract." }, Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All declarations of an abstract method must be consecutive." }, - Constructor_objects_of_abstract_type_cannot_be_assigned_to_constructor_objects_of_non_abstract_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Constructor objects of abstract type cannot be assigned to constructor objects of non-abstract type" }, + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, Only_an_ambient_class_can_be_merged_with_an_interface: { code: 2518, category: ts.DiagnosticCategory.Error, key: "Only an ambient class can be merged with an interface." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, @@ -9187,7 +9194,8 @@ var ts; } else { node.exportClause = parseNamedImportsOrExports(226); - if (parseOptional(130)) { + if (token === 130 || (token === 8 && !scanner.hasPrecedingLineBreak())) { + parseExpected(130); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -13263,7 +13271,7 @@ var ts; var id = getTypeListId(elementTypes); var type = tupleTypes[id]; if (!type) { - type = tupleTypes[id] = createObjectType(8192); + type = tupleTypes[id] = createObjectType(8192 | getWideningFlagsOfTypes(elementTypes)); type.elementTypes = elementTypes; } return type; @@ -14084,10 +14092,29 @@ var ts; var targetSignatures = getSignaturesOfType(target, kind); var result = -1; var saveErrorInfo = errorInfo; + var sourceSig = sourceSignatures[0]; + var targetSig = targetSignatures[0]; + if (sourceSig && targetSig) { + var sourceErasedSignature = getErasedSignature(sourceSig); + var targetErasedSignature = getErasedSignature(targetSig); + var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); + var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); + var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && ts.getDeclarationOfKind(sourceReturnType.symbol, 211); + var targetReturnDecl = targetReturnType && targetReturnType.symbol && ts.getDeclarationOfKind(targetReturnType.symbol, 211); + var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 256; + var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 256; + if (sourceIsAbstract && !targetIsAbstract) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0; + } + } outer: for (var _i = 0; _i < targetSignatures.length; _i++) { var t = targetSignatures[_i]; if (!t.hasStringLiterals || target.flags & 262144) { var localErrors = reportErrors; + var checkedAbstractAssignability = false; for (var _a = 0; _a < sourceSignatures.length; _a++) { var s = sourceSignatures[_a]; if (!s.hasStringLiterals || source.flags & 262144) { @@ -14135,12 +14162,12 @@ var ts; target = getErasedSignature(target); var result = -1; for (var i = 0; i < checkCount; i++) { - var s_1 = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - var t_1 = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); var saveErrorInfo = errorInfo; - var related = isRelatedTo(s_1, t_1, reportErrors); + var related = isRelatedTo(s, t, reportErrors); if (!related) { - related = isRelatedTo(t_1, s_1, false); + related = isRelatedTo(t, s, false); if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); @@ -14178,11 +14205,11 @@ var ts; } return 0; } - var t = getReturnTypeOfSignature(target); - if (t === voidType) + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) return result; - var s = getReturnTypeOfSignature(source); - return result & isRelatedTo(s, t, reportErrors); + var sourceReturnType = getReturnTypeOfSignature(source); + return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -14395,7 +14422,7 @@ var ts; return !!getPropertyOfType(type, "0"); } function isTupleType(type) { - return (type.flags & 8192) && !!type.elementTypes; + return !!(type.flags & 8192); } function getWidenedTypeOfObjectLiteral(type) { var properties = getPropertiesOfObjectType(type); @@ -14437,25 +14464,36 @@ var ts; if (isArrayType(type)) { return createArrayType(getWidenedType(type.typeArguments[0])); } + if (isTupleType(type)) { + return createTupleType(ts.map(type.elementTypes, getWidenedType)); + } } return type; } function reportWideningErrorsInType(type) { + var errorReported = false; if (type.flags & 16384) { - var errorReported = false; - ts.forEach(type.types, function (t) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; if (reportWideningErrorsInType(t)) { errorReported = true; } - }); - return errorReported; + } } if (isArrayType(type)) { return reportWideningErrorsInType(type.typeArguments[0]); } + if (isTupleType(type)) { + for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } if (type.flags & 524288) { - var errorReported = false; - ts.forEach(getPropertiesOfObjectType(type), function (p) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; var t = getTypeOfSymbol(p); if (t.flags & 1048576) { if (!reportWideningErrorsInType(t)) { @@ -14463,10 +14501,9 @@ var ts; } errorReported = true; } - }); - return errorReported; + } } - return false; + return errorReported; } function reportImplicitAnyError(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); @@ -14614,28 +14651,31 @@ var ts; inferFromTypes(sourceType, target); } } - else if (source.flags & 80896 && (target.flags & (4096 | 8192) || - (target.flags & 65536) && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { - if (isInProcess(source, target)) { - return; + else { + source = getApparentType(source); + if (source.flags & 80896 && (target.flags & (4096 | 8192) || + (target.flags & 65536) && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { + if (isInProcess(source, target)) { + return; + } + if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { + return; + } + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target, 0, 0); + inferFromIndexTypes(source, target, 1, 1); + inferFromIndexTypes(source, target, 0, 1); + depth--; } - if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { - return; - } - if (depth === 0) { - sourceStack = []; - targetStack = []; - } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target, 0, 0); - inferFromIndexTypes(source, target, 1, 1); - inferFromIndexTypes(source, target, 0, 1); - depth--; } } function inferFromProperties(source, target) { diff --git a/bin/tsserver.js b/bin/tsserver.js index abc95f7a760..9d582485e2f 100644 --- a/bin/tsserver.js +++ b/bin/tsserver.js @@ -933,7 +933,14 @@ var ts; newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, write: function (s) { - _fs.writeSync(1, s); + var buffer = new Buffer(s, 'utf8'); + var offset = 0; + var toWrite = buffer.length; + var written = 0; + while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) { + offset += written; + toWrite -= written; + } }, readFile: readFile, writeFile: writeFile, @@ -1401,7 +1408,7 @@ var ts; Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes containing abstract methods must be marked abstract." }, Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All declarations of an abstract method must be consecutive." }, - Constructor_objects_of_abstract_type_cannot_be_assigned_to_constructor_objects_of_non_abstract_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Constructor objects of abstract type cannot be assigned to constructor objects of non-abstract type" }, + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, Only_an_ambient_class_can_be_merged_with_an_interface: { code: 2518, category: ts.DiagnosticCategory.Error, key: "Only an ambient class can be merged with an interface." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, @@ -8904,7 +8911,8 @@ var ts; } else { node.exportClause = parseNamedImportsOrExports(226); - if (parseOptional(130)) { + if (token === 130 || (token === 8 && !scanner.hasPrecedingLineBreak())) { + parseExpected(130); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -13686,7 +13694,7 @@ var ts; var id = getTypeListId(elementTypes); var type = tupleTypes[id]; if (!type) { - type = tupleTypes[id] = createObjectType(8192); + type = tupleTypes[id] = createObjectType(8192 | getWideningFlagsOfTypes(elementTypes)); type.elementTypes = elementTypes; } return type; @@ -14507,10 +14515,29 @@ var ts; var targetSignatures = getSignaturesOfType(target, kind); var result = -1; var saveErrorInfo = errorInfo; + var sourceSig = sourceSignatures[0]; + var targetSig = targetSignatures[0]; + if (sourceSig && targetSig) { + var sourceErasedSignature = getErasedSignature(sourceSig); + var targetErasedSignature = getErasedSignature(targetSig); + var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); + var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); + var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && ts.getDeclarationOfKind(sourceReturnType.symbol, 211); + var targetReturnDecl = targetReturnType && targetReturnType.symbol && ts.getDeclarationOfKind(targetReturnType.symbol, 211); + var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 256; + var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 256; + if (sourceIsAbstract && !targetIsAbstract) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0; + } + } outer: for (var _i = 0; _i < targetSignatures.length; _i++) { var t = targetSignatures[_i]; if (!t.hasStringLiterals || target.flags & 262144) { var localErrors = reportErrors; + var checkedAbstractAssignability = false; for (var _a = 0; _a < sourceSignatures.length; _a++) { var s = sourceSignatures[_a]; if (!s.hasStringLiterals || source.flags & 262144) { @@ -14558,12 +14585,12 @@ var ts; target = getErasedSignature(target); var result = -1; for (var i = 0; i < checkCount; i++) { - var s_1 = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - var t_1 = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); var saveErrorInfo = errorInfo; - var related = isRelatedTo(s_1, t_1, reportErrors); + var related = isRelatedTo(s, t, reportErrors); if (!related) { - related = isRelatedTo(t_1, s_1, false); + related = isRelatedTo(t, s, false); if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); @@ -14601,11 +14628,11 @@ var ts; } return 0; } - var t = getReturnTypeOfSignature(target); - if (t === voidType) + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) return result; - var s = getReturnTypeOfSignature(source); - return result & isRelatedTo(s, t, reportErrors); + var sourceReturnType = getReturnTypeOfSignature(source); + return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -14818,7 +14845,7 @@ var ts; return !!getPropertyOfType(type, "0"); } function isTupleType(type) { - return (type.flags & 8192) && !!type.elementTypes; + return !!(type.flags & 8192); } function getWidenedTypeOfObjectLiteral(type) { var properties = getPropertiesOfObjectType(type); @@ -14860,25 +14887,36 @@ var ts; if (isArrayType(type)) { return createArrayType(getWidenedType(type.typeArguments[0])); } + if (isTupleType(type)) { + return createTupleType(ts.map(type.elementTypes, getWidenedType)); + } } return type; } function reportWideningErrorsInType(type) { + var errorReported = false; if (type.flags & 16384) { - var errorReported = false; - ts.forEach(type.types, function (t) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; if (reportWideningErrorsInType(t)) { errorReported = true; } - }); - return errorReported; + } } if (isArrayType(type)) { return reportWideningErrorsInType(type.typeArguments[0]); } + if (isTupleType(type)) { + for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } if (type.flags & 524288) { - var errorReported = false; - ts.forEach(getPropertiesOfObjectType(type), function (p) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; var t = getTypeOfSymbol(p); if (t.flags & 1048576) { if (!reportWideningErrorsInType(t)) { @@ -14886,10 +14924,9 @@ var ts; } errorReported = true; } - }); - return errorReported; + } } - return false; + return errorReported; } function reportImplicitAnyError(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); @@ -15037,28 +15074,31 @@ var ts; inferFromTypes(sourceType, target); } } - else if (source.flags & 80896 && (target.flags & (4096 | 8192) || - (target.flags & 65536) && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { - if (isInProcess(source, target)) { - return; + else { + source = getApparentType(source); + if (source.flags & 80896 && (target.flags & (4096 | 8192) || + (target.flags & 65536) && target.symbol && target.symbol.flags & (8192 | 2048 | 32))) { + if (isInProcess(source, target)) { + return; + } + if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { + return; + } + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, 0); + inferFromSignatures(source, target, 1); + inferFromIndexTypes(source, target, 0, 0); + inferFromIndexTypes(source, target, 1, 1); + inferFromIndexTypes(source, target, 0, 1); + depth--; } - if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { - return; - } - if (depth === 0) { - sourceStack = []; - targetStack = []; - } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0); - inferFromSignatures(source, target, 1); - inferFromIndexTypes(source, target, 0, 0); - inferFromIndexTypes(source, target, 1, 1); - inferFromIndexTypes(source, target, 0, 1); - depth--; } } function inferFromProperties(source, target) { @@ -31937,15 +31977,15 @@ var ts; var t; var pos = scanner.getStartPos(); while (pos < endPos) { - var t_2 = scanner.getToken(); - if (!ts.isTrivia(t_2)) { + var t_1 = scanner.getToken(); + if (!ts.isTrivia(t_1)) { break; } scanner.scan(); var item = { pos: pos, end: scanner.getStartPos(), - kind: t_2 + kind: t_1 }; pos = scanner.getStartPos(); if (!leadingTrivia) { @@ -33289,6 +33329,8 @@ var ts; case 15: case 18: case 19: + case 16: + case 17: case 77: case 101: case 53: @@ -33390,7 +33432,7 @@ var ts; } else if (tokenInfo.token.kind === listStartToken) { startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1, parent, parentDynamicIndentation, startLine); + var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1, parent, parentDynamicIndentation, parentStartLine); listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); } @@ -35052,6 +35094,12 @@ var ts; var newSourceFile = ts.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks); setSourceFileFields(newSourceFile, scriptSnapshot, version); newSourceFile.nameTable = undefined; + if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) { + if (sourceFile.scriptSnapshot.dispose) { + sourceFile.scriptSnapshot.dispose(); + } + sourceFile.scriptSnapshot = undefined; + } return newSourceFile; } } @@ -35908,20 +35956,20 @@ var ts; } function tryGetGlobalSymbols() { var objectLikeContainer; - var importClause; + var namedImportsOrExports; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); } - if (importClause = ts.getAncestor(contextToken, 220)) { - return tryGetImportClauseCompletionSymbols(importClause); + if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { + return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType; if ((jsxContainer.kind === 231) || (jsxContainer.kind === 232)) { attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { - symbols = filterJsxAttributes(jsxContainer.attributes, typeChecker.getPropertiesOfType(attrsType)); + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); isMemberCompletion = true; isNewIdentifierLocation = false; return true; @@ -35951,19 +35999,11 @@ var ts; function isCompletionListBlocker(contextToken) { var start = new Date().getTime(); var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || - isIdentifierDefinitionLocation(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || isDotOfNumericLiteral(contextToken); log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); return result; } - function shouldShowCompletionsInImportsClause(node) { - if (node) { - if (node.kind === 14 || node.kind === 23) { - return node.parent.kind === 222; - } - } - return false; - } function isNewIdentifierDefinitionLocation(previousToken) { if (previousToken) { var containingNodeKind = previousToken.parent.kind; @@ -36055,23 +36095,23 @@ var ts; } return true; } - function tryGetImportClauseCompletionSymbols(importClause) { - if (shouldShowCompletionsInImportsClause(contextToken)) { - isMemberCompletion = true; - isNewIdentifierLocation = false; - var importDeclaration = importClause.parent; - ts.Debug.assert(importDeclaration !== undefined && importDeclaration.kind === 219); - var exports_2; - var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importDeclaration.moduleSpecifier); - if (moduleSpecifierSymbol) { - exports_2 = typeChecker.getExportsOfModule(moduleSpecifierSymbol); - } - symbols = exports_2 ? filterModuleExports(exports_2, importDeclaration) : emptyArray; + function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + var declarationKind = namedImportsOrExports.kind === 222 ? + 219 : + 225; + var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); + var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; + if (!moduleSpecifier) { + return false; } - else { - isMemberCompletion = false; - isNewIdentifierLocation = true; + isMemberCompletion = true; + isNewIdentifierLocation = false; + var exports; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); + if (moduleSpecifierSymbol) { + exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); } + symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray; return true; } function tryGetObjectLikeCompletionContainer(contextToken) { @@ -36088,6 +36128,20 @@ var ts; } return undefined; } + function tryGetNamedImportsOrExportsForCompletion(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 14: + case 23: + switch (contextToken.parent.kind) { + case 222: + case 226: + return contextToken.parent; + } + } + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent_12 = contextToken.parent; @@ -36127,7 +36181,7 @@ var ts; } return false; } - function isIdentifierDefinitionLocation(contextToken) { + function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 23: @@ -36173,6 +36227,10 @@ var ts; case 107: case 108: return containingNodeKind === 135; + case 113: + containingNodeKind === 223 || + containingNodeKind === 227 || + containingNodeKind === 221; case 70: case 78: case 104: @@ -36208,25 +36266,20 @@ var ts; } return false; } - function filterModuleExports(exports, importDeclaration) { - var exisingImports = {}; - if (!importDeclaration.importClause) { - return exports; + function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { + var exisingImportsOrExports = {}; + for (var _i = 0; _i < namedImportsOrExports.length; _i++) { + var element = namedImportsOrExports[_i]; + if (element.getStart() <= position && position <= element.getEnd()) { + continue; + } + var name_31 = element.propertyName || element.name; + exisingImportsOrExports[name_31.text] = true; } - if (importDeclaration.importClause.namedBindings && - importDeclaration.importClause.namedBindings.kind === 222) { - ts.forEach(importDeclaration.importClause.namedBindings.elements, function (el) { - if (el.getStart() <= position && position <= el.getEnd()) { - return; - } - var name = el.propertyName || el.name; - exisingImports[name.text] = true; - }); + if (ts.isEmpty(exisingImportsOrExports)) { + return exportsOfModule; } - if (ts.isEmpty(exisingImports)) { - return exports; - } - return ts.filter(exports, function (e) { return !ts.lookUp(exisingImports, e.name); }); + return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(exisingImportsOrExports, e.name); }); } function filterObjectMembersList(contextualMemberSymbols, existingMembers) { if (!existingMembers || existingMembers.length === 0) { @@ -36252,15 +36305,9 @@ var ts; } existingMemberNames[existingName] = true; } - var filteredMembers = []; - ts.forEach(contextualMemberSymbols, function (s) { - if (!existingMemberNames[s.name]) { - filteredMembers.push(s); - } - }); - return filteredMembers; + return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); } - function filterJsxAttributes(attributes, symbols) { + function filterJsxAttributes(symbols, attributes) { var seenNames = {}; for (var _i = 0; _i < attributes.length; _i++) { var attr = attributes[_i]; @@ -36271,14 +36318,7 @@ var ts; seenNames[attr.name.text] = true; } } - var result = []; - for (var _a = 0; _a < symbols.length; _a++) { - var sym = symbols[_a]; - if (!seenNames[sym.name]) { - result.push(sym); - } - } - return result; + return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); } } function getCompletionsAtPosition(fileName, position) { @@ -36310,10 +36350,10 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameTable = getNameTable(sourceFile); - for (var name_31 in nameTable) { - if (!allNames[name_31]) { - allNames[name_31] = name_31; - var displayName = getCompletionEntryDisplayName(name_31, target, true); + for (var name_32 in nameTable) { + if (!allNames[name_32]) { + allNames[name_32] = name_32; + var displayName = getCompletionEntryDisplayName(name_32, target, true); if (displayName) { var entry = { name: displayName, @@ -37117,6 +37157,7 @@ var ts; if (hasKind(node.parent, 142) || hasKind(node.parent, 143)) { return getGetAndSetOccurrences(node.parent); } + break; default: if (ts.isModifier(node.kind) && node.parent && (ts.isDeclaration(node.parent) || node.parent.kind === 190)) { @@ -37216,12 +37257,13 @@ var ts; var container = declaration.parent; if (ts.isAccessibilityModifier(modifier)) { if (!(container.kind === 211 || + container.kind === 183 || (declaration.kind === 135 && hasKind(container, 141)))) { return undefined; } } else if (modifier === 110) { - if (container.kind !== 211) { + if (!(container.kind === 211 || container.kind === 183)) { return undefined; } } @@ -37230,6 +37272,11 @@ var ts; return undefined; } } + else if (modifier === 112) { + if (!(container.kind === 211 || declaration.kind === 211)) { + return undefined; + } + } else { return undefined; } @@ -37239,12 +37286,18 @@ var ts; switch (container.kind) { case 216: case 245: - nodes = container.statements; + if (modifierFlag & 256) { + nodes = declaration.members.concat(declaration); + } + else { + nodes = container.statements; + } break; case 141: nodes = container.parameters.concat(container.parent.members); break; case 211: + case 183: nodes = container.members; if (modifierFlag & 112) { var constructor = ts.forEach(container.members, function (member) { @@ -37254,6 +37307,9 @@ var ts; nodes = nodes.concat(constructor.parameters); } } + else if (modifierFlag & 256) { + nodes = nodes.concat(container); + } break; default: ts.Debug.fail("Invalid container kind."); @@ -37278,6 +37334,8 @@ var ts; return 1; case 119: return 2; + case 112: + return 256; default: ts.Debug.fail(); } @@ -37975,17 +38033,17 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_32 = node.text; + var name_33 = node.text; if (contextualType) { if (contextualType.flags & 16384) { - var unionProperty = contextualType.getProperty(name_32); + var unionProperty = contextualType.getProperty(name_33); if (unionProperty) { return [unionProperty]; } else { var result_4 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_32); + var symbol = t.getProperty(name_33); if (symbol) { result_4.push(symbol); } @@ -37994,7 +38052,7 @@ var ts; } } else { - var symbol_1 = contextualType.getProperty(name_32); + var symbol_1 = contextualType.getProperty(name_33); if (symbol_1) { return [symbol_1]; } @@ -38593,7 +38651,7 @@ var ts; return; } } - return 9; + return 2; } } function processElement(element) { @@ -39337,10 +39395,113 @@ var ts; this.fileHash = {}; this.nextFileId = 1; this.changeSeq = 0; + this.handlers = (_a = {}, + _a[CommandNames.Exit] = function () { + _this.exit(); + return {}; + }, + _a[CommandNames.Definition] = function (request) { + var defArgs = request.arguments; + return { response: _this.getDefinition(defArgs.line, defArgs.offset, defArgs.file) }; + }, + _a[CommandNames.TypeDefinition] = function (request) { + var defArgs = request.arguments; + return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file) }; + }, + _a[CommandNames.References] = function (request) { + var defArgs = request.arguments; + return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file) }; + }, + _a[CommandNames.Rename] = function (request) { + var renameArgs = request.arguments; + return { response: _this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings) }; + }, + _a[CommandNames.Open] = function (request) { + var openArgs = request.arguments; + _this.openClientFile(openArgs.file); + return {}; + }, + _a[CommandNames.Quickinfo] = function (request) { + var quickinfoArgs = request.arguments; + return { response: _this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file) }; + }, + _a[CommandNames.Format] = function (request) { + var formatArgs = request.arguments; + return { response: _this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file) }; + }, + _a[CommandNames.Formatonkey] = function (request) { + var formatOnKeyArgs = request.arguments; + return { response: _this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file) }; + }, + _a[CommandNames.Completions] = function (request) { + var completionsArgs = request.arguments; + return { response: _this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file) }; + }, + _a[CommandNames.CompletionDetails] = function (request) { + var completionDetailsArgs = request.arguments; + return { response: _this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file) }; + }, + _a[CommandNames.SignatureHelp] = function (request) { + var signatureHelpArgs = request.arguments; + return { response: _this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file) }; + }, + _a[CommandNames.Geterr] = function (request) { + var geterrArgs = request.arguments; + return { response: _this.getDiagnostics(geterrArgs.delay, geterrArgs.files), responseRequired: false }; + }, + _a[CommandNames.Change] = function (request) { + var changeArgs = request.arguments; + _this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); + return { responseRequired: false }; + }, + _a[CommandNames.Configure] = function (request) { + var configureArgs = request.arguments; + _this.projectService.setHostConfiguration(configureArgs); + _this.output(undefined, CommandNames.Configure, request.seq); + return { responseRequired: false }; + }, + _a[CommandNames.Reload] = function (request) { + var reloadArgs = request.arguments; + _this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); + return { responseRequired: false }; + }, + _a[CommandNames.Saveto] = function (request) { + var savetoArgs = request.arguments; + _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); + return { responseRequired: false }; + }, + _a[CommandNames.Close] = function (request) { + var closeArgs = request.arguments; + _this.closeClientFile(closeArgs.file); + return { responseRequired: false }; + }, + _a[CommandNames.Navto] = function (request) { + var navtoArgs = request.arguments; + return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount) }; + }, + _a[CommandNames.Brace] = function (request) { + var braceArguments = request.arguments; + return { response: _this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file) }; + }, + _a[CommandNames.NavBar] = function (request) { + var navBarArgs = request.arguments; + return { response: _this.getNavigationBarItems(navBarArgs.file) }; + }, + _a[CommandNames.Occurrences] = function (request) { + var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file; + return { response: _this.getOccurrences(line, offset, fileName) }; + }, + _a[CommandNames.ProjectInfo] = function (request) { + var _a = request.arguments, file = _a.file, needFileNameList = _a.needFileNameList; + return { response: _this.getProjectInfo(file, needFileNameList) }; + }, + _a + ); this.projectService = new server.ProjectService(host, logger, function (eventName, project, fileName) { _this.handleEvent(eventName, project, fileName); }); + var _a; } Session.prototype.handleEvent = function (eventName, project, fileName) { var _this = this; @@ -39957,6 +40118,23 @@ var ts; }; Session.prototype.exit = function () { }; + Session.prototype.addProtocolHandler = function (command, handler) { + if (this.handlers[command]) { + throw new Error("Protocol handler already exists for command \"" + command + "\""); + } + this.handlers[command] = handler; + }; + Session.prototype.executeCommand = function (request) { + var handler = this.handlers[request.command]; + if (handler) { + return handler(request); + } + else { + this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); + this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); + return { responseRequired: false }; + } + }; Session.prototype.onMessage = function (message) { if (this.logger.isVerbose()) { this.logger.info("request: " + message); @@ -39964,140 +40142,7 @@ var ts; } try { var request = JSON.parse(message); - var response; - var errorMessage; - var responseRequired = true; - switch (request.command) { - case CommandNames.Exit: { - this.exit(); - responseRequired = false; - break; - } - case CommandNames.Definition: { - var defArgs = request.arguments; - response = this.getDefinition(defArgs.line, defArgs.offset, defArgs.file); - break; - } - case CommandNames.TypeDefinition: { - var defArgs = request.arguments; - response = this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file); - break; - } - case CommandNames.References: { - var refArgs = request.arguments; - response = this.getReferences(refArgs.line, refArgs.offset, refArgs.file); - break; - } - case CommandNames.Rename: { - var renameArgs = request.arguments; - response = this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings); - break; - } - case CommandNames.Open: { - var openArgs = request.arguments; - this.openClientFile(openArgs.file); - responseRequired = false; - break; - } - case CommandNames.Quickinfo: { - var quickinfoArgs = request.arguments; - response = this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file); - break; - } - case CommandNames.Format: { - var formatArgs = request.arguments; - response = this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file); - break; - } - case CommandNames.Formatonkey: { - var formatOnKeyArgs = request.arguments; - response = this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file); - break; - } - case CommandNames.Completions: { - var completionsArgs = request.arguments; - response = this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file); - break; - } - case CommandNames.CompletionDetails: { - var completionDetailsArgs = request.arguments; - response = - this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file); - break; - } - case CommandNames.SignatureHelp: { - var signatureHelpArgs = request.arguments; - response = this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file); - break; - } - case CommandNames.Geterr: { - var geterrArgs = request.arguments; - response = this.getDiagnostics(geterrArgs.delay, geterrArgs.files); - responseRequired = false; - break; - } - case CommandNames.Change: { - var changeArgs = request.arguments; - this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); - responseRequired = false; - break; - } - case CommandNames.Configure: { - var configureArgs = request.arguments; - this.projectService.setHostConfiguration(configureArgs); - this.output(undefined, CommandNames.Configure, request.seq); - responseRequired = false; - break; - } - case CommandNames.Reload: { - var reloadArgs = request.arguments; - this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); - responseRequired = false; - break; - } - case CommandNames.Saveto: { - var savetoArgs = request.arguments; - this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); - responseRequired = false; - break; - } - case CommandNames.Close: { - var closeArgs = request.arguments; - this.closeClientFile(closeArgs.file); - responseRequired = false; - break; - } - case CommandNames.Navto: { - var navtoArgs = request.arguments; - response = this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount); - break; - } - case CommandNames.Brace: { - var braceArguments = request.arguments; - response = this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file); - break; - } - case CommandNames.NavBar: { - var navBarArgs = request.arguments; - response = this.getNavigationBarItems(navBarArgs.file); - break; - } - case CommandNames.Occurrences: { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file; - response = this.getOccurrences(line, offset, fileName); - break; - } - case CommandNames.ProjectInfo: { - var _b = request.arguments, file = _b.file, needFileNameList = _b.needFileNameList; - response = this.getProjectInfo(file, needFileNameList); - break; - } - default: { - this.projectService.log("Unrecognized JSON command: " + message); - this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); - break; - } - } + var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; if (this.logger.isVerbose()) { var elapsed = this.hrtime(start); var seconds = elapsed[0]; @@ -42027,6 +42072,11 @@ var ts; var decoded = JSON.parse(encoded); return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); }; + ScriptSnapshotShimAdapter.prototype.dispose = function () { + if ("dispose" in this.scriptSnapshotShim) { + this.scriptSnapshotShim.dispose(); + } + }; return ScriptSnapshotShimAdapter; })(); var LanguageServiceShimHostAdapter = (function () { diff --git a/bin/typescript.d.ts b/bin/typescript.d.ts index 869fbb32d98..ee69b9ca909 100644 --- a/bin/typescript.d.ts +++ b/bin/typescript.d.ts @@ -1591,6 +1591,8 @@ declare module "typescript" { * not happen and the entire document will be re - parsed. */ getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; + /** Releases all resources held by this script snapshot */ + dispose?(): void; } module ScriptSnapshot { function fromString(text: string): IScriptSnapshot; diff --git a/bin/typescript.js b/bin/typescript.js index 219a0b3924f..6035d71fa2b 100644 --- a/bin/typescript.js +++ b/bin/typescript.js @@ -1775,8 +1775,15 @@ var ts; newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, write: function (s) { + var buffer = new Buffer(s, 'utf8'); + var offset = 0; + var toWrite = buffer.length; + var written = 0; // 1 is a standard descriptor for stdout - _fs.writeSync(1, s); + while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) { + offset += written; + toWrite -= written; + } }, readFile: readFile, writeFile: writeFile, @@ -2247,7 +2254,7 @@ var ts; Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes containing abstract methods must be marked abstract." }, Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All declarations of an abstract method must be consecutive." }, - Constructor_objects_of_abstract_type_cannot_be_assigned_to_constructor_objects_of_non_abstract_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Constructor objects of abstract type cannot be assigned to constructor objects of non-abstract type" }, + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, Only_an_ambient_class_can_be_merged_with_an_interface: { code: 2518, category: ts.DiagnosticCategory.Error, key: "Only an ambient class can be merged with an interface." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, @@ -11517,7 +11524,11 @@ var ts; } else { node.exportClause = parseNamedImportsOrExports(226 /* NamedExports */); - if (parseOptional(130 /* FromKeyword */)) { + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token === 130 /* FromKeyword */ || (token === 8 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(130 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -16299,7 +16310,7 @@ var ts; var id = getTypeListId(elementTypes); var type = tupleTypes[id]; if (!type) { - type = tupleTypes[id] = createObjectType(8192 /* Tuple */); + type = tupleTypes[id] = createObjectType(8192 /* Tuple */ | getWideningFlagsOfTypes(elementTypes)); type.elementTypes = elementTypes; } return type; @@ -17200,10 +17211,33 @@ var ts; var targetSignatures = getSignaturesOfType(target, kind); var result = -1 /* True */; var saveErrorInfo = errorInfo; + // Because the "abstractness" of a class is the same across all construct signatures + // (internally we are checking the corresponding declaration), it is enough to perform + // the check and report an error once over all pairs of source and target construct signatures. + var sourceSig = sourceSignatures[0]; + // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. + var targetSig = targetSignatures[0]; + if (sourceSig && targetSig) { + var sourceErasedSignature = getErasedSignature(sourceSig); + var targetErasedSignature = getErasedSignature(targetSig); + var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); + var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); + var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && ts.getDeclarationOfKind(sourceReturnType.symbol, 211 /* ClassDeclaration */); + var targetReturnDecl = targetReturnType && targetReturnType.symbol && ts.getDeclarationOfKind(targetReturnType.symbol, 211 /* ClassDeclaration */); + var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 256 /* Abstract */; + var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 256 /* Abstract */; + if (sourceIsAbstract && !targetIsAbstract) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + } outer: for (var _i = 0; _i < targetSignatures.length; _i++) { var t = targetSignatures[_i]; if (!t.hasStringLiterals || target.flags & 262144 /* FromSignature */) { var localErrors = reportErrors; + var checkedAbstractAssignability = false; for (var _a = 0; _a < sourceSignatures.length; _a++) { var s = sourceSignatures[_a]; if (!s.hasStringLiterals || source.flags & 262144 /* FromSignature */) { @@ -17254,12 +17288,12 @@ var ts; target = getErasedSignature(target); var result = -1 /* True */; for (var i = 0; i < checkCount; i++) { - var s_1 = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - var t_1 = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); var saveErrorInfo = errorInfo; - var related = isRelatedTo(s_1, t_1, reportErrors); + var related = isRelatedTo(s, t, reportErrors); if (!related) { - related = isRelatedTo(t_1, s_1, false); + related = isRelatedTo(t, s, false); if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); @@ -17297,11 +17331,11 @@ var ts; } return 0 /* False */; } - var t = getReturnTypeOfSignature(target); - if (t === voidType) + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) return result; - var s = getReturnTypeOfSignature(source); - return result & isRelatedTo(s, t, reportErrors); + var sourceReturnType = getReturnTypeOfSignature(source); + return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -17537,7 +17571,7 @@ var ts; * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ function isTupleType(type) { - return (type.flags & 8192 /* Tuple */) && !!type.elementTypes; + return !!(type.flags & 8192 /* Tuple */); } function getWidenedTypeOfObjectLiteral(type) { var properties = getPropertiesOfObjectType(type); @@ -17579,25 +17613,47 @@ var ts; if (isArrayType(type)) { return createArrayType(getWidenedType(type.typeArguments[0])); } + if (isTupleType(type)) { + return createTupleType(ts.map(type.elementTypes, getWidenedType)); + } } return type; } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ function reportWideningErrorsInType(type) { + var errorReported = false; if (type.flags & 16384 /* Union */) { - var errorReported = false; - ts.forEach(type.types, function (t) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; if (reportWideningErrorsInType(t)) { errorReported = true; } - }); - return errorReported; + } } if (isArrayType(type)) { return reportWideningErrorsInType(type.typeArguments[0]); } + if (isTupleType(type)) { + for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } if (type.flags & 524288 /* ObjectLiteral */) { - var errorReported = false; - ts.forEach(getPropertiesOfObjectType(type), function (p) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; var t = getTypeOfSymbol(p); if (t.flags & 1048576 /* ContainsUndefinedOrNull */) { if (!reportWideningErrorsInType(t)) { @@ -17605,10 +17661,9 @@ var ts; } errorReported = true; } - }); - return errorReported; + } } - return false; + return errorReported; } function reportImplicitAnyError(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); @@ -17771,29 +17826,32 @@ var ts; inferFromTypes(sourceType, target); } } - else if (source.flags & 80896 /* ObjectType */ && (target.flags & (4096 /* Reference */ | 8192 /* Tuple */) || - (target.flags & 65536 /* Anonymous */) && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { - // If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members - if (isInProcess(source, target)) { - return; + else { + source = getApparentType(source); + if (source.flags & 80896 /* ObjectType */ && (target.flags & (4096 /* Reference */ | 8192 /* Tuple */) || + (target.flags & 65536 /* Anonymous */) && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { + // If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members + if (isInProcess(source, target)) { + return; + } + if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { + return; + } + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target, 0 /* String */, 0 /* String */); + inferFromIndexTypes(source, target, 1 /* Number */, 1 /* Number */); + inferFromIndexTypes(source, target, 0 /* String */, 1 /* Number */); + depth--; } - if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { - return; - } - if (depth === 0) { - sourceStack = []; - targetStack = []; - } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0 /* Call */); - inferFromSignatures(source, target, 1 /* Construct */); - inferFromIndexTypes(source, target, 0 /* String */, 0 /* String */); - inferFromIndexTypes(source, target, 1 /* Number */, 1 /* Number */); - inferFromIndexTypes(source, target, 0 /* String */, 1 /* Number */); - depth--; } } function inferFromProperties(source, target) { @@ -37768,8 +37826,8 @@ var ts; var pos = scanner.getStartPos(); // Read leading trivia and token while (pos < endPos) { - var t_2 = scanner.getToken(); - if (!ts.isTrivia(t_2)) { + var t_1 = scanner.getToken(); + if (!ts.isTrivia(t_1)) { break; } // consume leading trivia @@ -37777,7 +37835,7 @@ var ts; var item = { pos: pos, end: scanner.getStartPos(), - kind: t_2 + kind: t_1 }; pos = scanner.getStartPos(); if (!leadingTrivia) { @@ -39359,6 +39417,8 @@ var ts; case 15 /* CloseBraceToken */: case 18 /* OpenBracketToken */: case 19 /* CloseBracketToken */: + case 16 /* OpenParenToken */: + case 17 /* CloseParenToken */: case 77 /* ElseKeyword */: case 101 /* WhileKeyword */: case 53 /* AtToken */: @@ -39483,7 +39543,7 @@ var ts; else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, startLine); + var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); } @@ -41389,6 +41449,13 @@ var ts; // after incremental parsing nameTable might not be up-to-date // drop it so it can be lazily recreated later newSourceFile.nameTable = undefined; + // dispose all resources held by old script snapshot + if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) { + if (sourceFile.scriptSnapshot.dispose) { + sourceFile.scriptSnapshot.dispose(); + } + sourceFile.scriptSnapshot = undefined; + } return newSourceFile; } } @@ -42410,15 +42477,15 @@ var ts; } function tryGetGlobalSymbols() { var objectLikeContainer; - var importClause; + var namedImportsOrExports; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); } - if (importClause = ts.getAncestor(contextToken, 220 /* ImportClause */)) { + if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { // cursor is in an import clause // try to show exported member for imported module - return tryGetImportClauseCompletionSymbols(importClause); + return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType; @@ -42426,7 +42493,7 @@ var ts; // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { - symbols = filterJsxAttributes(jsxContainer.attributes, typeChecker.getPropertiesOfType(attrsType)); + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); isMemberCompletion = true; isNewIdentifierLocation = false; return true; @@ -42487,21 +42554,11 @@ var ts; function isCompletionListBlocker(contextToken) { var start = new Date().getTime(); var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || - isIdentifierDefinitionLocation(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || isDotOfNumericLiteral(contextToken); log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); return result; } - function shouldShowCompletionsInImportsClause(node) { - if (node) { - // import {| - // import {a,| - if (node.kind === 14 /* OpenBraceToken */ || node.kind === 23 /* CommaToken */) { - return node.parent.kind === 222 /* NamedImports */; - } - } - return false; - } function isNewIdentifierDefinitionLocation(previousToken) { if (previousToken) { var containingNodeKind = previousToken.parent.kind; @@ -42610,34 +42667,37 @@ var ts; return true; } /** - * Aggregates relevant symbols for completion in import clauses; for instance, + * Aggregates relevant symbols for completion in import clauses and export clauses + * whose declarations have a module specifier; for instance, symbols will be aggregated for * - * import { $ } from "moduleName"; + * import { | } from "moduleName"; + * export { a as foo, | } from "moduleName"; + * + * but not for + * + * export { | }; * * Relevant symbols are stored in the captured 'symbols' variable. * * @returns true if 'symbols' was successfully populated; false otherwise. */ - function tryGetImportClauseCompletionSymbols(importClause) { - // cursor is in import clause - // try to show exported member for imported module - if (shouldShowCompletionsInImportsClause(contextToken)) { - isMemberCompletion = true; - isNewIdentifierLocation = false; - var importDeclaration = importClause.parent; - ts.Debug.assert(importDeclaration !== undefined && importDeclaration.kind === 219 /* ImportDeclaration */); - var exports; - var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importDeclaration.moduleSpecifier); - if (moduleSpecifierSymbol) { - exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); - } - //let exports = typeInfoResolver.getExportsOfImportDeclaration(importDeclaration); - symbols = exports ? filterModuleExports(exports, importDeclaration) : emptyArray; + function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + var declarationKind = namedImportsOrExports.kind === 222 /* NamedImports */ ? + 219 /* ImportDeclaration */ : + 225 /* ExportDeclaration */; + var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); + var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; + if (!moduleSpecifier) { + return false; } - else { - isMemberCompletion = false; - isNewIdentifierLocation = true; + isMemberCompletion = true; + isNewIdentifierLocation = false; + var exports; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); + if (moduleSpecifierSymbol) { + exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); } + symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray; return true; } /** @@ -42658,6 +42718,24 @@ var ts; } return undefined; } + /** + * Returns the containing list of named imports or exports of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetNamedImportsOrExportsForCompletion(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 14 /* OpenBraceToken */: // import { | + case 23 /* CommaToken */: + switch (contextToken.parent.kind) { + case 222 /* NamedImports */: + case 226 /* NamedExports */: + return contextToken.parent; + } + } + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent_12 = contextToken.parent; @@ -42700,7 +42778,10 @@ var ts; } return false; } - function isIdentifierDefinitionLocation(contextToken) { + /** + * @returns true if we are certain that the currently edited location must define a new location; false otherwise. + */ + function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 23 /* CommaToken */: @@ -42746,6 +42827,10 @@ var ts; case 107 /* PrivateKeyword */: case 108 /* ProtectedKeyword */: return containingNodeKind === 135 /* Parameter */; + case 113 /* AsKeyword */: + containingNodeKind === 223 /* ImportSpecifier */ || + containingNodeKind === 227 /* ExportSpecifier */ || + containingNodeKind === 221 /* NamespaceImport */; case 70 /* ClassKeyword */: case 78 /* EnumKeyword */: case 104 /* InterfaceKeyword */: @@ -42782,27 +42867,37 @@ var ts; } return false; } - function filterModuleExports(exports, importDeclaration) { - var exisingImports = {}; - if (!importDeclaration.importClause) { - return exports; + /** + * Filters out completion suggestions for named imports or exports. + * + * @param exportsOfModule The list of symbols which a module exposes. + * @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. + * + * @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports + * do not occur at the current position and have not otherwise been typed. + */ + function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { + var exisingImportsOrExports = {}; + for (var _i = 0; _i < namedImportsOrExports.length; _i++) { + var element = namedImportsOrExports[_i]; + // If this is the current item we are editing right now, do not filter it out + if (element.getStart() <= position && position <= element.getEnd()) { + continue; + } + var name_31 = element.propertyName || element.name; + exisingImportsOrExports[name_31.text] = true; } - if (importDeclaration.importClause.namedBindings && - importDeclaration.importClause.namedBindings.kind === 222 /* NamedImports */) { - ts.forEach(importDeclaration.importClause.namedBindings.elements, function (el) { - // If this is the current item we are editing right now, do not filter it out - if (el.getStart() <= position && position <= el.getEnd()) { - return; - } - var name = el.propertyName || el.name; - exisingImports[name.text] = true; - }); + if (ts.isEmpty(exisingImportsOrExports)) { + return exportsOfModule; } - if (ts.isEmpty(exisingImports)) { - return exports; - } - return ts.filter(exports, function (e) { return !ts.lookUp(exisingImports, e.name); }); + return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(exisingImportsOrExports, e.name); }); } + /** + * Filters out completion suggestions for named imports or exports. + * + * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations + * do not occur at the current position and have not otherwise been typed. + */ function filterObjectMembersList(contextualMemberSymbols, existingMembers) { if (!existingMembers || existingMembers.length === 0) { return contextualMemberSymbols; @@ -42832,15 +42927,15 @@ var ts; } existingMemberNames[existingName] = true; } - var filteredMembers = []; - ts.forEach(contextualMemberSymbols, function (s) { - if (!existingMemberNames[s.name]) { - filteredMembers.push(s); - } - }); - return filteredMembers; + return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); } - function filterJsxAttributes(attributes, symbols) { + /** + * Filters out completion suggestions from 'symbols' according to existing JSX attributes. + * + * @returns Symbols to be suggested in a JSX element, barring those whose attributes + * do not occur at the current position and have not otherwise been typed. + */ + function filterJsxAttributes(symbols, attributes) { var seenNames = {}; for (var _i = 0; _i < attributes.length; _i++) { var attr = attributes[_i]; @@ -42852,14 +42947,7 @@ var ts; seenNames[attr.name.text] = true; } } - var result = []; - for (var _a = 0; _a < symbols.length; _a++) { - var sym = symbols[_a]; - if (!seenNames[sym.name]) { - result.push(sym); - } - } - return result; + return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); } } function getCompletionsAtPosition(fileName, position) { @@ -42892,10 +42980,10 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameTable = getNameTable(sourceFile); - for (var name_31 in nameTable) { - if (!allNames[name_31]) { - allNames[name_31] = name_31; - var displayName = getCompletionEntryDisplayName(name_31, target, true); + for (var name_32 in nameTable) { + if (!allNames[name_32]) { + allNames[name_32] = name_32; + var displayName = getCompletionEntryDisplayName(name_32, target, true); if (displayName) { var entry = { name: displayName, @@ -43764,6 +43852,7 @@ var ts; if (hasKind(node.parent, 142 /* GetAccessor */) || hasKind(node.parent, 143 /* SetAccessor */)) { return getGetAndSetOccurrences(node.parent); } + break; default: if (ts.isModifier(node.kind) && node.parent && (ts.isDeclaration(node.parent) || node.parent.kind === 190 /* VariableStatement */)) { @@ -43879,12 +43968,13 @@ var ts; // Make sure we only highlight the keyword when it makes sense to do so. if (ts.isAccessibilityModifier(modifier)) { if (!(container.kind === 211 /* ClassDeclaration */ || + container.kind === 183 /* ClassExpression */ || (declaration.kind === 135 /* Parameter */ && hasKind(container, 141 /* Constructor */)))) { return undefined; } } else if (modifier === 110 /* StaticKeyword */) { - if (container.kind !== 211 /* ClassDeclaration */) { + if (!(container.kind === 211 /* ClassDeclaration */ || container.kind === 183 /* ClassExpression */)) { return undefined; } } @@ -43893,6 +43983,11 @@ var ts; return undefined; } } + else if (modifier === 112 /* AbstractKeyword */) { + if (!(container.kind === 211 /* ClassDeclaration */ || declaration.kind === 211 /* ClassDeclaration */)) { + return undefined; + } + } else { // unsupported modifier return undefined; @@ -43903,12 +43998,19 @@ var ts; switch (container.kind) { case 216 /* ModuleBlock */: case 245 /* SourceFile */: - nodes = container.statements; + // Container is either a class declaration or the declaration is a classDeclaration + if (modifierFlag & 256 /* Abstract */) { + nodes = declaration.members.concat(declaration); + } + else { + nodes = container.statements; + } break; case 141 /* Constructor */: nodes = container.parameters.concat(container.parent.members); break; case 211 /* ClassDeclaration */: + case 183 /* ClassExpression */: nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -43920,6 +44022,9 @@ var ts; nodes = nodes.concat(constructor.parameters); } } + else if (modifierFlag & 256 /* Abstract */) { + nodes = nodes.concat(container); + } break; default: ts.Debug.fail("Invalid container kind."); @@ -43944,6 +44049,8 @@ var ts; return 1 /* Export */; case 119 /* DeclareKeyword */: return 2 /* Ambient */; + case 112 /* AbstractKeyword */: + return 256 /* Abstract */; default: ts.Debug.fail(); } @@ -44761,19 +44868,19 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_32 = node.text; + var name_33 = node.text; if (contextualType) { if (contextualType.flags & 16384 /* Union */) { // This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types) // if not, search the constituent types for the property - var unionProperty = contextualType.getProperty(name_32); + var unionProperty = contextualType.getProperty(name_33); if (unionProperty) { return [unionProperty]; } else { var result_4 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_32); + var symbol = t.getProperty(name_33); if (symbol) { result_4.push(symbol); } @@ -44782,7 +44889,7 @@ var ts; } } else { - var symbol_1 = contextualType.getProperty(name_32); + var symbol_1 = contextualType.getProperty(name_33); if (symbol_1) { return [symbol_1]; } @@ -45464,7 +45571,7 @@ var ts; return; } } - return 9 /* text */; + return 2 /* identifier */; } } function processElement(element) { @@ -46760,6 +46867,13 @@ var ts; var decoded = JSON.parse(encoded); return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); }; + ScriptSnapshotShimAdapter.prototype.dispose = function () { + // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments + // 'in' does not have this effect + if ("dispose" in this.scriptSnapshotShim) { + this.scriptSnapshotShim.dispose(); + } + }; return ScriptSnapshotShimAdapter; })(); var LanguageServiceShimHostAdapter = (function () { diff --git a/bin/typescriptServices.d.ts b/bin/typescriptServices.d.ts index cea8225468b..9840a5e688f 100644 --- a/bin/typescriptServices.d.ts +++ b/bin/typescriptServices.d.ts @@ -1591,6 +1591,8 @@ declare namespace ts { * not happen and the entire document will be re - parsed. */ getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; + /** Releases all resources held by this script snapshot */ + dispose?(): void; } module ScriptSnapshot { function fromString(text: string): IScriptSnapshot; diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js index 219a0b3924f..6035d71fa2b 100644 --- a/bin/typescriptServices.js +++ b/bin/typescriptServices.js @@ -1775,8 +1775,15 @@ var ts; newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, write: function (s) { + var buffer = new Buffer(s, 'utf8'); + var offset = 0; + var toWrite = buffer.length; + var written = 0; // 1 is a standard descriptor for stdout - _fs.writeSync(1, s); + while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) { + offset += written; + toWrite -= written; + } }, readFile: readFile, writeFile: writeFile, @@ -2247,7 +2254,7 @@ var ts; Classes_containing_abstract_methods_must_be_marked_abstract: { code: 2514, category: ts.DiagnosticCategory.Error, key: "Classes containing abstract methods must be marked abstract." }, Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2: { code: 2515, category: ts.DiagnosticCategory.Error, key: "Non-abstract class '{0}' does not implement inherited abstract member '{1}' from class '{2}'." }, All_declarations_of_an_abstract_method_must_be_consecutive: { code: 2516, category: ts.DiagnosticCategory.Error, key: "All declarations of an abstract method must be consecutive." }, - Constructor_objects_of_abstract_type_cannot_be_assigned_to_constructor_objects_of_non_abstract_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Constructor objects of abstract type cannot be assigned to constructor objects of non-abstract type" }, + Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type: { code: 2517, category: ts.DiagnosticCategory.Error, key: "Cannot assign an abstract constructor type to a non-abstract constructor type." }, Only_an_ambient_class_can_be_merged_with_an_interface: { code: 2518, category: ts.DiagnosticCategory.Error, key: "Only an ambient class can be merged with an interface." }, Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: ts.DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." }, Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: ts.DiagnosticCategory.Error, key: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." }, @@ -11517,7 +11524,11 @@ var ts; } else { node.exportClause = parseNamedImportsOrExports(226 /* NamedExports */); - if (parseOptional(130 /* FromKeyword */)) { + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token === 130 /* FromKeyword */ || (token === 8 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) { + parseExpected(130 /* FromKeyword */); node.moduleSpecifier = parseModuleSpecifier(); } } @@ -16299,7 +16310,7 @@ var ts; var id = getTypeListId(elementTypes); var type = tupleTypes[id]; if (!type) { - type = tupleTypes[id] = createObjectType(8192 /* Tuple */); + type = tupleTypes[id] = createObjectType(8192 /* Tuple */ | getWideningFlagsOfTypes(elementTypes)); type.elementTypes = elementTypes; } return type; @@ -17200,10 +17211,33 @@ var ts; var targetSignatures = getSignaturesOfType(target, kind); var result = -1 /* True */; var saveErrorInfo = errorInfo; + // Because the "abstractness" of a class is the same across all construct signatures + // (internally we are checking the corresponding declaration), it is enough to perform + // the check and report an error once over all pairs of source and target construct signatures. + var sourceSig = sourceSignatures[0]; + // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. + var targetSig = targetSignatures[0]; + if (sourceSig && targetSig) { + var sourceErasedSignature = getErasedSignature(sourceSig); + var targetErasedSignature = getErasedSignature(targetSig); + var sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); + var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); + var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && ts.getDeclarationOfKind(sourceReturnType.symbol, 211 /* ClassDeclaration */); + var targetReturnDecl = targetReturnType && targetReturnType.symbol && ts.getDeclarationOfKind(targetReturnType.symbol, 211 /* ClassDeclaration */); + var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 256 /* Abstract */; + var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 256 /* Abstract */; + if (sourceIsAbstract && !targetIsAbstract) { + if (reportErrors) { + reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); + } + return 0 /* False */; + } + } outer: for (var _i = 0; _i < targetSignatures.length; _i++) { var t = targetSignatures[_i]; if (!t.hasStringLiterals || target.flags & 262144 /* FromSignature */) { var localErrors = reportErrors; + var checkedAbstractAssignability = false; for (var _a = 0; _a < sourceSignatures.length; _a++) { var s = sourceSignatures[_a]; if (!s.hasStringLiterals || source.flags & 262144 /* FromSignature */) { @@ -17254,12 +17288,12 @@ var ts; target = getErasedSignature(target); var result = -1 /* True */; for (var i = 0; i < checkCount; i++) { - var s_1 = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - var t_1 = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + var s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + var t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); var saveErrorInfo = errorInfo; - var related = isRelatedTo(s_1, t_1, reportErrors); + var related = isRelatedTo(s, t, reportErrors); if (!related) { - related = isRelatedTo(t_1, s_1, false); + related = isRelatedTo(t, s, false); if (!related) { if (reportErrors) { reportError(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, source.parameters[i < sourceMax ? i : sourceMax].name, target.parameters[i < targetMax ? i : targetMax].name); @@ -17297,11 +17331,11 @@ var ts; } return 0 /* False */; } - var t = getReturnTypeOfSignature(target); - if (t === voidType) + var targetReturnType = getReturnTypeOfSignature(target); + if (targetReturnType === voidType) return result; - var s = getReturnTypeOfSignature(source); - return result & isRelatedTo(s, t, reportErrors); + var sourceReturnType = getReturnTypeOfSignature(source); + return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); } function signaturesIdenticalTo(source, target, kind) { var sourceSignatures = getSignaturesOfType(source, kind); @@ -17537,7 +17571,7 @@ var ts; * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ function isTupleType(type) { - return (type.flags & 8192 /* Tuple */) && !!type.elementTypes; + return !!(type.flags & 8192 /* Tuple */); } function getWidenedTypeOfObjectLiteral(type) { var properties = getPropertiesOfObjectType(type); @@ -17579,25 +17613,47 @@ var ts; if (isArrayType(type)) { return createArrayType(getWidenedType(type.typeArguments[0])); } + if (isTupleType(type)) { + return createTupleType(ts.map(type.elementTypes, getWidenedType)); + } } return type; } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ function reportWideningErrorsInType(type) { + var errorReported = false; if (type.flags & 16384 /* Union */) { - var errorReported = false; - ts.forEach(type.types, function (t) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; if (reportWideningErrorsInType(t)) { errorReported = true; } - }); - return errorReported; + } } if (isArrayType(type)) { return reportWideningErrorsInType(type.typeArguments[0]); } + if (isTupleType(type)) { + for (var _b = 0, _c = type.elementTypes; _b < _c.length; _b++) { + var t = _c[_b]; + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } if (type.flags & 524288 /* ObjectLiteral */) { - var errorReported = false; - ts.forEach(getPropertiesOfObjectType(type), function (p) { + for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) { + var p = _e[_d]; var t = getTypeOfSymbol(p); if (t.flags & 1048576 /* ContainsUndefinedOrNull */) { if (!reportWideningErrorsInType(t)) { @@ -17605,10 +17661,9 @@ var ts; } errorReported = true; } - }); - return errorReported; + } } - return false; + return errorReported; } function reportImplicitAnyError(declaration, type) { var typeAsString = typeToString(getWidenedType(type)); @@ -17771,29 +17826,32 @@ var ts; inferFromTypes(sourceType, target); } } - else if (source.flags & 80896 /* ObjectType */ && (target.flags & (4096 /* Reference */ | 8192 /* Tuple */) || - (target.flags & 65536 /* Anonymous */) && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { - // If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members - if (isInProcess(source, target)) { - return; + else { + source = getApparentType(source); + if (source.flags & 80896 /* ObjectType */ && (target.flags & (4096 /* Reference */ | 8192 /* Tuple */) || + (target.flags & 65536 /* Anonymous */) && target.symbol && target.symbol.flags & (8192 /* Method */ | 2048 /* TypeLiteral */ | 32 /* Class */))) { + // If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members + if (isInProcess(source, target)) { + return; + } + if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { + return; + } + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, 0 /* Call */); + inferFromSignatures(source, target, 1 /* Construct */); + inferFromIndexTypes(source, target, 0 /* String */, 0 /* String */); + inferFromIndexTypes(source, target, 1 /* Number */, 1 /* Number */); + inferFromIndexTypes(source, target, 0 /* String */, 1 /* Number */); + depth--; } - if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { - return; - } - if (depth === 0) { - sourceStack = []; - targetStack = []; - } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, 0 /* Call */); - inferFromSignatures(source, target, 1 /* Construct */); - inferFromIndexTypes(source, target, 0 /* String */, 0 /* String */); - inferFromIndexTypes(source, target, 1 /* Number */, 1 /* Number */); - inferFromIndexTypes(source, target, 0 /* String */, 1 /* Number */); - depth--; } } function inferFromProperties(source, target) { @@ -37768,8 +37826,8 @@ var ts; var pos = scanner.getStartPos(); // Read leading trivia and token while (pos < endPos) { - var t_2 = scanner.getToken(); - if (!ts.isTrivia(t_2)) { + var t_1 = scanner.getToken(); + if (!ts.isTrivia(t_1)) { break; } // consume leading trivia @@ -37777,7 +37835,7 @@ var ts; var item = { pos: pos, end: scanner.getStartPos(), - kind: t_2 + kind: t_1 }; pos = scanner.getStartPos(); if (!leadingTrivia) { @@ -39359,6 +39417,8 @@ var ts; case 15 /* CloseBraceToken */: case 18 /* OpenBracketToken */: case 19 /* CloseBracketToken */: + case 16 /* OpenParenToken */: + case 17 /* CloseParenToken */: case 77 /* ElseKeyword */: case 101 /* WhileKeyword */: case 53 /* AtToken */: @@ -39483,7 +39543,7 @@ var ts; else if (tokenInfo.token.kind === listStartToken) { // consume list start token startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; - var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, startLine); + var indentation_1 = computeIndentation(tokenInfo.token, startLine, -1 /* Unknown */, parent, parentDynamicIndentation, parentStartLine); listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentation_1.indentation, indentation_1.delta); consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); } @@ -41389,6 +41449,13 @@ var ts; // after incremental parsing nameTable might not be up-to-date // drop it so it can be lazily recreated later newSourceFile.nameTable = undefined; + // dispose all resources held by old script snapshot + if (sourceFile !== newSourceFile && sourceFile.scriptSnapshot) { + if (sourceFile.scriptSnapshot.dispose) { + sourceFile.scriptSnapshot.dispose(); + } + sourceFile.scriptSnapshot = undefined; + } return newSourceFile; } } @@ -42410,15 +42477,15 @@ var ts; } function tryGetGlobalSymbols() { var objectLikeContainer; - var importClause; + var namedImportsOrExports; var jsxContainer; if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) { return tryGetObjectLikeCompletionSymbols(objectLikeContainer); } - if (importClause = ts.getAncestor(contextToken, 220 /* ImportClause */)) { + if (namedImportsOrExports = tryGetNamedImportsOrExportsForCompletion(contextToken)) { // cursor is in an import clause // try to show exported member for imported module - return tryGetImportClauseCompletionSymbols(importClause); + return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } if (jsxContainer = tryGetContainingJsxElement(contextToken)) { var attrsType; @@ -42426,7 +42493,7 @@ var ts; // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); if (attrsType) { - symbols = filterJsxAttributes(jsxContainer.attributes, typeChecker.getPropertiesOfType(attrsType)); + symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); isMemberCompletion = true; isNewIdentifierLocation = false; return true; @@ -42487,21 +42554,11 @@ var ts; function isCompletionListBlocker(contextToken) { var start = new Date().getTime(); var result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) || - isIdentifierDefinitionLocation(contextToken) || + isSolelyIdentifierDefinitionLocation(contextToken) || isDotOfNumericLiteral(contextToken); log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start)); return result; } - function shouldShowCompletionsInImportsClause(node) { - if (node) { - // import {| - // import {a,| - if (node.kind === 14 /* OpenBraceToken */ || node.kind === 23 /* CommaToken */) { - return node.parent.kind === 222 /* NamedImports */; - } - } - return false; - } function isNewIdentifierDefinitionLocation(previousToken) { if (previousToken) { var containingNodeKind = previousToken.parent.kind; @@ -42610,34 +42667,37 @@ var ts; return true; } /** - * Aggregates relevant symbols for completion in import clauses; for instance, + * Aggregates relevant symbols for completion in import clauses and export clauses + * whose declarations have a module specifier; for instance, symbols will be aggregated for * - * import { $ } from "moduleName"; + * import { | } from "moduleName"; + * export { a as foo, | } from "moduleName"; + * + * but not for + * + * export { | }; * * Relevant symbols are stored in the captured 'symbols' variable. * * @returns true if 'symbols' was successfully populated; false otherwise. */ - function tryGetImportClauseCompletionSymbols(importClause) { - // cursor is in import clause - // try to show exported member for imported module - if (shouldShowCompletionsInImportsClause(contextToken)) { - isMemberCompletion = true; - isNewIdentifierLocation = false; - var importDeclaration = importClause.parent; - ts.Debug.assert(importDeclaration !== undefined && importDeclaration.kind === 219 /* ImportDeclaration */); - var exports; - var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importDeclaration.moduleSpecifier); - if (moduleSpecifierSymbol) { - exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); - } - //let exports = typeInfoResolver.getExportsOfImportDeclaration(importDeclaration); - symbols = exports ? filterModuleExports(exports, importDeclaration) : emptyArray; + function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports) { + var declarationKind = namedImportsOrExports.kind === 222 /* NamedImports */ ? + 219 /* ImportDeclaration */ : + 225 /* ExportDeclaration */; + var importOrExportDeclaration = ts.getAncestor(namedImportsOrExports, declarationKind); + var moduleSpecifier = importOrExportDeclaration.moduleSpecifier; + if (!moduleSpecifier) { + return false; } - else { - isMemberCompletion = false; - isNewIdentifierLocation = true; + isMemberCompletion = true; + isNewIdentifierLocation = false; + var exports; + var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier); + if (moduleSpecifierSymbol) { + exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol); } + symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray; return true; } /** @@ -42658,6 +42718,24 @@ var ts; } return undefined; } + /** + * Returns the containing list of named imports or exports of a context token, + * on the condition that one exists and that the context implies completion should be given. + */ + function tryGetNamedImportsOrExportsForCompletion(contextToken) { + if (contextToken) { + switch (contextToken.kind) { + case 14 /* OpenBraceToken */: // import { | + case 23 /* CommaToken */: + switch (contextToken.parent.kind) { + case 222 /* NamedImports */: + case 226 /* NamedExports */: + return contextToken.parent; + } + } + } + return undefined; + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent_12 = contextToken.parent; @@ -42700,7 +42778,10 @@ var ts; } return false; } - function isIdentifierDefinitionLocation(contextToken) { + /** + * @returns true if we are certain that the currently edited location must define a new location; false otherwise. + */ + function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { case 23 /* CommaToken */: @@ -42746,6 +42827,10 @@ var ts; case 107 /* PrivateKeyword */: case 108 /* ProtectedKeyword */: return containingNodeKind === 135 /* Parameter */; + case 113 /* AsKeyword */: + containingNodeKind === 223 /* ImportSpecifier */ || + containingNodeKind === 227 /* ExportSpecifier */ || + containingNodeKind === 221 /* NamespaceImport */; case 70 /* ClassKeyword */: case 78 /* EnumKeyword */: case 104 /* InterfaceKeyword */: @@ -42782,27 +42867,37 @@ var ts; } return false; } - function filterModuleExports(exports, importDeclaration) { - var exisingImports = {}; - if (!importDeclaration.importClause) { - return exports; + /** + * Filters out completion suggestions for named imports or exports. + * + * @param exportsOfModule The list of symbols which a module exposes. + * @param namedImportsOrExports The list of existing import/export specifiers in the import/export clause. + * + * @returns Symbols to be suggested at an import/export clause, barring those whose named imports/exports + * do not occur at the current position and have not otherwise been typed. + */ + function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { + var exisingImportsOrExports = {}; + for (var _i = 0; _i < namedImportsOrExports.length; _i++) { + var element = namedImportsOrExports[_i]; + // If this is the current item we are editing right now, do not filter it out + if (element.getStart() <= position && position <= element.getEnd()) { + continue; + } + var name_31 = element.propertyName || element.name; + exisingImportsOrExports[name_31.text] = true; } - if (importDeclaration.importClause.namedBindings && - importDeclaration.importClause.namedBindings.kind === 222 /* NamedImports */) { - ts.forEach(importDeclaration.importClause.namedBindings.elements, function (el) { - // If this is the current item we are editing right now, do not filter it out - if (el.getStart() <= position && position <= el.getEnd()) { - return; - } - var name = el.propertyName || el.name; - exisingImports[name.text] = true; - }); + if (ts.isEmpty(exisingImportsOrExports)) { + return exportsOfModule; } - if (ts.isEmpty(exisingImports)) { - return exports; - } - return ts.filter(exports, function (e) { return !ts.lookUp(exisingImports, e.name); }); + return ts.filter(exportsOfModule, function (e) { return !ts.lookUp(exisingImportsOrExports, e.name); }); } + /** + * Filters out completion suggestions for named imports or exports. + * + * @returns Symbols to be suggested in an object binding pattern or object literal expression, barring those whose declarations + * do not occur at the current position and have not otherwise been typed. + */ function filterObjectMembersList(contextualMemberSymbols, existingMembers) { if (!existingMembers || existingMembers.length === 0) { return contextualMemberSymbols; @@ -42832,15 +42927,15 @@ var ts; } existingMemberNames[existingName] = true; } - var filteredMembers = []; - ts.forEach(contextualMemberSymbols, function (s) { - if (!existingMemberNames[s.name]) { - filteredMembers.push(s); - } - }); - return filteredMembers; + return ts.filter(contextualMemberSymbols, function (m) { return !ts.lookUp(existingMemberNames, m.name); }); } - function filterJsxAttributes(attributes, symbols) { + /** + * Filters out completion suggestions from 'symbols' according to existing JSX attributes. + * + * @returns Symbols to be suggested in a JSX element, barring those whose attributes + * do not occur at the current position and have not otherwise been typed. + */ + function filterJsxAttributes(symbols, attributes) { var seenNames = {}; for (var _i = 0; _i < attributes.length; _i++) { var attr = attributes[_i]; @@ -42852,14 +42947,7 @@ var ts; seenNames[attr.name.text] = true; } } - var result = []; - for (var _a = 0; _a < symbols.length; _a++) { - var sym = symbols[_a]; - if (!seenNames[sym.name]) { - result.push(sym); - } - } - return result; + return ts.filter(symbols, function (a) { return !ts.lookUp(seenNames, a.name); }); } } function getCompletionsAtPosition(fileName, position) { @@ -42892,10 +42980,10 @@ var ts; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; var nameTable = getNameTable(sourceFile); - for (var name_31 in nameTable) { - if (!allNames[name_31]) { - allNames[name_31] = name_31; - var displayName = getCompletionEntryDisplayName(name_31, target, true); + for (var name_32 in nameTable) { + if (!allNames[name_32]) { + allNames[name_32] = name_32; + var displayName = getCompletionEntryDisplayName(name_32, target, true); if (displayName) { var entry = { name: displayName, @@ -43764,6 +43852,7 @@ var ts; if (hasKind(node.parent, 142 /* GetAccessor */) || hasKind(node.parent, 143 /* SetAccessor */)) { return getGetAndSetOccurrences(node.parent); } + break; default: if (ts.isModifier(node.kind) && node.parent && (ts.isDeclaration(node.parent) || node.parent.kind === 190 /* VariableStatement */)) { @@ -43879,12 +43968,13 @@ var ts; // Make sure we only highlight the keyword when it makes sense to do so. if (ts.isAccessibilityModifier(modifier)) { if (!(container.kind === 211 /* ClassDeclaration */ || + container.kind === 183 /* ClassExpression */ || (declaration.kind === 135 /* Parameter */ && hasKind(container, 141 /* Constructor */)))) { return undefined; } } else if (modifier === 110 /* StaticKeyword */) { - if (container.kind !== 211 /* ClassDeclaration */) { + if (!(container.kind === 211 /* ClassDeclaration */ || container.kind === 183 /* ClassExpression */)) { return undefined; } } @@ -43893,6 +43983,11 @@ var ts; return undefined; } } + else if (modifier === 112 /* AbstractKeyword */) { + if (!(container.kind === 211 /* ClassDeclaration */ || declaration.kind === 211 /* ClassDeclaration */)) { + return undefined; + } + } else { // unsupported modifier return undefined; @@ -43903,12 +43998,19 @@ var ts; switch (container.kind) { case 216 /* ModuleBlock */: case 245 /* SourceFile */: - nodes = container.statements; + // Container is either a class declaration or the declaration is a classDeclaration + if (modifierFlag & 256 /* Abstract */) { + nodes = declaration.members.concat(declaration); + } + else { + nodes = container.statements; + } break; case 141 /* Constructor */: nodes = container.parameters.concat(container.parent.members); break; case 211 /* ClassDeclaration */: + case 183 /* ClassExpression */: nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. @@ -43920,6 +44022,9 @@ var ts; nodes = nodes.concat(constructor.parameters); } } + else if (modifierFlag & 256 /* Abstract */) { + nodes = nodes.concat(container); + } break; default: ts.Debug.fail("Invalid container kind."); @@ -43944,6 +44049,8 @@ var ts; return 1 /* Export */; case 119 /* DeclareKeyword */: return 2 /* Ambient */; + case 112 /* AbstractKeyword */: + return 256 /* Abstract */; default: ts.Debug.fail(); } @@ -44761,19 +44868,19 @@ var ts; if (isNameOfPropertyAssignment(node)) { var objectLiteral = node.parent.parent; var contextualType = typeChecker.getContextualType(objectLiteral); - var name_32 = node.text; + var name_33 = node.text; if (contextualType) { if (contextualType.flags & 16384 /* Union */) { // This is a union type, first see if the property we are looking for is a union property (i.e. exists in all types) // if not, search the constituent types for the property - var unionProperty = contextualType.getProperty(name_32); + var unionProperty = contextualType.getProperty(name_33); if (unionProperty) { return [unionProperty]; } else { var result_4 = []; ts.forEach(contextualType.types, function (t) { - var symbol = t.getProperty(name_32); + var symbol = t.getProperty(name_33); if (symbol) { result_4.push(symbol); } @@ -44782,7 +44889,7 @@ var ts; } } else { - var symbol_1 = contextualType.getProperty(name_32); + var symbol_1 = contextualType.getProperty(name_33); if (symbol_1) { return [symbol_1]; } @@ -45464,7 +45571,7 @@ var ts; return; } } - return 9 /* text */; + return 2 /* identifier */; } } function processElement(element) { @@ -46760,6 +46867,13 @@ var ts; var decoded = JSON.parse(encoded); return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); }; + ScriptSnapshotShimAdapter.prototype.dispose = function () { + // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments + // 'in' does not have this effect + if ("dispose" in this.scriptSnapshotShim) { + this.scriptSnapshotShim.dispose(); + } + }; return ScriptSnapshotShimAdapter; })(); var LanguageServiceShimHostAdapter = (function () { diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index e839d6d6c9a..e842f9a4040 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -518,15 +518,21 @@ namespace ts { } else { declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes); - - let currentModuleIsConstEnumOnly = state === ModuleInstanceState.ConstEnumOnly; - if (node.symbol.constEnumOnlyModule === undefined) { - // non-merged case - use the current state - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; + if (node.symbol.flags & (SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.RegularEnum)) { + // if module was already merged with some function, class or non-const enum + // treat is a non-const-enum-only + node.symbol.constEnumOnlyModule = false; } else { - // merged case: module is const enum only if all its pieces are non-instantiated or const enum - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; + let currentModuleIsConstEnumOnly = state === ModuleInstanceState.ConstEnumOnly; + if (node.symbol.constEnumOnlyModule === undefined) { + // non-merged case - use the current state + node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; + } + else { + // merged case: module is const enum only if all its pieces are non-instantiated or const enum + node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; + } } } } @@ -1056,4 +1062,4 @@ namespace ts { : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } } -} +} diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0cd41a2a02b..83581be5552 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -59,7 +59,10 @@ namespace ts { isArgumentsSymbol: symbol => symbol === argumentsSymbol, getDiagnostics, getGlobalDiagnostics, - getTypeOfSymbolAtLocation, + + // The language service will always care about the narrowed type of a symbol, because that is + // the type the language says the symbol should have. + getTypeOfSymbolAtLocation: getNarrowedTypeOfSymbol, getDeclaredTypeOfSymbol, getPropertiesOfType, getPropertyOfType, @@ -69,7 +72,7 @@ namespace ts { getSymbolsInScope, getSymbolAtLocation, getShorthandAssignmentValueSymbol, - getTypeAtLocation, + getTypeAtLocation: getTypeOfNode, typeToString, getSymbolDisplayBuilder, symbolToString, @@ -159,8 +162,9 @@ namespace ts { let emitAwaiter = false; let emitGenerator = false; - let resolutionTargets: Object[] = []; + let resolutionTargets: TypeSystemEntity[] = []; let resolutionResults: boolean[] = []; + let resolutionPropertyNames: TypeSystemPropertyName[] = []; let mergedSymbols: Symbol[] = []; let symbolLinks: SymbolLinks[] = []; @@ -201,6 +205,15 @@ namespace ts { let assignableRelation: Map = {}; let identityRelation: Map = {}; + type TypeSystemEntity = Symbol | Type | Signature; + + const enum TypeSystemPropertyName { + Type, + ResolvedBaseConstructorType, + DeclaredType, + ResolvedReturnType + } + initializeTypeChecker(); return checker; @@ -1980,15 +1993,12 @@ namespace ts { } return _displayBuilder || (_displayBuilder = { - symbolToString: symbolToString, - typeToString: typeToString, buildSymbolDisplay: buildSymbolDisplay, buildTypeDisplay: buildTypeDisplay, buildTypeParameterDisplay: buildTypeParameterDisplay, buildParameterDisplay: buildParameterDisplay, buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildDisplayForTypeArgumentsAndDelimiters: buildDisplayForTypeArgumentsAndDelimiters, buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, buildSignatureDisplay: buildSignatureDisplay, buildReturnTypeDisplay: buildReturnTypeDisplay @@ -2177,35 +2187,69 @@ namespace ts { } } - // Push an entry on the type resolution stack. If an entry with the given target is not already on the stack, - // a new entry with that target and an associated result value of true is pushed on the stack, and the value - // true is returned. Otherwise, a circularity has occurred and the result values of the existing entry and - // all entries pushed after it are changed to false, and the value false is returned. The target object provides - // a unique identity for a particular type resolution result: Symbol instances are used to track resolution of - // SymbolLinks.type, SymbolLinks instances are used to track resolution of SymbolLinks.declaredType, and - // Signature instances are used to track resolution of Signature.resolvedReturnType. - function pushTypeResolution(target: Object): boolean { - let i = 0; - let count = resolutionTargets.length; - while (i < count && resolutionTargets[i] !== target) { - i++; - } - if (i < count) { - do { - resolutionResults[i++] = false; + /** + * Push an entry on the type resolution stack. If an entry with the given target and the given property name + * is already on the stack, and no entries in between already have a type, then a circularity has occurred. + * In this case, the result values of the existing entry and all entries pushed after it are changed to false, + * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned. + * In order to see if the same query has already been done before, the target object and the propertyName both + * must match the one passed in. + * + * @param target The symbol, type, or signature whose type is being queried + * @param propertyName The property name that should be used to query the target for its type + */ + function pushTypeResolution(target: TypeSystemEntity, propertyName: TypeSystemPropertyName): boolean { + let resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + if (resolutionCycleStartIndex >= 0) { + // A cycle was found + let { length } = resolutionTargets; + for (let i = resolutionCycleStartIndex; i < length; i++) { + resolutionResults[i] = false; } - while (i < count); return false; } resolutionTargets.push(target); resolutionResults.push(true); + resolutionPropertyNames.push(propertyName); return true; } + function findResolutionCycleStartIndex(target: TypeSystemEntity, propertyName: TypeSystemPropertyName): number { + for (let i = resolutionTargets.length - 1; i >= 0; i--) { + if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) { + return -1; + } + if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) { + return i; + } + } + + return -1; + } + + function hasType(target: TypeSystemEntity, propertyName: TypeSystemPropertyName): Type { + if (propertyName === TypeSystemPropertyName.Type) { + return getSymbolLinks(target).type; + } + if (propertyName === TypeSystemPropertyName.DeclaredType) { + return getSymbolLinks(target).declaredType; + } + if (propertyName === TypeSystemPropertyName.ResolvedBaseConstructorType) { + Debug.assert(!!((target).flags & TypeFlags.Class)); + return (target).resolvedBaseConstructorType; + } + if (propertyName === TypeSystemPropertyName.ResolvedReturnType) { + return (target).resolvedReturnType; + } + + Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); + } + // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. function popTypeResolution(): boolean { resolutionTargets.pop(); + resolutionPropertyNames.pop(); return resolutionResults.pop(); } @@ -2274,10 +2318,6 @@ namespace ts { // fact an iterable or array (depending on target language). let elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false); if (!declaration.dotDotDotToken) { - if (isTypeAny(elementType)) { - return elementType; - } - // Use specific property type when parent is a tuple or numeric index type when parent is an array let propName = "" + indexOf(pattern.elements, declaration); type = isTupleLikeType(parentType) @@ -2307,6 +2347,7 @@ namespace ts { if (declaration.parent.parent.kind === SyntaxKind.ForInStatement) { return anyType; } + if (declaration.parent.parent.kind === SyntaxKind.ForOfStatement) { // checkRightHandSideOfForOf will return undefined if the for-of expression type was // missing properties/signatures required to get its iteratedType (like @@ -2314,13 +2355,16 @@ namespace ts { // or it may have led to an error inside getElementTypeOfIterable. return checkRightHandSideOfForOf((declaration.parent.parent).expression) || anyType; } + if (isBindingPattern(declaration.parent)) { return getTypeForBindingElement(declaration); } + // Use type from type annotation if one is present if (declaration.type) { return getTypeFromTypeNode(declaration.type); } + if (declaration.kind === SyntaxKind.Parameter) { let func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present @@ -2336,14 +2380,22 @@ namespace ts { return type; } } + // Use the type of the initializer expression if one is present if (declaration.initializer) { return checkExpressionCached(declaration.initializer); } + // If it is a short-hand property assignment, use the type of the identifier if (declaration.kind === SyntaxKind.ShorthandPropertyAssignment) { return checkIdentifier(declaration.name); } + + // If the declaration specifies a binding pattern, use the type implied by the binding pattern + if (isBindingPattern(declaration.name)) { + return getTypeFromBindingPattern(declaration.name); + } + // No type specified and nothing can be inferred return undefined; } @@ -2429,13 +2481,10 @@ namespace ts { // tools see the actual type. return declaration.kind !== SyntaxKind.PropertyAssignment ? getWidenedType(type) : type; } - // If no type was specified and nothing could be inferred, and if the declaration specifies a binding pattern, use - // the type implied by the binding pattern - if (isBindingPattern(declaration.name)) { - return getTypeFromBindingPattern(declaration.name); - } + // Rest parameters default to type any[], other parameters default to type any type = declaration.dotDotDotToken ? anyArrayType : anyType; + // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && compilerOptions.noImplicitAny) { let root = getRootDeclaration(declaration); @@ -2463,7 +2512,7 @@ namespace ts { return links.type = checkExpression((declaration).expression); } // Handle variable, parameter or property - if (!pushTypeResolution(symbol)) { + if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { return unknownType; } let type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); @@ -2504,7 +2553,7 @@ namespace ts { function getTypeOfAccessors(symbol: Symbol): Type { let links = getSymbolLinks(symbol); if (!links.type) { - if (!pushTypeResolution(symbol)) { + if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { return unknownType; } let getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); @@ -2720,7 +2769,7 @@ namespace ts { if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; } - if (!pushTypeResolution(type)) { + if (!pushTypeResolution(type, TypeSystemPropertyName.ResolvedBaseConstructorType)) { return unknownType; } let baseConstructorType = checkExpression(baseTypeNode.expression); @@ -2847,7 +2896,7 @@ namespace ts { if (!links.declaredType) { // Note that we use the links object as the target here because the symbol object is used as the unique // identity for resolution of the 'type' property in SymbolLinks. - if (!pushTypeResolution(links)) { + if (!pushTypeResolution(symbol, TypeSystemPropertyName.DeclaredType)) { return unknownType; } let declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); @@ -3063,44 +3112,57 @@ namespace ts { setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); } - function signatureListsIdentical(s: Signature[], t: Signature[]): boolean { - if (s.length !== t.length) { - return false; - } - for (let i = 0; i < s.length; i++) { - if (!compareSignatures(s[i], t[i], /*compareReturnTypes*/ false, compareTypes)) { - return false; + function findMatchingSignature(signature: Signature, signatureList: Signature[]): Signature { + for (let s of signatureList) { + // Only signatures with no type parameters may differ in return types + if (compareSignatures(signature, s, /*compareReturnTypes*/ !!signature.typeParameters, compareTypes)) { + return s; } } - return true; } - // If the lists of call or construct signatures in the given types are all identical except for return types, - // and if none of the signatures are generic, return a list of signatures that has substitutes a union of the - // return types of the corresponding signatures in each resulting signature. - function getUnionSignatures(types: Type[], kind: SignatureKind): Signature[] { - let signatureLists = map(types, t => getSignaturesOfType(t, kind)); - let signatures = signatureLists[0]; - for (let signature of signatures) { - if (signature.typeParameters) { - return emptyArray; - } - } + function findMatchingSignatures(signature: Signature, signatureLists: Signature[][]): Signature[] { + let result: Signature[] = undefined; for (let i = 1; i < signatureLists.length; i++) { - if (!signatureListsIdentical(signatures, signatureLists[i])) { - return emptyArray; + let match = findMatchingSignature(signature, signatureLists[i]); + if (!match) { + return undefined; + } + if (!result) { + result = [signature]; + } + if (match !== signature) { + result.push(match); } - } - let result = map(signatures, cloneSignature); - for (var i = 0; i < result.length; i++) { - let s = result[i]; - // Clear resolved return type we possibly got from cloneSignature - s.resolvedReturnType = undefined; - s.unionSignatures = map(signatureLists, signatures => signatures[i]); } return result; } + // The signatures of a union type are those signatures that are present and identical in each of the + // constituent types, except that non-generic signatures may differ in return types. When signatures + // differ in return types, the resulting return type is the union of the constituent return types. + function getUnionSignatures(types: Type[], kind: SignatureKind): Signature[] { + let signatureLists = map(types, t => getSignaturesOfType(t, kind)); + let result: Signature[] = undefined; + for (let source of signatureLists[0]) { + let unionSignatures = findMatchingSignatures(source, signatureLists); + if (unionSignatures) { + let signature: Signature = undefined; + if (unionSignatures.length === 1 || source.typeParameters) { + signature = source; + } + else { + signature = cloneSignature(source); + // Clear resolved return type we possibly got from cloneSignature + signature.resolvedReturnType = undefined; + signature.unionSignatures = unionSignatures; + } + (result || (result = [])).push(signature); + } + } + return result || emptyArray; + } + function getUnionIndexType(types: Type[], kind: IndexKind): Type { let indexTypes: Type[] = []; for (let type of types) { @@ -3258,9 +3320,6 @@ namespace ts { * type itself. Note that the apparent type of a union type is the union type itself. */ function getApparentType(type: Type): Type { - if (type.flags & TypeFlags.Union) { - type = getReducedTypeOfUnionType(type); - } if (type.flags & TypeFlags.TypeParameter) { do { type = getConstraintOfTypeParameter(type); @@ -3365,6 +3424,29 @@ namespace ts { return undefined; } + // Check if a property with the given name is known anywhere in the given type. In an object + // type, a property is considered known if the object type is empty, if it has any index + // signatures, or if the property is actually declared in the type. In a union or intersection + // type, a property is considered known if it is known in any constituent type. + function isKnownProperty(type: Type, name: string): boolean { + if (type.flags & TypeFlags.ObjectType && type !== globalObjectType) { + var resolved = resolveStructuredTypeMembers(type); + return !!(resolved.properties.length === 0 || + resolved.stringIndexType || + resolved.numberIndexType || + getPropertyOfType(type, name)); + } + if (type.flags & TypeFlags.UnionOrIntersection) { + for (let t of (type).types) { + if (isKnownProperty(t, name)) { + return true; + } + } + return false; + } + return true; + } + function getSignaturesOfStructuredType(type: Type, kind: SignatureKind): Signature[] { if (type.flags & TypeFlags.StructuredType) { let resolved = resolveStructuredTypeMembers(type); @@ -3534,7 +3616,7 @@ namespace ts { function getReturnTypeOfSignature(signature: Signature): Type { if (!signature.resolvedReturnType) { - if (!pushTypeResolution(signature)) { + if (!pushTypeResolution(signature, TypeSystemPropertyName.ResolvedReturnType)) { return unknownType; } let type: Type; @@ -3943,7 +4025,7 @@ namespace ts { let id = getTypeListId(elementTypes); let type = tupleTypes[id]; if (!type) { - type = tupleTypes[id] = createObjectType(TypeFlags.Tuple); + type = tupleTypes[id] = createObjectType(TypeFlags.Tuple | getWideningFlagsOfTypes(elementTypes)); type.elementTypes = elementTypes; } return type; @@ -3974,26 +4056,79 @@ namespace ts { } } - function isSubtypeOfAny(candidate: Type, types: Type[]): boolean { + function isObjectLiteralTypeDuplicateOf(source: ObjectType, target: ObjectType): boolean { + let sourceProperties = getPropertiesOfObjectType(source); + let targetProperties = getPropertiesOfObjectType(target); + if (sourceProperties.length !== targetProperties.length) { + return false; + } + for (let sourceProp of sourceProperties) { + let targetProp = getPropertyOfObjectType(target, sourceProp.name); + if (!targetProp || + getDeclarationFlagsFromSymbol(targetProp) & (NodeFlags.Private | NodeFlags.Protected) || + !isTypeDuplicateOf(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp))) { + return false; + } + } + return true; + } + + function isTupleTypeDuplicateOf(source: TupleType, target: TupleType): boolean { + let sourceTypes = source.elementTypes; + let targetTypes = target.elementTypes; + if (sourceTypes.length !== targetTypes.length) { + return false; + } + for (var i = 0; i < sourceTypes.length; i++) { + if (!isTypeDuplicateOf(sourceTypes[i], targetTypes[i])) { + return false; + } + } + return true; + } + + // Returns true if the source type is a duplicate of the target type. A source type is a duplicate of + // a target type if the the two are identical, with the exception that the source type may have null or + // undefined in places where the target type doesn't. This is by design an asymmetric relationship. + function isTypeDuplicateOf(source: Type, target: Type): boolean { + if (source === target) { + return true; + } + if (source.flags & TypeFlags.Undefined || source.flags & TypeFlags.Null && !(target.flags & TypeFlags.Undefined)) { + return true; + } + if (source.flags & TypeFlags.ObjectLiteral && target.flags & TypeFlags.ObjectType) { + return isObjectLiteralTypeDuplicateOf(source, target); + } + if (isArrayType(source) && isArrayType(target)) { + return isTypeDuplicateOf((source).typeArguments[0], (target).typeArguments[0]); + } + if (isTupleType(source) && isTupleType(target)) { + return isTupleTypeDuplicateOf(source, target); + } + return isTypeIdenticalTo(source, target); + } + + function isTypeDuplicateOfSomeType(candidate: Type, types: Type[]): boolean { for (let type of types) { - if (candidate !== type && isTypeSubtypeOf(candidate, type)) { + if (candidate !== type && isTypeDuplicateOf(candidate, type)) { return true; } } return false; } - function removeSubtypes(types: Type[]) { + function removeDuplicateTypes(types: Type[]) { let i = types.length; while (i > 0) { i--; - if (isSubtypeOfAny(types[i], types)) { + if (isTypeDuplicateOfSomeType(types[i], types)) { types.splice(i, 1); } } } - function containsTypeAny(types: Type[]) { + function containsTypeAny(types: Type[]): boolean { for (let type of types) { if (isTypeAny(type)) { return true; @@ -4012,30 +4147,26 @@ namespace ts { } } - function compareTypeIds(type1: Type, type2: Type): number { - return type1.id - type2.id; - } - - // The noSubtypeReduction flag is there because it isn't possible to always do subtype reduction. The flag - // is true when creating a union type from a type node and when instantiating a union type. In both of those - // cases subtype reduction has to be deferred to properly support recursive union types. For example, a - // type alias of the form "type Item = string | (() => Item)" cannot be reduced during its declaration. - function getUnionType(types: Type[], noSubtypeReduction?: boolean): Type { + // We always deduplicate the constituent type set based on object identity, but we'll also deduplicate + // based on the structure of the types unless the noDeduplication flag is true, which is the case when + // creating a union type from a type node and when instantiating a union type. In both of those cases, + // structural deduplication has to be deferred to properly support recursive union types. For example, + // a type of the form "type Item = string | (() => Item)" cannot be deduplicated during its declaration. + function getUnionType(types: Type[], noDeduplication?: boolean): Type { if (types.length === 0) { return emptyObjectType; } let typeSet: Type[] = []; addTypesToSet(typeSet, types, TypeFlags.Union); - typeSet.sort(compareTypeIds); - if (noSubtypeReduction) { - if (containsTypeAny(typeSet)) { - return anyType; - } + if (containsTypeAny(typeSet)) { + return anyType; + } + if (noDeduplication) { removeAllButLast(typeSet, undefinedType); removeAllButLast(typeSet, nullType); } else { - removeSubtypes(typeSet); + removeDuplicateTypes(typeSet); } if (typeSet.length === 1) { return typeSet[0]; @@ -4045,38 +4176,19 @@ namespace ts { if (!type) { type = unionTypes[id] = createObjectType(TypeFlags.Union | getWideningFlagsOfTypes(typeSet)); type.types = typeSet; - type.reducedType = noSubtypeReduction ? undefined : type; } return type; } - // Subtype reduction is basically an optimization we do to avoid excessively large union types, which take longer - // to process and look strange in quick info and error messages. Semantically there is no difference between the - // reduced type and the type itself. So, when we detect a circularity we simply say that the reduced type is the - // type itself. - function getReducedTypeOfUnionType(type: UnionType): Type { - if (!type.reducedType) { - type.reducedType = circularType; - let reducedType = getUnionType(type.types, /*noSubtypeReduction*/ false); - if (type.reducedType === circularType) { - type.reducedType = reducedType; - } - } - else if (type.reducedType === circularType) { - type.reducedType = type; - } - return type.reducedType; - } - function getTypeFromUnionTypeNode(node: UnionTypeNode): Type { let links = getNodeLinks(node); if (!links.resolvedType) { - links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), /*noSubtypeReduction*/ true); + links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), /*noDeduplication*/ true); } return links.resolvedType; } - // We do not perform supertype reduction on intersection types. Intersection types are created only by the & + // We do not perform structural deduplication on intersection types. Intersection types are created only by the & // type operator and we can't reduce those because we want to support recursive intersection types. For example, // a type alias of the form "type List = T & { next: List }" cannot be reduced during its declaration. // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution @@ -4179,7 +4291,7 @@ namespace ts { // Callers should first ensure this by calling isTypeNode case SyntaxKind.Identifier: case SyntaxKind.QualifiedName: - let symbol = getSymbolInfo(node); + let symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); default: return unknownType; @@ -4244,15 +4356,18 @@ namespace ts { } function createInferenceMapper(context: InferenceContext): TypeMapper { - return t => { + let mapper: TypeMapper = t => { for (let i = 0; i < context.typeParameters.length; i++) { if (t === context.typeParameters[i]) { context.inferences[i].isFixed = true; return getInferredType(context, i); } } - return t; + return t; }; + + mapper.context = context; + return mapper; } function identityMapper(type: Type): Type { @@ -4354,7 +4469,7 @@ namespace ts { return createTupleType(instantiateList((type).elementTypes, mapper, instantiateType)); } if (type.flags & TypeFlags.Union) { - return getUnionType(instantiateList((type).types, mapper, instantiateType), /*noSubtypeReduction*/ true); + return getUnionType(instantiateList((type).types, mapper, instantiateType), /*noDeduplication*/ true); } if (type.flags & TypeFlags.Intersection) { return getIntersectionType(instantiateList((type).types, mapper, instantiateType)); @@ -4499,6 +4614,16 @@ namespace ts { errorInfo = chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } + function reportRelationError(message: DiagnosticMessage, source: Type, target: Type) { + let sourceType = typeToString(source); + let targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); + } + reportError(message || Diagnostics.Type_0_is_not_assignable_to_type_1, sourceType, targetType); + } + // Compare two types and return // Ternary.True if they are related with no assumptions, // Ternary.Maybe if they are related with assumptions of other relationships, or @@ -4518,7 +4643,23 @@ namespace ts { if (source === numberType && target.flags & TypeFlags.Enum) return Ternary.True; } } + + if (relation !== identityRelation && source.flags & TypeFlags.FreshObjectLiteral) { + if (hasExcessProperties(source, target, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, target); + } + return Ternary.False; + } + // Above we check for excess properties with respect to the entire target type. When union + // and intersection types are further deconstructed on the target side, we don't want to + // make the check again (as it might fail for a partial target type). Therefore we obtain + // the regular source type and proceed with that. + source = getRegularTypeOfObjectLiteral(source); + } + let saveErrorInfo = errorInfo; + if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (source).target === (target).target) { // We have type references to same target type, see if relationship holds for all type arguments if (result = typesRelatedTo((source).typeArguments, (target).typeArguments, reportErrors)) { @@ -4595,18 +4736,22 @@ namespace ts { } if (reportErrors) { - headMessage = headMessage || Diagnostics.Type_0_is_not_assignable_to_type_1; - let sourceType = typeToString(source); - let targetType = typeToString(target); - if (sourceType === targetType) { - sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); - targetType = typeToString(target, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); - } - reportError(headMessage, sourceType, targetType); + reportRelationError(headMessage, source, target); } return Ternary.False; } + function hasExcessProperties(source: FreshObjectLiteralType, target: Type, reportErrors: boolean): boolean { + for (let prop of getPropertiesOfObjectType(source)) { + if (!isKnownProperty(target, prop.name)) { + if (reportErrors) { + reportError(Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + } + return true; + } + } + } + function eachTypeRelatedToSomeType(source: UnionOrIntersectionType, target: UnionOrIntersectionType): Ternary { let result = Ternary.True; let sourceTypes = source.types; @@ -5299,8 +5444,26 @@ namespace ts { * Check if a Type was written as a tuple type literal. * Prefer using isTupleLikeType() unless the use of `elementTypes` is required. */ - function isTupleType(type: Type): boolean { - return (type.flags & TypeFlags.Tuple) && !!(type).elementTypes; + function isTupleType(type: Type): type is TupleType { + return !!(type.flags & TypeFlags.Tuple); + } + + function getRegularTypeOfObjectLiteral(type: Type): Type { + if (type.flags & TypeFlags.FreshObjectLiteral) { + let regularType = (type).regularType; + if (!regularType) { + regularType = createType((type).flags & ~TypeFlags.FreshObjectLiteral); + regularType.symbol = (type).symbol; + regularType.members = (type).members; + regularType.properties = (type).properties; + regularType.callSignatures = (type).callSignatures; + regularType.constructSignatures = (type).constructSignatures; + regularType.stringIndexType = (type).stringIndexType; + regularType.numberIndexType = (type).numberIndexType; + } + return regularType; + } + return type; } function getWidenedTypeOfObjectLiteral(type: Type): Type { @@ -5341,26 +5504,45 @@ namespace ts { if (isArrayType(type)) { return createArrayType(getWidenedType((type).typeArguments[0])); } + if (isTupleType(type)) { + return createTupleType(map(type.elementTypes, getWidenedType)); + } } return type; } + /** + * Reports implicit any errors that occur as a result of widening 'null' and 'undefined' + * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to + * getWidenedType. But in some cases getWidenedType is called without reporting errors + * (type argument inference is an example). + * + * The return value indicates whether an error was in fact reported. The particular circumstances + * are on a best effort basis. Currently, if the null or undefined that causes widening is inside + * an object literal property (arbitrarily deeply), this function reports an error. If no error is + * reported, reportImplicitAnyError is a suitable fallback to report a general error. + */ function reportWideningErrorsInType(type: Type): boolean { + let errorReported = false; if (type.flags & TypeFlags.Union) { - let errorReported = false; - forEach((type).types, t => { + for (let t of (type).types) { if (reportWideningErrorsInType(t)) { errorReported = true; } - }); - return errorReported; + } } if (isArrayType(type)) { return reportWideningErrorsInType((type).typeArguments[0]); } + if (isTupleType(type)) { + for (let t of type.elementTypes) { + if (reportWideningErrorsInType(t)) { + errorReported = true; + } + } + } if (type.flags & TypeFlags.ObjectLiteral) { - let errorReported = false; - forEach(getPropertiesOfObjectType(type), p => { + for (let p of getPropertiesOfObjectType(type)) { let t = getTypeOfSymbol(p); if (t.flags & TypeFlags.ContainsUndefinedOrNull) { if (!reportWideningErrorsInType(t)) { @@ -5368,10 +5550,9 @@ namespace ts { } errorReported = true; } - }); - return errorReported; + } } - return false; + return errorReported; } function reportImplicitAnyError(declaration: Declaration, type: Type) { @@ -5445,7 +5626,9 @@ namespace ts { function createInferenceContext(typeParameters: TypeParameter[], inferUnionTypes: boolean): InferenceContext { let inferences: TypeInferences[] = []; for (let unused of typeParameters) { - inferences.push({ primary: undefined, secondary: undefined, isFixed: false }); + inferences.push({ + primary: undefined, secondary: undefined, isFixed: false + }); } return { typeParameters, @@ -5538,30 +5721,33 @@ namespace ts { inferFromTypes(sourceType, target); } } - else if (source.flags & TypeFlags.ObjectType && (target.flags & (TypeFlags.Reference | TypeFlags.Tuple) || - (target.flags & TypeFlags.Anonymous) && target.symbol && target.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class))) { - // If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members - if (isInProcess(source, target)) { - return; - } - if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { - return; - } + else { + source = getApparentType(source); + if (source.flags & TypeFlags.ObjectType && (target.flags & (TypeFlags.Reference | TypeFlags.Tuple) || + (target.flags & TypeFlags.Anonymous) && target.symbol && target.symbol.flags & (SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.Class))) { + // If source is an object type, and target is a type reference, a tuple type, the type of a method, or a type literal, infer from members + if (isInProcess(source, target)) { + return; + } + if (isDeeplyNestedGeneric(source, sourceStack, depth) && isDeeplyNestedGeneric(target, targetStack, depth)) { + return; + } - if (depth === 0) { - sourceStack = []; - targetStack = []; + if (depth === 0) { + sourceStack = []; + targetStack = []; + } + sourceStack[depth] = source; + targetStack[depth] = target; + depth++; + inferFromProperties(source, target); + inferFromSignatures(source, target, SignatureKind.Call); + inferFromSignatures(source, target, SignatureKind.Construct); + inferFromIndexTypes(source, target, IndexKind.String, IndexKind.String); + inferFromIndexTypes(source, target, IndexKind.Number, IndexKind.Number); + inferFromIndexTypes(source, target, IndexKind.String, IndexKind.Number); + depth--; } - sourceStack[depth] = source; - targetStack[depth] = target; - depth++; - inferFromProperties(source, target); - inferFromSignatures(source, target, SignatureKind.Call); - inferFromSignatures(source, target, SignatureKind.Construct); - inferFromIndexTypes(source, target, IndexKind.String, IndexKind.String); - inferFromIndexTypes(source, target, IndexKind.Number, IndexKind.Number); - inferFromIndexTypes(source, target, IndexKind.String, IndexKind.Number); - depth--; } } @@ -5810,47 +5996,6 @@ namespace ts { } } - function resolveLocation(node: Node) { - // Resolve location from top down towards node if it is a context sensitive expression - // That helps in making sure not assigning types as any when resolved out of order - let containerNodes: Node[] = []; - for (let parent = node.parent; parent; parent = parent.parent) { - if ((isExpression(parent) || isObjectLiteralMethod(node)) && - isContextSensitive(parent)) { - containerNodes.unshift(parent); - } - } - - ts.forEach(containerNodes, node => { getTypeOfNode(node); }); - } - - function getSymbolAtLocation(node: Node): Symbol { - resolveLocation(node); - return getSymbolInfo(node); - } - - function getTypeAtLocation(node: Node): Type { - resolveLocation(node); - return getTypeOfNode(node); - } - - function getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type { - resolveLocation(node); - // Get the narrowed type of symbol at given location instead of just getting - // the type of the symbol. - // eg. - // function foo(a: string | number) { - // if (typeof a === "string") { - // a/**/ - // } - // } - // getTypeOfSymbol for a would return type of parameter symbol string | number - // Unless we provide location /**/, checker wouldn't know how to narrow the type - // By using getNarrowedTypeOfSymbol would return string since it would be able to narrow - // it by typeguard in the if true condition - return getNarrowedTypeOfSymbol(symbol, node); - } - // Get the narrowed type of a given symbol at a given location function getNarrowedTypeOfSymbol(symbol: Symbol, node: Node) { let type = getTypeOfSymbol(symbol); @@ -6743,10 +6888,23 @@ namespace ts { return result; } - // Presence of a contextual type mapper indicates inferential typing, except the identityMapper object is - // used as a special marker for other purposes. + /** + * Detect if the mapper implies an inference context. Specifically, there are 4 possible values + * for a mapper. Let's go through each one of them: + * + * 1. undefined - this means we are not doing inferential typing, but we may do contextual typing, + * which could cause us to assign a parameter a type + * 2. identityMapper - means we want to avoid assigning a parameter a type, whether or not we are in + * inferential typing (context is undefined for the identityMapper) + * 3. a mapper created by createInferenceMapper - we are doing inferential typing, we want to assign + * types to parameters and fix type parameters (context is defined) + * 4. an instantiation mapper created by createTypeMapper or createTypeEraser - this should never be + * passed as the contextual mapper when checking an expression (context is undefined for these) + * + * isInferentialContext is detecting if we are in case 3 + */ function isInferentialContext(mapper: TypeMapper) { - return mapper && mapper !== identityMapper; + return mapper && mapper.context; } // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property @@ -6934,7 +7092,7 @@ namespace ts { let stringIndexType = getIndexType(IndexKind.String); let numberIndexType = getIndexType(IndexKind.Number); let result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); - result.flags |= TypeFlags.ObjectLiteral | TypeFlags.ContainsObjectLiteral | (typeFlags & TypeFlags.ContainsUndefinedOrNull); + result.flags |= TypeFlags.ObjectLiteral | TypeFlags.FreshObjectLiteral | TypeFlags.ContainsObjectLiteral | (typeFlags & TypeFlags.ContainsUndefinedOrNull); return result; function getIndexType(kind: IndexKind) { @@ -6961,7 +7119,6 @@ namespace ts { } } - function checkJsxSelfClosingElement(node: JsxSelfClosingElement) { checkJsxOpeningLikeElement(node); return jsxElementType || anyType; @@ -8462,6 +8619,9 @@ namespace ts { if (!produceDiagnostics) { for (let candidate of candidates) { if (hasCorrectArity(node, args, candidate)) { + if (candidate.typeParameters && typeArguments) { + candidate = getSignatureInstantiation(candidate, map(typeArguments, getTypeFromTypeNode)); + } return candidate; } } @@ -8810,7 +8970,7 @@ namespace ts { } function checkAssertion(node: AssertionExpression) { - let exprType = checkExpression(node.expression); + let exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); let targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { let widenedType = getWidenedType(exprType); @@ -8831,13 +8991,52 @@ namespace ts { let len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); for (let i = 0; i < len; i++) { let parameter = signature.parameters[i]; - let links = getSymbolLinks(parameter); - links.type = instantiateType(getTypeAtPosition(context, i), mapper); + let contextualParameterType = getTypeAtPosition(context, i); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); } if (signature.hasRestParameter && context.hasRestParameter && signature.parameters.length >= context.parameters.length) { let parameter = lastOrUndefined(signature.parameters); - let links = getSymbolLinks(parameter); - links.type = instantiateType(getTypeOfSymbol(lastOrUndefined(context.parameters)), mapper); + let contextualParameterType = getTypeOfSymbol(lastOrUndefined(context.parameters)); + assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); + } + } + + function assignTypeToParameterAndFixTypeParameters(parameter: Symbol, contextualType: Type, mapper: TypeMapper) { + let links = getSymbolLinks(parameter); + if (!links.type) { + links.type = instantiateType(contextualType, mapper); + } + else if (isInferentialContext(mapper)) { + // Even if the parameter already has a type, it might be because it was given a type while + // processing the function as an argument to a prior signature during overload resolution. + // If this was the case, it may have caused some type parameters to be fixed. So here, + // we need to ensure that type parameters at the same positions get fixed again. This is + // done by calling instantiateType to attach the mapper to the contextualType, and then + // calling inferTypes to force a walk of contextualType so that all the correct fixing + // happens. The choice to pass in links.type may seem kind of arbitrary, but it serves + // to make sure that all the correct positions in contextualType are reached by the walk. + // Here is an example: + // + // interface Base { + // baseProp; + // } + // interface Derived extends Base { + // toBase(): Base; + // } + // + // var derived: Derived; + // + // declare function foo(x: T, func: (p: T) => T): T; + // declare function foo(x: T, func: (p: T) => T): T; + // + // var result = foo(derived, d => d.toBase()); + // + // We are typing d while checking the second overload. But we've already given d + // a type (Derived) from the first overload. However, we still want to fix the + // T in the second overload so that we do not infer Base as a candidate for T + // (inferring Base would make type argument inference inconsistent between the two + // overloads). + inferTypes(mapper.context, links.type, instantiateType(contextualType, mapper)); } } @@ -9057,27 +9256,36 @@ namespace ts { let links = getNodeLinks(node); let type = getTypeOfSymbol(node.symbol); - // Check if function expression is contextually typed and assign parameter types if so - if (!(links.flags & NodeCheckFlags.ContextChecked)) { + let contextSensitive = isContextSensitive(node); + let mightFixTypeParameters = contextSensitive && isInferentialContext(contextualMapper); + + // Check if function expression is contextually typed and assign parameter types if so. + // See the comment in assignTypeToParameterAndFixTypeParameters to understand why we need to + // check mightFixTypeParameters. + if (mightFixTypeParameters || !(links.flags & NodeCheckFlags.ContextChecked)) { let contextualSignature = getContextualSignature(node); // If a type check is started at a function expression that is an argument of a function call, obtaining the // contextual type may recursively get back to here during overload resolution of the call. If so, we will have // already assigned contextual types. - if (!(links.flags & NodeCheckFlags.ContextChecked)) { + let contextChecked = !!(links.flags & NodeCheckFlags.ContextChecked); + if (mightFixTypeParameters || !contextChecked) { links.flags |= NodeCheckFlags.ContextChecked; if (contextualSignature) { let signature = getSignaturesOfType(type, SignatureKind.Call)[0]; - if (isContextSensitive(node)) { + if (contextSensitive) { assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); } - if (!node.type && !signature.resolvedReturnType) { + if (mightFixTypeParameters || !node.type && !signature.resolvedReturnType) { let returnType = getReturnTypeFromBody(node, contextualMapper); if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; } } } - checkSignatureDeclaration(node); + + if (!contextChecked) { + checkSignatureDeclaration(node); + } } } @@ -9587,7 +9795,7 @@ namespace ts { return getUnionType([leftType, rightType]); case SyntaxKind.EqualsToken: checkAssignmentOperator(rightType); - return rightType; + return getRegularTypeOfObjectLiteral(rightType); case SyntaxKind.CommaToken: return rightType; } @@ -9767,7 +9975,7 @@ namespace ts { } function instantiateTypeWithSingleGenericCallSignature(node: Expression | MethodDeclaration, type: Type, contextualMapper?: TypeMapper) { - if (contextualMapper && contextualMapper !== identityMapper) { + if (isInferentialContext(contextualMapper)) { let signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { let contextualType = getContextualType(node); @@ -10012,7 +10220,7 @@ namespace ts { } else { checkTypeAssignableTo(typePredicate.type, - getTypeAtLocation(node.parameters[typePredicate.parameterIndex]), + getTypeOfNode(node.parameters[typePredicate.parameterIndex]), typePredicateNode.type); } } @@ -13634,7 +13842,7 @@ namespace ts { return undefined; } - function getSymbolInfo(node: Node) { + function getSymbolAtLocation(node: Node) { if (isInsideWithStatementBody(node)) { // We cannot answer semantic questions within a with block, do not proceed any further return undefined; @@ -13645,10 +13853,22 @@ namespace ts { return getSymbolOfNode(node.parent); } - if (node.kind === SyntaxKind.Identifier && isInRightSideOfImportOrExportAssignment(node)) { - return node.parent.kind === SyntaxKind.ExportAssignment - ? getSymbolOfEntityNameOrPropertyAccessExpression(node) - : getSymbolOfPartOfRightHandSideOfImportEquals(node); + if (node.kind === SyntaxKind.Identifier) { + if (isInRightSideOfImportOrExportAssignment(node)) { + return node.parent.kind === SyntaxKind.ExportAssignment + ? getSymbolOfEntityNameOrPropertyAccessExpression(node) + : getSymbolOfPartOfRightHandSideOfImportEquals(node); + } + else if (node.parent.kind === SyntaxKind.BindingElement && + node.parent.parent.kind === SyntaxKind.ObjectBindingPattern && + node === (node.parent).propertyName) { + let typeOfPattern = getTypeOfNode(node.parent.parent); + let propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, (node).text); + + if (propertyDeclaration) { + return propertyDeclaration; + } + } } switch (node.kind) { @@ -13725,24 +13945,24 @@ namespace ts { } if (isTypeDeclaration(node)) { - // In this case, we call getSymbolOfNode instead of getSymbolInfo because it is a declaration + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration let symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); } if (isTypeDeclarationName(node)) { - let symbol = getSymbolInfo(node); + let symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); } if (isDeclaration(node)) { - // In this case, we call getSymbolOfNode instead of getSymbolInfo because it is a declaration + // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration let symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } if (isDeclarationName(node)) { - let symbol = getSymbolInfo(node); + let symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -13751,7 +13971,7 @@ namespace ts { } if (isInRightSideOfImportOrExportAssignment(node)) { - let symbol = getSymbolInfo(node); + let symbol = getSymbolAtLocation(node); let declaredType = symbol && getDeclaredTypeOfSymbol(symbol); return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); } @@ -13920,7 +14140,11 @@ namespace ts { return true; } // const enums and modules that contain only const enums are not considered values from the emit perespective - return target !== unknownSymbol && target && target.flags & SymbolFlags.Value && !isConstEnumOrConstEnumOnlyModule(target); + // unless 'preserveConstEnums' option is set to true + return target !== unknownSymbol && + target && + target.flags & SymbolFlags.Value && + (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target)); } function isConstEnumOrConstEnumOnlyModule(s: Symbol): boolean { diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index a0a95d47c8c..b91399e8ee1 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -254,6 +254,7 @@ namespace ts { Only_a_void_function_can_be_called_with_the_new_keyword: { code: 2350, category: DiagnosticCategory.Error, key: "Only a void function can be called with the 'new' keyword." }, Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature: { code: 2351, category: DiagnosticCategory.Error, key: "Cannot use 'new' with an expression whose type lacks a call or construct signature." }, Neither_type_0_nor_type_1_is_assignable_to_the_other: { code: 2352, category: DiagnosticCategory.Error, key: "Neither type '{0}' nor type '{1}' is assignable to the other." }, + Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: DiagnosticCategory.Error, key: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, No_best_common_type_exists_among_return_expressions: { code: 2354, category: DiagnosticCategory.Error, key: "No best common type exists among return expressions." }, A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2355, category: DiagnosticCategory.Error, key: "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: DiagnosticCategory.Error, key: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index acf4e74ae9f..9fda73740ba 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1005,6 +1005,10 @@ "category": "Error", "code": 2352 }, + "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'.": { + "category": "Error", + "code": 2353 + }, "No best common type exists among return expressions.": { "category": "Error", "code": 2354 diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index fd0d4ad796e..c77324eefd4 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -3012,6 +3012,26 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return result; } + function emitEs6ExportDefaultCompat(node: Node) { + if (node.parent.kind === SyntaxKind.SourceFile) { + Debug.assert(!!(node.flags & NodeFlags.Default) || node.kind === SyntaxKind.ExportAssignment); + // only allow export default at a source file level + if (compilerOptions.module === ModuleKind.CommonJS || compilerOptions.module === ModuleKind.AMD || compilerOptions.module === ModuleKind.UMD) { + if (!currentSourceFile.symbol.exports["___esModule"]) { + if (languageVersion === ScriptTarget.ES5) { + // default value of configurable, enumerable, writable are `false`. + write("Object.defineProperty(exports, \"__esModule\", { value: true });"); + writeLine(); + } + else if (languageVersion === ScriptTarget.ES3) { + write("exports.__esModule = true;"); + writeLine(); + } + } + } + } + } + function emitExportMemberAssignment(node: FunctionLikeDeclaration | ClassDeclaration) { if (node.flags & NodeFlags.Export) { writeLine(); @@ -3034,9 +3054,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } else { if (node.flags & NodeFlags.Default) { + emitEs6ExportDefaultCompat(node); if (languageVersion === ScriptTarget.ES3) { write("exports[\"default\"]"); - } else { + } + else { write("exports.default"); } } @@ -3249,7 +3271,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitAssignmentExpression(root: BinaryExpression) { let target = root.left; let value = root.right; - if (isAssignmentExpressionStatement) { + + if (isEmptyObjectLiteralOrArrayLiteral(target)) { + emit(value); + } + else if (isAssignmentExpressionStatement) { emitDestructuringAssignment(target, value); } else { @@ -4215,10 +4241,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } } + let startIndex = 0; + write(" {"); scopeEmitStart(node, "constructor"); increaseIndent(); if (ctor) { + // Emit all the directive prologues (like "use strict"). These have to come before + // any other preamble code we write (like parameter initializers). + startIndex = emitDirectivePrologues(ctor.body.statements, /*startWithNewLine*/ true); emitDetachedComments(ctor.body.statements); } emitCaptureThisForNodeIfNecessary(node); @@ -4253,7 +4284,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (superCall) { statements = statements.slice(1); } - emitLines(statements); + emitLinesStartingAt(statements, startIndex); } emitTempDeclarations(/*newLine*/ true); writeLine(); @@ -5398,17 +5429,43 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi (!isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { emitLeadingComments(node); emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); - write("var "); + + // variable declaration for import-equals declaration can be hoisted in system modules + // in this case 'var' should be omitted and emit should contain only initialization + let variableDeclarationIsHoisted = shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true); + + // is it top level export import v = a.b.c in system module? + // if yes - it needs to be rewritten as exporter('v', v = a.b.c) + let isExported = isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ true); + + if (!variableDeclarationIsHoisted) { + Debug.assert(!isExported); + + if (isES6ExportedDeclaration(node)) { + write("export "); + write("var "); + } + else if (!(node.flags & NodeFlags.Export)) { + write("var "); + } } - else if (!(node.flags & NodeFlags.Export)) { - write("var "); + + + if (isExported) { + write(`${exportFunctionForFile}("`); + emitNodeWithoutSourceMap(node.name); + write(`", `); } + emitModuleMemberName(node); write(" = "); emit(node.moduleReference); - write(";"); + + if (isExported) { + write(")"); + } + + write(";"); emitEnd(node); emitExportImportAssignments(node); emitTrailingComments(node); @@ -5529,6 +5586,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(")"); } else { + emitEs6ExportDefaultCompat(node); emitContainingModuleName(node); if (languageVersion === ScriptTarget.ES3) { write("[\"default\"] = "); @@ -5747,6 +5805,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(`function ${exportStarFunction}(m) {`); increaseIndent(); writeLine(); + write(`var exports = {};`); + writeLine(); write(`for(var n in m) {`); increaseIndent(); writeLine(); @@ -5754,10 +5814,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (localNames) { write(`&& !${localNames}.hasOwnProperty(n)`); } - write(`) ${exportFunctionForFile}(n, m[n]);`); + write(`) exports[n] = m[n];`); decreaseIndent(); writeLine(); write("}"); + writeLine(); + write(`${exportFunctionForFile}(exports);`) decreaseIndent(); writeLine(); write("}"); @@ -5929,6 +5991,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } return; } + + if (isInternalModuleImportEqualsDeclaration(node)) { + if (!hoistedVars) { + hoistedVars = []; + } + + hoistedVars.push(node.name); + return; + } if (isBindingPattern(node)) { forEach((node).elements, visit); @@ -6090,16 +6161,23 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if ((importNode).exportClause) { // export {a, b as c} from 'foo' // emit as: - // exports('a', _foo["a"]) - // exports('c', _foo["b"]) + // var reexports = {} + // reexports['a'] = _foo["a"]; + // reexports['c'] = _foo["b"]; + // exports_(reexports); + let reexportsVariableName = makeUniqueName("reexports"); + writeLine(); + write(`var ${reexportsVariableName} = {};`) + writeLine(); for (let e of (importNode).exportClause.elements) { - writeLine(); - write(`${exportFunctionForFile}("`); + write(`${reexportsVariableName}["`); emitNodeWithoutSourceMap(e.name); - write(`", ${parameterName}["`); + write(`"] = ${parameterName}["`); emitNodeWithoutSourceMap(e.propertyName || e.name); - write(`"]);`); + write(`"];`); + writeLine(); } + write(`${exportFunctionForFile}(${reexportsVariableName});`); } else { writeLine(); @@ -6126,14 +6204,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLine(); for (let i = startIndex; i < node.statements.length; ++i) { let statement = node.statements[i]; - // - imports/exports are not emitted for system modules + // - external module related imports/exports are not emitted for system modules // - function declarations are not emitted because they were already hoisted switch (statement.kind) { case SyntaxKind.ExportDeclaration: case SyntaxKind.ImportDeclaration: - case SyntaxKind.ImportEqualsDeclaration: case SyntaxKind.FunctionDeclaration: continue; + case SyntaxKind.ImportEqualsDeclaration: + if (!isInternalModuleImportEqualsDeclaration(statement)) { + continue; + } } writeLine(); emit(statement); diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index fecff11b1b4..127d1b58ee4 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -3295,7 +3295,7 @@ namespace ts { function parseSuperExpression(): MemberExpression { let expression = parseTokenNode(); - if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.DotToken) { + if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.DotToken || token === SyntaxKind.OpenBracketToken) { return expression; } @@ -5135,7 +5135,12 @@ namespace ts { } else { node.exportClause = parseNamedImportsOrExports(SyntaxKind.NamedExports); - if (parseOptional(SyntaxKind.FromKeyword)) { + + // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios, + // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`) + // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect. + if (token === SyntaxKind.FromKeyword || (token === SyntaxKind.StringLiteral && !scanner.hasPrecedingLineBreak())) { + parseExpected(SyntaxKind.FromKeyword) node.moduleSpecifier = parseModuleSpecifier(); } } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index e0f16a00c2b..8d5596c6f64 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1762,10 +1762,12 @@ namespace ts { FromSignature = 0x00040000, // Created for signature assignment check ObjectLiteral = 0x00080000, // Originates in an object literal /* @internal */ - ContainsUndefinedOrNull = 0x00100000, // Type is or contains Undefined or Null type + FreshObjectLiteral = 0x00100000, // Fresh object literal type /* @internal */ - ContainsObjectLiteral = 0x00200000, // Type is or contains object literal type - ESSymbol = 0x00400000, // Type of symbol primitive introduced in ES6 + ContainsUndefinedOrNull = 0x00200000, // Type is or contains Undefined or Null type + /* @internal */ + ContainsObjectLiteral = 0x00400000, // Type is or contains object literal type + ESSymbol = 0x00800000, // Type of symbol primitive introduced in ES6 /* @internal */ Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null, @@ -1858,6 +1860,14 @@ namespace ts { numberIndexType?: Type; // Numeric index type } + /* @internal */ + // Object literals are initially marked fresh. Freshness disappears following an assignment, + // before a type assertion, or when when an object literal's type is widened. The regular + // version of a fresh type is identical except for the TypeFlags.FreshObjectLiteral flag. + export interface FreshObjectLiteralType extends ResolvedType { + regularType: ResolvedType; // Regular version of fresh type + } + // Just a place to cache element types of iterables and iterators /* @internal */ export interface IterableOrIteratorType extends ObjectType, UnionType { @@ -1912,6 +1922,9 @@ namespace ts { /* @internal */ export interface TypeMapper { (t: TypeParameter): Type; + context?: InferenceContext; // The inference context this mapper was created from. + // Only inference mappers have this set (in createInferenceMapper). + // The identity mapper and regular instantiation mappers do not need it. } /* @internal */ @@ -2208,6 +2221,7 @@ namespace ts { export interface CompilerHost { getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; + getCancellationToken?(): CancellationToken; getDefaultLibFileName(options: CompilerOptions): string; writeFile: WriteFileCallback; getCurrentDirectory(): string; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 5174589cdcf..56eb2415cf9 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -568,7 +568,7 @@ namespace ts { } } - export function isVariableLike(node: Node): boolean { + export function isVariableLike(node: Node): node is VariableLikeDeclaration { if (node) { switch (node.kind) { case SyntaxKind.BindingElement: @@ -965,7 +965,7 @@ namespace ts { return ((node).moduleReference).expression; } - export function isInternalModuleImportEqualsDeclaration(node: Node) { + export function isInternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration { return node.kind === SyntaxKind.ImportEqualsDeclaration && (node).moduleReference.kind !== SyntaxKind.ExternalModuleReference; } @@ -1981,6 +1981,17 @@ namespace ts { (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent).name === node); } + export function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean { + let kind = expression.kind; + if (kind === SyntaxKind.ObjectLiteralExpression) { + return (expression).properties.length === 0; + } + if (kind === SyntaxKind.ArrayLiteralExpression) { + return (expression).elements.length === 0; + } + return false; + } + export function getLocalSymbolForExportDefault(symbol: Symbol) { return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & NodeFlags.Default) ? symbol.valueDeclaration.localSymbol : undefined; } diff --git a/src/harness/compilerRunner.ts b/src/harness/compilerRunner.ts index 39d4b053956..b1d43302372 100644 --- a/src/harness/compilerRunner.ts +++ b/src/harness/compilerRunner.ts @@ -42,27 +42,26 @@ class CompilerBaselineRunner extends RunnerBase { describe('compiler tests for ' + fileName, () => { // Mocha holds onto the closure environment of the describe callback even after the test is done. // Everything declared here should be cleared out in the "after" callback. - var justName: string; - var content: string; - var testCaseContent: { settings: Harness.TestCaseParser.CompilerSetting[]; testUnitData: Harness.TestCaseParser.TestUnitData[]; } + let justName: string; + let content: string; + let testCaseContent: { settings: Harness.TestCaseParser.CompilerSetting[]; testUnitData: Harness.TestCaseParser.TestUnitData[]; }; - var units: Harness.TestCaseParser.TestUnitData[]; - var tcSettings: Harness.TestCaseParser.CompilerSetting[]; - var createNewInstance: boolean; + let units: Harness.TestCaseParser.TestUnitData[]; + let tcSettings: Harness.TestCaseParser.CompilerSetting[]; - var lastUnit: Harness.TestCaseParser.TestUnitData; - var rootDir: string; + let lastUnit: Harness.TestCaseParser.TestUnitData; + let rootDir: string; - var result: Harness.Compiler.CompilerResult; - var program: ts.Program; - var options: ts.CompilerOptions; + let result: Harness.Compiler.CompilerResult; + let program: ts.Program; + let options: ts.CompilerOptions; // equivalent to the files that will be passed on the command line - var toBeCompiled: { unitName: string; content: string }[]; + let toBeCompiled: { unitName: string; content: string }[]; // equivalent to other files on the file system not directly passed to the compiler (ie things that are referenced by other files) - var otherFiles: { unitName: string; content: string }[]; - var harnessCompiler: Harness.Compiler.HarnessCompiler; + let otherFiles: { unitName: string; content: string }[]; + let harnessCompiler: Harness.Compiler.HarnessCompiler; - var createNewInstance = false; + let createNewInstance = false; before(() => { justName = fileName.replace(/^.*[\\\/]/, ''); // strips the fileName from the path. @@ -105,7 +104,7 @@ class CompilerBaselineRunner extends RunnerBase { /* The compiler doesn't handle certain flags flipping during a single compilation setting. Tests on these flags will need a fresh compiler instance for themselves and then create a fresh one for the next test. Would be nice to get dev fixes eventually to remove this limitation. */ - for (var i = 0; i < tcSettings.length; ++i) { + for (let i = 0; i < tcSettings.length; ++i) { // noImplicitAny is passed to getCompiler, but target is just passed in the settings blob to setCompilerSettings if (!createNewInstance && (tcSettings[i].flag == "noimplicitany" || tcSettings[i].flag === 'target')) { harnessCompiler = Harness.Compiler.getCompiler(); @@ -162,7 +161,7 @@ class CompilerBaselineRunner extends RunnerBase { it('Correct sourcemap content for ' + fileName, () => { if (options.sourceMap || options.inlineSourceMap) { Harness.Baseline.runBaseline('Correct sourcemap content for ' + fileName, justName.replace(/\.tsx?$/, '.sourcemap.txt'), () => { - var record = result.getSourceMapRecord(); + let record = result.getSourceMapRecord(); if (options.noEmitOnError && result.errors.length !== 0 && record === undefined) { // Because of the noEmitOnError option no files are created. We need to return null because baselining isn't required. return null; @@ -180,18 +179,18 @@ class CompilerBaselineRunner extends RunnerBase { // check js output Harness.Baseline.runBaseline('Correct JS output for ' + fileName, justName.replace(/\.tsx?/, '.js'), () => { - var tsCode = ''; - var tsSources = otherFiles.concat(toBeCompiled); + let tsCode = ''; + let tsSources = otherFiles.concat(toBeCompiled); if (tsSources.length > 1) { tsCode += '//// [' + fileName + '] ////\r\n\r\n'; } - for (var i = 0; i < tsSources.length; i++) { + for (let i = 0; i < tsSources.length; i++) { tsCode += '//// [' + Harness.Path.getFileName(tsSources[i].unitName) + ']\r\n'; tsCode += tsSources[i].content + (i < (tsSources.length - 1) ? '\r\n' : ''); } - var jsCode = ''; - for (var i = 0; i < result.files.length; i++) { + let jsCode = ''; + for (let i = 0; i < result.files.length; i++) { jsCode += '//// [' + Harness.Path.getFileName(result.files[i].fileName) + ']\r\n'; jsCode += getByteOrderMarkText(result.files[i]); jsCode += result.files[i].code; @@ -199,14 +198,14 @@ class CompilerBaselineRunner extends RunnerBase { if (result.declFilesCode.length > 0) { jsCode += '\r\n\r\n'; - for (var i = 0; i < result.declFilesCode.length; i++) { + for (let i = 0; i < result.declFilesCode.length; i++) { jsCode += '//// [' + Harness.Path.getFileName(result.declFilesCode[i].fileName) + ']\r\n'; jsCode += getByteOrderMarkText(result.declFilesCode[i]); jsCode += result.declFilesCode[i].code; } } - var declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) { + let declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) { harnessCompiler.setCompilerSettings(tcSettings); }, options); @@ -244,8 +243,8 @@ class CompilerBaselineRunner extends RunnerBase { return null; } - var sourceMapCode = ''; - for (var i = 0; i < result.sourceMaps.length; i++) { + let sourceMapCode = ''; + for (let i = 0; i < result.sourceMaps.length; i++) { sourceMapCode += '//// [' + Harness.Path.getFileName(result.sourceMaps[i].fileName) + ']\r\n'; sourceMapCode += getByteOrderMarkText(result.sourceMaps[i]); sourceMapCode += result.sourceMaps[i].code; @@ -293,7 +292,7 @@ class CompilerBaselineRunner extends RunnerBase { // Produce baselines. The first gives the types for all expressions. // The second gives symbols for all identifiers. - var e1: Error, e2: Error; + let e1: Error, e2: Error; try { checkBaseLines(/*isSymbolBaseLine:*/ false); } @@ -335,20 +334,20 @@ class CompilerBaselineRunner extends RunnerBase { let typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {}; allFiles.forEach(file => { - var codeLines = file.content.split('\n'); + let codeLines = file.content.split('\n'); typeWriterResults[file.unitName].forEach(result => { if (isSymbolBaseline && !result.symbol) { return; } - var typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type; - var formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString; + let typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type; + let formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString; if (!typeMap[file.unitName]) { typeMap[file.unitName] = {}; } - var typeInfo = [formattedLine]; - var existingTypeInfo = typeMap[file.unitName][result.line]; + let typeInfo = [formattedLine]; + let existingTypeInfo = typeMap[file.unitName][result.line]; if (existingTypeInfo) { typeInfo = existingTypeInfo.concat(typeInfo); } @@ -356,11 +355,11 @@ class CompilerBaselineRunner extends RunnerBase { }); typeLines.push('=== ' + file.unitName + ' ===\r\n'); - for (var i = 0; i < codeLines.length; i++) { - var currentCodeLine = codeLines[i]; + for (let i = 0; i < codeLines.length; i++) { + let currentCodeLine = codeLines[i]; typeLines.push(currentCodeLine + '\r\n'); if (typeMap[file.unitName]) { - var typeInfo = typeMap[file.unitName][i]; + let typeInfo = typeMap[file.unitName][i]; if (typeInfo) { typeInfo.forEach(ty => { typeLines.push('>' + ty + '\r\n'); @@ -388,13 +387,13 @@ class CompilerBaselineRunner extends RunnerBase { public initializeTests() { describe(this.testSuiteName + ' tests', () => { describe("Setup compiler for compiler baselines", () => { - var harnessCompiler = Harness.Compiler.getCompiler(); + let harnessCompiler = Harness.Compiler.getCompiler(); this.parseOptions(); }); // this will set up a series of describe/it blocks to run between the setup and cleanup phases if (this.tests.length === 0) { - var testFiles = this.enumerateFiles(this.basePath, /\.tsx?$/, { recursive: true }); + let testFiles = this.enumerateFiles(this.basePath, /\.tsx?$/, { recursive: true }); testFiles.forEach(fn => { fn = fn.replace(/\\/g, "/"); this.checkTestCodeOutput(fn); @@ -405,7 +404,7 @@ class CompilerBaselineRunner extends RunnerBase { } describe("Cleanup after compiler baselines", () => { - var harnessCompiler = Harness.Compiler.getCompiler(); + let harnessCompiler = Harness.Compiler.getCompiler(); }); }); } @@ -417,8 +416,8 @@ class CompilerBaselineRunner extends RunnerBase { this.decl = false; this.output = false; - var opts = this.options.split(','); - for (var i = 0; i < opts.length; i++) { + let opts = this.options.split(','); + for (let i = 0; i < opts.length; i++) { switch (opts[i]) { case 'error': this.errors = true; diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index c374f8add60..02ca17cefd7 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -1,6 +1,6 @@ // // Copyright (c) Microsoft Corporation. All rights reserved. -// +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -26,9 +26,8 @@ module FourSlash { export interface FourSlashFile { // The contents of the file (with markers, etc stripped out) content: string; - fileName: string; - + version: number; // File-specific options (name/value pairs) fileOptions: { [index: string]: string; }; } @@ -100,7 +99,7 @@ module FourSlash { end: number; } - var entityMap: ts.Map = { + let entityMap: ts.Map = { '&': '&', '"': '"', "'": ''', @@ -116,7 +115,7 @@ module FourSlash { // Name of testcase metadata including ts.CompilerOptions properties that will be used by globalOptions // To add additional option, add property into the testOptMetadataNames, refer the property in either globalMetadataNames or fileMetadataNames // Add cases into convertGlobalOptionsToCompilationsSettings function for the compiler to acknowledge such option from meta data - var metadataOptionNames = { + let metadataOptionNames = { baselineFile: 'BaselineFile', declaration: 'declaration', emitThisFile: 'emitThisFile', // This flag is used for testing getEmitOutput feature. It allows test-cases to indicate what file to be output in multiple files project @@ -132,15 +131,15 @@ module FourSlash { }; // List of allowed metadata names - var fileMetadataNames = [metadataOptionNames.fileName, metadataOptionNames.emitThisFile, metadataOptionNames.resolveReference]; - var globalMetadataNames = [metadataOptionNames.allowNonTsExtensions, metadataOptionNames.baselineFile, metadataOptionNames.declaration, + let fileMetadataNames = [metadataOptionNames.fileName, metadataOptionNames.emitThisFile, metadataOptionNames.resolveReference]; + let globalMetadataNames = [metadataOptionNames.allowNonTsExtensions, metadataOptionNames.baselineFile, metadataOptionNames.declaration, metadataOptionNames.mapRoot, metadataOptionNames.module, metadataOptionNames.out, - metadataOptionNames.outDir, metadataOptionNames.sourceMap, metadataOptionNames.sourceRoot] + metadataOptionNames.outDir, metadataOptionNames.sourceMap, metadataOptionNames.sourceRoot]; function convertGlobalOptionsToCompilerOptions(globalOptions: { [idx: string]: string }): ts.CompilerOptions { - var settings: ts.CompilerOptions = { target: ts.ScriptTarget.ES5 }; + let settings: ts.CompilerOptions = { target: ts.ScriptTarget.ES5 }; // Convert all property in globalOptions into ts.CompilationSettings - for (var prop in globalOptions) { + for (let prop in globalOptions) { if (globalOptions.hasOwnProperty(prop)) { switch (prop) { case metadataOptionNames.allowNonTsExtensions: @@ -185,14 +184,14 @@ module FourSlash { return settings; } - export var currentTestState: TestState = null; + export let currentTestState: TestState = null; function assertionMessage(msg: string) { return "\nMarker: " + currentTestState.lastKnownMarker + "\nChecking: " + msg + "\n\n"; } export class TestCancellationToken implements ts.HostCancellationToken { // 0 - cancelled - // >0 - not cancelled + // >0 - not cancelled // <0 - not cancelled and value denotes number of isCancellationRequested after which token become cancelled private static NotCanceled: number = -1; private numberOfCallsBeforeCancellation: number = TestCancellationToken.NotCanceled; @@ -271,11 +270,11 @@ module FourSlash { private taoInvalidReason: string = null; private inputFiles: ts.Map = {}; // Map between inputFile's fileName and its content for easily looking up when resolving references - + // Add input file which has matched file name with the given reference-file path. // This is necessary when resolveReference flag is specified private addMatchedInputFile(referenceFilePath: string) { - var inputFile = this.inputFiles[referenceFilePath]; + let inputFile = this.inputFiles[referenceFilePath]; if (inputFile && !Harness.isLibraryFile(referenceFilePath)) { this.languageServiceAdapterHost.addScript(referenceFilePath, inputFile); } @@ -297,13 +296,13 @@ module FourSlash { constructor(private basePath: string, private testType: FourSlashTestType, public testData: FourSlashData) { // Create a new Services Adapter this.cancellationToken = new TestCancellationToken(); - var compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions); - var languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions); + let compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions); + let languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions); this.languageServiceAdapterHost = languageServiceAdapter.getHost(); this.languageService = languageServiceAdapter.getLanguageService(); // Initialize the language service with all the scripts - var startResolveFileRef: FourSlashFile; + let startResolveFileRef: FourSlashFile; ts.forEach(testData.files, file => { // Create map between fileName and its content for easily looking up when resolveReference flag is specified @@ -320,14 +319,14 @@ module FourSlash { // Add the entry-point file itself into the languageServiceShimHost this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content); - var resolvedResult = languageServiceAdapter.getPreProcessedFileInfo(startResolveFileRef.fileName, startResolveFileRef.content); - var referencedFiles: ts.FileReference[] = resolvedResult.referencedFiles; - var importedFiles: ts.FileReference[] = resolvedResult.importedFiles; + let resolvedResult = languageServiceAdapter.getPreProcessedFileInfo(startResolveFileRef.fileName, startResolveFileRef.content); + let referencedFiles: ts.FileReference[] = resolvedResult.referencedFiles; + let importedFiles: ts.FileReference[] = resolvedResult.importedFiles; // Add triple reference files into language-service host ts.forEach(referencedFiles, referenceFile => { // Fourslash insert tests/cases/fourslash into inputFile.unitName so we will properly append the same base directory to refFile path - var referenceFilePath = this.basePath + '/' + referenceFile.fileName; + let referenceFilePath = this.basePath + '/' + referenceFile.fileName; this.addMatchedInputFile(referenceFilePath); }); @@ -335,7 +334,7 @@ module FourSlash { ts.forEach(importedFiles, importedFile => { // Fourslash insert tests/cases/fourslash into inputFile.unitName and import statement doesn't require ".ts" // so convert them before making appropriate comparison - var importedFilePath = this.basePath + '/' + importedFile.fileName + ".ts"; + let importedFilePath = this.basePath + '/' + importedFile.fileName + ".ts"; this.addMatchedInputFile(importedFilePath); }); @@ -370,8 +369,8 @@ module FourSlash { }; this.testData.files.forEach(file => { - var fileName = file.fileName.replace(Harness.IO.directoryName(file.fileName), '').substr(1); - var fileNameWithoutExtension = fileName.substr(0, fileName.lastIndexOf(".")); + let fileName = file.fileName.replace(Harness.IO.directoryName(file.fileName), '').substr(1); + let fileNameWithoutExtension = fileName.substr(0, fileName.lastIndexOf(".")); this.scenarioActions.push(''); }); @@ -380,18 +379,18 @@ module FourSlash { } private getFileContent(fileName: string): string { - var script = this.languageServiceAdapterHost.getScriptInfo(fileName); + let script = this.languageServiceAdapterHost.getScriptInfo(fileName); return script.content; } // Entry points from fourslash.ts public goToMarker(name = '') { - var marker = this.getMarkerByName(name); + let marker = this.getMarkerByName(name); if (this.activeFile.fileName !== marker.fileName) { this.openFile(marker.fileName); } - var content = this.getFileContent(marker.fileName); + let content = this.getFileContent(marker.fileName); if (marker.position === -1 || marker.position > content.length) { throw new Error('Marker "' + name + '" has been invalidated by unrecoverable edits to the file.'); } @@ -402,8 +401,8 @@ module FourSlash { public goToPosition(pos: number) { this.currentCaretPosition = pos; - var lineStarts = ts.computeLineStarts(this.getFileContent(this.activeFile.fileName)); - var lineCharPos = ts.computeLineAndCharacterOfPosition(lineStarts, pos); + let lineStarts = ts.computeLineStarts(this.getFileContent(this.activeFile.fileName)); + let lineCharPos = ts.computeLineAndCharacterOfPosition(lineStarts, pos); this.scenarioActions.push(``); } @@ -421,24 +420,24 @@ module FourSlash { public openFile(index: number): void; public openFile(name: string): void; public openFile(indexOrName: any) { - var fileToOpen: FourSlashFile = this.findFile(indexOrName); + let fileToOpen: FourSlashFile = this.findFile(indexOrName); fileToOpen.fileName = ts.normalizeSlashes(fileToOpen.fileName); this.activeFile = fileToOpen; - var fileName = fileToOpen.fileName.replace(Harness.IO.directoryName(fileToOpen.fileName), '').substr(1); + let fileName = fileToOpen.fileName.replace(Harness.IO.directoryName(fileToOpen.fileName), '').substr(1); this.scenarioActions.push(''); - + // Let the host know that this file is now open this.languageServiceAdapterHost.openFile(fileToOpen.fileName); } public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) { - var startMarker = this.getMarkerByName(startMarkerName); - var endMarker = this.getMarkerByName(endMarkerName); - var predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) { + let startMarker = this.getMarkerByName(startMarkerName); + let endMarker = this.getMarkerByName(endMarkerName); + let predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) { return ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false; }; - var exists = this.anyErrorInRange(predicate, startMarker, endMarker); + let exists = this.anyErrorInRange(predicate, startMarker, endMarker); this.taoInvalidReason = 'verifyErrorExistsBetweenMarkers NYI'; @@ -458,10 +457,10 @@ module FourSlash { } private getDiagnostics(fileName: string): ts.Diagnostic[] { - var syntacticErrors = this.languageService.getSyntacticDiagnostics(fileName); - var semanticErrors = this.languageService.getSemanticDiagnostics(fileName); + let syntacticErrors = this.languageService.getSyntacticDiagnostics(fileName); + let semanticErrors = this.languageService.getSemanticDiagnostics(fileName); - var diagnostics: ts.Diagnostic[] = []; + let diagnostics: ts.Diagnostic[] = []; diagnostics.push.apply(diagnostics, syntacticErrors); diagnostics.push.apply(diagnostics, semanticErrors); @@ -469,10 +468,10 @@ module FourSlash { } private getAllDiagnostics(): ts.Diagnostic[] { - var diagnostics: ts.Diagnostic[] = []; + let diagnostics: ts.Diagnostic[] = []; - var fileNames = this.languageServiceAdapterHost.getFilenames(); - for (var i = 0, n = fileNames.length; i < n; i++) { + let fileNames = this.languageServiceAdapterHost.getFilenames(); + for (let i = 0, n = fileNames.length; i < n; i++) { diagnostics.push.apply(this.getDiagnostics(fileNames[i])); } @@ -480,8 +479,8 @@ module FourSlash { } public verifyErrorExistsAfterMarker(markerName: string, negative: boolean, after: boolean) { - var marker: Marker = this.getMarkerByName(markerName); - var predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean; + let marker: Marker = this.getMarkerByName(markerName); + let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean; if (after) { predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) { @@ -495,8 +494,8 @@ module FourSlash { this.taoInvalidReason = 'verifyErrorExistsAfterMarker NYI'; - var exists = this.anyErrorInRange(predicate, marker); - var diagnostics = this.getAllDiagnostics(); + let exists = this.anyErrorInRange(predicate, marker); + let diagnostics = this.getAllDiagnostics(); if (exists !== negative) { this.printErrorLog(negative, diagnostics); @@ -506,12 +505,13 @@ module FourSlash { private anyErrorInRange(predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean, startMarker: Marker, endMarker?: Marker) { - var errors = this.getDiagnostics(startMarker.fileName); - var exists = false; + let errors = this.getDiagnostics(startMarker.fileName); + let exists = false; - var startPos = startMarker.position; + let startPos = startMarker.position; + let endPos: number = undefined; if (endMarker !== undefined) { - var endPos = endMarker.position; + endPos = endMarker.position; } errors.forEach(function (error: ts.Diagnostic) { @@ -538,40 +538,40 @@ module FourSlash { } public verifyNumberOfErrorsInCurrentFile(expected: number) { - var errors = this.getDiagnostics(this.activeFile.fileName); - var actual = errors.length; + let errors = this.getDiagnostics(this.activeFile.fileName); + let actual = errors.length; this.scenarioActions.push(''); if (actual !== expected) { this.printErrorLog(false, errors); - var errorMsg = "Actual number of errors (" + actual + ") does not match expected number (" + expected + ")"; + let errorMsg = "Actual number of errors (" + actual + ") does not match expected number (" + expected + ")"; Harness.IO.log(errorMsg); this.raiseError(errorMsg); } } public verifyEval(expr: string, value: any) { - var emit = this.languageService.getEmitOutput(this.activeFile.fileName); + let emit = this.languageService.getEmitOutput(this.activeFile.fileName); if (emit.outputFiles.length !== 1) { throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName); } this.taoInvalidReason = 'verifyEval impossible'; - var evaluation = new Function(emit.outputFiles[0].text + ';\r\nreturn (' + expr + ');')(); + let evaluation = new Function(emit.outputFiles[0].text + ';\r\nreturn (' + expr + ');')(); if (evaluation !== value) { this.raiseError('Expected evaluation of expression "' + expr + '" to equal "' + value + '", but got "' + evaluation + '"'); } } public verifyGetEmitOutputForCurrentFile(expected: string): void { - var emit = this.languageService.getEmitOutput(this.activeFile.fileName); + let emit = this.languageService.getEmitOutput(this.activeFile.fileName); if (emit.outputFiles.length !== 1) { throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName); } this.taoInvalidReason = 'verifyGetEmitOutputForCurrentFile impossible'; - var actual = emit.outputFiles[0].text; + let actual = emit.outputFiles[0].text; if (actual !== expected) { this.raiseError("Expected emit output to be '" + expected + "', but got '" + actual + "'"); } @@ -585,7 +585,7 @@ module FourSlash { this.taoInvalidReason = 'verifyMemberListContains only supports the "symbol" parameter'; } - var members = this.getMemberListAtCaret(); + let members = this.getMemberListAtCaret(); if (members) { this.assertItemInCompletionList(members.entries, symbol, text, documentation, kind); } @@ -607,10 +607,10 @@ module FourSlash { this.scenarioActions.push(''); } - var members = this.getMemberListAtCaret(); + let members = this.getMemberListAtCaret(); if (members) { - var match = members.entries.length === expectedCount; + let match = members.entries.length === expectedCount; if ((!match && !negative) || (match && negative)) { this.raiseError("Member list count was " + members.entries.length + ". Expected " + expectedCount); @@ -625,7 +625,7 @@ module FourSlash { this.scenarioActions.push(''); this.scenarioActions.push(''); - var members = this.getMemberListAtCaret(); + let members = this.getMemberListAtCaret(); if (members && members.entries.filter(e => e.name === symbol).length !== 0) { this.raiseError('Member list did contain ' + symbol); } @@ -634,8 +634,8 @@ module FourSlash { public verifyCompletionListItemsCountIsGreaterThan(count: number) { this.taoInvalidReason = 'verifyCompletionListItemsCountIsGreaterThan NYI'; - var completions = this.getCompletionListAtCaret(); - var itemsCount = completions.entries.length; + let completions = this.getCompletionListAtCaret(); + let itemsCount = completions.entries.length; if (itemsCount <= count) { this.raiseError('Expected completion list items count to be greater than ' + count + ', but is actually ' + itemsCount); @@ -649,13 +649,13 @@ module FourSlash { this.scenarioActions.push(''); } - var members = this.getMemberListAtCaret(); + let members = this.getMemberListAtCaret(); if ((!members || members.entries.length === 0) && negative) { this.raiseError("Member list is empty at Caret"); } else if ((members && members.entries.length !== 0) && !negative) { - var errorMsg = "\n" + "Member List contains: [" + members.entries[0].name; - for (var i = 1; i < members.entries.length; i++) { + let errorMsg = "\n" + "Member List contains: [" + members.entries[0].name; + for (let i = 1; i < members.entries.length; i++) { errorMsg += ", " + members.entries[i].name; } errorMsg += "]\n"; @@ -668,24 +668,24 @@ module FourSlash { public verifyCompletionListIsEmpty(negative: boolean) { this.scenarioActions.push(''); - var completions = this.getCompletionListAtCaret(); + let completions = this.getCompletionListAtCaret(); if ((!completions || completions.entries.length === 0) && negative) { - this.raiseError("Completion list is empty at Caret"); - } else if ((completions && completions.entries.length !== 0) && !negative) { - - var errorMsg = "\n" + "Completion List contains: [" + completions.entries[0].name; - for (var i = 1; i < completions.entries.length; i++) { + this.raiseError("Completion list is empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition); + } + else if (completions && completions.entries.length !== 0 && !negative) { + let errorMsg = "\n" + "Completion List contains: [" + completions.entries[0].name; + for (let i = 1; i < completions.entries.length; i++) { errorMsg += ", " + completions.entries[i].name; } errorMsg += "]\n"; - Harness.IO.log(errorMsg); - this.raiseError("Completion list is not empty at Caret"); + this.raiseError("Completion list is not empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition + errorMsg); } } + public verifyCompletionListAllowsNewIdentifier(negative: boolean) { - var completions = this.getCompletionListAtCaret(); + let completions = this.getCompletionListAtCaret(); if ((completions && !completions.isNewIdentifierLocation) && !negative) { this.raiseError("Expected builder completion entry"); @@ -695,7 +695,7 @@ module FourSlash { } public verifyCompletionListContains(symbol: string, text?: string, documentation?: string, kind?: string) { - var completions = this.getCompletionListAtCaret(); + let completions = this.getCompletionListAtCaret(); if (completions) { this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind); } @@ -737,7 +737,7 @@ module FourSlash { this.scenarioActions.push(''); this.scenarioActions.push(''); - var completions = this.getCompletionListAtCaret(); + let completions = this.getCompletionListAtCaret(); if (completions) { let filterCompletions = completions.entries.filter(e => e.name === symbol); filterCompletions = expectedKind ? filterCompletions.filter(e => e.kind === expectedKind) : filterCompletions; @@ -755,7 +755,7 @@ module FourSlash { error += "Expected documentation: " + expectedDocumentation + " to equal: " + ts.displayPartsToString(details.documentation) + "."; } if (expectedKind) { - error += "Expected kind: " + expectedKind + " to equal: " + filterCompletions[0].kind + "." + error += "Expected kind: " + expectedKind + " to equal: " + filterCompletions[0].kind + "."; } this.raiseError(error); } @@ -765,7 +765,7 @@ module FourSlash { public verifyCompletionEntryDetails(entryName: string, expectedText: string, expectedDocumentation?: string, kind?: string) { this.taoInvalidReason = 'verifyCompletionEntryDetails NYI'; - var details = this.getCompletionEntryDetails(entryName); + let details = this.getCompletionEntryDetails(entryName); assert.equal(ts.displayPartsToString(details.displayParts), expectedText, assertionMessage("completion entry details text")); @@ -781,14 +781,14 @@ module FourSlash { public verifyReferencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) { this.taoInvalidReason = 'verifyReferencesAtPositionListContains NYI'; - var references = this.getReferencesAtCaret(); + let references = this.getReferencesAtCaret(); if (!references || references.length === 0) { this.raiseError('verifyReferencesAtPositionListContains failed - found 0 references, expected at least one.'); } - for (var i = 0; i < references.length; i++) { - var reference = references[i]; + for (let i = 0; i < references.length; i++) { + let reference = references[i]; if (reference && reference.fileName === fileName && reference.textSpan.start === start && ts.textSpanEnd(reference.textSpan) === end) { if (typeof isWriteAccess !== "undefined" && reference.isWriteAccess !== isWriteAccess) { this.raiseError('verifyReferencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ' + reference.isWriteAccess + ', expected: ' + isWriteAccess + '.'); @@ -797,18 +797,18 @@ module FourSlash { } } - var missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; + let missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; this.raiseError('verifyReferencesAtPositionListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(references) + ')'); } public verifyReferencesCountIs(count: number, localFilesOnly: boolean = true) { this.taoInvalidReason = 'verifyReferences NYI'; - var references = this.getReferencesAtCaret(); - var referencesCount = 0; + let references = this.getReferencesAtCaret(); + let referencesCount = 0; if (localFilesOnly) { - var localFiles = this.testData.files.map(file => file.fileName); + let localFiles = this.testData.files.map(file => file.fileName); // Count only the references in local files. Filter the ones in lib and other files. ts.forEach(references, entry => { if (localFiles.some((fileName) => fileName === entry.fileName)) { @@ -821,7 +821,7 @@ module FourSlash { } if (referencesCount !== count) { - var condition = localFilesOnly ? "excluding libs" : "including libs"; + let condition = localFilesOnly ? "excluding libs" : "including libs"; this.raiseError("Expected references count (" + condition + ") to be " + count + ", but is actually " + referencesCount); } } @@ -847,18 +847,18 @@ module FourSlash { } public getSyntacticDiagnostics(expected: string) { - var diagnostics = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); + let diagnostics = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); this.testDiagnostics(expected, diagnostics); } public getSemanticDiagnostics(expected: string) { - var diagnostics = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); + let diagnostics = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); this.testDiagnostics(expected, diagnostics); } private testDiagnostics(expected: string, diagnostics: ts.Diagnostic[]) { - var realized = ts.realizeDiagnostics(diagnostics, "\r\n"); - var actual = JSON.stringify(realized, null, " "); + let realized = ts.realizeDiagnostics(diagnostics, "\r\n"); + let actual = JSON.stringify(realized, null, " "); assert.equal(actual, expected); } @@ -870,9 +870,9 @@ module FourSlash { } }); - var actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); - var actualQuickInfoText = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.displayParts) : ""; - var actualQuickInfoDocumentation = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.documentation) : ""; + let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + let actualQuickInfoText = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.displayParts) : ""; + let actualQuickInfoDocumentation = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.documentation) : ""; if (negative) { if (expectedText !== undefined) { @@ -900,7 +900,7 @@ module FourSlash { this.scenarioActions.push(''); function getDisplayPartsJson(displayParts: ts.SymbolDisplayPart[]) { - var result = ""; + let result = ""; ts.forEach(displayParts, part => { if (result) { result += ",\n "; @@ -917,7 +917,7 @@ module FourSlash { return result; } - var actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); assert.equal(actualQuickInfo.kind, kind, this.messageAtLastKnownMarker("QuickInfo kind")); assert.equal(actualQuickInfo.kindModifiers, kindModifiers, this.messageAtLastKnownMarker("QuickInfo kindModifiers")); assert.equal(JSON.stringify(actualQuickInfo.textSpan), JSON.stringify(textSpan), this.messageAtLastKnownMarker("QuickInfo textSpan")); @@ -926,12 +926,12 @@ module FourSlash { } public verifyRenameLocations(findInStrings: boolean, findInComments: boolean) { - var renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); + let renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (renameInfo.canRename) { - var references = this.languageService.findRenameLocations( + let references = this.languageService.findRenameLocations( this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments); - var ranges = this.getRanges(); + let ranges = this.getRanges(); if (!references) { if (ranges.length !== 0) { @@ -947,9 +947,9 @@ module FourSlash { ranges = ranges.sort((r1, r2) => r1.start - r2.start); references = references.sort((r1, r2) => r1.textSpan.start - r2.textSpan.start); - for (var i = 0, n = ranges.length; i < n; i++) { - var reference = references[i]; - var range = ranges[i]; + for (let i = 0, n = ranges.length; i < n; i++) { + let reference = references[i]; + let range = ranges[i]; if (reference.textSpan.start !== range.start || ts.textSpanEnd(reference.textSpan) !== range.end) { @@ -966,7 +966,7 @@ module FourSlash { public verifyQuickInfoExists(negative: boolean) { this.taoInvalidReason = 'verifyQuickInfoExists NYI'; - var actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); if (negative) { if (actualQuickInfo) { this.raiseError('verifyQuickInfoExists failed. Expected quick info NOT to exist'); @@ -982,17 +982,17 @@ module FourSlash { public verifyCurrentSignatureHelpIs(expected: string) { this.taoInvalidReason = 'verifyCurrentSignatureHelpIs NYI'; - var help = this.getActiveSignatureHelpItem(); + let help = this.getActiveSignatureHelpItem(); assert.equal( ts.displayPartsToString(help.prefixDisplayParts) + help.parameters.map(p => ts.displayPartsToString(p.displayParts)).join(ts.displayPartsToString(help.separatorDisplayParts)) + ts.displayPartsToString(help.suffixDisplayParts), expected); } - public verifyCurrentParameterIsVariable(isVariable: boolean) { - this.taoInvalidReason = 'verifyCurrentParameterIsVariable NYI'; + public verifyCurrentParameterIsletiable(isVariable: boolean) { + this.taoInvalidReason = 'verifyCurrentParameterIsletiable NYI'; - var signature = this.getActiveSignatureHelpItem(); + let signature = this.getActiveSignatureHelpItem(); assert.isNotNull(signature); assert.equal(isVariable, signature.isVariadic); } @@ -1000,24 +1000,24 @@ module FourSlash { public verifyCurrentParameterHelpName(name: string) { this.taoInvalidReason = 'verifyCurrentParameterHelpName NYI'; - var activeParameter = this.getActiveParameter(); - var activeParameterName = activeParameter.name; + let activeParameter = this.getActiveParameter(); + let activeParameterName = activeParameter.name; assert.equal(activeParameterName, name); } public verifyCurrentParameterSpanIs(parameter: string) { this.taoInvalidReason = 'verifyCurrentParameterSpanIs NYI'; - var activeSignature = this.getActiveSignatureHelpItem(); - var activeParameter = this.getActiveParameter(); + let activeSignature = this.getActiveSignatureHelpItem(); + let activeParameter = this.getActiveParameter(); assert.equal(ts.displayPartsToString(activeParameter.displayParts), parameter); } public verifyCurrentParameterHelpDocComment(docComment: string) { this.taoInvalidReason = 'verifyCurrentParameterHelpDocComment NYI'; - var activeParameter = this.getActiveParameter(); - var activeParameterDocComment = activeParameter.documentation; + let activeParameter = this.getActiveParameter(); + let activeParameterDocComment = activeParameter.documentation; assert.equal(ts.displayPartsToString(activeParameterDocComment), docComment, assertionMessage("current parameter Help DocComment")); } @@ -1036,7 +1036,7 @@ module FourSlash { public verifyCurrentSignatureHelpDocComment(docComment: string) { this.taoInvalidReason = 'verifyCurrentSignatureHelpDocComment NYI'; - var actualDocComment = this.getActiveSignatureHelpItem().documentation; + let actualDocComment = this.getActiveSignatureHelpItem().documentation; assert.equal(ts.displayPartsToString(actualDocComment), docComment, assertionMessage("current signature help doc comment")); } @@ -1044,22 +1044,22 @@ module FourSlash { this.scenarioActions.push(''); this.scenarioActions.push(''); - var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - var actual = help && help.items ? help.items.length : 0; + let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + let actual = help && help.items ? help.items.length : 0; assert.equal(actual, expected); } public verifySignatureHelpArgumentCount(expected: number) { this.taoInvalidReason = 'verifySignatureHelpArgumentCount NYI'; - var signatureHelpItems = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - var actual = signatureHelpItems.argumentCount; + let signatureHelpItems = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + let actual = signatureHelpItems.argumentCount; assert.equal(actual, expected); } public verifySignatureHelpPresent(shouldBePresent = true) { this.taoInvalidReason = 'verifySignatureHelpPresent NYI'; - var actual = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + let actual = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); if (shouldBePresent) { if (!actual) { this.raiseError("Expected signature help to be present, but it wasn't"); @@ -1078,7 +1078,7 @@ module FourSlash { } public verifyRenameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string) { - var renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); + let renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (!renameInfo.canRename) { this.raiseError("Rename did not succeed"); } @@ -1092,7 +1092,7 @@ module FourSlash { this.raiseError("Expected a single range to be selected in the test file."); } - var expectedRange = this.getRanges()[0]; + let expectedRange = this.getRanges()[0]; if (renameInfo.triggerSpan.start !== expectedRange.start || ts.textSpanEnd(renameInfo.triggerSpan) !== expectedRange.end) { this.raiseError("Expected triggerSpan [" + expectedRange.start + "," + expectedRange.end + "). Got [" + @@ -1101,7 +1101,7 @@ module FourSlash { } public verifyRenameInfoFailed(message?: string) { - var renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); + let renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (renameInfo.canRename) { this.raiseError("Rename was expected to fail"); } @@ -1110,26 +1110,26 @@ module FourSlash { } private getActiveSignatureHelpItem() { - var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - var index = help.selectedItemIndex; + let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + let index = help.selectedItemIndex; return help.items[index]; } private getActiveParameter(): ts.SignatureHelpParameter { - var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - var item = help.items[help.selectedItemIndex]; - var currentParam = help.argumentIndex; + let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + let item = help.items[help.selectedItemIndex]; + let currentParam = help.argumentIndex; return item.parameters[currentParam]; } private alignmentForExtraInfo = 50; private spanInfoToString(pos: number, spanInfo: ts.TextSpan, prefixString: string) { - var resultString = "SpanInfo: " + JSON.stringify(spanInfo); + let resultString = "SpanInfo: " + JSON.stringify(spanInfo); if (spanInfo) { - var spanString = this.activeFile.content.substr(spanInfo.start, spanInfo.length); - var spanLineMap = ts.computeLineStarts(spanString); - for (var i = 0; i < spanLineMap.length; i++) { + let spanString = this.activeFile.content.substr(spanInfo.start, spanInfo.length); + let spanLineMap = ts.computeLineStarts(spanString); + for (let i = 0; i < spanLineMap.length; i++) { if (!i) { resultString += "\n"; } @@ -1142,19 +1142,20 @@ module FourSlash { } private baselineCurrentFileLocations(getSpanAtPos: (pos: number) => ts.TextSpan): string { - var fileLineMap = ts.computeLineStarts(this.activeFile.content); - var nextLine = 0; - var resultString = ""; - var currentLine: string; - var previousSpanInfo: string; - var startColumn: number; - var length: number; - var prefixString = " >"; + let fileLineMap = ts.computeLineStarts(this.activeFile.content); + let nextLine = 0; + let resultString = ""; + let currentLine: string; + let previousSpanInfo: string; + let startColumn: number; + let length: number; + let prefixString = " >"; - var addSpanInfoString = () => { + let pos = 0; + let addSpanInfoString = () => { if (previousSpanInfo) { resultString += currentLine; - var thisLineMarker = repeatString(startColumn, " ") + repeatString(length, "~"); + let thisLineMarker = repeatString(startColumn, " ") + repeatString(length, "~"); thisLineMarker += repeatString(this.alignmentForExtraInfo - thisLineMarker.length - prefixString.length + 1, " "); resultString += thisLineMarker; resultString += "=> Pos: (" + (pos - length) + " to " + (pos - 1) + ") "; @@ -1163,7 +1164,7 @@ module FourSlash { } }; - for (var pos = 0; pos < this.activeFile.content.length; pos++) { + for (; pos < this.activeFile.content.length; pos++) { if (pos === 0 || pos === fileLineMap[nextLine]) { nextLine++; addSpanInfoString(); @@ -1174,7 +1175,7 @@ module FourSlash { startColumn = 0; length = 0; } - var spanInfo = this.spanInfoToString(pos, getSpanAtPos(pos), prefixString); + let spanInfo = this.spanInfoToString(pos, getSpanAtPos(pos), prefixString); if (previousSpanInfo && previousSpanInfo !== spanInfo) { addSpanInfoString(); previousSpanInfo = spanInfo; @@ -1190,8 +1191,8 @@ module FourSlash { return resultString; function repeatString(count: number, char: string) { - var result = ""; - for (var i = 0; i < count; i++) { + let result = ""; + for (let i = 0; i < count; i++) { result += char; } return result; @@ -1218,11 +1219,11 @@ module FourSlash { public baselineGetEmitOutput() { this.taoInvalidReason = 'baselineGetEmitOutput impossible'; // Find file to be emitted - var emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on + let emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on - var allFourSlashFiles = this.testData.files; - for (var idx = 0; idx < allFourSlashFiles.length; ++idx) { - var file = allFourSlashFiles[idx]; + let allFourSlashFiles = this.testData.files; + for (let idx = 0; idx < allFourSlashFiles.length; ++idx) { + let file = allFourSlashFiles[idx]; if (file.fileOptions[metadataOptionNames.emitThisFile] === "true") { // Find a file with the flag emitThisFile turned on emitFiles.push(file); @@ -1238,23 +1239,23 @@ module FourSlash { "Generate getEmitOutput baseline : " + emitFiles.join(" "), this.testData.globalOptions[metadataOptionNames.baselineFile], () => { - var resultString = ""; + let resultString = ""; // Loop through all the emittedFiles and emit them one by one emitFiles.forEach(emitFile => { - var emitOutput = this.languageService.getEmitOutput(emitFile.fileName); + let emitOutput = this.languageService.getEmitOutput(emitFile.fileName); // Print emitOutputStatus in readable format resultString += "EmitSkipped: " + emitOutput.emitSkipped + ts.sys.newLine; if (emitOutput.emitSkipped) { resultString += "Diagnostics:" + ts.sys.newLine; - var diagnostics = ts.getPreEmitDiagnostics(this.languageService.getProgram()); - for (var i = 0, n = diagnostics.length; i < n; i++) { + let diagnostics = ts.getPreEmitDiagnostics(this.languageService.getProgram()); + for (let i = 0, n = diagnostics.length; i < n; i++) { resultString += " " + diagnostics[0].messageText + ts.sys.newLine; } } emitOutput.outputFiles.forEach((outputFile, idx, array) => { - var fileName = "FileName : " + outputFile.name + ts.sys.newLine; + let fileName = "FileName : " + outputFile.name + ts.sys.newLine; resultString = resultString + fileName + outputFile.text; }); resultString += ts.sys.newLine; @@ -1274,19 +1275,19 @@ module FourSlash { } public printCurrentParameterHelp() { - var help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); Harness.IO.log(JSON.stringify(help)); } public printCurrentQuickInfo() { - var quickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + let quickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); Harness.IO.log(JSON.stringify(quickInfo)); } public printErrorList() { - var syntacticErrors = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); - var semanticErrors = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); - var errorList = syntacticErrors.concat(semanticErrors); + let syntacticErrors = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); + let semanticErrors = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); + let errorList = syntacticErrors.concat(semanticErrors); Harness.IO.log('Error list (' + errorList.length + ' errors)'); if (errorList.length) { @@ -1300,11 +1301,11 @@ module FourSlash { } public printCurrentFileState(makeWhitespaceVisible = false, makeCaretVisible = true) { - for (var i = 0; i < this.testData.files.length; i++) { - var file = this.testData.files[i]; - var active = (this.activeFile === file); + for (let i = 0; i < this.testData.files.length; i++) { + let file = this.testData.files[i]; + let active = (this.activeFile === file); Harness.IO.log('=== Script (' + file.fileName + ') ' + (active ? '(active, cursor at |)' : '') + ' ==='); - var content = this.getFileContent(file.fileName); + let content = this.getFileContent(file.fileName); if (active) { content = content.substr(0, this.currentCaretPosition) + (makeCaretVisible ? '|' : "") + content.substr(this.currentCaretPosition); } @@ -1316,22 +1317,22 @@ module FourSlash { } public printCurrentSignatureHelp() { - var sigHelp = this.getActiveSignatureHelpItem(); + let sigHelp = this.getActiveSignatureHelpItem(); Harness.IO.log(JSON.stringify(sigHelp)); } public printMemberListMembers() { - var members = this.getMemberListAtCaret(); + let members = this.getMemberListAtCaret(); Harness.IO.log(JSON.stringify(members)); } public printCompletionListMembers() { - var completions = this.getCompletionListAtCaret(); + let completions = this.getCompletionListAtCaret(); Harness.IO.log(JSON.stringify(completions)); } public printReferences() { - var references = this.getReferencesAtCaret(); + let references = this.getReferencesAtCaret(); ts.forEach(references, entry => { Harness.IO.log(JSON.stringify(entry)); }); @@ -1344,26 +1345,26 @@ module FourSlash { public deleteChar(count = 1) { this.scenarioActions.push(''); - var offset = this.currentCaretPosition; - var ch = ""; + let offset = this.currentCaretPosition; + let ch = ""; - var checkCadence = (count >> 2) + 1 + let checkCadence = (count >> 2) + 1; - for (var i = 0; i < count; i++) { + for (let i = 0; i < count; i++) { // Make the edit this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset + 1, ch); this.updateMarkersForEdit(this.activeFile.fileName, offset, offset + 1, ch); if (i % checkCadence === 0) { - this.checkPostEditInvariants(); + this.checkPostEditInletiants(); } // Handle post-keystroke formatting if (this.enableFormatting) { - var edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); + let edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); - //this.checkPostEditInvariants(); + // this.checkPostEditInletiants(); } } } @@ -1372,7 +1373,7 @@ module FourSlash { this.currentCaretPosition = offset; this.fixCaretPosition(); - this.checkPostEditInvariants(); + this.checkPostEditInletiants(); } public replace(start: number, length: number, text: string) { @@ -1380,29 +1381,29 @@ module FourSlash { this.languageServiceAdapterHost.editScript(this.activeFile.fileName, start, start + length, text); this.updateMarkersForEdit(this.activeFile.fileName, start, start + length, text); - this.checkPostEditInvariants(); + this.checkPostEditInletiants(); } public deleteCharBehindMarker(count = 1) { this.scenarioActions.push(''); - var offset = this.currentCaretPosition; - var ch = ""; - var checkCadence = (count >> 2) + 1 + let offset = this.currentCaretPosition; + let ch = ""; + let checkCadence = (count >> 2) + 1; - for (var i = 0; i < count; i++) { + for (let i = 0; i < count; i++) { offset--; // Make the edit this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset + 1, ch); this.updateMarkersForEdit(this.activeFile.fileName, offset, offset + 1, ch); if (i % checkCadence === 0) { - this.checkPostEditInvariants(); + this.checkPostEditInletiants(); } // Handle post-keystroke formatting if (this.enableFormatting) { - var edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); + let edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); } @@ -1413,7 +1414,7 @@ module FourSlash { this.currentCaretPosition = offset; this.fixCaretPosition(); - this.checkPostEditInvariants(); + this.checkPostEditInletiants(); } // Enters lines of text at the current caret position @@ -1431,13 +1432,13 @@ module FourSlash { // language service APIs to mimic Visual Studio's behavior // as much as possible private typeHighFidelity(text: string) { - var offset = this.currentCaretPosition; - var prevChar = ' '; - var checkCadence = (text.length >> 2) + 1; + let offset = this.currentCaretPosition; + let prevChar = ' '; + let checkCadence = (text.length >> 2) + 1; - for (var i = 0; i < text.length; i++) { + for (let i = 0; i < text.length; i++) { // Make the edit - var ch = text.charAt(i); + let ch = text.charAt(i); this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset, ch); this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, offset); @@ -1453,17 +1454,17 @@ module FourSlash { } if (i % checkCadence === 0) { - this.checkPostEditInvariants(); + this.checkPostEditInletiants(); // this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); // this.languageService.getSemanticDiagnostics(this.activeFile.fileName); } // Handle post-keystroke formatting if (this.enableFormatting) { - var edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); + let edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); - // this.checkPostEditInvariants(); + // this.checkPostEditInletiants(); } } } @@ -1472,26 +1473,26 @@ module FourSlash { this.currentCaretPosition = offset; this.fixCaretPosition(); - this.checkPostEditInvariants(); + this.checkPostEditInletiants(); } // Enters text as if the user had pasted it public paste(text: string) { this.scenarioActions.push(''); - var start = this.currentCaretPosition; - var offset = this.currentCaretPosition; + let start = this.currentCaretPosition; + let offset = this.currentCaretPosition; this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset, text); this.updateMarkersForEdit(this.activeFile.fileName, offset, offset, text); - this.checkPostEditInvariants(); + this.checkPostEditInletiants(); offset += text.length; // Handle formatting if (this.enableFormatting) { - var edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions); + let edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); - this.checkPostEditInvariants(); + this.checkPostEditInletiants(); } } @@ -1499,27 +1500,27 @@ module FourSlash { this.currentCaretPosition = offset; this.fixCaretPosition(); - this.checkPostEditInvariants(); + this.checkPostEditInletiants(); } - private checkPostEditInvariants() { - if (this.testType !== FourSlashTestType.Native) { - // getSourcefile() results can not be serialized. Only perform these verifications + private checkPostEditInletiants() { + if (this.testType !== FourSlashTestType.Native) { + // getSourcefile() results can not be serialized. Only perform these verifications // if running against a native LS object. return; } - var incrementalSourceFile = this.languageService.getSourceFile(this.activeFile.fileName); + let incrementalSourceFile = this.languageService.getSourceFile(this.activeFile.fileName); Utils.assertInvariants(incrementalSourceFile, /*parent:*/ undefined); - var incrementalSyntaxDiagnostics = incrementalSourceFile.parseDiagnostics; + let incrementalSyntaxDiagnostics = incrementalSourceFile.parseDiagnostics; // Check syntactic structure - var content = this.getFileContent(this.activeFile.fileName); + let content = this.getFileContent(this.activeFile.fileName); - var referenceSourceFile = ts.createLanguageServiceSourceFile( + let referenceSourceFile = ts.createLanguageServiceSourceFile( this.activeFile.fileName, createScriptSnapShot(content), ts.ScriptTarget.Latest, /*version:*/ "0", /*setNodeParents:*/ false); - var referenceSyntaxDiagnostics = referenceSourceFile.parseDiagnostics; + let referenceSyntaxDiagnostics = referenceSourceFile.parseDiagnostics; Utils.assertDiagnosticsEquals(incrementalSyntaxDiagnostics, referenceSyntaxDiagnostics); Utils.assertStructuralEquals(incrementalSourceFile, referenceSourceFile); @@ -1529,7 +1530,7 @@ module FourSlash { // The caret can potentially end up between the \r and \n, which is confusing. If // that happens, move it back one character if (this.currentCaretPosition > 0) { - var ch = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition - 1, this.currentCaretPosition); + let ch = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition - 1, this.currentCaretPosition); if (ch === '\r') { this.currentCaretPosition--; } @@ -1539,21 +1540,21 @@ module FourSlash { private applyEdits(fileName: string, edits: ts.TextChange[], isFormattingEdit = false): number { // We get back a set of edits, but langSvc.editScript only accepts one at a time. Use this to keep track // of the incremental offset from each edit to the next. Assumption is that these edit ranges don't overlap - var runningOffset = 0; + let runningOffset = 0; edits = edits.sort((a, b) => a.span.start - b.span.start); // Get a snapshot of the content of the file so we can make sure any formatting edits didn't destroy non-whitespace characters - var oldContent = this.getFileContent(this.activeFile.fileName); - for (var j = 0; j < edits.length; j++) { + let oldContent = this.getFileContent(this.activeFile.fileName); + for (let j = 0; j < edits.length; j++) { this.languageServiceAdapterHost.editScript(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText); this.updateMarkersForEdit(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText); - var change = (edits[j].span.start - ts.textSpanEnd(edits[j].span)) + edits[j].newText.length; + let change = (edits[j].span.start - ts.textSpanEnd(edits[j].span)) + edits[j].newText.length; runningOffset += change; // TODO: Consider doing this at least some of the time for higher fidelity. Currently causes a failure (bug 707150) // this.languageService.getScriptLexicalStructure(fileName); } if (isFormattingEdit) { - var newContent = this.getFileContent(fileName); + let newContent = this.getFileContent(fileName); if (newContent.replace(/\s/g, '') !== oldContent.replace(/\s/g, '')) { this.raiseError('Formatting operation destroyed non-whitespace content'); @@ -1567,7 +1568,7 @@ module FourSlash { } public setFormatOptions(formatCodeOptions: ts.FormatCodeOptions): ts.FormatCodeOptions { - var oldFormatCodeOptions = this.formatCodeOptions; + let oldFormatCodeOptions = this.formatCodeOptions; this.formatCodeOptions = formatCodeOptions; return oldFormatCodeOptions; } @@ -1575,7 +1576,7 @@ module FourSlash { public formatDocument() { this.scenarioActions.push(''); - var edits = this.languageService.getFormattingEditsForDocument(this.activeFile.fileName, this.formatCodeOptions); + let edits = this.languageService.getFormattingEditsForDocument(this.activeFile.fileName, this.formatCodeOptions); this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, true); this.fixCaretPosition(); } @@ -1583,14 +1584,14 @@ module FourSlash { public formatSelection(start: number, end: number) { this.taoInvalidReason = 'formatSelection NYI'; - var edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, end, this.formatCodeOptions); + let edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, end, this.formatCodeOptions); this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, true); this.fixCaretPosition(); } private updateMarkersForEdit(fileName: string, minChar: number, limChar: number, text: string) { - for (var i = 0; i < this.testData.markers.length; i++) { - var marker = this.testData.markers[i]; + for (let i = 0; i < this.testData.markers.length; i++) { + let marker = this.testData.markers[i]; if (marker.fileName === fileName) { if (marker.position > minChar) { if (marker.position < limChar) { @@ -1610,7 +1611,7 @@ module FourSlash { } public goToEOF() { - var len = this.getFileContent(this.activeFile.fileName).length; + let len = this.getFileContent(this.activeFile.fileName).length; this.goToPosition(len); } @@ -1621,7 +1622,7 @@ module FourSlash { this.taoInvalidReason = 'GoToDefinition not supported for non-zero definition indices'; } - var definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); if (!definitions || !definitions.length) { this.raiseError('goToDefinition failed - expected to at least one definition location but got 0'); } @@ -1630,7 +1631,7 @@ module FourSlash { this.raiseError('goToDefinition failed - definitionIndex value (' + definitionIndex + ') exceeds definition list size (' + definitions.length + ')'); } - var definition = definitions[definitionIndex]; + let definition = definitions[definitionIndex]; this.openFile(definition.fileName); this.currentCaretPosition = definition.textSpan.start; } @@ -1643,7 +1644,7 @@ module FourSlash { this.taoInvalidReason = 'GoToTypeDefinition not supported for non-zero definition indices'; } - var definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + let definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); if (!definitions || !definitions.length) { this.raiseError('goToTypeDefinition failed - expected to at least one definition location but got 0'); } @@ -1652,7 +1653,7 @@ module FourSlash { this.raiseError('goToTypeDefinition failed - definitionIndex value (' + definitionIndex + ') exceeds definition list size (' + definitions.length + ')'); } - var definition = definitions[definitionIndex]; + let definition = definitions[definitionIndex]; this.openFile(definition.fileName); this.currentCaretPosition = definition.textSpan.start; } @@ -1660,9 +1661,9 @@ module FourSlash { public verifyDefinitionLocationExists(negative: boolean) { this.taoInvalidReason = 'verifyDefinitionLocationExists NYI'; - var definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - var foundDefinitions = definitions && definitions.length; + let foundDefinitions = definitions && definitions.length; if (foundDefinitions && negative) { this.raiseError('goToDefinition - expected to 0 definition locations but got ' + definitions.length); @@ -1673,19 +1674,19 @@ module FourSlash { } public verifyDefinitionsCount(negative: boolean, expectedCount: number) { - var assertFn = negative ? assert.notEqual : assert.equal; + let assertFn = negative ? assert.notEqual : assert.equal; - var definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - var actualCount = definitions && definitions.length || 0; + let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + let actualCount = definitions && definitions.length || 0; assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Definitions Count")); } public verifyTypeDefinitionsCount(negative: boolean, expectedCount: number) { - var assertFn = negative ? assert.notEqual : assert.equal; + let assertFn = negative ? assert.notEqual : assert.equal; - var definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - var actualCount = definitions && definitions.length || 0; + let definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + let actualCount = definitions && definitions.length || 0; assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Type definitions Count")); } @@ -1693,9 +1694,9 @@ module FourSlash { public verifyDefinitionsName(negative: boolean, expectedName: string, expectedContainerName: string) { this.taoInvalidReason = 'verifyDefinititionsInfo NYI'; - var definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - var actualDefinitionName = definitions && definitions.length ? definitions[0].name : ""; - var actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : ""; + let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + let actualDefinitionName = definitions && definitions.length ? definitions[0].name : ""; + let actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : ""; if (negative) { assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name")); assert.notEqual(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name")); @@ -1718,7 +1719,7 @@ module FourSlash { public verifyCaretAtMarker(markerName = '') { this.taoInvalidReason = 'verifyCaretAtMarker NYI'; - var pos = this.getMarkerByName(markerName); + let pos = this.getMarkerByName(markerName); if (pos.fileName !== this.activeFile.fileName) { throw new Error('verifyCaretAtMarker failed - expected to be in file "' + pos.fileName + '", but was in file "' + this.activeFile.fileName + '"'); } @@ -1734,8 +1735,8 @@ module FourSlash { public verifyIndentationAtCurrentPosition(numberOfSpaces: number) { this.taoInvalidReason = 'verifyIndentationAtCurrentPosition NYI'; - var actual = this.getIndentation(this.activeFile.fileName, this.currentCaretPosition); - var lineCol = this.getLineColStringAtPosition(this.currentCaretPosition); + let actual = this.getIndentation(this.activeFile.fileName, this.currentCaretPosition); + let lineCol = this.getLineColStringAtPosition(this.currentCaretPosition); if (actual !== numberOfSpaces) { this.raiseError('verifyIndentationAtCurrentPosition failed at ' + lineCol + ' - expected: ' + numberOfSpaces + ', actual: ' + actual); } @@ -1744,8 +1745,8 @@ module FourSlash { public verifyIndentationAtPosition(fileName: string, position: number, numberOfSpaces: number) { this.taoInvalidReason = 'verifyIndentationAtPosition NYI'; - var actual = this.getIndentation(fileName, position); - var lineCol = this.getLineColStringAtPosition(position); + let actual = this.getIndentation(fileName, position); + let lineCol = this.getLineColStringAtPosition(position); if (actual !== numberOfSpaces) { this.raiseError('verifyIndentationAtPosition failed at ' + lineCol + ' - expected: ' + numberOfSpaces + ', actual: ' + actual); } @@ -1754,7 +1755,7 @@ module FourSlash { public verifyCurrentLineContent(text: string) { this.taoInvalidReason = 'verifyCurrentLineContent NYI'; - var actual = this.getCurrentLineContent(); + let actual = this.getCurrentLineContent(); if (actual !== text) { throw new Error('verifyCurrentLineContent\n' + '\tExpected: "' + text + '"\n' + @@ -1765,8 +1766,8 @@ module FourSlash { public verifyCurrentFileContent(text: string) { this.taoInvalidReason = 'verifyCurrentFileContent NYI'; - var actual = this.getFileContent(this.activeFile.fileName); - var replaceNewlines = (str: string) => str.replace(/\r\n/g, "\n"); + let actual = this.getFileContent(this.activeFile.fileName); + let replaceNewlines = (str: string) => str.replace(/\r\n/g, "\n"); if (replaceNewlines(actual) !== replaceNewlines(text)) { throw new Error('verifyCurrentFileContent\n' + '\tExpected: "' + text + '"\n' + @@ -1777,7 +1778,7 @@ module FourSlash { public verifyTextAtCaretIs(text: string) { this.taoInvalidReason = 'verifyCurrentFileContent NYI'; - var actual = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition, this.currentCaretPosition + text.length); + let actual = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition, this.currentCaretPosition + text.length); if (actual !== text) { throw new Error('verifyTextAtCaretIs\n' + '\tExpected: "' + text + '"\n' + @@ -1788,14 +1789,14 @@ module FourSlash { public verifyCurrentNameOrDottedNameSpanText(text: string) { this.taoInvalidReason = 'verifyCurrentNameOrDottedNameSpanText NYI'; - var span = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition); + let span = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition); if (!span) { this.raiseError('verifyCurrentNameOrDottedNameSpanText\n' + '\tExpected: "' + text + '"\n' + '\t Actual: undefined'); } - var actual = this.getFileContent(this.activeFile.fileName).substring(span.start, ts.textSpanEnd(span)); + let actual = this.getFileContent(this.activeFile.fileName).substring(span.start, ts.textSpanEnd(span)); if (actual !== text) { this.raiseError('verifyCurrentNameOrDottedNameSpanText\n' + '\tExpected: "' + text + '"\n' + @@ -1832,11 +1833,11 @@ module FourSlash { jsonMismatchString()); } - for (var i = 0; i < expected.length; i++) { - var expectedClassification = expected[i]; - var actualClassification = actual[i]; + for (let i = 0; i < expected.length; i++) { + let expectedClassification = expected[i]; + let actualClassification = actual[i]; - var expectedType: string = (ts.ClassificationTypeNames)[expectedClassification.classificationType]; + let expectedType: string = (ts.ClassificationTypeNames)[expectedClassification.classificationType]; if (expectedType !== actualClassification.classificationType) { this.raiseError('verifyClassifications failed - expected classifications type to be ' + expectedType + ', but was ' + @@ -1844,11 +1845,11 @@ module FourSlash { jsonMismatchString()); } - var expectedSpan = expectedClassification.textSpan; - var actualSpan = actualClassification.textSpan; + let expectedSpan = expectedClassification.textSpan; + let actualSpan = actualClassification.textSpan; if (expectedSpan) { - var expectedLength = expectedSpan.end - expectedSpan.start; + let expectedLength = expectedSpan.end - expectedSpan.start; if (expectedSpan.start !== actualSpan.start || expectedLength !== actualSpan.length) { this.raiseError("verifyClassifications failed - expected span of text to be " + @@ -1858,7 +1859,7 @@ module FourSlash { } } - var actualText = this.activeFile.content.substr(actualSpan.start, actualSpan.length); + let actualText = this.activeFile.content.substr(actualSpan.start, actualSpan.length); if (expectedClassification.text !== actualText) { this.raiseError('verifyClassifications failed - expected classified text to be ' + expectedClassification.text + ', but was ' + @@ -1883,21 +1884,21 @@ module FourSlash { assert.equal( expected.join(","), actual.fileNameList.map( file => { - return file.replace(this.basePath + "/", "") + return file.replace(this.basePath + "/", ""); }).join(",") ); } } public verifySemanticClassifications(expected: { classificationType: string; text: string }[]) { - var actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, + let actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length)); this.verifyClassifications(expected, actual); } public verifySyntacticClassifications(expected: { classificationType: string; text: string }[]) { - var actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName, + let actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length)); this.verifyClassifications(expected, actual); @@ -1906,15 +1907,15 @@ module FourSlash { public verifyOutliningSpans(spans: TextSpan[]) { this.taoInvalidReason = 'verifyOutliningSpans NYI'; - var actual = this.languageService.getOutliningSpans(this.activeFile.fileName); + let actual = this.languageService.getOutliningSpans(this.activeFile.fileName); if (actual.length !== spans.length) { this.raiseError('verifyOutliningSpans failed - expected total spans to be ' + spans.length + ', but was ' + actual.length); } - for (var i = 0; i < spans.length; i++) { - var expectedSpan = spans[i]; - var actualSpan = actual[i]; + for (let i = 0; i < spans.length; i++) { + let expectedSpan = spans[i]; + let actualSpan = actual[i]; if (expectedSpan.start !== actualSpan.textSpan.start || expectedSpan.end !== ts.textSpanEnd(actualSpan.textSpan)) { this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualSpan.textSpan.start + ',' + ts.textSpanEnd(actualSpan.textSpan) + ')'); } @@ -1922,17 +1923,17 @@ module FourSlash { } public verifyTodoComments(descriptors: string[], spans: TextSpan[]) { - var actual = this.languageService.getTodoComments(this.activeFile.fileName, + let actual = this.languageService.getTodoComments(this.activeFile.fileName, descriptors.map(d => { return { text: d, priority: 0 }; })); if (actual.length !== spans.length) { this.raiseError('verifyTodoComments failed - expected total spans to be ' + spans.length + ', but was ' + actual.length); } - for (var i = 0; i < spans.length; i++) { - var expectedSpan = spans[i]; - var actualComment = actual[i]; - var actualCommentSpan = ts.createTextSpan(actualComment.position, actualComment.message.length); + for (let i = 0; i < spans.length; i++) { + let expectedSpan = spans[i]; + let actualComment = actual[i]; + let actualCommentSpan = ts.createTextSpan(actualComment.position, actualComment.message.length); if (expectedSpan.start !== actualCommentSpan.start || expectedSpan.end !== ts.textSpanEnd(actualCommentSpan)) { this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualCommentSpan.start + ',' + ts.textSpanEnd(actualCommentSpan) + ')'); @@ -1943,13 +1944,13 @@ module FourSlash { public verifyMatchingBracePosition(bracePosition: number, expectedMatchPosition: number) { this.taoInvalidReason = 'verifyMatchingBracePosition NYI'; - var actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); + let actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); if (actual.length !== 2) { this.raiseError('verifyMatchingBracePosition failed - expected result to contain 2 spans, but it had ' + actual.length); } - var actualMatchPosition = -1; + let actualMatchPosition = -1; if (bracePosition === actual[0].start) { actualMatchPosition = actual[1].start; } else if (bracePosition === actual[1].start) { @@ -1966,7 +1967,7 @@ module FourSlash { public verifyNoMatchingBracePosition(bracePosition: number) { this.taoInvalidReason = 'verifyNoMatchingBracePosition NYI'; - var actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); + let actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); if (actual.length !== 0) { this.raiseError('verifyNoMatchingBracePosition failed - expected: 0 spans, actual: ' + actual.length); @@ -1980,12 +1981,12 @@ module FourSlash { public verifyNavigationItemsCount(expected: number, searchValue: string, matchKind?: string) { this.taoInvalidReason = 'verifyNavigationItemsCount NYI'; - var items = this.languageService.getNavigateToItems(searchValue); - var actual = 0; - var item: ts.NavigateToItem = null; + let items = this.languageService.getNavigateToItems(searchValue); + let actual = 0; + let item: ts.NavigateToItem = null; // Count only the match that match the same MatchKind - for (var i = 0; i < items.length; ++i) { + for (let i = 0; i < items.length; ++i) { item = items[i]; if (!matchKind || item.matchKind === matchKind) { actual++; @@ -2010,14 +2011,14 @@ module FourSlash { parentName?: string) { this.taoInvalidReason = 'verifyNavigationItemsListContains NYI'; - var items = this.languageService.getNavigateToItems(searchValue); + let items = this.languageService.getNavigateToItems(searchValue); if (!items || items.length === 0) { this.raiseError('verifyNavigationItemsListContains failed - found 0 navigation items, expected at least one.'); } - for (var i = 0; i < items.length; i++) { - var item = items[i]; + for (let i = 0; i < items.length; i++) { + let item = items[i]; if (item && item.name === name && item.kind === kind && (matchKind === undefined || item.matchKind === matchKind) && (fileName === undefined || item.fileName === fileName) && @@ -2028,7 +2029,7 @@ module FourSlash { // if there was an explicit match kind specified, then it should be validated. if (matchKind !== undefined) { - var missingItem = { name: name, kind: kind, searchValue: searchValue, matchKind: matchKind, fileName: fileName, parentName: parentName }; + let missingItem = { name: name, kind: kind, searchValue: searchValue, matchKind: matchKind, fileName: fileName, parentName: parentName }; this.raiseError('verifyNavigationItemsListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(items) + ')'); } } @@ -2036,8 +2037,8 @@ module FourSlash { public verifyGetScriptLexicalStructureListCount(expected: number) { this.taoInvalidReason = 'verifyNavigationItemsListContains impossible'; - var items = this.languageService.getNavigationBarItems(this.activeFile.fileName); - var actual = this.getNavigationBarItemsCount(items); + let items = this.languageService.getNavigationBarItems(this.activeFile.fileName); + let actual = this.getNavigationBarItemsCount(items); if (expected !== actual) { this.raiseError('verifyGetScriptLexicalStructureListCount failed - found: ' + actual + ' navigation items, expected: ' + expected + '.'); @@ -2045,9 +2046,9 @@ module FourSlash { } private getNavigationBarItemsCount(items: ts.NavigationBarItem[]) { - var result = 0; + let result = 0; if (items) { - for (var i = 0, n = items.length; i < n; i++) { + for (let i = 0, n = items.length; i < n; i++) { result++; result += this.getNavigationBarItemsCount(items[i].childItems); } @@ -2062,7 +2063,7 @@ module FourSlash { markerPosition?: number) { this.taoInvalidReason = 'verifGetScriptLexicalStructureListContains impossible'; - var items = this.languageService.getNavigationBarItems(this.activeFile.fileName); + let items = this.languageService.getNavigationBarItems(this.activeFile.fileName); if (!items || items.length === 0) { this.raiseError('verifyGetScriptLexicalStructureListContains failed - found 0 navigation items, expected at least one.'); @@ -2072,14 +2073,14 @@ module FourSlash { return; } - var missingItem = { name: name, kind: kind }; + let missingItem = { name: name, kind: kind }; this.raiseError('verifyGetScriptLexicalStructureListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(items, null, " ") + ')'); } private navigationBarItemsContains(items: ts.NavigationBarItem[], name: string, kind: string) { if (items) { - for (var i = 0; i < items.length; i++) { - var item = items[i]; + for (let i = 0; i < items.length; i++) { + let item = items[i]; if (item && item.text === name && item.kind === kind) { return true; } @@ -2094,25 +2095,25 @@ module FourSlash { } public printNavigationItems(searchValue: string) { - var items = this.languageService.getNavigateToItems(searchValue); - var length = items && items.length; + let items = this.languageService.getNavigateToItems(searchValue); + let length = items && items.length; Harness.IO.log('NavigationItems list (' + length + ' items)'); - for (var i = 0; i < length; i++) { - var item = items[i]; + for (let i = 0; i < length; i++) { + let item = items[i]; Harness.IO.log('name: ' + item.name + ', kind: ' + item.kind + ', parentName: ' + item.containerName + ', fileName: ' + item.fileName); } } public printScriptLexicalStructureItems() { - var items = this.languageService.getNavigationBarItems(this.activeFile.fileName); - var length = items && items.length; + let items = this.languageService.getNavigationBarItems(this.activeFile.fileName); + let length = items && items.length; Harness.IO.log('NavigationItems list (' + length + ' items)'); - for (var i = 0; i < length; i++) { - var item = items[i]; + for (let i = 0; i < length; i++) { + let item = items[i]; Harness.IO.log('name: ' + item.text + ', kind: ' + item.kind); } } @@ -2124,14 +2125,14 @@ module FourSlash { public verifyOccurrencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) { this.taoInvalidReason = 'verifyOccurrencesAtPositionListContains NYI'; - var occurances = this.getOccurancesAtCurrentPosition(); + let occurances = this.getOccurancesAtCurrentPosition(); if (!occurances || occurances.length === 0) { this.raiseError('verifyOccurancesAtPositionListContains failed - found 0 references, expected at least one.'); } - for (var i = 0; i < occurances.length; i++) { - var occurance = occurances[i]; + for (let i = 0; i < occurances.length; i++) { + let occurance = occurances[i]; if (occurance && occurance.fileName === fileName && occurance.textSpan.start === start && ts.textSpanEnd(occurance.textSpan) === end) { if (typeof isWriteAccess !== "undefined" && occurance.isWriteAccess !== isWriteAccess) { this.raiseError('verifyOccurancesAtPositionListContains failed - item isWriteAccess value doe not match, actual: ' + occurance.isWriteAccess + ', expected: ' + isWriteAccess + '.'); @@ -2140,15 +2141,15 @@ module FourSlash { } } - var missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; + let missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; this.raiseError('verifyOccurancesAtPositionListContains failed - could not find the item: ' + JSON.stringify(missingItem) + ' in the returned list: (' + JSON.stringify(occurances) + ')'); } public verifyOccurrencesAtPositionListCount(expectedCount: number) { this.taoInvalidReason = 'verifyOccurrencesAtPositionListCount NYI'; - var occurances = this.getOccurancesAtCurrentPosition(); - var actualCount = occurances ? occurances.length : 0; + let occurances = this.getOccurancesAtCurrentPosition(); + let actualCount = occurances ? occurances.length : 0; if (expectedCount !== actualCount) { this.raiseError('verifyOccurrencesAtPositionListCount failed - actual: ' + actualCount + ', expected:' + expectedCount); } @@ -2156,13 +2157,13 @@ module FourSlash { // Get the text of the entire line the caret is currently at private getCurrentLineContent() { - var text = this.getFileContent(this.activeFile.fileName) + let text = this.getFileContent(this.activeFile.fileName); - var pos = this.currentCaretPosition; - var startPos = pos, endPos = pos; + let pos = this.currentCaretPosition; + let startPos = pos, endPos = pos; while (startPos > 0) { - var ch = text.charCodeAt(startPos - 1); + let ch = text.charCodeAt(startPos - 1); if (ch === ts.CharacterCodes.carriageReturn || ch === ts.CharacterCodes.lineFeed) { break; } @@ -2171,7 +2172,7 @@ module FourSlash { } while (endPos < text.length) { - var ch = text.charCodeAt(endPos); + let ch = text.charCodeAt(endPos); if (ch === ts.CharacterCodes.carriageReturn || ch === ts.CharacterCodes.lineFeed) { break; @@ -2191,11 +2192,11 @@ module FourSlash { this.taoInvalidReason = 'assertItemInCompletionList only supports the "name" parameter'; } - for (var i = 0; i < items.length; i++) { - var item = items[i]; + for (let i = 0; i < items.length; i++) { + let item = items[i]; if (item.name === name) { if (documentation != undefined || text !== undefined) { - var details = this.getCompletionEntryDetails(item.name); + let details = this.getCompletionEntryDetails(item.name); if (documentation !== undefined) { assert.equal(ts.displayPartsToString(details.documentation), documentation, assertionMessage("completion item documentation")); @@ -2213,30 +2214,30 @@ module FourSlash { } } - var itemsString = items.map((item) => JSON.stringify({ name: item.name, kind: item.kind })).join(",\n"); + let itemsString = items.map((item) => JSON.stringify({ name: item.name, kind: item.kind })).join(",\n"); this.raiseError('Expected "' + JSON.stringify({ name, text, documentation, kind }) + '" to be in list [' + itemsString + ']'); } private findFile(indexOrName: any) { - var result: FourSlashFile = null; + let result: FourSlashFile = null; if (typeof indexOrName === 'number') { - var index = indexOrName; + let index = indexOrName; if (index >= this.testData.files.length) { throw new Error('File index (' + index + ') in openFile was out of range. There are only ' + this.testData.files.length + ' files in this test.'); } else { result = this.testData.files[index]; } } else if (typeof indexOrName === 'string') { - var name = indexOrName; + let name = indexOrName; // names are stored in the compiler with this relative path, this allows people to use goTo.file on just the fileName name = name.indexOf('/') === -1 ? (this.basePath + '/' + name) : name; - var availableNames: string[] = []; - var foundIt = false; - for (var i = 0; i < this.testData.files.length; i++) { - var fn = this.testData.files[i].fileName; + let availableNames: string[] = []; + let foundIt = false; + for (let i = 0; i < this.testData.files.length; i++) { + let fn = this.testData.files[i].fileName; if (fn) { if (fn === name) { result = this.testData.files[i]; @@ -2258,15 +2259,15 @@ module FourSlash { } private getLineColStringAtPosition(position: number) { - var pos = this.languageServiceAdapterHost.positionToLineAndCharacter(this.activeFile.fileName, position); + let pos = this.languageServiceAdapterHost.positionToLineAndCharacter(this.activeFile.fileName, position); return 'line ' + (pos.line + 1) + ', col ' + pos.character; } private getMarkerByName(markerName: string) { - var markerPos = this.testData.markerPositions[markerName]; + let markerPos = this.testData.markerPositions[markerName]; if (markerPos === undefined) { - var markerNames: string[] = []; - for (var m in this.testData.markerPositions) markerNames.push(m); + let markerNames: string[] = []; + for (let m in this.testData.markerPositions) markerNames.push(m); throw new Error('Unknown marker "' + markerName + '" Available markers: ' + markerNames.map(m => '"' + m + '"').join(', ')); } else { return markerPos; @@ -2286,7 +2287,7 @@ module FourSlash { } public setCancelled(numberOfCalls: number): void { - this.cancellationToken.setCancelled(numberOfCalls) + this.cancellationToken.setCancelled(numberOfCalls); } public resetCancelled(): void { @@ -2295,12 +2296,12 @@ module FourSlash { } // TOOD: should these just use the Harness's stdout/stderr? - var fsOutput = new Harness.Compiler.WriterAggregator(); - var fsErrors = new Harness.Compiler.WriterAggregator(); - export var xmlData: TestXmlData[] = []; + let fsOutput = new Harness.Compiler.WriterAggregator(); + let fsErrors = new Harness.Compiler.WriterAggregator(); + export let xmlData: TestXmlData[] = []; export function runFourSlashTest(basePath: string, testType: FourSlashTestType, fileName: string) { - var content = Harness.IO.readFile(fileName); - var xml = runFourSlashTestContent(basePath, testType, content, fileName); + let content = Harness.IO.readFile(fileName); + let xml = runFourSlashTestContent(basePath, testType, content, fileName); xmlData.push(xml); } @@ -2365,8 +2366,8 @@ module FourSlash { } function chompLeadingSpace(content: string) { - var lines = content.split("\n"); - for (var i = 0; i < lines.length; i++) { + let lines = content.split("\n"); + for (let i = 0; i < lines.length; i++) { if ((lines[i].length !== 0) && (lines[i].charAt(0) !== ' ')) { return content; } @@ -2377,31 +2378,31 @@ module FourSlash { function parseTestData(basePath: string, contents: string, fileName: string): FourSlashData { // Regex for parsing options in the format "@Alpha: Value of any sort" - var optionRegex = /^\s*@(\w+): (.*)\s*/; + let optionRegex = /^\s*@(\w+): (.*)\s*/; // List of all the subfiles we've parsed out - var files: FourSlashFile[] = []; + let files: FourSlashFile[] = []; // Global options - var globalOptions: { [s: string]: string; } = {}; + let globalOptions: { [s: string]: string; } = {}; // Marker positions // Split up the input file by line // Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so // we have to string-based splitting instead and try to figure out the delimiting chars - var lines = contents.split('\n'); + let lines = contents.split('\n'); - var markerPositions: MarkerMap = {}; - var markers: Marker[] = []; - var ranges: Range[] = []; + let markerPositions: MarkerMap = {}; + let markers: Marker[] = []; + let ranges: Range[] = []; // Stuff related to the subfile we're parsing - var currentFileContent: string = null; - var currentFileName = fileName; - var currentFileOptions: { [s: string]: string } = {}; + let currentFileContent: string = null; + let currentFileName = fileName; + let currentFileOptions: { [s: string]: string } = {}; - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - var lineLength = line.length; + for (let i = 0; i < lines.length; i++) { + let line = lines[i]; + let lineLength = line.length; if (lineLength > 0 && line.charAt(lineLength - 1) === '\r') { line = line.substr(0, lineLength - 1); @@ -2421,17 +2422,17 @@ module FourSlash { currentFileContent = currentFileContent + line.substr(4); } else if (line.substr(0, 2) === '//') { // Comment line, check for global/file @options and record them - var match = optionRegex.exec(line.substr(2)); + let match = optionRegex.exec(line.substr(2)); if (match) { - var globalMetadataNamesIndex = globalMetadataNames.indexOf(match[1]); - var fileMetadataNamesIndex = fileMetadataNames.indexOf(match[1]); + let globalMetadataNamesIndex = globalMetadataNames.indexOf(match[1]); + let fileMetadataNamesIndex = fileMetadataNames.indexOf(match[1]); if (globalMetadataNamesIndex === -1) { if (fileMetadataNamesIndex === -1) { throw new Error('Unrecognized metadata name "' + match[1] + '". Available global metadata names are: ' + globalMetadataNames.join(', ') + '; file metadata names are: ' + fileMetadataNames.join(', ')); } else if (fileMetadataNamesIndex === fileMetadataNames.indexOf(metadataOptionNames.fileName)) { // Found an @FileName directive, if this is not the first then create a new subfile if (currentFileContent) { - var file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); + let file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); file.fileOptions = currentFileOptions; // Store result file @@ -2464,7 +2465,7 @@ module FourSlash { } else { // Empty line or code line, terminate current subfile if there is one if (currentFileContent) { - var file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); + let file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); file.fileOptions = currentFileOptions; // Store result file @@ -2494,12 +2495,12 @@ module FourSlash { } function reportError(fileName: string, line: number, col: number, message: string) { - var errorMessage = fileName + "(" + line + "," + col + "): " + message; + let errorMessage = fileName + "(" + line + "," + col + "): " + message; throw new Error(errorMessage); } function recordObjectMarker(fileName: string, location: ILocationInformation, text: string, markerMap: MarkerMap, markers: Marker[]): Marker { - var markerValue: any = undefined; + let markerValue: any = undefined; try { // Attempt to parse the marker value as JSON markerValue = JSON.parse("{ " + text + " }"); @@ -2512,7 +2513,7 @@ module FourSlash { return null; } - var marker: Marker = { + let marker: Marker = { fileName: fileName, position: location.position, data: markerValue @@ -2529,14 +2530,14 @@ module FourSlash { } function recordMarker(fileName: string, location: ILocationInformation, name: string, markerMap: MarkerMap, markers: Marker[]): Marker { - var marker: Marker = { + let marker: Marker = { fileName: fileName, position: location.position }; // Verify markers for uniqueness if (markerMap[name] !== undefined) { - var message = "Marker '" + name + "' is duplicated in the source file contents."; + let message = "Marker '" + name + "' is duplicated in the source file contents."; reportError(marker.fileName, location.sourceLine, location.sourceColumn, message); return null; } else { @@ -2550,34 +2551,34 @@ module FourSlash { content = chompLeadingSpace(content); // Any slash-star comment with a character not in this string is not a marker. - var validMarkerChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$1234567890_'; + let validMarkerChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$1234567890_'; /// The file content (minus metacharacters) so far - var output: string = ""; + let output: string = ""; /// The current marker (or maybe multi-line comment?) we're parsing, possibly - var openMarker: ILocationInformation = null; + let openMarker: ILocationInformation = null; /// A stack of the open range markers that are still unclosed - var openRanges: IRangeLocationInformation[] = []; + let openRanges: IRangeLocationInformation[] = []; /// A list of ranges we've collected so far */ - var localRanges: Range[] = []; + let localRanges: Range[] = []; /// The latest position of the start of an unflushed plain text area - var lastNormalCharPosition: number = 0; + let lastNormalCharPosition: number = 0; /// The total number of metacharacters removed from the file (so far) - var difference: number = 0; + let difference: number = 0; /// The fourslash file state object we are generating - var state: State = State.none; + let state: State = State.none; /// Current position data - var line: number = 1; - var column: number = 1; + let line: number = 1; + let column: number = 1; - var flush = (lastSafeCharIndex: number) => { + let flush = (lastSafeCharIndex: number) => { if (lastSafeCharIndex === undefined) { output = output + content.substr(lastNormalCharPosition); } else { @@ -2586,9 +2587,9 @@ module FourSlash { }; if (content.length > 0) { - var previousChar = content.charAt(0); - for (var i = 1; i < content.length; i++) { - var currentChar = content.charAt(i); + let previousChar = content.charAt(0); + for (let i = 1; i < content.length; i++) { + let currentChar = content.charAt(i); switch (state) { case State.none: if (previousChar === "[" && currentChar === "|") { @@ -2605,12 +2606,12 @@ module FourSlash { difference += 2; } else if (previousChar === "|" && currentChar === "]") { // found a range end - var rangeStart = openRanges.pop(); + let rangeStart = openRanges.pop(); if (!rangeStart) { reportError(fileName, line, column, "Found range end with no matching start."); } - var range: Range = { + let range: Range = { fileName: fileName, start: rangeStart.position, end: (i - 1) - difference, @@ -2648,8 +2649,8 @@ module FourSlash { // Object markers are only ever terminated by |} and have no content restrictions if (previousChar === "|" && currentChar === "}") { // Record the marker - var objectMarkerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); - var marker = recordObjectMarker(fileName, openMarker, objectMarkerNameText, markerMap, markers); + let objectMarkerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); + let marker = recordObjectMarker(fileName, openMarker, objectMarkerNameText, markerMap, markers); if (openRanges.length > 0) { openRanges[openRanges.length - 1].marker = marker; @@ -2669,8 +2670,8 @@ module FourSlash { if (previousChar === "*" && currentChar === "/") { // Record the marker // start + 2 to ignore the */, -1 on the end to ignore the * (/ is next) - var markerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); - var marker = recordMarker(fileName, openMarker, markerNameText, markerMap, markers); + let markerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); + let marker = recordMarker(fileName, openMarker, markerNameText, markerMap, markers); if (openRanges.length > 0) { openRanges[openRanges.length - 1].marker = marker; @@ -2718,7 +2719,7 @@ module FourSlash { flush(undefined); if (openRanges.length > 0) { - var openRange = openRanges[0]; + let openRange = openRanges[0]; reportError(fileName, openRange.sourceLine, openRange.sourceColumn, "Unterminated range."); } diff --git a/src/harness/fourslashRunner.ts b/src/harness/fourslashRunner.ts index 97a7f191ec9..05a11c4f52d 100644 --- a/src/harness/fourslashRunner.ts +++ b/src/harness/fourslashRunner.ts @@ -35,40 +35,40 @@ class FourSlashRunner extends RunnerBase { this.tests = this.enumerateFiles(this.basePath, /\.ts/i, { recursive: false }); } - describe(this.testSuiteName + ' tests', () => { + describe(this.testSuiteName + ' tests', () => { this.tests.forEach((fn: string) => { describe(fn, () => { fn = ts.normalizeSlashes(fn); - var justName = fn.replace(/^.*[\\\/]/, ''); - + let justName = fn.replace(/^.*[\\\/]/, ''); + // Convert to relative path - var testIndex = fn.indexOf('tests/'); + let testIndex = fn.indexOf('tests/'); if (testIndex >= 0) fn = fn.substr(testIndex); - if (justName && !justName.match(/fourslash\.ts$/i) && !justName.match(/\.d\.ts$/i)) { - it(this.testSuiteName + ' test ' + justName + ' runs correctly',() => { + if (justName && !justName.match(/fourslash\.ts$/i) && !justName.match(/\.d\.ts$/i)) { + it(this.testSuiteName + ' test ' + justName + ' runs correctly', () => { FourSlash.runFourSlashTest(this.basePath, this.testType, fn); }); } }); - }); + }); describe('Generate Tao XML', () => { - var invalidReasons: any = {}; + let invalidReasons: any = {}; FourSlash.xmlData.forEach(xml => { if (xml.invalidReason !== null) { invalidReasons[xml.invalidReason] = (invalidReasons[xml.invalidReason] || 0) + 1; } }); - var invalidReport: { reason: string; count: number }[] = []; - for (var reason in invalidReasons) { + let invalidReport: { reason: string; count: number }[] = []; + for (let reason in invalidReasons) { if (invalidReasons.hasOwnProperty(reason)) { invalidReport.push({ reason: reason, count: invalidReasons[reason] }); } } invalidReport.sort((lhs, rhs) => lhs.count > rhs.count ? -1 : lhs.count === rhs.count ? 0 : 1); - var lines: string[] = []; + let lines: string[] = []; lines.push('