Merge remote-tracking branch 'upstream/master' into fix3903

Conflicts:
	tests/baselines/reference/tsxElementResolution9.errors.txt
This commit is contained in:
Ryan Cavanaugh
2015-07-22 10:01:08 -07:00
512 changed files with 9436 additions and 7712 deletions
+11 -8
View File
@@ -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 });
+83 -43
View File
@@ -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) {
+304 -254
View File
@@ -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 () {
+2
View File
@@ -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;
+243 -129
View File
@@ -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 () {
+2
View File
@@ -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;
+243 -129
View File
@@ -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 () {
+14 -8
View File
@@ -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);
}
}
}
}
+451 -227
View File
File diff suppressed because it is too large Load Diff
@@ -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." },
+4
View File
@@ -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
+99 -18
View File
@@ -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((<BindingPattern>node).elements, visit);
@@ -6090,16 +6161,23 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if ((<ExportDeclaration>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 (<ExportDeclaration>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);
+7 -2
View File
@@ -3295,7 +3295,7 @@ namespace ts {
function parseSuperExpression(): MemberExpression {
let expression = parseTokenNode<PrimaryExpression>();
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();
}
}
+17 -3
View File
@@ -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;
+13 -2
View File
@@ -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 (<ExternalModuleReference>(<ImportEqualsDeclaration>node).moduleReference).expression;
}
export function isInternalModuleImportEqualsDeclaration(node: Node) {
export function isInternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration {
return node.kind === SyntaxKind.ImportEqualsDeclaration && (<ImportEqualsDeclaration>node).moduleReference.kind !== SyntaxKind.ExternalModuleReference;
}
@@ -1981,6 +1981,17 @@ namespace ts {
(node.parent.kind === SyntaxKind.PropertyAccessExpression && (<PropertyAccessExpression>node.parent).name === node);
}
export function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean {
let kind = expression.kind;
if (kind === SyntaxKind.ObjectLiteralExpression) {
return (<ObjectLiteralExpression>expression).properties.length === 0;
}
if (kind === SyntaxKind.ArrayLiteralExpression) {
return (<ArrayLiteralExpression>expression).elements.length === 0;
}
return false;
}
export function getLocalSymbolForExportDefault(symbol: Symbol) {
return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & NodeFlags.Default) ? symbol.valueDeclaration.localSymbol : undefined;
}
+39 -40
View File
@@ -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;
+370 -369
View File
File diff suppressed because it is too large Load Diff
+11 -11
View File
@@ -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('<!-- Blocked Test Report');
invalidReport.forEach((reasonAndCount) => {
lines.push(reasonAndCount.count + ' tests blocked by ' + reasonAndCount.reason);
+170 -175
View File
@@ -33,8 +33,6 @@ declare var __dirname: string; // Node-specific
var global = <any>Function("return this").call(null);
module Utils {
var global = <any>Function("return this").call(null);
// Setup some globals based on the current environment
export const enum ExecutionEnvironment {
Node,
@@ -54,17 +52,17 @@ module Utils {
}
}
export var currentExecutionEnvironment = getExecutionEnvironment();
export let currentExecutionEnvironment = getExecutionEnvironment();
export function evalFile(fileContents: string, fileName: string, nodeContext?: any) {
var environment = getExecutionEnvironment();
let environment = getExecutionEnvironment();
switch (environment) {
case ExecutionEnvironment.CScript:
case ExecutionEnvironment.Browser:
eval(fileContents);
break;
case ExecutionEnvironment.Node:
var vm = require('vm');
let vm = require('vm');
if (nodeContext) {
vm.runInNewContext(fileContents, nodeContext, fileName);
} else {
@@ -81,7 +79,7 @@ module Utils {
// Split up the input file by line
// Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so
// we have to use string-based splitting instead and try to figure out the delimiting chars
var lines = content.split('\r\n');
let lines = content.split('\r\n');
if (lines.length === 1) {
lines = content.split('\n');
@@ -98,8 +96,9 @@ module Utils {
path = "tests/" + path;
}
let content: string = undefined;
try {
var content = ts.sys.readFile(Harness.userSpecifiedRoot + path);
content = ts.sys.readFile(Harness.userSpecifiedRoot + path);
}
catch (err) {
return undefined;
@@ -109,11 +108,11 @@ module Utils {
}
export function memoize<T extends Function>(f: T): T {
var cache: { [idx: string]: any } = {};
let cache: { [idx: string]: any } = {};
return <any>(function () {
var key = Array.prototype.join.call(arguments);
var cachedResult = cache[key];
let key = Array.prototype.join.call(arguments);
let cachedResult = cache[key];
if (cachedResult) {
return cachedResult;
} else {
@@ -140,7 +139,7 @@ module Utils {
});
// Make sure each of the children is in order.
var currentPos = 0;
let currentPos = 0;
ts.forEachChild(node,
child => {
assert.isFalse(child.pos < currentPos, "child.pos < currentPos");
@@ -151,22 +150,22 @@ module Utils {
assert.isFalse(array.end > node.end, "array.end > node.end");
assert.isFalse(array.pos < currentPos, "array.pos < currentPos");
for (var i = 0, n = array.length; i < n; i++) {
for (let i = 0, n = array.length; i < n; i++) {
assert.isFalse(array[i].pos < currentPos, "array[i].pos < currentPos");
currentPos = array[i].end
currentPos = array[i].end;
}
currentPos = array.end;
});
var childNodesAndArrays: any[] = [];
ts.forEachChild(node, child => { childNodesAndArrays.push(child) }, array => { childNodesAndArrays.push(array) });
let childNodesAndArrays: any[] = [];
ts.forEachChild(node, child => { childNodesAndArrays.push(child); }, array => { childNodesAndArrays.push(array); });
for (var childName in node) {
for (let childName in node) {
if (childName === "parent" || childName === "nextContainer" || childName === "modifiers" || childName === "externalModuleIndicator") {
continue;
}
var child = (<any>node)[childName];
let child = (<any>node)[childName];
if (isNodeOrArray(child)) {
assert.isFalse(childNodesAndArrays.indexOf(child) < 0,
"Missing child when forEach'ing over node: " + (<any>ts).SyntaxKind[node.kind] + "-" + childName);
@@ -194,7 +193,7 @@ module Utils {
}
export function sourceFileToJSON(file: ts.Node): string {
return JSON.stringify(file,(k, v) => {
return JSON.stringify(file, (k, v) => {
return isNodeOrArray(v) ? serializeNode(v) : v;
}, " ");
@@ -203,7 +202,7 @@ module Utils {
return k;
}
return (<any>ts).SyntaxKind[k]
return (<any>ts).SyntaxKind[k];
}
function getFlagName(flags: any, f: number): any {
@@ -211,7 +210,7 @@ module Utils {
return 0;
}
var result = "";
let result = "";
ts.forEach(Object.getOwnPropertyNames(flags), (v: any) => {
if (isFinite(v)) {
v = +v;
@@ -234,7 +233,7 @@ module Utils {
function getParserContextFlagName(f: number) { return getFlagName((<any>ts).ParserContextFlags, f); }
function serializeNode(n: ts.Node): any {
var o: any = { kind: getKindName(n.kind) };
let o: any = { kind: getKindName(n.kind) };
if (ts.containsParseError(n)) {
o.containsParseError = true;
}
@@ -268,7 +267,7 @@ module Utils {
// Clear the flag that are produced by aggregating child values.. That is ephemeral
// data we don't care about in the dump. We only care what the parser set directly
// on the ast.
var value = n.parserContextFlags & ts.ParserContextFlags.ParserGeneratedFlags;
let value = n.parserContextFlags & ts.ParserContextFlags.ParserGeneratedFlags;
if (value) {
o[propertyName] = getParserContextFlagName(value);
}
@@ -313,9 +312,9 @@ module Utils {
assert.equal(array1.length, array2.length, "array1.length !== array2.length");
for (var i = 0, n = array1.length; i < n; i++) {
var d1 = array1[i];
var d2 = array2[i];
for (let i = 0, n = array1.length; i < n; i++) {
let d1 = array1[i];
let d2 = array2[i];
assert.equal(d1.start, d2.start, "d1.start !== d2.start");
assert.equal(d1.length, d2.length, "d1.length !== d2.length");
@@ -346,14 +345,14 @@ module Utils {
ts.forEachChild(node1,
child1 => {
var childName = findChildName(node1, child1);
var child2: ts.Node = (<any>node2)[childName];
let childName = findChildName(node1, child1);
let child2: ts.Node = (<any>node2)[childName];
assertStructuralEquals(child1, child2);
},
(array1: ts.NodeArray<ts.Node>) => {
var childName = findChildName(node1, array1);
var array2: ts.NodeArray<ts.Node> = (<any>node2)[childName];
let childName = findChildName(node1, array1);
let array2: ts.NodeArray<ts.Node> = (<any>node2)[childName];
assertArrayStructuralEquals(array1, array2);
});
@@ -370,13 +369,13 @@ module Utils {
assert.equal(array1.end, array2.end, "array1.end !== array2.end");
assert.equal(array1.length, array2.length, "array1.length !== array2.length");
for (var i = 0, n = array1.length; i < n; i++) {
for (let i = 0, n = array1.length; i < n; i++) {
assertStructuralEquals(array1[i], array2[i]);
}
}
function findChildName(parent: any, child: any) {
for (var name in parent) {
for (let name in parent) {
if (parent.hasOwnProperty(name) && parent[name] === child) {
return name;
}
@@ -393,8 +392,8 @@ module Harness.Path {
export function filePath(fullPath: string) {
fullPath = ts.normalizeSlashes(fullPath);
var components = fullPath.split("/");
var path: string[] = components.slice(0, components.length - 1);
let components = fullPath.split("/");
let path: string[] = components.slice(0, components.length - 1);
return path.join("/") + "/";
}
}
@@ -422,19 +421,19 @@ module Harness {
}
export module CScript {
var fso: any;
let fso: any;
if (global.ActiveXObject) {
fso = new global.ActiveXObject("Scripting.FileSystemObject");
} else {
fso = {};
}
export var readFile: typeof IO.readFile = ts.sys.readFile;
export var writeFile: typeof IO.writeFile = ts.sys.writeFile;
export var directoryName: typeof IO.directoryName = fso.GetParentFolderName;
export var directoryExists: typeof IO.directoryExists = fso.FolderExists;
export var fileExists: typeof IO.fileExists = fso.FileExists;
export var log: typeof IO.log = global.WScript && global.WScript.StdOut.WriteLine;
export let readFile: typeof IO.readFile = ts.sys.readFile;
export let writeFile: typeof IO.writeFile = ts.sys.writeFile;
export let directoryName: typeof IO.directoryName = fso.GetParentFolderName;
export let directoryExists: typeof IO.directoryExists = fso.FolderExists;
export let fileExists: typeof IO.fileExists = fso.FileExists;
export let log: typeof IO.log = global.WScript && global.WScript.StdOut.WriteLine;
export function createDirectory(path: string) {
if (directoryExists(path)) {
@@ -448,11 +447,11 @@ module Harness {
}
}
export var listFiles: typeof IO.listFiles = (path, spec?, options?) => {
export let listFiles: typeof IO.listFiles = (path, spec?, options?) => {
options = options || <{ recursive?: boolean; }>{};
function filesInFolder(folder: any, root: string): string[] {
var paths: string[] = [];
var fc: any;
let paths: string[] = [];
let fc: any;
if (options.recursive) {
fc = new Enumerator(folder.subfolders);
@@ -473,17 +472,16 @@ module Harness {
return paths;
}
var folder: any = fso.GetFolder(path);
var paths: string[] = [];
let folder: any = fso.GetFolder(path);
let paths: string[] = [];
return filesInFolder(folder, path);
}
};
}
export module Node {
declare var require: any;
var fs: any, pathModule: any;
declare let require: any;
let fs: any, pathModule: any;
if (require) {
fs = require('fs');
pathModule = require('path');
@@ -491,10 +489,10 @@ module Harness {
fs = pathModule = {};
}
export var readFile: typeof IO.readFile = ts.sys.readFile;
export var writeFile: typeof IO.writeFile = ts.sys.writeFile;
export var fileExists: typeof IO.fileExists = fs.existsSync;
export var log: typeof IO.log = console.log;
export let readFile: typeof IO.readFile = ts.sys.readFile;
export let writeFile: typeof IO.writeFile = ts.sys.writeFile;
export let fileExists: typeof IO.fileExists = fs.existsSync;
export let log: typeof IO.log = console.log;
export function createDirectory(path: string) {
if (!directoryExists(path)) {
@@ -514,7 +512,7 @@ module Harness {
}
export function directoryName(path: string) {
var dirPath = pathModule.dirname(path);
let dirPath = pathModule.dirname(path);
// Node will just continue to repeat the root path, rather than return null
if (dirPath === path) {
@@ -524,16 +522,16 @@ module Harness {
}
}
export var listFiles: typeof IO.listFiles = (path, spec?, options?) => {
export let listFiles: typeof IO.listFiles = (path, spec?, options?) => {
options = options || <{ recursive?: boolean; }>{};
function filesInFolder(folder: string): string[] {
var paths: string[] = [];
let paths: string[] = [];
var files = fs.readdirSync(folder);
for (var i = 0; i < files.length; i++) {
var pathToFile = pathModule.join(folder, files[i]);
var stat = fs.statSync(pathToFile);
let files = fs.readdirSync(folder);
for (let i = 0; i < files.length; i++) {
let pathToFile = pathModule.join(folder, files[i]);
let stat = fs.statSync(pathToFile);
if (options.recursive && stat.isDirectory()) {
paths = paths.concat(filesInFolder(pathToFile));
}
@@ -546,23 +544,23 @@ module Harness {
}
return filesInFolder(path);
}
};
export var getMemoryUsage: typeof IO.getMemoryUsage = () => {
export let getMemoryUsage: typeof IO.getMemoryUsage = () => {
if (global.gc) {
global.gc();
}
return process.memoryUsage().heapUsed;
}
};
}
export module Network {
var serverRoot = "http://localhost:8888/";
let serverRoot = "http://localhost:8888/";
// Unused?
var newLine = '\r\n';
var currentDirectory = () => '';
var supportsCodePage = () => false;
let newLine = '\r\n';
let currentDirectory = () => '';
let supportsCodePage = () => false;
module Http {
function waitForXHR(xhr: XMLHttpRequest) {
@@ -572,7 +570,7 @@ module Harness {
/// Ask the server to use node's path.resolve to resolve the given path
function getResolvedPathFromServer(path: string) {
var xhr = new XMLHttpRequest();
let xhr = new XMLHttpRequest();
try {
xhr.open("GET", path + "?resolve", false);
xhr.send();
@@ -591,7 +589,7 @@ module Harness {
/// Ask the server for the contents of the file at the given URL via a simple GET request
export function getFileFromServerSync(url: string): XHRResponse {
var xhr = new XMLHttpRequest();
let xhr = new XMLHttpRequest();
try {
xhr.open("GET", url, false);
xhr.send();
@@ -605,10 +603,10 @@ module Harness {
/// Submit a POST request to the server to do the given action (ex WRITE, DELETE) on the provided URL
export function writeToServerSync(url: string, action: string, contents?: string): XHRResponse {
var xhr = new XMLHttpRequest();
let xhr = new XMLHttpRequest();
try {
var action = '?action=' + action;
xhr.open('POST', url + action, false);
let actionMsg = '?action=' + action;
xhr.open('POST', url + actionMsg, false);
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.send(contents);
}
@@ -633,7 +631,7 @@ module Harness {
}
function directoryNameImpl(path: string) {
var dirPath = path;
let dirPath = path;
// root of the server
if (dirPath.match(/localhost:\d+$/) || dirPath.match(/localhost:\d+\/$/)) {
dirPath = null;
@@ -646,22 +644,22 @@ module Harness {
if (dirPath.match(/.*\/$/)) {
dirPath = dirPath.substring(0, dirPath.length - 2);
}
var dirPath = dirPath.substring(0, dirPath.lastIndexOf('/'));
dirPath = dirPath.substring(0, dirPath.lastIndexOf('/'));
}
return dirPath;
}
export var directoryName: typeof IO.directoryName = Utils.memoize(directoryNameImpl);
export let directoryName: typeof IO.directoryName = Utils.memoize(directoryNameImpl);
export function fileExists(path: string): boolean {
var response = Http.getFileFromServerSync(serverRoot + path);
let response = Http.getFileFromServerSync(serverRoot + path);
return response.status === 200;
}
export function _listFilesImpl(path: string, spec?: RegExp, options?: any) {
var response = Http.getFileFromServerSync(serverRoot + path);
let response = Http.getFileFromServerSync(serverRoot + path);
if (response.status === 200) {
var results = response.responseText.split(',');
let results = response.responseText.split(',');
if (spec) {
return results.filter(file => spec.test(file));
} else {
@@ -672,12 +670,12 @@ module Harness {
return [''];
}
};
export var listFiles = Utils.memoize(_listFilesImpl);
export let listFiles = Utils.memoize(_listFilesImpl);
export var log = console.log;
export let log = console.log;
export function readFile(file: string) {
var response = Http.getFileFromServerSync(serverRoot + file);
let response = Http.getFileFromServerSync(serverRoot + file);
if (response.status === 200) {
return response.responseText;
} else {
@@ -706,9 +704,9 @@ module Harness {
}
module Harness {
var tcServicesFileName = "typescriptServices.js";
let tcServicesFileName = "typescriptServices.js";
export var libFolder: string;
export let libFolder: string;
switch (Utils.getExecutionEnvironment()) {
case Utils.ExecutionEnvironment.CScript:
libFolder = "built/local/";
@@ -725,7 +723,7 @@ module Harness {
default:
throw new Error('Unknown context');
}
export var tcServicesFile = IO.readFile(tcServicesFileName);
export let tcServicesFile = IO.readFile(tcServicesFileName);
export interface SourceMapEmitterCallback {
(emittedFile: string, emittedLine: number, emittedColumn: number, sourceFile: string, sourceLine: number, sourceColumn: number, sourceName: string): void;
@@ -777,7 +775,7 @@ module Harness {
/** create file gets the whole path to create, so this works as expected with the --out parameter */
public writeFile(s: string, contents: string, writeByteOrderMark: boolean): void {
var writer: ITextWriter;
let writer: ITextWriter;
if (this.fileCollection[s]) {
writer = <ITextWriter>this.fileCollection[s];
}
@@ -795,10 +793,10 @@ module Harness {
public reset() { this.fileCollection = {}; }
public toArray(): { fileName: string; file: WriterAggregator; }[] {
var result: { fileName: string; file: WriterAggregator; }[] = [];
for (var p in this.fileCollection) {
let result: { fileName: string; file: WriterAggregator; }[] = [];
for (let p in this.fileCollection) {
if (this.fileCollection.hasOwnProperty(p)) {
var current = <Harness.Compiler.WriterAggregator>this.fileCollection[p];
let current = <Harness.Compiler.WriterAggregator>this.fileCollection[p];
if (current.lines.length > 0) {
if (p.indexOf('.d.ts') !== -1) { current.lines.unshift(['////[', Path.getFileName(p), ']'].join('')); }
result.push({ fileName: p, file: this.fileCollection[p] });
@@ -813,11 +811,11 @@ module Harness {
fileName: string,
sourceText: string,
languageVersion: ts.ScriptTarget) {
// We'll only assert invariants outside of light mode.
// We'll only assert inletiants outside of light mode.
const shouldAssertInvariants = !Harness.lightMode;
// Only set the parent nodes if we're asserting invariants. We don't need them otherwise.
var result = ts.createSourceFile(fileName, sourceText, languageVersion, /*setParentNodes:*/ shouldAssertInvariants);
// Only set the parent nodes if we're asserting inletiants. We don't need them otherwise.
let result = ts.createSourceFile(fileName, sourceText, languageVersion, /*setParentNodes:*/ shouldAssertInvariants);
if (shouldAssertInvariants) {
Utils.assertInvariants(result, /*parent:*/ undefined);
@@ -829,13 +827,13 @@ module Harness {
const carriageReturnLineFeed = "\r\n";
const lineFeed = "\n";
export var defaultLibFileName = 'lib.d.ts';
export var defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
export var defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.es6.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
export let defaultLibFileName = 'lib.d.ts';
export let defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
export let defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + 'lib.core.es6.d.ts'), /*languageVersion*/ ts.ScriptTarget.Latest);
// Cache these between executions so we don't have to re-parse them for every test
export var fourslashFileName = 'fourslash.ts';
export var fourslashSourceFile: ts.SourceFile;
export let fourslashFileName = 'fourslash.ts';
export let fourslashSourceFile: ts.SourceFile;
export function getCanonicalFileName(fileName: string): string {
return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
@@ -855,13 +853,13 @@ module Harness {
return useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
var filemap: { [fileName: string]: ts.SourceFile; } = {};
var getCurrentDirectory = currentDirectory === undefined ? ts.sys.getCurrentDirectory : () => currentDirectory;
let filemap: { [fileName: string]: ts.SourceFile; } = {};
let getCurrentDirectory = currentDirectory === undefined ? ts.sys.getCurrentDirectory : () => currentDirectory;
// Register input files
function register(file: { unitName: string; content: string; }) {
if (file.content !== undefined) {
var fileName = ts.normalizePath(file.unitName);
let fileName = ts.normalizePath(file.unitName);
filemap[getCanonicalFileName(fileName)] = createSourceFileAndAssertInvariants(fileName, file.content, scriptTarget);
}
};
@@ -880,11 +878,11 @@ module Harness {
return filemap[getCanonicalFileName(fn)];
}
else if (currentDirectory) {
var canonicalAbsolutePath = getCanonicalFileName(ts.getNormalizedAbsolutePath(fn, currentDirectory));
let canonicalAbsolutePath = getCanonicalFileName(ts.getNormalizedAbsolutePath(fn, currentDirectory));
return Object.prototype.hasOwnProperty.call(filemap, getCanonicalFileName(canonicalAbsolutePath)) ? filemap[canonicalAbsolutePath] : undefined;
}
else if (fn === fourslashFileName) {
var tsFn = 'tests/cases/fourslash/' + fourslashFileName;
let tsFn = 'tests/cases/fourslash/' + fourslashFileName;
fourslashSourceFile = fourslashSourceFile || createSourceFileAndAssertInvariants(tsFn, Harness.IO.readFile(tsFn), scriptTarget);
return fourslashSourceFile;
}
@@ -980,27 +978,27 @@ module Harness {
// Files from built\local that are requested by test "@includeBuiltFiles" to be in the context.
// Treat them as library files, so include them in build, but not in baselines.
var includeBuiltFiles: { unitName: string; content: string }[] = [];
let includeBuiltFiles: { unitName: string; content: string }[] = [];
var useCaseSensitiveFileNames = ts.sys.useCaseSensitiveFileNames;
let useCaseSensitiveFileNames = ts.sys.useCaseSensitiveFileNames;
this.settings.forEach(setCompilerOptionForSetting);
var fileOutputs: GeneratedFile[] = [];
let fileOutputs: GeneratedFile[] = [];
var programFiles = inputFiles.concat(includeBuiltFiles).map(file => file.unitName);
let programFiles = inputFiles.concat(includeBuiltFiles).map(file => file.unitName);
var compilerHost = createCompilerHost(
let compilerHost = createCompilerHost(
inputFiles.concat(includeBuiltFiles).concat(otherFiles),
(fn, contents, writeByteOrderMark) => fileOutputs.push({ fileName: fn, code: contents, writeByteOrderMark: writeByteOrderMark }),
options.target, useCaseSensitiveFileNames, currentDirectory, options.newLine);
var program = ts.createProgram(programFiles, options, compilerHost);
let program = ts.createProgram(programFiles, options, compilerHost);
var emitResult = program.emit();
let emitResult = program.emit();
var errors = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
let errors = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
this.lastErrors = errors;
var result = new CompilerResult(fileOutputs, errors, program, ts.sys.getCurrentDirectory(), emitResult.sourceMaps);
let result = new CompilerResult(fileOutputs, errors, program, ts.sys.getCurrentDirectory(), emitResult.sourceMaps);
onComplete(result, program);
// reset what newline means in case the last test changed it
@@ -1193,12 +1191,12 @@ module Harness {
throw new Error('There were no errors and declFiles generated did not match number of js files generated');
}
let declInputFiles: { unitName: string; content: string }[] = [];
let declOtherFiles: { unitName: string; content: string }[] = [];
let declResult: Harness.Compiler.CompilerResult;
// if the .d.ts is non-empty, confirm it compiles correctly as well
if (options.declaration && result.errors.length === 0 && result.declFilesCode.length > 0) {
var declInputFiles: { unitName: string; content: string }[] = [];
var declOtherFiles: { unitName: string; content: string }[] = [];
var declResult: Harness.Compiler.CompilerResult;
ts.forEach(inputFiles, file => addDtsFile(file, declInputFiles));
ts.forEach(otherFiles, file => addDtsFile(file, declOtherFiles));
this.compileFiles(declInputFiles, declOtherFiles, function (compileResult) { declResult = compileResult; },
@@ -1212,20 +1210,20 @@ module Harness {
dtsFiles.push(file);
}
else if (isTS(file.unitName)) {
var declFile = findResultCodeFile(file.unitName);
let declFile = findResultCodeFile(file.unitName);
if (!findUnit(declFile.fileName, declInputFiles) && !findUnit(declFile.fileName, declOtherFiles)) {
dtsFiles.push({ unitName: declFile.fileName, content: declFile.code });
}
}
function findResultCodeFile(fileName: string) {
var sourceFile = result.program.getSourceFile(fileName);
let sourceFile = result.program.getSourceFile(fileName);
assert(sourceFile, "Program has no source file with name '" + fileName + "'");
// Is this file going to be emitted separately
var sourceFileName: string;
let sourceFileName: string;
if (ts.isExternalModule(sourceFile) || !options.out) {
if (options.outDir) {
var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, result.currentDirectoryForProgram);
let sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, result.currentDirectoryForProgram);
sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), "");
sourceFileName = ts.combinePaths(options.outDir, sourceFilePath);
}
@@ -1238,7 +1236,7 @@ module Harness {
sourceFileName = options.out;
}
var dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts";
let dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts";
return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined);
}
@@ -1251,7 +1249,7 @@ module Harness {
}
function normalizeLineEndings(text: string, lineEnding: string): string {
var normalized = text.replace(/\r\n?/g, '\n');
let normalized = text.replace(/\r\n?/g, '\n');
if (lineEnding !== '\n') {
normalized = normalized.replace(/\n/g, lineEnding);
}
@@ -1260,10 +1258,10 @@ module Harness {
export function minimalDiagnosticsToString(diagnostics: ts.Diagnostic[]) {
// This is basically copied from tsc.ts's reportError to replicate what tsc does
var errorOutput = "";
let errorOutput = "";
ts.forEach(diagnostics, diagnostic => {
if (diagnostic.file) {
var lineAndCharacter = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
let lineAndCharacter = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
errorOutput += diagnostic.file.fileName + "(" + (lineAndCharacter.line + 1) + "," + (lineAndCharacter.character + 1) + "): ";
}
@@ -1275,14 +1273,14 @@ module Harness {
export function getErrorBaseline(inputFiles: { unitName: string; content: string }[], diagnostics: ts.Diagnostic[]) {
diagnostics.sort(ts.compareDiagnostics);
var outputLines: string[] = [];
let outputLines: string[] = [];
// Count up all the errors we find so we don't miss any
var totalErrorsReported = 0;
let totalErrorsReported = 0;
function outputErrorText(error: ts.Diagnostic) {
var message = ts.flattenDiagnosticMessageText(error.messageText, ts.sys.newLine);
let message = ts.flattenDiagnosticMessageText(error.messageText, ts.sys.newLine);
var errLines = RunnerBase.removeFullPaths(message)
let errLines = RunnerBase.removeFullPaths(message)
.split('\n')
.map(s => s.length > 0 && s.charAt(s.length - 1) === '\r' ? s.substr(0, s.length - 1) : s)
.filter(s => s.length > 0)
@@ -1293,14 +1291,14 @@ module Harness {
}
// Report global errors
var globalErrors = diagnostics.filter(err => !err.file);
let globalErrors = diagnostics.filter(err => !err.file);
globalErrors.forEach(outputErrorText);
// 'merge' the lines of each input file with any errors associated with it
inputFiles.filter(f => f.content !== undefined).forEach(inputFile => {
// Filter down to the errors in the file
var fileErrors = diagnostics.filter(e => {
var errFn = e.file;
let fileErrors = diagnostics.filter(e => {
let errFn = e.file;
return errFn && errFn.fileName === inputFile.unitName;
});
@@ -1309,13 +1307,13 @@ module Harness {
outputLines.push('==== ' + inputFile.unitName + ' (' + fileErrors.length + ' errors) ====');
// Make sure we emit something for every error
var markedErrorCount = 0;
let markedErrorCount = 0;
// For each line, emit the line followed by any error squiggles matching this 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 lineStarts = ts.computeLineStarts(inputFile.content);
var lines = inputFile.content.split('\n');
let lineStarts = ts.computeLineStarts(inputFile.content);
let lines = inputFile.content.split('\n');
if (lines.length === 1) {
lines = lines[0].split("\r");
}
@@ -1325,8 +1323,8 @@ module Harness {
line = line.substr(0, line.length - 1);
}
var thisLineStart = lineStarts[lineIndex];
var nextLineStart: number;
let thisLineStart = lineStarts[lineIndex];
let nextLineStart: number;
// On the last line of the file, fake the next line start number so that we handle errors on the last character of the file correctly
if (lineIndex === lines.length - 1) {
nextLineStart = inputFile.content.length;
@@ -1340,11 +1338,11 @@ module Harness {
let end = ts.textSpanEnd(err);
if ((end >= thisLineStart) && ((err.start < nextLineStart) || (lineIndex === lines.length - 1))) {
// How many characters from the start of this line the error starts at (could be positive or negative)
var relativeOffset = err.start - thisLineStart;
let relativeOffset = err.start - thisLineStart;
// How many characters of the error are on this line (might be longer than this line in reality)
var length = (end - err.start) - Math.max(0, thisLineStart - err.start);
let length = (end - err.start) - Math.max(0, thisLineStart - err.start);
// Calculate the start of the squiggle
var squiggleStart = Math.max(0, relativeOffset);
let squiggleStart = Math.max(0, relativeOffset);
// TODO/REVIEW: this doesn't work quite right in the browser if a multi file test has files whose names are just the right length relative to one another
outputLines.push(' ' + line.substr(0, squiggleStart).replace(/[^\s]/g, ' ') + new Array(Math.min(length, line.length - squiggleStart) + 1).join('~'));
@@ -1364,11 +1362,11 @@ module Harness {
assert.equal(markedErrorCount, fileErrors.length, 'count of errors in ' + inputFile.unitName);
});
var numLibraryDiagnostics = ts.countWhere(diagnostics, diagnostic => {
let numLibraryDiagnostics = ts.countWhere(diagnostics, diagnostic => {
return diagnostic.file && (isLibraryFile(diagnostic.file.fileName) || isBuiltFile(diagnostic.file.fileName));
});
var numTest262HarnessDiagnostics = ts.countWhere(diagnostics, diagnostic => {
let numTest262HarnessDiagnostics = ts.countWhere(diagnostics, diagnostic => {
// Count an error generated from tests262-harness folder.This should only apply for test262
return diagnostic.file && diagnostic.file.fileName.indexOf("test262-harness") >= 0;
});
@@ -1385,7 +1383,7 @@ module Harness {
outputFiles.sort((a, b) => cleanName(a.fileName).localeCompare(cleanName(b.fileName)));
// Emit them
var result = '';
let result = '';
for (let outputFile of outputFiles) {
// Some extra spacing if this isn't the first file
if (result.length) {
@@ -1401,13 +1399,13 @@ module Harness {
return result;
function cleanName(fn: string) {
var lastSlash = ts.normalizeSlashes(fn).lastIndexOf('/');
let lastSlash = ts.normalizeSlashes(fn).lastIndexOf('/');
return fn.substr(lastSlash + 1).toLowerCase();
}
}
/** The harness' compiler instance used when tests are actually run. Reseting or changing settings of this compiler instance must be done within a test case (i.e., describe/it) */
var harnessCompiler: HarnessCompiler;
let harnessCompiler: HarnessCompiler;
/** Returns the singleton harness compiler instance for generating and running tests.
If required a fresh compiler instance will be created, otherwise the existing singleton will be re-used.
@@ -1420,8 +1418,6 @@ module Harness {
export function compileString(code: string, unitName: string, callback: (result: CompilerResult) => void) {
// NEWTODO: Re-implement 'compileString'
throw new Error('compileString NYI');
//var harnessCompiler = Harness.Compiler.getCompiler(Harness.Compiler.CompilerInstance.RunTime);
//harnessCompiler.compileString(code, unitName, callback);
}
export interface GeneratedFile {
@@ -1513,10 +1509,10 @@ module Harness {
}
// Regex for parsing options in the format "@Alpha: Value of any sort"
var optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines
let optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines
// List of allowed metadata names
var fileMetadataNames = ["filename", "comments", "declaration", "module",
let fileMetadataNames = ["filename", "comments", "declaration", "module",
"nolib", "sourcemap", "target", "out", "outdir", "noemithelpers", "noemitonerror",
"noimplicitany", "noresolve", "newline", "normalizenewline", "emitbom",
"errortruncation", "usecasesensitivefilenames", "preserveconstenums",
@@ -1527,9 +1523,9 @@ module Harness {
function extractCompilerSettings(content: string): CompilerSetting[] {
var opts: CompilerSetting[] = [];
let opts: CompilerSetting[] = [];
var match: RegExpExecArray;
let match: RegExpExecArray;
while ((match = optionRegex.exec(content)) != null) {
opts.push({ flag: match[1], value: match[2] });
}
@@ -1539,26 +1535,26 @@ module Harness {
/** Given a test file containing // @FileName directives, return an array of named units of code to be added to an existing compiler instance */
export function makeUnitsFromTest(code: string, fileName: string): { settings: CompilerSetting[]; testUnitData: TestUnitData[]; } {
var settings = extractCompilerSettings(code);
let settings = extractCompilerSettings(code);
// List of all the subfiles we've parsed out
var testUnitData: TestUnitData[] = [];
let testUnitData: TestUnitData[] = [];
var lines = Utils.splitContentByNewlines(code);
let lines = Utils.splitContentByNewlines(code);
// Stuff related to the subfile we're parsing
var currentFileContent: string = null;
var currentFileOptions: any = {};
var currentFileName: any = null;
var refs: string[] = [];
let currentFileContent: string = null;
let currentFileOptions: any = {};
let currentFileName: any = null;
let refs: string[] = [];
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var testMetaData = optionRegex.exec(line);
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
let testMetaData = optionRegex.exec(line);
if (testMetaData) {
// Comment line, check for global/file @options and record them
optionRegex.lastIndex = 0;
var metaDataName = testMetaData[1].toLowerCase();
let metaDataName = testMetaData[1].toLowerCase();
if (metaDataName === "filename") {
currentFileOptions[testMetaData[1]] = testMetaData[2];
} else {
@@ -1568,8 +1564,7 @@ module Harness {
// New metadata statement after having collected some code to go with the previous metadata
if (currentFileName) {
// Store result file
var newTestFile =
{
let newTestFile = {
content: currentFileContent,
name: currentFileName,
fileOptions: currentFileOptions,
@@ -1604,7 +1599,7 @@ module Harness {
currentFileName = testUnitData.length > 0 ? currentFileName : Path.getFileName(fileName);
// EOF, push whatever remains
var newTestFile2 = {
let newTestFile2 = {
content: currentFileContent || '',
name: currentFileName,
fileOptions: currentFileOptions,
@@ -1651,7 +1646,7 @@ module Harness {
}
}
var fileCache: { [idx: string]: boolean } = {};
let fileCache: { [idx: string]: boolean } = {};
function generateActual(actualFileName: string, generateContent: () => string): string {
// For now this is written using TypeScript, because sys is not available when running old test cases.
// But we need to move to sys once we have
@@ -1662,7 +1657,7 @@ module Harness {
return;
}
var parentDirectory = IO.directoryName(dirName);
let parentDirectory = IO.directoryName(dirName);
if (parentDirectory != "") {
createDirectoryStructure(parentDirectory);
}
@@ -1678,7 +1673,7 @@ module Harness {
IO.deleteFile(actualFileName);
}
var actual = generateContent();
let actual = generateContent();
if (actual === undefined) {
throw new Error('The generated content was "undefined". Return "null" if no baselining is required."');
@@ -1701,13 +1696,13 @@ module Harness {
return;
}
var refFileName = referencePath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
let refFileName = referencePath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
if (actual === null) {
actual = '<no content>';
}
var expected = '<no content>';
let expected = '<no content>';
if (IO.fileExists(refFileName)) {
expected = IO.readFile(refFileName);
}
@@ -1716,10 +1711,10 @@ module Harness {
}
function writeComparison(expected: string, actual: string, relativeFileName: string, actualFileName: string, descriptionForDescribe: string) {
var encoded_actual = (new Buffer(actual)).toString('utf8')
let encoded_actual = (new Buffer(actual)).toString('utf8');
if (expected != encoded_actual) {
// Overwrite & issue error
var errMsg = 'The baseline file ' + relativeFileName + ' has changed';
let errMsg = 'The baseline file ' + relativeFileName + ' has changed';
throw new Error(errMsg);
}
}
@@ -1731,17 +1726,17 @@ module Harness {
runImmediately = false,
opts?: BaselineOptions): void {
var actual = <string>undefined;
var actualFileName = localPath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
let actual = <string>undefined;
let actualFileName = localPath(relativeFileName, opts && opts.Baselinefolder, opts && opts.Subfolder);
if (runImmediately) {
actual = generateActual(actualFileName, generateContent);
var comparison = compareToBaseline(actual, relativeFileName, opts);
let comparison = compareToBaseline(actual, relativeFileName, opts);
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName, descriptionForDescribe);
} else {
actual = generateActual(actualFileName, generateContent);
var comparison = compareToBaseline(actual, relativeFileName, opts);
let comparison = compareToBaseline(actual, relativeFileName, opts);
writeComparison(comparison.expected, comparison.actual, relativeFileName, actualFileName, descriptionForDescribe);
}
}
@@ -1756,11 +1751,11 @@ module Harness {
}
export function getDefaultLibraryFile(): { unitName: string, content: string } {
var libFile = Harness.userSpecifiedRoot + Harness.libFolder + "/" + "lib.d.ts";
let libFile = Harness.userSpecifiedRoot + Harness.libFolder + "/" + "lib.d.ts";
return {
unitName: libFile,
content: IO.readFile(libFile)
}
};
}
if (Error) (<any>Error).stackTraceLimit = 1;
+32 -32
View File
@@ -26,9 +26,9 @@ module Harness.LanguageService {
public editContent(start: number, end: number, newText: string): void {
// Apply edits
var prefix = this.content.substring(0, start);
var middle = newText;
var suffix = this.content.substring(end);
let prefix = this.content.substring(0, start);
let middle = newText;
let suffix = this.content.substring(end);
this.setContent(prefix + middle + suffix);
// Store edit range + new length of script
@@ -48,10 +48,10 @@ module Harness.LanguageService {
return ts.unchangedTextChangeRange;
}
var initialEditRangeIndex = this.editRanges.length - (this.version - startVersion);
var lastEditRangeIndex = this.editRanges.length - (this.version - endVersion);
let initialEditRangeIndex = this.editRanges.length - (this.version - startVersion);
let lastEditRangeIndex = this.editRanges.length - (this.version - endVersion);
var entries = this.editRanges.slice(initialEditRangeIndex, lastEditRangeIndex);
let entries = this.editRanges.slice(initialEditRangeIndex, lastEditRangeIndex);
return ts.collapseTextChangeRangesAcrossMultipleVersions(entries.map(e => e.textChangeRange));
}
}
@@ -74,7 +74,7 @@ module Harness.LanguageService {
}
public getChangeRange(oldScript: ts.IScriptSnapshot): ts.TextChangeRange {
var oldShim = <ScriptSnapshot>oldScript;
let oldShim = <ScriptSnapshot>oldScript;
return this.scriptInfo.getTextChangeRangeBetweenVersions(oldShim.version, this.version);
}
}
@@ -92,9 +92,9 @@ module Harness.LanguageService {
}
public getChangeRange(oldScript: ts.ScriptSnapshotShim): string {
var oldShim = <ScriptSnapshotProxy>oldScript;
let oldShim = <ScriptSnapshotProxy>oldScript;
var range = this.scriptSnapshot.getChangeRange(oldShim.scriptSnapshot);
let range = this.scriptSnapshot.getChangeRange(oldShim.scriptSnapshot);
if (range === null) {
return null;
}
@@ -130,8 +130,8 @@ module Harness.LanguageService {
}
public getFilenames(): string[] {
var fileNames: string[] = [];
ts.forEachKey(this.fileNameToScript,(fileName) => { fileNames.push(fileName); });
let fileNames: string[] = [];
ts.forEachKey(this.fileNameToScript, (fileName) => { fileNames.push(fileName); });
return fileNames;
}
@@ -144,7 +144,7 @@ module Harness.LanguageService {
}
public editScript(fileName: string, start: number, end: number, newText: string) {
var script = this.getScriptInfo(fileName);
let script = this.getScriptInfo(fileName);
if (script !== null) {
script.editContent(start, end, newText);
return;
@@ -161,7 +161,7 @@ module Harness.LanguageService {
* @param col 0 based index
*/
public positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter {
var script: ScriptInfo = this.fileNameToScript[fileName];
let script: ScriptInfo = this.fileNameToScript[fileName];
assert.isNotNull(script);
return ts.computeLineAndCharacterOfPosition(script.lineMap, position);
@@ -176,11 +176,11 @@ module Harness.LanguageService {
getDefaultLibFileName(): string { return ""; }
getScriptFileNames(): string[] { return this.getFilenames(); }
getScriptSnapshot(fileName: string): ts.IScriptSnapshot {
var script = this.getScriptInfo(fileName);
let script = this.getScriptInfo(fileName);
return script ? new ScriptSnapshot(script) : undefined;
}
getScriptVersion(fileName: string): string {
var script = this.getScriptInfo(fileName);
let script = this.getScriptInfo(fileName);
return script ? script.version.toString() : undefined;
}
@@ -220,7 +220,7 @@ module Harness.LanguageService {
getDefaultLibFileName(): string { return this.nativeHost.getDefaultLibFileName(); }
getScriptFileNames(): string { return JSON.stringify(this.nativeHost.getScriptFileNames()); }
getScriptSnapshot(fileName: string): ts.ScriptSnapshotShim {
var nativeScriptSnapshot = this.nativeHost.getScriptSnapshot(fileName);
let nativeScriptSnapshot = this.nativeHost.getScriptSnapshot(fileName);
return nativeScriptSnapshot && new ScriptSnapshotProxy(nativeScriptSnapshot);
}
getScriptVersion(fileName: string): string { return this.nativeHost.getScriptVersion(fileName); }
@@ -242,13 +242,13 @@ module Harness.LanguageService {
throw new Error("NYI");
}
getClassificationsForLine(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.ClassificationResult {
var result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split('\n');
var entries: ts.ClassificationInfo[] = [];
var i = 0;
var position = 0;
let result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split('\n');
let entries: ts.ClassificationInfo[] = [];
let i = 0;
let position = 0;
for (; i < result.length - 1; i += 2) {
var t = entries[i / 2] = {
let t = entries[i / 2] = {
length: parseInt(result[i]),
classification: parseInt(result[i + 1])
};
@@ -256,7 +256,7 @@ module Harness.LanguageService {
assert.isTrue(t.length > 0, "Result length should be greater than 0, got :" + t.length);
position += t.length;
}
var finalLexState = parseInt(result[result.length - 1]);
let finalLexState = parseInt(result[result.length - 1]);
assert.equal(position, text.length, "Expected cumulative length of all entries to match the length of the source. expected: " + text.length + ", but got: " + position);
@@ -268,7 +268,7 @@ module Harness.LanguageService {
}
function unwrapJSONCallResult(result: string): any {
var parsedResult = JSON.parse(result);
let parsedResult = JSON.parse(result);
if (parsedResult.error) {
throw new Error("Language Service Shim Error: " + JSON.stringify(parsedResult.error));
}
@@ -282,7 +282,7 @@ module Harness.LanguageService {
constructor(private shim: ts.LanguageServiceShim) {
}
private unwrappJSONCallResult(result: string): any {
var parsedResult = JSON.parse(result);
let parsedResult = JSON.parse(result);
if (parsedResult.error) {
throw new Error("Language Service Shim Error: " + JSON.stringify(parsedResult.error));
}
@@ -404,16 +404,16 @@ module Harness.LanguageService {
getLanguageService(): ts.LanguageService { return new LanguageServiceShimProxy(this.factory.createLanguageServiceShim(this.host)); }
getClassifier(): ts.Classifier { return new ClassifierShimProxy(this.factory.createClassifierShim(this.host)); }
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo {
var shimResult: {
let shimResult: {
referencedFiles: ts.IFileReference[];
importedFiles: ts.IFileReference[];
isLibFile: boolean;
};
var coreServicesShim = this.factory.createCoreServicesShim(this.host);
let coreServicesShim = this.factory.createCoreServicesShim(this.host);
shimResult = unwrapJSONCallResult(coreServicesShim.getPreProcessedFileInfo(fileName, ts.ScriptSnapshot.fromString(fileContents)));
var convertResult: ts.PreProcessedFileInfo = {
let convertResult: ts.PreProcessedFileInfo = {
referencedFiles: [],
importedFiles: [],
isLibFile: shimResult.isLibFile
@@ -496,7 +496,7 @@ module Harness.LanguageService {
fileName = Harness.Compiler.defaultLibFileName;
}
var snapshot = this.host.getScriptSnapshot(fileName);
let snapshot = this.host.getScriptSnapshot(fileName);
return snapshot && snapshot.getText(0, snapshot.getLength());
}
@@ -574,13 +574,13 @@ module Harness.LanguageService {
private client: ts.server.SessionClient;
constructor(cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
// This is the main host that tests use to direct tests
var clientHost = new SessionClientHost(cancellationToken, options);
var client = new ts.server.SessionClient(clientHost);
let clientHost = new SessionClientHost(cancellationToken, options);
let client = new ts.server.SessionClient(clientHost);
// This host is just a proxy for the clientHost, it uses the client
// host to answer server queries about files on disk
var serverHost = new SessionServerHost(clientHost);
var server = new ts.server.Session(serverHost, Buffer.byteLength, process.hrtime, serverHost);
let serverHost = new SessionServerHost(clientHost);
let server = new ts.server.Session(serverHost, Buffer.byteLength, process.hrtime, serverHost);
// Fake the connection between the client and the server
serverHost.writeMessage = client.onMessage.bind(client);
+20 -19
View File
@@ -12,6 +12,7 @@ interface FindFileResult {
}
interface IOLog {
timestamp: string;
arguments: string[];
executingPath: string;
currentDirectory: string;
@@ -70,9 +71,9 @@ interface PlaybackControl {
}
module Playback {
var recordLog: IOLog = undefined;
var replayLog: IOLog = undefined;
var recordLogFileNameBase = '';
let recordLog: IOLog = undefined;
let replayLog: IOLog = undefined;
let recordLogFileNameBase = '';
interface Memoized<T> {
(s: string): T;
@@ -80,8 +81,8 @@ module Playback {
}
function memoize<T>(func: (s: string) => T): Memoized<T> {
var lookup: { [s: string]: T } = {};
var run: Memoized<T> = <Memoized<T>>((s: string) => {
let lookup: { [s: string]: T } = {};
let run: Memoized<T> = <Memoized<T>>((s: string) => {
if (lookup.hasOwnProperty(s)) return lookup[s];
return lookup[s] = func(s);
});
@@ -161,10 +162,10 @@ module Playback {
}
function findResultByFields<T>(logArray: { result?: T }[], expectedFields: {}, defaultValue?: T): T {
var predicate = (entry: { result?: T }) => {
let predicate = (entry: { result?: T }) => {
return Object.getOwnPropertyNames(expectedFields).every((name) => (<any>entry)[name] === (<any>expectedFields)[name]);
};
var results = logArray.filter(entry => predicate(entry));
let results = logArray.filter(entry => predicate(entry));
if (results.length === 0) {
if (defaultValue !== undefined) {
return defaultValue;
@@ -176,17 +177,17 @@ module Playback {
}
function findResultByPath<T>(wrapper: { resolvePath(s: string): string }, logArray: { path: string; result?: T }[], expectedPath: string, defaultValue?: T): T {
var normalizedName = ts.normalizeSlashes(expectedPath).toLowerCase();
let normalizedName = ts.normalizeSlashes(expectedPath).toLowerCase();
// Try to find the result through normal fileName
for (var i = 0; i < logArray.length; i++) {
for (let i = 0; i < logArray.length; i++) {
if (ts.normalizeSlashes(logArray[i].path).toLowerCase() === normalizedName) {
return logArray[i].result;
}
}
// Fallback, try to resolve the target paths as well
if (replayLog.pathsResolved.length > 0) {
var normalizedResolvedName = wrapper.resolvePath(expectedPath).toLowerCase();
for (var i = 0; i < logArray.length; i++) {
let normalizedResolvedName = wrapper.resolvePath(expectedPath).toLowerCase();
for (let i = 0; i < logArray.length; i++) {
if (wrapper.resolvePath(logArray[i].path).toLowerCase() === normalizedResolvedName) {
return logArray[i].result;
}
@@ -200,9 +201,9 @@ module Playback {
}
}
var pathEquivCache: any = {};
let pathEquivCache: any = {};
function pathsAreEquivalent(left: string, right: string, wrapper: { resolvePath(s: string): string }) {
var key = left + '-~~-' + right;
let key = left + '-~~-' + right;
function areSame(a: string, b: string) {
return ts.normalizeSlashes(a).toLowerCase() === ts.normalizeSlashes(b).toLowerCase();
}
@@ -219,11 +220,11 @@ module Playback {
}
function noOpReplay(name: string) {
//console.log("Swallowed write operation during replay: " + name);
// console.log("Swallowed write operation during replay: " + name);
}
export function wrapSystem(underlying: ts.System): PlaybackSystem {
var wrapper: PlaybackSystem = <any>{};
let wrapper: PlaybackSystem = <any>{};
initWrapper(wrapper, underlying);
wrapper.startReplayFromFile = logFn => {
@@ -231,8 +232,8 @@ module Playback {
};
wrapper.endRecord = () => {
if (recordLog !== undefined) {
var i = 0;
var fn = () => recordLogFileNameBase + i + '.json';
let i = 0;
let fn = () => recordLogFileNameBase + i + '.json';
while (underlying.fileExists(fn())) i++;
underlying.writeFile(fn(), JSON.stringify(recordLog));
recordLog = undefined;
@@ -289,8 +290,8 @@ module Playback {
wrapper.readFile = recordReplay(wrapper.readFile, underlying)(
(path) => {
var result = underlying.readFile(path);
var logEntry = { path: path, codepage: 0, result: { contents: result, codepage: 0 } };
let result = underlying.readFile(path);
let logEntry = { path: path, codepage: 0, result: { contents: result, codepage: 0 } };
recordLog.filesRead.push(logEntry);
return result;
},
+44 -41
View File
@@ -46,7 +46,7 @@ interface BatchCompileProjectTestCaseResult extends CompileProjectFilesResult {
class ProjectRunner extends RunnerBase {
public initializeTests() {
if (this.tests.length === 0) {
var testFiles = this.enumerateFiles("tests/cases/project", /\.json$/, { recursive: true });
let testFiles = this.enumerateFiles("tests/cases/project", /\.json$/, { recursive: true });
testFiles.forEach(fn => {
fn = fn.replace(/\\/g, "/");
this.runProjectTestCase(fn);
@@ -58,10 +58,11 @@ class ProjectRunner extends RunnerBase {
}
private runProjectTestCase(testCaseFileName: string) {
var testCase: ProjectRunnerTestCase;
let testCase: ProjectRunnerTestCase;
let testFileText: string = null;
try {
var testFileText = ts.sys.readFile(testCaseFileName);
testFileText = ts.sys.readFile(testCaseFileName);
}
catch (e) {
assert(false, "Unable to open testcase file: " + testCaseFileName + ": " + e.message);
@@ -73,7 +74,7 @@ class ProjectRunner extends RunnerBase {
catch (e) {
assert(false, "Testcase: " + testCaseFileName + " does not contain valid json format: " + e.message);
}
var testCaseJustName = testCaseFileName.replace(/^.*[\\\/]/, '').replace(/\.json/, "");
let testCaseJustName = testCaseFileName.replace(/^.*[\\\/]/, '').replace(/\.json/, "");
function moduleNameToString(moduleKind: ts.ModuleKind) {
return moduleKind === ts.ModuleKind.AMD
@@ -97,9 +98,9 @@ class ProjectRunner extends RunnerBase {
}
function cleanProjectUrl(url: string) {
var diskProjectPath = ts.normalizeSlashes(ts.sys.resolvePath(testCase.projectRoot));
var projectRootUrl = "file:///" + diskProjectPath;
var normalizedProjectRoot = ts.normalizeSlashes(testCase.projectRoot);
let diskProjectPath = ts.normalizeSlashes(ts.sys.resolvePath(testCase.projectRoot));
let projectRootUrl = "file:///" + diskProjectPath;
let normalizedProjectRoot = ts.normalizeSlashes(testCase.projectRoot);
diskProjectPath = diskProjectPath.substr(0, diskProjectPath.lastIndexOf(normalizedProjectRoot));
projectRootUrl = projectRootUrl.substr(0, projectRootUrl.lastIndexOf(normalizedProjectRoot));
if (url && url.length) {
@@ -124,21 +125,21 @@ class ProjectRunner extends RunnerBase {
return ts.sys.resolvePath(testCase.projectRoot);
}
function compileProjectFiles(moduleKind: ts.ModuleKind, getInputFiles: ()=> string[],
function compileProjectFiles(moduleKind: ts.ModuleKind, getInputFiles: () => string[],
getSourceFileText: (fileName: string) => string,
writeFile: (fileName: string, data: string, writeByteOrderMark: boolean) => void): CompileProjectFilesResult {
var program = ts.createProgram(getInputFiles(), createCompilerOptions(), createCompilerHost());
var errors = ts.getPreEmitDiagnostics(program);
let program = ts.createProgram(getInputFiles(), createCompilerOptions(), createCompilerHost());
let errors = ts.getPreEmitDiagnostics(program);
var emitResult = program.emit();
let emitResult = program.emit();
errors = ts.concatenate(errors, emitResult.diagnostics);
var sourceMapData = emitResult.sourceMaps;
let sourceMapData = emitResult.sourceMaps;
// Clean up source map data that will be used in baselining
if (sourceMapData) {
for (var i = 0; i < sourceMapData.length; i++) {
for (var j = 0; j < sourceMapData[i].sourceMapSources.length; j++) {
for (let i = 0; i < sourceMapData.length; i++) {
for (let j = 0; j < sourceMapData[i].sourceMapSources.length; j++) {
sourceMapData[i].sourceMapSources[j] = cleanProjectUrl(sourceMapData[i].sourceMapSources[j]);
}
sourceMapData[i].jsSourceMappingURL = cleanProjectUrl(sourceMapData[i].jsSourceMappingURL);
@@ -168,12 +169,12 @@ class ProjectRunner extends RunnerBase {
}
function getSourceFile(fileName: string, languageVersion: ts.ScriptTarget): ts.SourceFile {
var sourceFile: ts.SourceFile = undefined;
let sourceFile: ts.SourceFile = undefined;
if (fileName === Harness.Compiler.defaultLibFileName) {
sourceFile = languageVersion === ts.ScriptTarget.ES6 ? Harness.Compiler.defaultES6LibSourceFile : Harness.Compiler.defaultLibSourceFile;
}
else {
var text = getSourceFileText(fileName);
let text = getSourceFileText(fileName);
if (text !== undefined) {
sourceFile = Harness.Compiler.createSourceFileAndAssertInvariants(fileName, text, languageVersion);
}
@@ -196,11 +197,11 @@ class ProjectRunner extends RunnerBase {
}
function batchCompilerProjectTestCase(moduleKind: ts.ModuleKind): BatchCompileProjectTestCaseResult{
var nonSubfolderDiskFiles = 0;
let nonSubfolderDiskFiles = 0;
var outputFiles: BatchCompileProjectTestCaseEmittedFile[] = [];
let outputFiles: BatchCompileProjectTestCaseEmittedFile[] = [];
var projectCompilerResult = compileProjectFiles(moduleKind, () => testCase.inputFiles, getSourceFileText, writeFile);
let projectCompilerResult = compileProjectFiles(moduleKind, () => testCase.inputFiles, getSourceFileText, writeFile);
return {
moduleKind,
program: projectCompilerResult.program,
@@ -211,8 +212,9 @@ class ProjectRunner extends RunnerBase {
};
function getSourceFileText(fileName: string): string {
let text: string = undefined;
try {
var text = ts.sys.readFile(ts.isRootedDiskPath(fileName)
text = ts.sys.readFile(ts.isRootedDiskPath(fileName)
? fileName
: ts.normalizeSlashes(testCase.projectRoot) + "/" + ts.normalizeSlashes(fileName));
}
@@ -223,11 +225,11 @@ class ProjectRunner extends RunnerBase {
}
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean) {
var diskFileName = ts.isRootedDiskPath(fileName)
let diskFileName = ts.isRootedDiskPath(fileName)
? fileName
: ts.normalizeSlashes(testCase.projectRoot) + "/" + ts.normalizeSlashes(fileName);
var diskRelativeName = ts.getRelativePathToDirectoryOrUrl(testCase.projectRoot, diskFileName,
let diskRelativeName = ts.getRelativePathToDirectoryOrUrl(testCase.projectRoot, diskFileName,
getCurrentDirectory(), Harness.Compiler.getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
if (ts.isRootedDiskPath(diskRelativeName) || diskRelativeName.substr(0, 3) === "../") {
// If the generated output file resides in the parent folder or is rooted path,
@@ -240,22 +242,22 @@ class ProjectRunner extends RunnerBase {
if (Harness.Compiler.isJS(fileName)) {
// Make sure if there is URl we have it cleaned up
var indexOfSourceMapUrl = data.lastIndexOf("//# sourceMappingURL=");
let indexOfSourceMapUrl = data.lastIndexOf("//# sourceMappingURL=");
if (indexOfSourceMapUrl !== -1) {
data = data.substring(0, indexOfSourceMapUrl + 21) + cleanProjectUrl(data.substring(indexOfSourceMapUrl + 21));
}
}
else if (Harness.Compiler.isJSMap(fileName)) {
// Make sure sources list is cleaned
var sourceMapData = JSON.parse(data);
for (var i = 0; i < sourceMapData.sources.length; i++) {
let sourceMapData = JSON.parse(data);
for (let i = 0; i < sourceMapData.sources.length; i++) {
sourceMapData.sources[i] = cleanProjectUrl(sourceMapData.sources[i]);
}
sourceMapData.sourceRoot = cleanProjectUrl(sourceMapData.sourceRoot);
data = JSON.stringify(sourceMapData);
}
var outputFilePath = getProjectOutputFolder(diskRelativeName, moduleKind);
let outputFilePath = getProjectOutputFolder(diskRelativeName, moduleKind);
// Actual writing of file as in tc.ts
function ensureDirectoryStructure(directoryname: string) {
if (directoryname) {
@@ -273,36 +275,37 @@ class ProjectRunner extends RunnerBase {
}
function compileCompileDTsFiles(compilerResult: BatchCompileProjectTestCaseResult) {
var allInputFiles: { emittedFileName: string; code: string; }[] = [];
var compilerOptions = compilerResult.program.getCompilerOptions();
let allInputFiles: { emittedFileName: string; code: string; }[] = [];
let compilerOptions = compilerResult.program.getCompilerOptions();
ts.forEach(compilerResult.program.getSourceFiles(), sourceFile => {
if (Harness.Compiler.isDTS(sourceFile.fileName)) {
allInputFiles.unshift({ emittedFileName: sourceFile.fileName, code: sourceFile.text });
}
else if (ts.shouldEmitToOwnFile(sourceFile, compilerResult.program.getCompilerOptions())) {
let emitOutputFilePathWithoutExtension: string = undefined;
if (compilerOptions.outDir) {
var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, compilerResult.program.getCurrentDirectory());
let sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.fileName, compilerResult.program.getCurrentDirectory());
sourceFilePath = sourceFilePath.replace(compilerResult.program.getCommonSourceDirectory(), "");
var emitOutputFilePathWithoutExtension = ts.removeFileExtension(ts.combinePaths(compilerOptions.outDir, sourceFilePath));
emitOutputFilePathWithoutExtension = ts.removeFileExtension(ts.combinePaths(compilerOptions.outDir, sourceFilePath));
}
else {
var emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName);
emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.fileName);
}
var outputDtsFileName = emitOutputFilePathWithoutExtension + ".d.ts";
let outputDtsFileName = emitOutputFilePathWithoutExtension + ".d.ts";
allInputFiles.unshift(findOutpuDtsFile(outputDtsFileName));
}
else {
var outputDtsFileName = ts.removeFileExtension(compilerOptions.out) + ".d.ts";
var outputDtsFile = findOutpuDtsFile(outputDtsFileName);
let outputDtsFileName = ts.removeFileExtension(compilerOptions.out) + ".d.ts";
let outputDtsFile = findOutpuDtsFile(outputDtsFileName);
if (!ts.contains(allInputFiles, outputDtsFile)) {
allInputFiles.unshift(outputDtsFile);
}
}
});
return compileProjectFiles(compilerResult.moduleKind,getInputFiles, getSourceFileText, writeFile);
return compileProjectFiles(compilerResult.moduleKind, getInputFiles, getSourceFileText, writeFile);
function findOutpuDtsFile(fileName: string) {
return ts.forEach(compilerResult.outputFiles, outputFile => outputFile.emittedFileName === fileName ? outputFile : undefined);
@@ -319,7 +322,7 @@ class ProjectRunner extends RunnerBase {
}
function getErrorsBaseline(compilerResult: CompileProjectFilesResult) {
var inputFiles = ts.map(ts.filter(compilerResult.program.getSourceFiles(),
let inputFiles = ts.map(ts.filter(compilerResult.program.getSourceFiles(),
sourceFile => sourceFile.fileName !== "lib.d.ts"),
sourceFile => {
return { unitName: sourceFile.fileName, content: sourceFile.text };
@@ -328,13 +331,15 @@ class ProjectRunner extends RunnerBase {
return Harness.Compiler.getErrorBaseline(inputFiles, compilerResult.errors);
}
var name = 'Compiling project for ' + testCase.scenario + ': testcase ' + testCaseFileName;
let name = 'Compiling project for ' + testCase.scenario + ': testcase ' + testCaseFileName;
describe('Projects tests', () => {
describe(name, () => {
function verifyCompilerResults(moduleKind: ts.ModuleKind) {
let compilerResult: BatchCompileProjectTestCaseResult;
function getCompilerResolutionInfo() {
var resolutionInfo: ProjectRunnerTestCaseResolutionInfo = {
let resolutionInfo: ProjectRunnerTestCaseResolutionInfo = {
scenario: testCase.scenario,
projectRoot: testCase.projectRoot,
inputFiles: testCase.inputFiles,
@@ -357,8 +362,6 @@ class ProjectRunner extends RunnerBase {
return resolutionInfo;
}
var compilerResult: BatchCompileProjectTestCaseResult;
it(name + ": " + moduleNameToString(moduleKind) , () => {
// Compile using node
compilerResult = batchCompilerProjectTestCase(moduleKind);
@@ -410,7 +413,7 @@ class ProjectRunner extends RunnerBase {
it('Errors in generated Dts files for (' + moduleNameToString(moduleKind) + '): ' + testCaseFileName, () => {
if (!compilerResult.errors.length && testCase.declaration) {
var dTsCompileResult = compileCompileDTsFiles(compilerResult);
let dTsCompileResult = compileCompileDTsFiles(compilerResult);
if (dTsCompileResult.errors.length) {
Harness.Baseline.runBaseline('Errors in generated Dts files for (' + moduleNameToString(compilerResult.moduleKind) + '): ' + testCaseFileName, getBaselineFolder(compilerResult.moduleKind) + testCaseJustName + '.dts.errors.txt', () => {
return getErrorsBaseline(dTsCompileResult);
+11 -11
View File
@@ -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
@@ -20,26 +20,26 @@
/// <reference path='rwcRunner.ts' />
/// <reference path='harness.ts' />
let runners: RunnerBase[] = [];
let iterations: number = 1;
function runTests(runners: RunnerBase[]) {
for (var i = iterations; i > 0; i--) {
for (var j = 0; j < runners.length; j++) {
for (let i = iterations; i > 0; i--) {
for (let j = 0; j < runners.length; j++) {
runners[j].initializeTests();
}
}
}
var runners: RunnerBase[] = [];
var iterations: number = 1;
// users can define tests to run in mytest.config that will override cmd line args, otherwise use cmd line args (test.config), otherwise no options
var mytestconfig = 'mytest.config';
var testconfig = 'test.config';
var testConfigFile =
let mytestconfig = 'mytest.config';
let testconfig = 'test.config';
let testConfigFile =
Harness.IO.fileExists(mytestconfig) ? Harness.IO.readFile(mytestconfig) :
(Harness.IO.fileExists(testconfig) ? Harness.IO.readFile(testconfig) : '');
if (testConfigFile !== '') {
var testConfig = JSON.parse(testConfigFile);
let testConfig = JSON.parse(testConfigFile);
if (testConfig.light) {
Harness.lightMode = true;
}
@@ -99,7 +99,7 @@ if (runners.length === 0) {
runners.push(new FourSlashRunner(FourSlashTestType.Native));
runners.push(new FourSlashRunner(FourSlashTestType.Shims));
runners.push(new FourSlashRunner(FourSlashTestType.Server));
//runners.push(new GeneratedFourslashRunner());
// runners.push(new GeneratedFourslashRunner());
}
ts.sys.newLine = '\r\n';
+6 -8
View File
@@ -1,6 +1,6 @@
/// <reference path="harness.ts" />
class RunnerBase {
abstract class RunnerBase {
constructor() { }
// contains the tests to run
@@ -18,23 +18,21 @@ class RunnerBase {
/** Setup the runner's tests so that they are ready to be executed by the harness
* The first test should be a describe/it block that sets up the harness's compiler instance appropriately
*/
public initializeTests(): void {
throw new Error('method not implemented');
}
public abstract initializeTests(): void;
/** Replaces instances of full paths with fileNames only */
static removeFullPaths(path: string) {
var fixedPath = path;
let fixedPath = path;
// full paths either start with a drive letter or / for *nix, shouldn't have \ in the path at this point
var fullPath = /(\w+:|\/)?([\w+\-\.]|\/)*\.tsx?/g;
var fullPathList = fixedPath.match(fullPath);
let fullPath = /(\w+:|\/)?([\w+\-\.]|\/)*\.tsx?/g;
let fullPathList = fixedPath.match(fullPath);
if (fullPathList) {
fullPathList.forEach((match: string) => fixedPath = fixedPath.replace(match, Harness.Path.getFileName(match)));
}
// when running in the browser the 'full path' is the host name, shows up in error baselines
var localHost = /http:\/localhost:\d+/g;
let localHost = /http:\/localhost:\d+/g;
fixedPath = fixedPath.replace(localHost, '');
return fixedPath;
}
+28 -27
View File
@@ -5,9 +5,9 @@
module RWC {
function runWithIOLog(ioLog: IOLog, fn: () => void) {
var oldSys = ts.sys;
let oldSys = ts.sys;
var wrappedSys = Playback.wrapSystem(ts.sys);
let wrappedSys = Playback.wrapSystem(ts.sys);
wrappedSys.startReplayFromData(ioLog);
ts.sys = wrappedSys;
@@ -21,17 +21,17 @@ module RWC {
export function runRWCTest(jsonPath: string) {
describe("Testing a RWC project: " + jsonPath, () => {
var inputFiles: { unitName: string; content: string; }[] = [];
var otherFiles: { unitName: string; content: string; }[] = [];
var compilerResult: Harness.Compiler.CompilerResult;
var compilerOptions: ts.CompilerOptions;
var baselineOpts: Harness.Baseline.BaselineOptions = {
let inputFiles: { unitName: string; content: string; }[] = [];
let otherFiles: { unitName: string; content: string; }[] = [];
let compilerResult: Harness.Compiler.CompilerResult;
let compilerOptions: ts.CompilerOptions;
let baselineOpts: Harness.Baseline.BaselineOptions = {
Subfolder: 'rwc',
Baselinefolder: 'internal/baselines'
};
var baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
var currentDirectory: string;
var useCustomLibraryFile: boolean;
let baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
let currentDirectory: string;
let useCustomLibraryFile: boolean;
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
@@ -50,10 +50,10 @@ module RWC {
});
it('can compile', () => {
var harnessCompiler = Harness.Compiler.getCompiler();
var opts: ts.ParsedCommandLine;
let harnessCompiler = Harness.Compiler.getCompiler();
let opts: ts.ParsedCommandLine;
var ioLog: IOLog = JSON.parse(Harness.IO.readFile(jsonPath));
let ioLog: IOLog = JSON.parse(Harness.IO.readFile(jsonPath));
currentDirectory = ioLog.currentDirectory;
useCustomLibraryFile = ioLog.useCustomLibraryFile;
runWithIOLog(ioLog, () => {
@@ -77,7 +77,7 @@ module RWC {
for (let fileRead of ioLog.filesRead) {
// Check if the file is already added into the set of input files.
var resolvedPath = ts.normalizeSlashes(ts.sys.resolvePath(fileRead.path));
var inInputList = ts.forEach(inputFiles, inputFile => inputFile.unitName === resolvedPath);
let inInputList = ts.forEach(inputFiles, inputFile => inputFile.unitName === resolvedPath);
if (!Harness.isLibraryFile(fileRead.path)) {
if (inInputList) {
@@ -117,12 +117,13 @@ module RWC {
});
function getHarnessCompilerInputUnit(fileName: string) {
var unitName = ts.normalizeSlashes(ts.sys.resolvePath(fileName));
let unitName = ts.normalizeSlashes(ts.sys.resolvePath(fileName));
let content: string = null;
try {
var content = ts.sys.readFile(unitName);
content = ts.sys.readFile(unitName);
}
catch (e) {
// Leave content undefined.
content = ts.sys.readFile(fileName);
}
return { unitName, content };
}
@@ -155,13 +156,13 @@ module RWC {
}, false, baselineOpts);
});
//it('has correct source map record', () => {
// if (compilerOptions.sourceMap) {
// Harness.Baseline.runBaseline('has correct source map record', baseName + '.sourcemap.txt', () => {
// return compilerResult.getSourceMapRecord();
// }, false, baselineOpts);
// }
//});
/*it('has correct source map record', () => {
if (compilerOptions.sourceMap) {
Harness.Baseline.runBaseline('has correct source map record', baseName + '.sourcemap.txt', () => {
return compilerResult.getSourceMapRecord();
}, false, baselineOpts);
}
});*/
it('has the expected errors', () => {
Harness.Baseline.runBaseline('has the expected errors', baseName + '.errors.txt', () => {
@@ -178,7 +179,7 @@ module RWC {
it('has the expected errors in generated declaration files', () => {
if (compilerOptions.declaration && !compilerResult.errors.length) {
Harness.Baseline.runBaseline('has the expected errors in generated declaration files', baseName + '.dts.errors.txt', () => {
var declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult,
let declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult,
/*settingscallback*/ undefined, compilerOptions, currentDirectory);
if (declFileCompilationResult.declResult.errors.length === 0) {
return null;
@@ -204,8 +205,8 @@ class RWCRunner extends RunnerBase {
*/
public initializeTests(): void {
// Read in and evaluate the test list
var testList = Harness.IO.listFiles(RWCRunner.sourcePath, /.+\.json$/);
for (var i = 0; i < testList.length; i++) {
let testList = Harness.IO.listFiles(RWCRunner.sourcePath, /.+\.json$/);
for (let i = 0; i < testList.length; i++) {
this.runTest(testList[i]);
}
}
+54 -53
View File
@@ -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
@@ -23,12 +23,12 @@ module Harness.SourceMapRecoder {
}
module SourceMapDecoder {
var sourceMapMappings: string;
var sourceMapNames: string[];
var decodingIndex: number;
var prevNameIndex: number;
var decodeOfEncodedMapping: ts.SourceMapSpan;
var errorDecodeOfEncodedMapping: string;
let sourceMapMappings: string;
let sourceMapNames: string[];
let decodingIndex: number;
let prevNameIndex: number;
let decodeOfEncodedMapping: ts.SourceMapSpan;
let errorDecodeOfEncodedMapping: string;
export function initializeSourceMapDecoding(sourceMapData: ts.SourceMapData) {
sourceMapMappings = sourceMapData.sourceMapMappings;
@@ -82,9 +82,9 @@ module Harness.SourceMapRecoder {
return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(sourceMapMappings.charAt(decodingIndex));
}
var moreDigits = true;
var shiftCount = 0;
var value = 0;
let moreDigits = true;
let shiftCount = 0;
let value = 0;
for (; moreDigits; decodingIndex++) {
if (createErrorIfCondition(decodingIndex >= sourceMapMappings.length, "Error in decoding base64VLQFormatDecode, past the mapping string")) {
@@ -92,7 +92,7 @@ module Harness.SourceMapRecoder {
}
// 6 digit number
var currentByte = base64FormatDecode();
let currentByte = base64FormatDecode();
// If msb is set, we still have more bits to continue
moreDigits = (currentByte & 32) !== 0;
@@ -143,7 +143,7 @@ module Harness.SourceMapRecoder {
return { error: errorDecodeOfEncodedMapping, sourceMapSpan: decodeOfEncodedMapping };
}
// 2. Relative sourceIndex
// 2. Relative sourceIndex
decodeOfEncodedMapping.sourceIndex += base64VLQFormatDecode();
// Incorrect sourceIndex dont support this map
if (createErrorIfCondition(decodeOfEncodedMapping.sourceIndex < 0, "Invalid sourceIndex found")) {
@@ -165,7 +165,7 @@ module Harness.SourceMapRecoder {
return { error: errorDecodeOfEncodedMapping, sourceMapSpan: decodeOfEncodedMapping };
}
// 4. Relative sourceColumn 0 based
// 4. Relative sourceColumn 0 based
decodeOfEncodedMapping.sourceColumn += base64VLQFormatDecode();
// Incorrect sourceColumn dont support this map
if (createErrorIfCondition(decodeOfEncodedMapping.sourceColumn < 1, "Invalid sourceLine found")) {
@@ -203,19 +203,19 @@ module Harness.SourceMapRecoder {
}
module SourceMapSpanWriter {
var sourceMapRecoder: Compiler.WriterAggregator;
var sourceMapSources: string[];
var sourceMapNames: string[];
let sourceMapRecoder: Compiler.WriterAggregator;
let sourceMapSources: string[];
let sourceMapNames: string[];
var jsFile: Compiler.GeneratedFile;
var jsLineMap: number[];
var tsCode: string;
var tsLineMap: number[];
let jsFile: Compiler.GeneratedFile;
let jsLineMap: number[];
let tsCode: string;
let tsLineMap: number[];
var spansOnSingleLine: SourceMapSpanWithDecodeErrors[];
var prevWrittenSourcePos: number;
var prevWrittenJsLine: number;
var spanMarkerContinues: boolean;
let spansOnSingleLine: SourceMapSpanWithDecodeErrors[];
let prevWrittenSourcePos: number;
let prevWrittenJsLine: number;
let spanMarkerContinues: boolean;
export function intializeSourceMapSpanWriter(sourceMapRecordWriter: Compiler.WriterAggregator, sourceMapData: ts.SourceMapData, currentJsFile: Compiler.GeneratedFile) {
sourceMapRecoder = sourceMapRecordWriter;
@@ -244,7 +244,7 @@ module Harness.SourceMapRecoder {
}
function getSourceMapSpanString(mapEntry: ts.SourceMapSpan, getAbsentNameIndex?: boolean) {
var mapString = "Emitted(" + mapEntry.emittedLine + ", " + mapEntry.emittedColumn + ") Source(" + mapEntry.sourceLine + ", " + mapEntry.sourceColumn + ") + SourceIndex(" + mapEntry.sourceIndex + ")";
let mapString = "Emitted(" + mapEntry.emittedLine + ", " + mapEntry.emittedColumn + ") Source(" + mapEntry.sourceLine + ", " + mapEntry.sourceColumn + ") + SourceIndex(" + mapEntry.sourceIndex + ")";
if (mapEntry.nameIndex >= 0 && mapEntry.nameIndex < sourceMapNames.length) {
mapString += " name (" + sourceMapNames[mapEntry.nameIndex] + ")";
}
@@ -259,8 +259,8 @@ module Harness.SourceMapRecoder {
export function recordSourceMapSpan(sourceMapSpan: ts.SourceMapSpan) {
// verify the decoded span is same as the new span
var decodeResult = SourceMapDecoder.decodeNextEncodedSourceMapSpan();
var decodedErrors: string[];
let decodeResult = SourceMapDecoder.decodeNextEncodedSourceMapSpan();
let decodedErrors: string[];
if (decodeResult.error
|| decodeResult.sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine
|| decodeResult.sourceMapSpan.emittedColumn !== sourceMapSpan.emittedColumn
@@ -278,7 +278,7 @@ module Harness.SourceMapRecoder {
}
if (spansOnSingleLine.length && spansOnSingleLine[0].sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine) {
// On different line from the one that we have been recording till now,
// On different line from the one that we have been recording till now,
writeRecordedSpans();
spansOnSingleLine = [{ sourceMapSpan: sourceMapSpan, decodeErrors: decodedErrors }];
}
@@ -317,8 +317,8 @@ module Harness.SourceMapRecoder {
}
function getTextOfLine(line: number, lineMap: number[], code: string) {
var startPos = lineMap[line];
var endPos = lineMap[line + 1];
let startPos = lineMap[line];
let endPos = lineMap[line + 1];
return code.substring(startPos, endPos);
}
@@ -329,14 +329,16 @@ module Harness.SourceMapRecoder {
}
function writeRecordedSpans() {
let markerIds: string[] = [];
function getMarkerId(markerIndex: number) {
var markerId = "";
let markerId = "";
if (spanMarkerContinues) {
assert.isTrue(markerIndex === 0);
markerId = "1->";
}
else {
var markerId = "" + (markerIndex + 1);
markerId = "" + (markerIndex + 1);
if (markerId.length < 2) {
markerId = markerId + " ";
}
@@ -345,10 +347,10 @@ module Harness.SourceMapRecoder {
return markerId;
}
var prevEmittedCol: number;
let prevEmittedCol: number;
function iterateSpans(fn: (currentSpan: SourceMapSpanWithDecodeErrors, index: number) => void) {
prevEmittedCol = 1;
for (var i = 0; i < spansOnSingleLine.length; i++) {
for (let i = 0; i < spansOnSingleLine.length; i++) {
fn(spansOnSingleLine[i], i);
prevEmittedCol = spansOnSingleLine[i].sourceMapSpan.emittedColumn;
}
@@ -356,18 +358,18 @@ module Harness.SourceMapRecoder {
function writeSourceMapIndent(indentLength: number, indentPrefix: string) {
sourceMapRecoder.Write(indentPrefix);
for (var i = 1; i < indentLength; i++) {
for (let i = 1; i < indentLength; i++) {
sourceMapRecoder.Write(" ");
}
}
function writeSourceMapMarker(currentSpan: SourceMapSpanWithDecodeErrors, index: number, endColumn = currentSpan.sourceMapSpan.emittedColumn, endContinues?: boolean) {
var markerId = getMarkerId(index);
let markerId = getMarkerId(index);
markerIds.push(markerId);
writeSourceMapIndent(prevEmittedCol, markerId);
for (var i = prevEmittedCol; i < endColumn; i++) {
for (let i = prevEmittedCol; i < endColumn; i++) {
sourceMapRecoder.Write("^");
}
if (endContinues) {
@@ -378,8 +380,8 @@ module Harness.SourceMapRecoder {
}
function writeSourceMapSourceText(currentSpan: SourceMapSpanWithDecodeErrors, index: number) {
var sourcePos = tsLineMap[currentSpan.sourceMapSpan.sourceLine - 1] + (currentSpan.sourceMapSpan.sourceColumn - 1);
var sourceText = "";
let sourcePos = tsLineMap[currentSpan.sourceMapSpan.sourceLine - 1] + (currentSpan.sourceMapSpan.sourceColumn - 1);
let sourceText = "";
if (prevWrittenSourcePos < sourcePos) {
// Position that goes forward, get text
sourceText = tsCode.substring(prevWrittenSourcePos, sourcePos);
@@ -387,14 +389,14 @@ module Harness.SourceMapRecoder {
if (currentSpan.decodeErrors) {
// If there are decode errors, write
for (var i = 0; i < currentSpan.decodeErrors.length; i++) {
for (let i = 0; i < currentSpan.decodeErrors.length; i++) {
writeSourceMapIndent(prevEmittedCol, markerIds[index]);
sourceMapRecoder.WriteLine(currentSpan.decodeErrors[i]);
}
}
var tsCodeLineMap = ts.computeLineStarts(sourceText);
for (var i = 0; i < tsCodeLineMap.length; i++) {
let tsCodeLineMap = ts.computeLineStarts(sourceText);
for (let i = 0; i < tsCodeLineMap.length; i++) {
writeSourceMapIndent(prevEmittedCol, i === 0 ? markerIds[index] : " >");
sourceMapRecoder.Write(getTextOfLine(i, tsCodeLineMap, sourceText));
if (i === tsCodeLineMap.length - 1) {
@@ -410,16 +412,15 @@ module Harness.SourceMapRecoder {
}
if (spansOnSingleLine.length) {
var currentJsLine = spansOnSingleLine[0].sourceMapSpan.emittedLine;
let currentJsLine = spansOnSingleLine[0].sourceMapSpan.emittedLine;
// Write js line
writeJsFileLines(currentJsLine);
// Emit markers
var markerIds: string[] = [];
iterateSpans(writeSourceMapMarker);
var jsFileText = getTextOfLine(currentJsLine, jsLineMap, jsFile.code);
let jsFileText = getTextOfLine(currentJsLine, jsLineMap, jsFile.code);
if (prevEmittedCol < jsFileText.length) {
// There is remaining text on this line that will be part of next source span so write marker that continues
writeSourceMapMarker(undefined, spansOnSingleLine.length, /*endColumn*/ jsFileText.length, /*endContinues*/ true);
@@ -437,16 +438,16 @@ module Harness.SourceMapRecoder {
}
export function getSourceMapRecord(sourceMapDataList: ts.SourceMapData[], program: ts.Program, jsFiles: Compiler.GeneratedFile[]) {
var sourceMapRecoder = new Compiler.WriterAggregator();
let sourceMapRecoder = new Compiler.WriterAggregator();
for (var i = 0; i < sourceMapDataList.length; i++) {
var sourceMapData = sourceMapDataList[i];
var prevSourceFile: ts.SourceFile = null;
for (let i = 0; i < sourceMapDataList.length; i++) {
let sourceMapData = sourceMapDataList[i];
let prevSourceFile: ts.SourceFile = null;
SourceMapSpanWriter.intializeSourceMapSpanWriter(sourceMapRecoder, sourceMapData, jsFiles[i]);
for (var j = 0; j < sourceMapData.sourceMapDecodedMappings.length; j++) {
var decodedSourceMapping = sourceMapData.sourceMapDecodedMappings[j];
var currentSourceFile = program.getSourceFile(sourceMapData.inputSourceFileNames[decodedSourceMapping.sourceIndex]);
for (let j = 0; j < sourceMapData.sourceMapDecodedMappings.length; j++) {
let decodedSourceMapping = sourceMapData.sourceMapDecodedMappings[j];
let currentSourceFile = program.getSourceFile(sourceMapData.inputSourceFileNames[decodedSourceMapping.sourceIndex]);
if (currentSourceFile !== prevSourceFile) {
SourceMapSpanWriter.recordNewSourceFileSpan(decodedSourceMapping, currentSourceFile.text);
prevSourceFile = currentSourceFile;
@@ -455,7 +456,7 @@ module Harness.SourceMapRecoder {
SourceMapSpanWriter.recordSourceMapSpan(decodedSourceMapping);
}
}
SourceMapSpanWriter.close();// If the last spans werent emitted, emit them
SourceMapSpanWriter.close(); // If the last spans werent emitted, emit them
}
sourceMapRecoder.Close();
return sourceMapRecoder.lines.join('\r\n');
+14 -14
View File
@@ -27,7 +27,7 @@ class Test262BaselineRunner extends RunnerBase {
describe('test262 test for ' + filePath, () => {
// 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 testState: {
let testState: {
filename: string;
compilerResult: Harness.Compiler.CompilerResult;
inputFiles: { unitName: string; content: string }[];
@@ -35,11 +35,11 @@ class Test262BaselineRunner extends RunnerBase {
};
before(() => {
var content = Harness.IO.readFile(filePath);
var testFilename = ts.removeFileExtension(filePath).replace(/\//g, '_') + ".test";
var testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, testFilename);
let content = Harness.IO.readFile(filePath);
let testFilename = ts.removeFileExtension(filePath).replace(/\//g, '_') + ".test";
let testCaseContent = Harness.TestCaseParser.makeUnitsFromTest(content, testFilename);
var inputFiles = testCaseContent.testUnitData.map(unit => {
let inputFiles = testCaseContent.testUnitData.map(unit => {
return { unitName: Test262BaselineRunner.getTestFilePath(unit.name), content: unit.content };
});
@@ -63,14 +63,14 @@ class Test262BaselineRunner extends RunnerBase {
it('has the expected emitted code', () => {
Harness.Baseline.runBaseline('has the expected emitted code', testState.filename + '.output.js', () => {
var files = testState.compilerResult.files.filter(f=> f.fileName !== Test262BaselineRunner.helpersFilePath);
let files = testState.compilerResult.files.filter(f => f.fileName !== Test262BaselineRunner.helpersFilePath);
return Harness.Compiler.collateOutputs(files);
}, false, Test262BaselineRunner.baselineOptions);
});
it('has the expected errors', () => {
Harness.Baseline.runBaseline('has the expected errors', testState.filename + '.errors.txt', () => {
var errors = testState.compilerResult.errors;
let errors = testState.compilerResult.errors;
if (errors.length === 0) {
return null;
}
@@ -79,14 +79,14 @@ class Test262BaselineRunner extends RunnerBase {
}, false, Test262BaselineRunner.baselineOptions);
});
it('satisfies invariants', () => {
var sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
it('satisfies inletiants', () => {
let sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
Utils.assertInvariants(sourceFile, /*parent:*/ undefined);
});
it('has the expected AST',() => {
Harness.Baseline.runBaseline('has the expected AST', testState.filename + '.AST.txt',() => {
var sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
it('has the expected AST', () => {
Harness.Baseline.runBaseline('has the expected AST', testState.filename + '.AST.txt', () => {
let sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
return Utils.sourceFileToJSON(sourceFile);
}, false, Test262BaselineRunner.baselineOptions);
});
@@ -96,7 +96,7 @@ class Test262BaselineRunner extends RunnerBase {
public initializeTests() {
// 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(Test262BaselineRunner.basePath, Test262BaselineRunner.testFileExtensionRegex, { recursive: true });
let testFiles = this.enumerateFiles(Test262BaselineRunner.basePath, Test262BaselineRunner.testFileExtensionRegex, { recursive: true });
testFiles.forEach(fn => {
this.runTest(ts.normalizePath(fn));
});
@@ -105,4 +105,4 @@ class Test262BaselineRunner extends RunnerBase {
this.tests.forEach(test => this.runTest(test));
}
}
}
}
+11 -11
View File
@@ -13,7 +13,7 @@ class TypeWriterWalker {
private checker: ts.TypeChecker;
constructor(private program: ts.Program, fullTypeCheck: boolean) {
// Consider getting both the diagnostics checker and the non-diagnostics checker to verify
// Consider getting both the diagnostics checker and the non-diagnostics checker to verify
// they are consistent.
this.checker = fullTypeCheck
? program.getDiagnosticsProducingTypeChecker()
@@ -21,7 +21,7 @@ class TypeWriterWalker {
}
public getTypeAndSymbols(fileName: string): TypeWriterResult[] {
var sourceFile = this.program.getSourceFile(fileName);
let sourceFile = this.program.getSourceFile(fileName);
this.currentSourceFile = sourceFile;
this.results = [];
this.visitNode(sourceFile);
@@ -37,19 +37,19 @@ class TypeWriterWalker {
}
private logTypeAndSymbol(node: ts.Node): void {
var actualPos = ts.skipTrivia(this.currentSourceFile.text, node.pos);
var lineAndCharacter = this.currentSourceFile.getLineAndCharacterOfPosition(actualPos);
var sourceText = ts.getTextOfNodeFromSourceText(this.currentSourceFile.text, node);
let actualPos = ts.skipTrivia(this.currentSourceFile.text, node.pos);
let lineAndCharacter = this.currentSourceFile.getLineAndCharacterOfPosition(actualPos);
let sourceText = ts.getTextOfNodeFromSourceText(this.currentSourceFile.text, node);
// Workaround to ensure we output 'C' instead of 'typeof C' for base class expressions
// var type = this.checker.getTypeAtLocation(node);
var type = node.parent && ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent) && this.checker.getTypeAtLocation(node.parent) || this.checker.getTypeAtLocation(node);
// let type = this.checker.getTypeAtLocation(node);
let type = node.parent && ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent) && this.checker.getTypeAtLocation(node.parent) || this.checker.getTypeAtLocation(node);
ts.Debug.assert(type !== undefined, "type doesn't exist");
var symbol = this.checker.getSymbolAtLocation(node);
let symbol = this.checker.getSymbolAtLocation(node);
var typeString = this.checker.typeToString(type, node.parent, ts.TypeFormatFlags.NoTruncation);
var symbolString: string;
let typeString = this.checker.typeToString(type, node.parent, ts.TypeFormatFlags.NoTruncation);
let symbolString: string;
if (symbol) {
symbolString = "Symbol(" + this.checker.symbolToString(symbol, node.parent);
if (symbol.declarations) {
@@ -57,7 +57,7 @@ class TypeWriterWalker {
symbolString += ", ";
let declSourceFile = declaration.getSourceFile();
let declLineAndCharacter = declSourceFile.getLineAndCharacterOfPosition(declaration.pos);
symbolString += `Decl(${ ts.getBaseFileName(declSourceFile.fileName) }, ${ declLineAndCharacter.line }, ${ declLineAndCharacter.character })`
symbolString += `Decl(${ ts.getBaseFileName(declSourceFile.fileName) }, ${ declLineAndCharacter.line }, ${ declLineAndCharacter.character })`;
}
}
symbolString += ")";
+3 -3
View File
@@ -971,14 +971,14 @@ interface JSON {
* @param replacer A function that transforms the results.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer: (key: string, value: any) => any, space: any): string;
stringify(value: any, replacer: (key: string, value: any) => any, space: string | number): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer Array that transforms the results.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
stringify(value: any, replacer: any[], space: any): string;
stringify(value: any, replacer: any[], space: string | number): string;
}
/**
* An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
@@ -1181,4 +1181,4 @@ interface PromiseLike<T> {
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;
}
}
+1 -1
View File
@@ -377,7 +377,7 @@ interface String {
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
contains(searchString: string, position?: number): boolean;
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
+1 -3
View File
@@ -202,9 +202,7 @@ namespace ts.server {
return {
isMemberCompletion: false,
isNewIdentifierLocation: false,
entries: response.body,
fileName: fileName,
position: position
entries: response.body
};
}
+17 -17
View File
@@ -842,53 +842,53 @@ namespace ts.server {
private handlers : Map<(request: protocol.Request) => {response?: any, responseRequired?: boolean}> = {
[CommandNames.Exit]: () => {
this.exit();
return {};
return { responseRequired: false};
},
[CommandNames.Definition]: (request: protocol.Request) => {
var defArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getDefinition(defArgs.line, defArgs.offset, defArgs.file)};
return {response: this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true};
},
[CommandNames.TypeDefinition]: (request: protocol.Request) => {
var defArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file)};
return {response: this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true};
},
[CommandNames.References]: (request: protocol.Request) => {
var defArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getReferences(defArgs.line, defArgs.offset, defArgs.file)};
return {response: this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true};
},
[CommandNames.Rename]: (request: protocol.Request) => {
var renameArgs = <protocol.RenameRequestArgs>request.arguments;
return {response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings)}
return {response: this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true}
},
[CommandNames.Open]: (request: protocol.Request) => {
var openArgs = <protocol.OpenRequestArgs>request.arguments;
this.openClientFile(openArgs.file);
return {}
return {responseRequired: false}
},
[CommandNames.Quickinfo]: (request: protocol.Request) => {
var quickinfoArgs = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file)};
return {response: this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true};
},
[CommandNames.Format]: (request: protocol.Request) => {
var formatArgs = <protocol.FormatRequestArgs>request.arguments;
return {response: this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file)};
return {response: this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true};
},
[CommandNames.Formatonkey]: (request: protocol.Request) => {
var formatOnKeyArgs = <protocol.FormatOnKeyRequestArgs>request.arguments;
return {response: this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file)};
return {response: this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true};
},
[CommandNames.Completions]: (request: protocol.Request) => {
var completionsArgs = <protocol.CompletionsRequestArgs>request.arguments;
return {response: this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file)}
return {response: this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true}
},
[CommandNames.CompletionDetails]: (request: protocol.Request) => {
var completionDetailsArgs = <protocol.CompletionDetailsRequestArgs>request.arguments;
return {response: this.getCompletionEntryDetails(completionDetailsArgs.line,completionDetailsArgs.offset,
completionDetailsArgs.entryNames,completionDetailsArgs.file)}
completionDetailsArgs.entryNames,completionDetailsArgs.file), responseRequired: true}
},
[CommandNames.SignatureHelp]: (request: protocol.Request) => {
var signatureHelpArgs = <protocol.SignatureHelpRequestArgs>request.arguments;
return {response: this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file)}
return {response: this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true}
},
[CommandNames.Geterr]: (request: protocol.Request) => {
var geterrArgs = <protocol.GeterrRequestArgs>request.arguments;
@@ -923,23 +923,23 @@ namespace ts.server {
},
[CommandNames.Navto]: (request: protocol.Request) => {
var navtoArgs = <protocol.NavtoRequestArgs>request.arguments;
return {response: this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount)};
return {response: this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount), responseRequired: true};
},
[CommandNames.Brace]: (request: protocol.Request) => {
var braceArguments = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file)};
return {response: this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true};
},
[CommandNames.NavBar]: (request: protocol.Request) => {
var navBarArgs = <protocol.FileRequestArgs>request.arguments;
return {response: this.getNavigationBarItems(navBarArgs.file)};
return {response: this.getNavigationBarItems(navBarArgs.file), responseRequired: true};
},
[CommandNames.Occurrences]: (request: protocol.Request) => {
var { line, offset, file: fileName } = <protocol.FileLocationRequestArgs>request.arguments;
return {response: this.getOccurrences(line, offset, fileName)};
return {response: this.getOccurrences(line, offset, fileName), responseRequired: true};
},
[CommandNames.ProjectInfo]: (request: protocol.Request) => {
var { file, needFileNameList } = <protocol.ProjectInfoRequestArgs>request.arguments;
return {response: this.getProjectInfo(file, needFileNameList)};
return {response: this.getProjectInfo(file, needFileNameList), responseRequired: true};
},
};
addProtocolHandler(command: string, handler: (request: protocol.Request) => {response?: any, responseRequired: boolean}) {
+133 -82
View File
@@ -91,6 +91,9 @@ 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;
}
export module ScriptSnapshot {
@@ -1102,6 +1105,7 @@ namespace ts {
}
export interface HighlightSpan {
fileName?: string;
textSpan: TextSpan;
kind: string;
}
@@ -1408,7 +1412,9 @@ namespace ts {
* @param fileName The name of the file to be released
* @param compilationSettings The compilation settings used to acquire the file
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
reportStats(): string;
}
// TODO: move these to enums
@@ -1863,6 +1869,16 @@ namespace 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;
}
}
@@ -3015,17 +3031,17 @@ namespace ts {
function tryGetGlobalSymbols(): boolean {
let objectLikeContainer: ObjectLiteralExpression | BindingPattern;
let importClause: ImportClause;
let namedImportsOrExports: NamedImportsOrExports;
let jsxContainer: JsxOpeningLikeElement;
if (objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken)) {
return tryGetObjectLikeCompletionSymbols(objectLikeContainer);
}
if (importClause = <ImportClause>getAncestor(contextToken, SyntaxKind.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)) {
@@ -3035,7 +3051,7 @@ namespace ts {
attrsType = typeChecker.getJsxElementAttributesType(<JsxOpeningLikeElement>jsxContainer);
if (attrsType) {
symbols = filterJsxAttributes((<JsxOpeningLikeElement>jsxContainer).attributes, typeChecker.getPropertiesOfType(attrsType));
symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), (<JsxOpeningLikeElement>jsxContainer).attributes);
isMemberCompletion = true;
isNewIdentifierLocation = false;
return true;
@@ -3104,24 +3120,12 @@ namespace ts {
function isCompletionListBlocker(contextToken: Node): boolean {
let start = new Date().getTime();
let result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken) ||
isIdentifierDefinitionLocation(contextToken) ||
isSolelyIdentifierDefinitionLocation(contextToken) ||
isDotOfNumericLiteral(contextToken);
log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - start));
return result;
}
function shouldShowCompletionsInImportsClause(node: Node): boolean {
if (node) {
// import {|
// import {a,|
if (node.kind === SyntaxKind.OpenBraceToken || node.kind === SyntaxKind.CommaToken) {
return node.parent.kind === SyntaxKind.NamedImports;
}
}
return false;
}
function isNewIdentifierDefinitionLocation(previousToken: Node): boolean {
if (previousToken) {
let containingNodeKind = previousToken.parent.kind;
@@ -3233,8 +3237,19 @@ namespace ts {
// We are *only* completing on properties from the type being destructured.
isNewIdentifierLocation = false;
typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
existingMembers = (<BindingPattern>objectLikeContainer).elements;
let rootDeclaration = getRootDeclaration(objectLikeContainer.parent);
if (isVariableLike(rootDeclaration)) {
// We don't want to complete using the type acquired by the shape
// of the binding pattern; we are only interested in types acquired
// through type declaration or inference.
if (rootDeclaration.initializer || rootDeclaration.type) {
typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
existingMembers = (<BindingPattern>objectLikeContainer).elements;
}
}
else {
Debug.fail("Root declaration is not variable-like.")
}
}
else {
Debug.fail("Expected object literal or binding pattern, got " + objectLikeContainer.kind);
@@ -3253,38 +3268,42 @@ namespace ts {
}
/**
* 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: ImportClause): boolean {
// cursor is in import clause
// try to show exported member for imported module
if (shouldShowCompletionsInImportsClause(contextToken)) {
isMemberCompletion = true;
isNewIdentifierLocation = false;
function tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports: NamedImportsOrExports): boolean {
let declarationKind = namedImportsOrExports.kind === SyntaxKind.NamedImports ?
SyntaxKind.ImportDeclaration :
SyntaxKind.ExportDeclaration;
let importOrExportDeclaration = <ImportDeclaration | ExportDeclaration>getAncestor(namedImportsOrExports, declarationKind);
let moduleSpecifier = importOrExportDeclaration.moduleSpecifier;
let importDeclaration = <ImportDeclaration>importClause.parent;
Debug.assert(importDeclaration !== undefined && importDeclaration.kind === SyntaxKind.ImportDeclaration);
let exports: Symbol[];
let moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importDeclaration.moduleSpecifier);
if (moduleSpecifierSymbol) {
exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol);
}
//let exports = typeInfoResolver.getExportsOfImportDeclaration(importDeclaration);
symbols = exports ? filterModuleExports(exports, importDeclaration) : emptyArray;
if (!moduleSpecifier) {
return false;
}
else {
isMemberCompletion = false;
isNewIdentifierLocation = true;
isMemberCompletion = true;
isNewIdentifierLocation = false;
let exports: Symbol[];
let moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(importOrExportDeclaration.moduleSpecifier);
if (moduleSpecifierSymbol) {
exports = typeChecker.getExportsOfModule(moduleSpecifierSymbol);
}
symbols = exports ? filterNamedImportOrExportCompletionItems(exports, namedImportsOrExports.elements) : emptyArray;
return true;
}
@@ -3308,6 +3327,26 @@ namespace 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: Node): NamedImportsOrExports {
if (contextToken) {
switch (contextToken.kind) {
case SyntaxKind.OpenBraceToken: // import { |
case SyntaxKind.CommaToken: // import { a as 0, |
switch (contextToken.parent.kind) {
case SyntaxKind.NamedImports:
case SyntaxKind.NamedExports:
return <NamedImportsOrExports>contextToken.parent;
}
}
}
return undefined;
}
function tryGetContainingJsxElement(contextToken: Node): JsxOpeningLikeElement {
if (contextToken) {
let parent = contextToken.parent;
@@ -3355,7 +3394,10 @@ namespace ts {
return false;
}
function isIdentifierDefinitionLocation(contextToken: Node): boolean {
/**
* @returns true if we are certain that the currently edited location must define a new location; false otherwise.
*/
function isSolelyIdentifierDefinitionLocation(contextToken: Node): boolean {
let containingNodeKind = contextToken.parent.kind;
switch (contextToken.kind) {
case SyntaxKind.CommaToken:
@@ -3412,6 +3454,11 @@ namespace ts {
case SyntaxKind.ProtectedKeyword:
return containingNodeKind === SyntaxKind.Parameter;
case SyntaxKind.AsKeyword:
containingNodeKind === SyntaxKind.ImportSpecifier ||
containingNodeKind === SyntaxKind.ExportSpecifier ||
containingNodeKind === SyntaxKind.NamespaceImport;
case SyntaxKind.ClassKeyword:
case SyntaxKind.EnumKeyword:
case SyntaxKind.InterfaceKeyword:
@@ -3453,33 +3500,41 @@ namespace ts {
return false;
}
function filterModuleExports(exports: Symbol[], importDeclaration: ImportDeclaration): Symbol[] {
let exisingImports: Map<boolean> = {};
/**
* 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: Symbol[], namedImportsOrExports: ImportOrExportSpecifier[]): Symbol[] {
let exisingImportsOrExports: Map<boolean> = {};
if (!importDeclaration.importClause) {
return exports;
for (let element of namedImportsOrExports) {
// If this is the current item we are editing right now, do not filter it out
if (element.getStart() <= position && position <= element.getEnd()) {
continue;
}
let name = element.propertyName || element.name;
exisingImportsOrExports[name.text] = true;
}
if (importDeclaration.importClause.namedBindings &&
importDeclaration.importClause.namedBindings.kind === SyntaxKind.NamedImports) {
forEach((<NamedImports>importDeclaration.importClause.namedBindings).elements, 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;
}
let name = el.propertyName || el.name;
exisingImports[name.text] = true;
});
if (isEmpty(exisingImportsOrExports)) {
return exportsOfModule;
}
if (isEmpty(exisingImports)) {
return exports;
}
return filter(exports, e => !lookUp(exisingImports, e.name));
return filter(exportsOfModule, e => !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: Symbol[], existingMembers: Declaration[]): Symbol[] {
if (!existingMembers || existingMembers.length === 0) {
return contextualMemberSymbols;
@@ -3514,17 +3569,16 @@ namespace ts {
existingMemberNames[existingName] = true;
}
let filteredMembers: Symbol[] = [];
forEach(contextualMemberSymbols, s => {
if (!existingMemberNames[s.name]) {
filteredMembers.push(s);
}
});
return filteredMembers;
return filter(contextualMemberSymbols, m => !lookUp(existingMemberNames, m.name));
}
function filterJsxAttributes(attributes: NodeArray<JsxAttribute | JsxSpreadAttribute>, symbols: Symbol[]): Symbol[] {
/**
* 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: Symbol[], attributes: NodeArray<JsxAttribute | JsxSpreadAttribute>): Symbol[] {
let seenNames: Map<boolean> = {};
for (let attr of attributes) {
// If this is the current item we are editing right now, do not filter it out
@@ -3536,13 +3590,8 @@ namespace ts {
seenNames[(<JsxAttribute>attr).name.text] = true;
}
}
let result: Symbol[] = [];
for (let sym of symbols) {
if (!seenNames[sym.name]) {
result.push(sym);
}
}
return result;
return filter(symbols, a => !lookUp(seenNames, a.name));
}
}
@@ -4682,12 +4731,13 @@ namespace ts {
// Make sure we only highlight the keyword when it makes sense to do so.
if (isAccessibilityModifier(modifier)) {
if (!(container.kind === SyntaxKind.ClassDeclaration ||
container.kind === SyntaxKind.ClassExpression ||
(declaration.kind === SyntaxKind.Parameter && hasKind(container, SyntaxKind.Constructor)))) {
return undefined;
}
}
else if (modifier === SyntaxKind.StaticKeyword) {
if (container.kind !== SyntaxKind.ClassDeclaration) {
if (!(container.kind === SyntaxKind.ClassDeclaration || container.kind === SyntaxKind.ClassExpression)) {
return undefined;
}
}
@@ -4726,12 +4776,13 @@ namespace ts {
(<ClassDeclaration>container.parent).members);
break;
case SyntaxKind.ClassDeclaration:
nodes = (<ClassDeclaration>container).members;
case SyntaxKind.ClassExpression:
nodes = (<ClassLikeDeclaration>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.
if (modifierFlag & NodeFlags.AccessibilityModifier) {
let constructor = forEach((<ClassDeclaration>container).members, member => {
let constructor = forEach((<ClassLikeDeclaration>container).members, member => {
return member.kind === SyntaxKind.Constructor && <ConstructorDeclaration>member;
});
+32 -6
View File
@@ -34,6 +34,9 @@ namespace ts {
* Or undefined value if there was no change.
*/
getChangeRange(oldSnapshot: ScriptSnapshotShim): string;
/** Releases all resources held by this script snapshot */
dispose?(): void;
}
export interface Logger {
@@ -61,8 +64,13 @@ namespace ts {
/** Public interface of the the of a config service shim instance.*/
export interface CoreServicesShimHost extends Logger {
/** Returns a JSON-encoded value of the type: string[] */
readDirectory(rootDir: string, extension: string): string;
/**
* Returns a JSON-encoded value of the type: string[]
*
* @param exclude A JSON encoded string[] containing the paths to exclude
* when enumerating the directory.
*/
readDirectory(rootDir: string, extension: string, exclude?: string): string;
}
///
@@ -243,6 +251,14 @@ namespace ts {
return createTextChangeRange(
createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
}
public dispose(): void {
// 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();
}
}
}
export class LanguageServiceShimHostAdapter implements LanguageServiceHost {
@@ -375,8 +391,18 @@ namespace ts {
constructor(private shimHost: CoreServicesShimHost) {
}
public readDirectory(rootDir: string, extension: string): string[] {
var encoded = this.shimHost.readDirectory(rootDir, extension);
public readDirectory(rootDir: string, extension: string, exclude: string[]): string[] {
// Wrap the API changes for 1.5 release. This try/catch
// should be removed once TypeScript 1.5 has shipped.
// Also consider removing the optional designation for
// the exclude param at this time.
var encoded: string;
try {
encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude));
}
catch (e) {
encoded = this.shimHost.readDirectory(rootDir, extension);
}
return JSON.parse(encoded);
}
}
@@ -428,11 +454,11 @@ namespace ts {
}
}
export function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { message: string; start: number; length: number; category: string; } []{
export function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { message: string; start: number; length: number; category: string; code: number; } []{
return diagnostics.map(d => realizeDiagnostic(d, newLine));
}
function realizeDiagnostic(diagnostic: Diagnostic, newLine: string): { message: string; start: number; length: number; category: string; } {
function realizeDiagnostic(diagnostic: Diagnostic, newLine: string): { message: string; start: number; length: number; category: string; code: number; } {
return {
message: flattenDiagnosticMessageText(diagnostic.messageText, newLine),
start: diagnostic.start,
@@ -1,4 +1,4 @@
tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,6): error TS2461: Type 'string | number' is not an array type.
tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,6): error TS2461: Type 'number | string' is not an array type.
tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,7): error TS2322: Type 'number' is not assignable to type 'string'.
tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,14): error TS2322: Type 'string' is not assignable to type 'number'.
@@ -8,7 +8,7 @@ tests/cases/conformance/statements/for-ofStatements/ES5For-of30.ts(3,14): error
var tuple: [number, string] = [2, "3"];
for ([a = 1, b = ""] of tuple) {
~~~~~~~~~~~~~~~
!!! error TS2461: Type 'string | number' is not an array type.
!!! error TS2461: Type 'number | string' is not an array type.
~
!!! error TS2322: Type 'number' is not assignable to type 'string'.
~
@@ -1,4 +1,4 @@
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck11.ts(3,6): error TS2322: Type 'string | number' is not assignable to type 'string'.
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck11.ts(3,6): error TS2322: Type 'number | string' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string'.
@@ -7,5 +7,5 @@ tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck11.ts(3,6)
var v: string;
for (v of union) { }
~
!!! error TS2322: Type 'string | number' is not assignable to type 'string'.
!!! error TS2322: Type 'number | string' is not assignable to type 'string'.
!!! error TS2322: Type 'number' is not assignable to type 'string'.
@@ -3,6 +3,6 @@ var union: string | number[];
>union : string | number[]
for (var v of union) { }
>v : string | number
>v : number | string
>union : string | number[]
@@ -1,8 +1,8 @@
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck9.ts(2,15): error TS2461: Type 'number | symbol | string[]' is not an array type.
tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck9.ts(2,15): error TS2461: Type 'string[] | number | symbol' is not an array type.
==== tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck9.ts (1 errors) ====
var union: string | string[] | number | symbol;
for (let v of union) { }
~~~~~
!!! error TS2461: Type 'number | symbol | string[]' is not an array type.
!!! error TS2461: Type 'string[] | number | symbol' is not an array type.
@@ -6,14 +6,14 @@ enum Color { R, G, B }
>B : Color
function f1(x: Color | string) {
>f1 : (x: string | Color) => void
>x : string | Color
>f1 : (x: Color | string) => void
>x : Color | string
>Color : Color
if (typeof x === "number") {
>typeof x === "number" : boolean
>typeof x : string
>x : string | Color
>x : Color | string
>"number" : string
var y = x;
@@ -35,14 +35,14 @@ function f1(x: Color | string) {
}
function f2(x: Color | string | string[]) {
>f2 : (x: string | Color | string[]) => void
>x : string | Color | string[]
>f2 : (x: Color | string | string[]) => void
>x : Color | string | string[]
>Color : Color
if (typeof x === "object") {
>typeof x === "object" : boolean
>typeof x : string
>x : string | Color | string[]
>x : Color | string | string[]
>"object" : string
var y = x;
@@ -55,7 +55,7 @@ function f2(x: Color | string | string[]) {
if (typeof x === "number") {
>typeof x === "number" : boolean
>typeof x : string
>x : string | Color | string[]
>x : Color | string | string[]
>"number" : string
var z = x;
@@ -77,7 +77,7 @@ function f2(x: Color | string | string[]) {
if (typeof x === "string") {
>typeof x === "string" : boolean
>typeof x : string
>x : string | Color | string[]
>x : Color | string | string[]
>"string" : string
var a = x;
@@ -34,7 +34,7 @@ var d2: IHasVisualizationModel = i || moduleA;
var d2: IHasVisualizationModel = moduleA || i;
>d2 : IHasVisualizationModel
>IHasVisualizationModel : IHasVisualizationModel
>moduleA || i : IHasVisualizationModel
>moduleA || i : typeof moduleA
>moduleA : typeof moduleA
>i : IHasVisualizationModel
@@ -0,0 +1,22 @@
tests/cases/compiler/aliasesInSystemModule1.ts(2,24): error TS2307: Cannot find module 'foo'.
==== tests/cases/compiler/aliasesInSystemModule1.ts (1 errors) ====
import alias = require('foo');
~~~~~
!!! error TS2307: Cannot find module 'foo'.
import cls = alias.Class;
export import cls2 = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
module M {
export import cls = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
}
@@ -0,0 +1,42 @@
//// [aliasesInSystemModule1.ts]
import alias = require('foo');
import cls = alias.Class;
export import cls2 = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
module M {
export import cls = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
}
//// [aliasesInSystemModule1.js]
System.register(['foo'], function(exports_1) {
var alias;
var cls, cls2, x, y, z, M;
return {
setters:[
function (_alias) {
alias = _alias;
}],
execute: function() {
cls = alias.Class;
exports_1("cls2", cls2 = alias.Class);
x = new alias.Class();
y = new cls();
z = new cls2();
(function (M) {
M.cls = alias.Class;
var x = new alias.Class();
var y = new M.cls();
var z = new cls2();
})(M || (M = {}));
}
}
});
@@ -0,0 +1,21 @@
tests/cases/compiler/aliasesInSystemModule2.ts(2,21): error TS2307: Cannot find module 'foo'.
==== tests/cases/compiler/aliasesInSystemModule2.ts (1 errors) ====
import {alias} from "foo";
~~~~~
!!! error TS2307: Cannot find module 'foo'.
import cls = alias.Class;
export import cls2 = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
module M {
export import cls = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
}
@@ -0,0 +1,41 @@
//// [aliasesInSystemModule2.ts]
import {alias} from "foo";
import cls = alias.Class;
export import cls2 = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
module M {
export import cls = alias.Class;
let x = new alias.Class();
let y = new cls();
let z = new cls2();
}
//// [aliasesInSystemModule2.js]
System.register(["foo"], function(exports_1) {
var foo_1;
var cls, cls2, x, y, z, M;
return {
setters:[
function (_foo_1) {
foo_1 = _foo_1;
}],
execute: function() {
cls = foo_1.alias.Class;
exports_1("cls2", cls2 = foo_1.alias.Class);
x = new foo_1.alias.Class();
y = new cls();
z = new cls2();
(function (M) {
M.cls = foo_1.alias.Class;
var x = new foo_1.alias.Class();
var y = new M.cls();
var z = new cls2();
})(M || (M = {}));
}
}
});
@@ -1,6 +1,7 @@
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(13,12): error TS2493: Tuple type '[string, number]' with length '2' cannot be assigned to tuple with length '3'.
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(14,12): error TS2460: Type 'StrNum' has no property '2'.
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(15,5): error TS2461: Type '{ 0: string; 1: number; }' is not an array type.
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(15,12): error TS2460: Type '{ 0: string; 1: number; }' has no property '2'.
tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(16,5): error TS2322: Type '[string, number]' is not assignable to type '[number, number, number]'.
Types of property '0' are incompatible.
Type 'string' is not assignable to type 'number'.
@@ -46,7 +47,7 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(30,5): error
Type 'string' is not assignable to type 'number'.
==== tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts (18 errors) ====
==== tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts (19 errors) ====
interface StrNum extends Array<string|number> {
0: string;
1: number;
@@ -68,6 +69,8 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(30,5): error
var [g, h, i] = z;
~~~~~~~~~
!!! error TS2461: Type '{ 0: string; 1: number; }' is not an array type.
~
!!! error TS2460: Type '{ 0: string; 1: number; }' has no property '2'.
var j1: [number, number, number] = x;
~~
!!! error TS2322: Type '[string, number]' is not assignable to type '[number, number, number]'.
@@ -294,8 +294,8 @@ module EmptyTypes {
// Order matters here so test all the variants
var a1 = [{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }];
>a1 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : { x: any; y: string; }[]
>a1 : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -313,8 +313,8 @@ module EmptyTypes {
>'a' : string
var a2 = [{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }];
>a2 : { x: any; y: string; }[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>a2 : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>{ x: anyObj, y: 'a' } : { x: any; y: string; }
>x : any
>anyObj : any
@@ -332,8 +332,8 @@ module EmptyTypes {
>'a' : string
var a3 = [{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }];
>a3 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>a3 : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -366,22 +366,22 @@ module EmptyTypes {
>base2 : typeof base2
var b1 = [baseObj, base2Obj, ifaceObj];
>b1 : iface[]
>[baseObj, base2Obj, ifaceObj] : iface[]
>b1 : base[]
>[baseObj, base2Obj, ifaceObj] : base[]
>baseObj : base
>base2Obj : base2
>ifaceObj : iface
var b2 = [base2Obj, baseObj, ifaceObj];
>b2 : iface[]
>[base2Obj, baseObj, ifaceObj] : iface[]
>b2 : base2[]
>[base2Obj, baseObj, ifaceObj] : base2[]
>base2Obj : base2
>baseObj : base
>ifaceObj : iface
var b3 = [baseObj, ifaceObj, base2Obj];
>b3 : iface[]
>[baseObj, ifaceObj, base2Obj] : iface[]
>b3 : base[]
>[baseObj, ifaceObj, base2Obj] : base[]
>baseObj : base
>ifaceObj : iface
>base2Obj : base2
@@ -639,7 +639,7 @@ module NonEmptyTypes {
>x : number
>y : base
>base : base
>[{ x: 7, y: new derived() }, { x: 5, y: new base() }] : { x: number; y: base; }[]
>[{ x: 7, y: new derived() }, { x: 5, y: new base() }] : ({ x: number; y: derived; } | { x: number; y: base; })[]
>{ x: 7, y: new derived() } : { x: number; y: derived; }
>x : number
>7 : number
@@ -658,7 +658,7 @@ module NonEmptyTypes {
>x : boolean
>y : base
>base : base
>[{ x: true, y: new derived() }, { x: false, y: new base() }] : { x: boolean; y: base; }[]
>[{ x: true, y: new derived() }, { x: false, y: new base() }] : ({ x: boolean; y: derived; } | { x: boolean; y: base; })[]
>{ x: true, y: new derived() } : { x: boolean; y: derived; }
>x : boolean
>true : boolean
@@ -697,8 +697,8 @@ module NonEmptyTypes {
// Order matters here so test all the variants
var a1 = [{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }];
>a1 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : { x: any; y: string; }[]
>a1 : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>[{ x: 0, y: 'a' }, { x: 'a', y: 'a' }, { x: anyObj, y: 'a' }] : ({ x: number; y: string; } | { x: string; y: string; } | { x: any; y: string; })[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -716,8 +716,8 @@ module NonEmptyTypes {
>'a' : string
var a2 = [{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }];
>a2 : { x: any; y: string; }[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>a2 : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>[{ x: anyObj, y: 'a' }, { x: 0, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: any; y: string; } | { x: number; y: string; } | { x: string; y: string; })[]
>{ x: anyObj, y: 'a' } : { x: any; y: string; }
>x : any
>anyObj : any
@@ -735,8 +735,8 @@ module NonEmptyTypes {
>'a' : string
var a3 = [{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }];
>a3 : { x: any; y: string; }[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : { x: any; y: string; }[]
>a3 : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>[{ x: 0, y: 'a' }, { x: anyObj, y: 'a' }, { x: 'a', y: 'a' }] : ({ x: number; y: string; } | { x: any; y: string; } | { x: string; y: string; })[]
>{ x: 0, y: 'a' } : { x: number; y: string; }
>x : number
>0 : number
@@ -769,29 +769,29 @@ module NonEmptyTypes {
>base2 : typeof base2
var b1 = [baseObj, base2Obj, ifaceObj];
>b1 : iface[]
>[baseObj, base2Obj, ifaceObj] : iface[]
>b1 : (base | base2 | iface)[]
>[baseObj, base2Obj, ifaceObj] : (base | base2 | iface)[]
>baseObj : base
>base2Obj : base2
>ifaceObj : iface
var b2 = [base2Obj, baseObj, ifaceObj];
>b2 : iface[]
>[base2Obj, baseObj, ifaceObj] : iface[]
>b2 : (base2 | base | iface)[]
>[base2Obj, baseObj, ifaceObj] : (base2 | base | iface)[]
>base2Obj : base2
>baseObj : base
>ifaceObj : iface
var b3 = [baseObj, ifaceObj, base2Obj];
>b3 : iface[]
>[baseObj, ifaceObj, base2Obj] : iface[]
>b3 : (base | iface | base2)[]
>[baseObj, ifaceObj, base2Obj] : (base | iface | base2)[]
>baseObj : base
>ifaceObj : iface
>base2Obj : base2
var b4 = [ifaceObj, baseObj, base2Obj];
>b4 : iface[]
>[ifaceObj, baseObj, base2Obj] : iface[]
>b4 : (iface | base | base2)[]
>[ifaceObj, baseObj, base2Obj] : (iface | base | base2)[]
>ifaceObj : iface
>baseObj : base
>base2Obj : base2
@@ -1,6 +1,6 @@
tests/cases/compiler/arrayCast.ts(3,1): error TS2352: Neither type '{ foo: string; }[]' nor type '{ id: number; }[]' is assignable to the other.
Type '{ foo: string; }' is not assignable to type '{ id: number; }'.
Property 'id' is missing in type '{ foo: string; }'.
Object literal may only specify known properties, and 'foo' does not exist in type '{ id: number; }'.
==== tests/cases/compiler/arrayCast.ts (1 errors) ====
@@ -10,7 +10,7 @@ tests/cases/compiler/arrayCast.ts(3,1): error TS2352: Neither type '{ foo: strin
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2352: Neither type '{ foo: string; }[]' nor type '{ id: number; }[]' is assignable to the other.
!!! error TS2352: Type '{ foo: string; }' is not assignable to type '{ id: number; }'.
!!! error TS2352: Property 'id' is missing in type '{ foo: string; }'.
!!! error TS2352: Object literal may only specify known properties, and 'foo' does not exist in type '{ id: number; }'.
// Should succeed, as the {} element causes the type of the array to be {}[]
<{ id: number; }[]>[{ foo: "s" }, {}];
@@ -1,7 +1,7 @@
tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionContextualTyping.ts(8,5): error TS2322: Type '[number, number, number, string]' is not assignable to type '[number, number, number]'.
Types of property 'pop' are incompatible.
Type '() => string | number' is not assignable to type '() => number'.
Type 'string | number' is not assignable to type 'number'.
Type '() => number | string' is not assignable to type '() => number'.
Type 'number | string' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionContextualTyping.ts(14,5): error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'.
Property '0' is missing in type 'number[]'.
@@ -19,8 +19,8 @@ tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionConte
~~~~
!!! error TS2322: Type '[number, number, number, string]' is not assignable to type '[number, number, number]'.
!!! error TS2322: Types of property 'pop' are incompatible.
!!! error TS2322: Type '() => string | number' is not assignable to type '() => number'.
!!! error TS2322: Type 'string | number' is not assignable to type 'number'.
!!! error TS2322: Type '() => number | string' is not assignable to type '() => number'.
!!! error TS2322: Type 'number | string' is not assignable to type 'number'.
!!! error TS2322: Type 'string' is not assignable to type 'number'.
// In a contextually typed array literal expression containing one or more spread elements,
@@ -0,0 +1,72 @@
tests/cases/compiler/arrayLiteralTypeInference.ts(13,5): error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type 'Action[]'.
Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type 'Action'.
Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'.
Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'.
tests/cases/compiler/arrayLiteralTypeInference.ts(29,5): error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type '{ id: number; }[]'.
Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type '{ id: number; }'.
Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'.
Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'.
==== tests/cases/compiler/arrayLiteralTypeInference.ts (2 errors) ====
class Action {
id: number;
}
class ActionA extends Action {
value: string;
}
class ActionB extends Action {
trueNess: boolean;
}
var x1: Action[] = [
~~
!!! error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type 'Action[]'.
!!! error TS2322: Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type 'Action'.
!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'.
!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'.
{ id: 2, trueness: false },
{ id: 3, name: "three" }
]
var x2: Action[] = [
new ActionA(),
new ActionB()
]
var x3: Action[] = [
new Action(),
new ActionA(),
new ActionB()
]
var z1: { id: number }[] =
~~
!!! error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type '{ id: number; }[]'.
!!! error TS2322: Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type '{ id: number; }'.
!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'.
!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'.
[
{ id: 2, trueness: false },
{ id: 3, name: "three" }
]
var z2: { id: number }[] =
[
new ActionA(),
new ActionB()
]
var z3: { id: number }[] =
[
new Action(),
new ActionA(),
new ActionB()
]
@@ -1,113 +0,0 @@
=== tests/cases/compiler/arrayLiteralTypeInference.ts ===
class Action {
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
id: number;
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 0, 14))
}
class ActionA extends Action {
>ActionA : Symbol(ActionA, Decl(arrayLiteralTypeInference.ts, 2, 1))
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
value: string;
>value : Symbol(value, Decl(arrayLiteralTypeInference.ts, 4, 30))
}
class ActionB extends Action {
>ActionB : Symbol(ActionB, Decl(arrayLiteralTypeInference.ts, 6, 1))
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
trueNess: boolean;
>trueNess : Symbol(trueNess, Decl(arrayLiteralTypeInference.ts, 8, 30))
}
var x1: Action[] = [
>x1 : Symbol(x1, Decl(arrayLiteralTypeInference.ts, 12, 3))
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
{ id: 2, trueness: false },
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 13, 5))
>trueness : Symbol(trueness, Decl(arrayLiteralTypeInference.ts, 13, 12))
{ id: 3, name: "three" }
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 14, 5))
>name : Symbol(name, Decl(arrayLiteralTypeInference.ts, 14, 12))
]
var x2: Action[] = [
>x2 : Symbol(x2, Decl(arrayLiteralTypeInference.ts, 17, 3))
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
new ActionA(),
>ActionA : Symbol(ActionA, Decl(arrayLiteralTypeInference.ts, 2, 1))
new ActionB()
>ActionB : Symbol(ActionB, Decl(arrayLiteralTypeInference.ts, 6, 1))
]
var x3: Action[] = [
>x3 : Symbol(x3, Decl(arrayLiteralTypeInference.ts, 22, 3))
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
new Action(),
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
new ActionA(),
>ActionA : Symbol(ActionA, Decl(arrayLiteralTypeInference.ts, 2, 1))
new ActionB()
>ActionB : Symbol(ActionB, Decl(arrayLiteralTypeInference.ts, 6, 1))
]
var z1: { id: number }[] =
>z1 : Symbol(z1, Decl(arrayLiteralTypeInference.ts, 28, 3))
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 28, 9))
[
{ id: 2, trueness: false },
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 30, 9))
>trueness : Symbol(trueness, Decl(arrayLiteralTypeInference.ts, 30, 16))
{ id: 3, name: "three" }
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 31, 9))
>name : Symbol(name, Decl(arrayLiteralTypeInference.ts, 31, 16))
]
var z2: { id: number }[] =
>z2 : Symbol(z2, Decl(arrayLiteralTypeInference.ts, 34, 3))
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 34, 9))
[
new ActionA(),
>ActionA : Symbol(ActionA, Decl(arrayLiteralTypeInference.ts, 2, 1))
new ActionB()
>ActionB : Symbol(ActionB, Decl(arrayLiteralTypeInference.ts, 6, 1))
]
var z3: { id: number }[] =
>z3 : Symbol(z3, Decl(arrayLiteralTypeInference.ts, 40, 3))
>id : Symbol(id, Decl(arrayLiteralTypeInference.ts, 40, 9))
[
new Action(),
>Action : Symbol(Action, Decl(arrayLiteralTypeInference.ts, 0, 0))
new ActionA(),
>ActionA : Symbol(ActionA, Decl(arrayLiteralTypeInference.ts, 2, 1))
new ActionB()
>ActionB : Symbol(ActionB, Decl(arrayLiteralTypeInference.ts, 6, 1))
]
@@ -1,144 +0,0 @@
=== tests/cases/compiler/arrayLiteralTypeInference.ts ===
class Action {
>Action : Action
id: number;
>id : number
}
class ActionA extends Action {
>ActionA : ActionA
>Action : Action
value: string;
>value : string
}
class ActionB extends Action {
>ActionB : ActionB
>Action : Action
trueNess: boolean;
>trueNess : boolean
}
var x1: Action[] = [
>x1 : Action[]
>Action : Action
>[ { id: 2, trueness: false }, { id: 3, name: "three" }] : ({ id: number; trueness: boolean; } | { id: number; name: string; })[]
{ id: 2, trueness: false },
>{ id: 2, trueness: false } : { id: number; trueness: boolean; }
>id : number
>2 : number
>trueness : boolean
>false : boolean
{ id: 3, name: "three" }
>{ id: 3, name: "three" } : { id: number; name: string; }
>id : number
>3 : number
>name : string
>"three" : string
]
var x2: Action[] = [
>x2 : Action[]
>Action : Action
>[ new ActionA(), new ActionB()] : (ActionA | ActionB)[]
new ActionA(),
>new ActionA() : ActionA
>ActionA : typeof ActionA
new ActionB()
>new ActionB() : ActionB
>ActionB : typeof ActionB
]
var x3: Action[] = [
>x3 : Action[]
>Action : Action
>[ new Action(), new ActionA(), new ActionB()] : Action[]
new Action(),
>new Action() : Action
>Action : typeof Action
new ActionA(),
>new ActionA() : ActionA
>ActionA : typeof ActionA
new ActionB()
>new ActionB() : ActionB
>ActionB : typeof ActionB
]
var z1: { id: number }[] =
>z1 : { id: number; }[]
>id : number
[
>[ { id: 2, trueness: false }, { id: 3, name: "three" } ] : ({ id: number; trueness: boolean; } | { id: number; name: string; })[]
{ id: 2, trueness: false },
>{ id: 2, trueness: false } : { id: number; trueness: boolean; }
>id : number
>2 : number
>trueness : boolean
>false : boolean
{ id: 3, name: "three" }
>{ id: 3, name: "three" } : { id: number; name: string; }
>id : number
>3 : number
>name : string
>"three" : string
]
var z2: { id: number }[] =
>z2 : { id: number; }[]
>id : number
[
>[ new ActionA(), new ActionB() ] : (ActionA | ActionB)[]
new ActionA(),
>new ActionA() : ActionA
>ActionA : typeof ActionA
new ActionB()
>new ActionB() : ActionB
>ActionB : typeof ActionB
]
var z3: { id: number }[] =
>z3 : { id: number; }[]
>id : number
[
>[ new Action(), new ActionA(), new ActionB() ] : Action[]
new Action(),
>new Action() : Action
>Action : typeof Action
new ActionA(),
>new ActionA() : ActionA
>ActionA : typeof ActionA
new ActionB()
>new ActionB() : ActionB
>ActionB : typeof ActionB
]
@@ -23,8 +23,8 @@ var as = [a, b]; // { x: number; y?: number };[]
>b : { x: number; z?: number; }
var bs = [b, a]; // { x: number; z?: number };[]
>bs : ({ x: number; y?: number; } | { x: number; z?: number; })[]
>[b, a] : ({ x: number; y?: number; } | { x: number; z?: number; })[]
>bs : ({ x: number; z?: number; } | { x: number; y?: number; })[]
>[b, a] : ({ x: number; z?: number; } | { x: number; y?: number; })[]
>b : { x: number; z?: number; }
>a : { x: number; y?: number; }
@@ -36,8 +36,8 @@ var cs = [a, b, c]; // { x: number; y?: number };[]
>c : { x: number; a?: number; }
var ds = [(x: Object) => 1, (x: string) => 2]; // { (x:Object) => number }[]
>ds : ((x: Object) => number)[]
>[(x: Object) => 1, (x: string) => 2] : ((x: Object) => number)[]
>ds : (((x: Object) => number) | ((x: string) => number))[]
>[(x: Object) => 1, (x: string) => 2] : (((x: Object) => number) | ((x: string) => number))[]
>(x: Object) => 1 : (x: Object) => number
>x : Object
>Object : Object
@@ -47,8 +47,8 @@ var ds = [(x: Object) => 1, (x: string) => 2]; // { (x:Object) => number }[]
>2 : number
var es = [(x: string) => 2, (x: Object) => 1]; // { (x:string) => number }[]
>es : ((x: string) => number)[]
>[(x: string) => 2, (x: Object) => 1] : ((x: string) => number)[]
>es : (((x: string) => number) | ((x: Object) => number))[]
>[(x: string) => 2, (x: Object) => 1] : (((x: string) => number) | ((x: Object) => number))[]
>(x: string) => 2 : (x: string) => number
>x : string
>2 : number
@@ -0,0 +1,50 @@
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts(24,5): error TS2322: Type '({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]' is not assignable to type '{ [n: number]: { a: string; b: number; }; }'.
Index signatures are incompatible.
Type '{ a: string; b: number; c: string; } | { a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'.
Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'.
Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'.
==== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts (1 errors) ====
// Empty array literal with no contextual type has type Undefined[]
var arr1= [[], [1], ['']];
var arr2 = [[null], [1], ['']];
// Array literal with elements of only EveryType E has type E[]
var stringArrArr = [[''], [""]];
var stringArr = ['', ""];
var numberArr = [0, 0.0, 0x00, 1e1];
var boolArr = [false, true, false, true];
class C { private p; }
var classArr = [new C(), new C()];
var classTypeArray = [C, C, C];
var classTypeArray: Array<typeof C>; // Should OK, not be a parse error
// Contextual type C with numeric index signature makes array literal of EveryType E of type BCT(E,C)[]
var context1: { [n: number]: { a: string; b: number; }; } = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
~~~~~~~~
!!! error TS2322: Type '({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]' is not assignable to type '{ [n: number]: { a: string; b: number; }; }'.
!!! error TS2322: Index signatures are incompatible.
!!! error TS2322: Type '{ a: string; b: number; c: string; } | { a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'.
!!! error TS2322: Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'.
!!! error TS2322: Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'.
var context2 = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
// Contextual type C with numeric index signature of type Base makes array literal of Derived have type Base[]
class Base { private p; }
class Derived1 extends Base { private m };
class Derived2 extends Base { private n };
var context3: Base[] = [new Derived1(), new Derived2()];
// Contextual type C with numeric index signature of type Base makes array literal of Derived1 and Derived2 have type Base[]
var context4: Base[] = [new Derived1(), new Derived1()];
@@ -1,94 +0,0 @@
=== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts ===
// Empty array literal with no contextual type has type Undefined[]
var arr1= [[], [1], ['']];
>arr1 : Symbol(arr1, Decl(arrayLiterals.ts, 2, 3))
var arr2 = [[null], [1], ['']];
>arr2 : Symbol(arr2, Decl(arrayLiterals.ts, 4, 3))
// Array literal with elements of only EveryType E has type E[]
var stringArrArr = [[''], [""]];
>stringArrArr : Symbol(stringArrArr, Decl(arrayLiterals.ts, 8, 3))
var stringArr = ['', ""];
>stringArr : Symbol(stringArr, Decl(arrayLiterals.ts, 10, 3))
var numberArr = [0, 0.0, 0x00, 1e1];
>numberArr : Symbol(numberArr, Decl(arrayLiterals.ts, 12, 3))
var boolArr = [false, true, false, true];
>boolArr : Symbol(boolArr, Decl(arrayLiterals.ts, 14, 3))
class C { private p; }
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
>p : Symbol(p, Decl(arrayLiterals.ts, 16, 9))
var classArr = [new C(), new C()];
>classArr : Symbol(classArr, Decl(arrayLiterals.ts, 17, 3))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
var classTypeArray = [C, C, C];
>classTypeArray : Symbol(classTypeArray, Decl(arrayLiterals.ts, 19, 3), Decl(arrayLiterals.ts, 20, 3))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
var classTypeArray: Array<typeof C>; // Should OK, not be a parse error
>classTypeArray : Symbol(classTypeArray, Decl(arrayLiterals.ts, 19, 3), Decl(arrayLiterals.ts, 20, 3))
>Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11))
>C : Symbol(C, Decl(arrayLiterals.ts, 14, 41))
// Contextual type C with numeric index signature makes array literal of EveryType E of type BCT(E,C)[]
var context1: { [n: number]: { a: string; b: number; }; } = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
>context1 : Symbol(context1, Decl(arrayLiterals.ts, 23, 3))
>n : Symbol(n, Decl(arrayLiterals.ts, 23, 17))
>a : Symbol(a, Decl(arrayLiterals.ts, 23, 30))
>b : Symbol(b, Decl(arrayLiterals.ts, 23, 41))
>a : Symbol(a, Decl(arrayLiterals.ts, 23, 62))
>b : Symbol(b, Decl(arrayLiterals.ts, 23, 69))
>c : Symbol(c, Decl(arrayLiterals.ts, 23, 75))
>a : Symbol(a, Decl(arrayLiterals.ts, 23, 86))
>b : Symbol(b, Decl(arrayLiterals.ts, 23, 93))
>c : Symbol(c, Decl(arrayLiterals.ts, 23, 99))
var context2 = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
>context2 : Symbol(context2, Decl(arrayLiterals.ts, 24, 3))
>a : Symbol(a, Decl(arrayLiterals.ts, 24, 17))
>b : Symbol(b, Decl(arrayLiterals.ts, 24, 24))
>c : Symbol(c, Decl(arrayLiterals.ts, 24, 30))
>a : Symbol(a, Decl(arrayLiterals.ts, 24, 41))
>b : Symbol(b, Decl(arrayLiterals.ts, 24, 48))
>c : Symbol(c, Decl(arrayLiterals.ts, 24, 54))
// Contextual type C with numeric index signature of type Base makes array literal of Derived have type Base[]
class Base { private p; }
>Base : Symbol(Base, Decl(arrayLiterals.ts, 24, 63))
>p : Symbol(p, Decl(arrayLiterals.ts, 27, 12))
class Derived1 extends Base { private m };
>Derived1 : Symbol(Derived1, Decl(arrayLiterals.ts, 27, 25))
>Base : Symbol(Base, Decl(arrayLiterals.ts, 24, 63))
>m : Symbol(m, Decl(arrayLiterals.ts, 28, 29))
class Derived2 extends Base { private n };
>Derived2 : Symbol(Derived2, Decl(arrayLiterals.ts, 28, 42))
>Base : Symbol(Base, Decl(arrayLiterals.ts, 24, 63))
>n : Symbol(n, Decl(arrayLiterals.ts, 29, 29))
var context3: Base[] = [new Derived1(), new Derived2()];
>context3 : Symbol(context3, Decl(arrayLiterals.ts, 30, 3))
>Base : Symbol(Base, Decl(arrayLiterals.ts, 24, 63))
>Derived1 : Symbol(Derived1, Decl(arrayLiterals.ts, 27, 25))
>Derived2 : Symbol(Derived2, Decl(arrayLiterals.ts, 28, 42))
// Contextual type C with numeric index signature of type Base makes array literal of Derived1 and Derived2 have type Base[]
var context4: Base[] = [new Derived1(), new Derived1()];
>context4 : Symbol(context4, Decl(arrayLiterals.ts, 33, 3))
>Base : Symbol(Base, Decl(arrayLiterals.ts, 24, 63))
>Derived1 : Symbol(Derived1, Decl(arrayLiterals.ts, 27, 25))
>Derived1 : Symbol(Derived1, Decl(arrayLiterals.ts, 27, 25))
@@ -1,153 +0,0 @@
=== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts ===
// Empty array literal with no contextual type has type Undefined[]
var arr1= [[], [1], ['']];
>arr1 : (number[] | string[])[]
>[[], [1], ['']] : (number[] | string[])[]
>[] : undefined[]
>[1] : number[]
>1 : number
>[''] : string[]
>'' : string
var arr2 = [[null], [1], ['']];
>arr2 : (number[] | string[])[]
>[[null], [1], ['']] : (number[] | string[])[]
>[null] : null[]
>null : null
>[1] : number[]
>1 : number
>[''] : string[]
>'' : string
// Array literal with elements of only EveryType E has type E[]
var stringArrArr = [[''], [""]];
>stringArrArr : string[][]
>[[''], [""]] : string[][]
>[''] : string[]
>'' : string
>[""] : string[]
>"" : string
var stringArr = ['', ""];
>stringArr : string[]
>['', ""] : string[]
>'' : string
>"" : string
var numberArr = [0, 0.0, 0x00, 1e1];
>numberArr : number[]
>[0, 0.0, 0x00, 1e1] : number[]
>0 : number
>0.0 : number
>0x00 : number
>1e1 : number
var boolArr = [false, true, false, true];
>boolArr : boolean[]
>[false, true, false, true] : boolean[]
>false : boolean
>true : boolean
>false : boolean
>true : boolean
class C { private p; }
>C : C
>p : any
var classArr = [new C(), new C()];
>classArr : C[]
>[new C(), new C()] : C[]
>new C() : C
>C : typeof C
>new C() : C
>C : typeof C
var classTypeArray = [C, C, C];
>classTypeArray : typeof C[]
>[C, C, C] : typeof C[]
>C : typeof C
>C : typeof C
>C : typeof C
var classTypeArray: Array<typeof C>; // Should OK, not be a parse error
>classTypeArray : typeof C[]
>Array : T[]
>C : typeof C
// Contextual type C with numeric index signature makes array literal of EveryType E of type BCT(E,C)[]
var context1: { [n: number]: { a: string; b: number; }; } = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
>context1 : { [n: number]: { a: string; b: number; }; }
>n : number
>a : string
>b : number
>[{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }] : ({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]
>{ a: '', b: 0, c: '' } : { a: string; b: number; c: string; }
>a : string
>'' : string
>b : number
>0 : number
>c : string
>'' : string
>{ a: "", b: 3, c: 0 } : { a: string; b: number; c: number; }
>a : string
>"" : string
>b : number
>3 : number
>c : number
>0 : number
var context2 = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }];
>context2 : ({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]
>[{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }] : ({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]
>{ a: '', b: 0, c: '' } : { a: string; b: number; c: string; }
>a : string
>'' : string
>b : number
>0 : number
>c : string
>'' : string
>{ a: "", b: 3, c: 0 } : { a: string; b: number; c: number; }
>a : string
>"" : string
>b : number
>3 : number
>c : number
>0 : number
// Contextual type C with numeric index signature of type Base makes array literal of Derived have type Base[]
class Base { private p; }
>Base : Base
>p : any
class Derived1 extends Base { private m };
>Derived1 : Derived1
>Base : Base
>m : any
class Derived2 extends Base { private n };
>Derived2 : Derived2
>Base : Base
>n : any
var context3: Base[] = [new Derived1(), new Derived2()];
>context3 : Base[]
>Base : Base
>[new Derived1(), new Derived2()] : (Derived1 | Derived2)[]
>new Derived1() : Derived1
>Derived1 : typeof Derived1
>new Derived2() : Derived2
>Derived2 : typeof Derived2
// Contextual type C with numeric index signature of type Base makes array literal of Derived1 and Derived2 have type Base[]
var context4: Base[] = [new Derived1(), new Derived1()];
>context4 : Base[]
>Base : Base
>[new Derived1(), new Derived1()] : Derived1[]
>new Derived1() : Derived1
>Derived1 : typeof Derived1
>new Derived1() : Derived1
>Derived1 : typeof Derived1
@@ -24,8 +24,8 @@ var a1 = ["hello", "world"]
>"world" : string
var a2 = [, , , ...a0, "hello"];
>a2 : (string | number)[]
>[, , , ...a0, "hello"] : (string | number)[]
>a2 : (number | string)[]
>[, , , ...a0, "hello"] : (number | string)[]
> : undefined
> : undefined
> : undefined
@@ -151,8 +151,8 @@ interface myArray2 extends Array<Number|String> { }
>String : String
var d0 = [1, true, ...temp,]; // has type (string|number|boolean)[]
>d0 : (string | number | boolean)[]
>[1, true, ...temp,] : (string | number | boolean)[]
>d0 : (number | boolean | string)[]
>[1, true, ...temp,] : (number | boolean | string)[]
>1 : number
>true : boolean
>...temp : string
@@ -214,8 +214,8 @@ var d8: number[][] = [[...temp1]]
>temp1 : number[]
var d9 = [[...temp1], ...["hello"]];
>d9 : (string | number[])[]
>[[...temp1], ...["hello"]] : (string | number[])[]
>d9 : (number[] | string)[]
>[[...temp1], ...["hello"]] : (number[] | string)[]
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
@@ -24,8 +24,8 @@ var a1 = ["hello", "world"]
>"world" : string
var a2 = [, , , ...a0, "hello"];
>a2 : (string | number)[]
>[, , , ...a0, "hello"] : (string | number)[]
>a2 : (number | string)[]
>[, , , ...a0, "hello"] : (number | string)[]
> : undefined
> : undefined
> : undefined
@@ -140,8 +140,8 @@ interface myArray2 extends Array<Number|String> { }
>String : String
var d0 = [1, true, ...temp, ]; // has type (string|number|boolean)[]
>d0 : (string | number | boolean)[]
>[1, true, ...temp, ] : (string | number | boolean)[]
>d0 : (number | boolean | string)[]
>[1, true, ...temp, ] : (number | boolean | string)[]
>1 : number
>true : boolean
>...temp : string
@@ -176,10 +176,10 @@ var d4: myArray2 = [...temp, ...temp1];
>temp1 : number[]
var d5 = [...a2];
>d5 : (string | number)[]
>[...a2] : (string | number)[]
>...a2 : string | number
>a2 : (string | number)[]
>d5 : (number | string)[]
>[...a2] : (number | string)[]
>...a2 : number | string
>a2 : (number | string)[]
var d6 = [...a3];
>d6 : number[]
@@ -201,8 +201,8 @@ var d8: number[][] = [[...temp1]]
>temp1 : number[]
var d9 = [[...temp1], ...["hello"]];
>d9 : (string | number[])[]
>[[...temp1], ...["hello"]] : (string | number[])[]
>d9 : (number[] | string)[]
>[[...temp1], ...["hello"]] : (number[] | string)[]
>[...temp1] : number[]
>...temp1 : number
>temp1 : number[]
@@ -5,18 +5,18 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(11,5): error
Type 'string' is not assignable to type 'boolean'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(17,5): error TS2322: Type '[number, number, string, boolean]' is not assignable to type '[number, number]'.
Types of property 'pop' are incompatible.
Type '() => string | number | boolean' is not assignable to type '() => number'.
Type 'string | number | boolean' is not assignable to type 'number'.
Type '() => number | string | boolean' is not assignable to type '() => number'.
Type 'number | string | boolean' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(32,5): error TS2322: Type '(number[] | string[])[]' is not assignable to type 'tup'.
Property '0' is missing in type '(number[] | string[])[]'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(33,5): error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'.
Property '0' is missing in type 'number[]'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error TS2322: Type '(string | number)[]' is not assignable to type 'myArray'.
tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error TS2322: Type '(number | string)[]' is not assignable to type 'myArray'.
Types of property 'push' are incompatible.
Type '(...items: (string | number)[]) => number' is not assignable to type '(...items: Number[]) => number'.
Type '(...items: (number | string)[]) => number' is not assignable to type '(...items: Number[]) => number'.
Types of parameters 'items' and 'items' are incompatible.
Type 'string | number' is not assignable to type 'Number'.
Type 'number | string' is not assignable to type 'Number'.
Type 'string' is not assignable to type 'Number'.
Property 'toFixed' is missing in type 'String'.
@@ -49,8 +49,8 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error
~~~~~~~~
!!! error TS2322: Type '[number, number, string, boolean]' is not assignable to type '[number, number]'.
!!! error TS2322: Types of property 'pop' are incompatible.
!!! error TS2322: Type '() => string | number | boolean' is not assignable to type '() => number'.
!!! error TS2322: Type 'string | number | boolean' is not assignable to type 'number'.
!!! error TS2322: Type '() => number | string | boolean' is not assignable to type '() => number'.
!!! error TS2322: Type 'number | string | boolean' is not assignable to type 'number'.
!!! error TS2322: Type 'string' is not assignable to type 'number'.
// The resulting type an array literal expression is determined as follows:
@@ -76,11 +76,11 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error
!!! error TS2322: Property '0' is missing in type 'number[]'.
var c2: myArray = [...temp1, ...temp]; // Error cannot assign (number|string)[] to number[]
~~
!!! error TS2322: Type '(string | number)[]' is not assignable to type 'myArray'.
!!! error TS2322: Type '(number | string)[]' is not assignable to type 'myArray'.
!!! error TS2322: Types of property 'push' are incompatible.
!!! error TS2322: Type '(...items: (string | number)[]) => number' is not assignable to type '(...items: Number[]) => number'.
!!! error TS2322: Type '(...items: (number | string)[]) => number' is not assignable to type '(...items: Number[]) => number'.
!!! error TS2322: Types of parameters 'items' and 'items' are incompatible.
!!! error TS2322: Type 'string | number' is not assignable to type 'Number'.
!!! error TS2322: Type 'number | string' is not assignable to type 'Number'.
!!! error TS2322: Type 'string' is not assignable to type 'Number'.
!!! error TS2322: Property 'toFixed' is missing in type 'String'.
@@ -77,8 +77,8 @@ var myDerivedList: DerivedList<number>;
>DerivedList : DerivedList<U>
var as = [list, myDerivedList]; // List<number>[]
>as : List<number>[]
>[list, myDerivedList] : List<number>[]
>as : (List<number> | DerivedList<number>)[]
>[list, myDerivedList] : (List<number> | DerivedList<number>)[]
>list : List<number>
>myDerivedList : DerivedList<number>
@@ -0,0 +1,35 @@
tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts(17,13): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts(26,10): error TS2349: Cannot invoke an expression whose type lacks a call signature.
==== tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts (2 errors) ====
// valid uses of arrays of function types
var x = [() => 1, () => { }];
var r2 = x[0]();
class C {
foo: string;
}
var y = [C, C];
var r3 = new y[0]();
var a: { (x: number): number; (x: string): string; };
var b: { (x: number): number; (x: string): string; };
var c: { (x: number): number; (x: any): any; };
var z = [a, b, c];
var r4 = z[0];
var r5 = r4(''); // any not string
~~
!!! error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
var r5b = r4(1);
var a2: { <T>(x: T): number; (x: string): string;};
var b2: { <T>(x: T): number; (x: string): string; };
var c2: { (x: number): number; <T>(x: T): any; };
var z2 = [a2, b2, c2];
var r6 = z2[0];
var r7 = r6(''); // any not string
~~~~~~
!!! error TS2349: Cannot invoke an expression whose type lacks a call signature.
@@ -1,93 +0,0 @@
=== tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts ===
// valid uses of arrays of function types
var x = [() => 1, () => { }];
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 2, 3))
var r2 = x[0]();
>r2 : Symbol(r2, Decl(arrayOfFunctionTypes3.ts, 3, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 2, 3))
class C {
>C : Symbol(C, Decl(arrayOfFunctionTypes3.ts, 3, 16))
foo: string;
>foo : Symbol(foo, Decl(arrayOfFunctionTypes3.ts, 5, 9))
}
var y = [C, C];
>y : Symbol(y, Decl(arrayOfFunctionTypes3.ts, 8, 3))
>C : Symbol(C, Decl(arrayOfFunctionTypes3.ts, 3, 16))
>C : Symbol(C, Decl(arrayOfFunctionTypes3.ts, 3, 16))
var r3 = new y[0]();
>r3 : Symbol(r3, Decl(arrayOfFunctionTypes3.ts, 9, 3))
>y : Symbol(y, Decl(arrayOfFunctionTypes3.ts, 8, 3))
var a: { (x: number): number; (x: string): string; };
>a : Symbol(a, Decl(arrayOfFunctionTypes3.ts, 11, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 11, 10))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 11, 31))
var b: { (x: number): number; (x: string): string; };
>b : Symbol(b, Decl(arrayOfFunctionTypes3.ts, 12, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 12, 10))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 12, 31))
var c: { (x: number): number; (x: any): any; };
>c : Symbol(c, Decl(arrayOfFunctionTypes3.ts, 13, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 13, 10))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 13, 31))
var z = [a, b, c];
>z : Symbol(z, Decl(arrayOfFunctionTypes3.ts, 14, 3))
>a : Symbol(a, Decl(arrayOfFunctionTypes3.ts, 11, 3))
>b : Symbol(b, Decl(arrayOfFunctionTypes3.ts, 12, 3))
>c : Symbol(c, Decl(arrayOfFunctionTypes3.ts, 13, 3))
var r4 = z[0];
>r4 : Symbol(r4, Decl(arrayOfFunctionTypes3.ts, 15, 3))
>z : Symbol(z, Decl(arrayOfFunctionTypes3.ts, 14, 3))
var r5 = r4(''); // any not string
>r5 : Symbol(r5, Decl(arrayOfFunctionTypes3.ts, 16, 3))
>r4 : Symbol(r4, Decl(arrayOfFunctionTypes3.ts, 15, 3))
var r5b = r4(1);
>r5b : Symbol(r5b, Decl(arrayOfFunctionTypes3.ts, 17, 3))
>r4 : Symbol(r4, Decl(arrayOfFunctionTypes3.ts, 15, 3))
var a2: { <T>(x: T): number; (x: string): string;};
>a2 : Symbol(a2, Decl(arrayOfFunctionTypes3.ts, 19, 3))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 19, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 19, 14))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 19, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 19, 30))
var b2: { <T>(x: T): number; (x: string): string; };
>b2 : Symbol(b2, Decl(arrayOfFunctionTypes3.ts, 20, 3))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 20, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 20, 14))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 20, 11))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 20, 30))
var c2: { (x: number): number; <T>(x: T): any; };
>c2 : Symbol(c2, Decl(arrayOfFunctionTypes3.ts, 21, 3))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 21, 11))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 21, 32))
>x : Symbol(x, Decl(arrayOfFunctionTypes3.ts, 21, 35))
>T : Symbol(T, Decl(arrayOfFunctionTypes3.ts, 21, 32))
var z2 = [a2, b2, c2];
>z2 : Symbol(z2, Decl(arrayOfFunctionTypes3.ts, 23, 3))
>a2 : Symbol(a2, Decl(arrayOfFunctionTypes3.ts, 19, 3))
>b2 : Symbol(b2, Decl(arrayOfFunctionTypes3.ts, 20, 3))
>c2 : Symbol(c2, Decl(arrayOfFunctionTypes3.ts, 21, 3))
var r6 = z2[0];
>r6 : Symbol(r6, Decl(arrayOfFunctionTypes3.ts, 24, 3))
>z2 : Symbol(z2, Decl(arrayOfFunctionTypes3.ts, 23, 3))
var r7 = r6(''); // any not string
>r7 : Symbol(r7, Decl(arrayOfFunctionTypes3.ts, 25, 3))
>r6 : Symbol(r6, Decl(arrayOfFunctionTypes3.ts, 24, 3))
@@ -1,116 +0,0 @@
=== tests/cases/conformance/types/specifyingTypes/typeLiterals/arrayOfFunctionTypes3.ts ===
// valid uses of arrays of function types
var x = [() => 1, () => { }];
>x : (() => void)[]
>[() => 1, () => { }] : (() => void)[]
>() => 1 : () => number
>1 : number
>() => { } : () => void
var r2 = x[0]();
>r2 : void
>x[0]() : void
>x[0] : () => void
>x : (() => void)[]
>0 : number
class C {
>C : C
foo: string;
>foo : string
}
var y = [C, C];
>y : typeof C[]
>[C, C] : typeof C[]
>C : typeof C
>C : typeof C
var r3 = new y[0]();
>r3 : C
>new y[0]() : C
>y[0] : typeof C
>y : typeof C[]
>0 : number
var a: { (x: number): number; (x: string): string; };
>a : { (x: number): number; (x: string): string; }
>x : number
>x : string
var b: { (x: number): number; (x: string): string; };
>b : { (x: number): number; (x: string): string; }
>x : number
>x : string
var c: { (x: number): number; (x: any): any; };
>c : { (x: number): number; (x: any): any; }
>x : number
>x : any
var z = [a, b, c];
>z : { (x: number): number; (x: any): any; }[]
>[a, b, c] : { (x: number): number; (x: any): any; }[]
>a : { (x: number): number; (x: string): string; }
>b : { (x: number): number; (x: string): string; }
>c : { (x: number): number; (x: any): any; }
var r4 = z[0];
>r4 : { (x: number): number; (x: any): any; }
>z[0] : { (x: number): number; (x: any): any; }
>z : { (x: number): number; (x: any): any; }[]
>0 : number
var r5 = r4(''); // any not string
>r5 : any
>r4('') : any
>r4 : { (x: number): number; (x: any): any; }
>'' : string
var r5b = r4(1);
>r5b : number
>r4(1) : number
>r4 : { (x: number): number; (x: any): any; }
>1 : number
var a2: { <T>(x: T): number; (x: string): string;};
>a2 : { <T>(x: T): number; (x: string): string; }
>T : T
>x : T
>T : T
>x : string
var b2: { <T>(x: T): number; (x: string): string; };
>b2 : { <T>(x: T): number; (x: string): string; }
>T : T
>x : T
>T : T
>x : string
var c2: { (x: number): number; <T>(x: T): any; };
>c2 : { (x: number): number; <T>(x: T): any; }
>x : number
>T : T
>x : T
>T : T
var z2 = [a2, b2, c2];
>z2 : { (x: number): number; <T>(x: T): any; }[]
>[a2, b2, c2] : { (x: number): number; <T>(x: T): any; }[]
>a2 : { <T>(x: T): number; (x: string): string; }
>b2 : { <T>(x: T): number; (x: string): string; }
>c2 : { (x: number): number; <T>(x: T): any; }
var r6 = z2[0];
>r6 : { (x: number): number; <T>(x: T): any; }
>z2[0] : { (x: number): number; <T>(x: T): any; }
>z2 : { (x: number): number; <T>(x: T): any; }[]
>0 : number
var r7 = r6(''); // any not string
>r7 : any
>r6('') : any
>r6 : { (x: number): number; <T>(x: T): any; }
>'' : string
@@ -70,6 +70,7 @@ var p6 = ({ a }) => { };
var p7 = ({ a: { b } }) => { };
>p7 : Symbol(p7, Decl(arrowFunctionExpressions.ts, 21, 3))
>a : Symbol(a)
>b : Symbol(b, Decl(arrowFunctionExpressions.ts, 21, 16))
var p8 = ({ a = 1 }) => { };
@@ -78,6 +79,7 @@ var p8 = ({ a = 1 }) => { };
var p9 = ({ a: { b = 1 } = { b: 1 } }) => { };
>p9 : Symbol(p9, Decl(arrowFunctionExpressions.ts, 23, 3))
>a : Symbol(a)
>b : Symbol(b, Decl(arrowFunctionExpressions.ts, 23, 16))
>b : Symbol(b, Decl(arrowFunctionExpressions.ts, 23, 28))
+3 -3
View File
@@ -24,12 +24,12 @@ var z = Date as any as string;
// Should parse as a union type, not a bitwise 'or' of (32 as number) and 'string'
var j = 32 as number|string;
>j : string | number
>32 as number|string : string | number
>j : number | string
>32 as number|string : number | string
>32 : number
j = '';
>j = '' : string
>j : string | number
>j : number | string
>'' : string
@@ -1,7 +1,7 @@
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatBetweenTupleAndArray.ts(17,1): error TS2322: Type '[number, string]' is not assignable to type 'number[]'.
Types of property 'pop' are incompatible.
Type '() => string | number' is not assignable to type '() => number'.
Type 'string | number' is not assignable to type 'number'.
Type '() => number | string' is not assignable to type '() => number'.
Type 'number | string' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatBetweenTupleAndArray.ts(18,1): error TS2322: Type '{}[]' is not assignable to type '[{}]'.
Property '0' is missing in type '{}[]'.
@@ -28,8 +28,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme
~~~~~~~~
!!! error TS2322: Type '[number, string]' is not assignable to type 'number[]'.
!!! error TS2322: Types of property 'pop' are incompatible.
!!! error TS2322: Type '() => string | number' is not assignable to type '() => number'.
!!! error TS2322: Type 'string | number' is not assignable to type 'number'.
!!! error TS2322: Type '() => number | string' is not assignable to type '() => number'.
!!! error TS2322: Type 'number | string' is not assignable to type 'number'.
!!! error TS2322: Type 'string' is not assignable to type 'number'.
emptyObjTuple = emptyObjArray;
~~~~~~~~~~~~~
@@ -1,7 +1,9 @@
tests/cases/compiler/assignmentCompatBug2.ts(1,5): error TS2322: Type '{ a: number; }' is not assignable to type '{ b: number; }'.
Property 'b' is missing in type '{ a: number; }'.
Object literal may only specify known properties, and 'a' does not exist in type '{ b: number; }'.
tests/cases/compiler/assignmentCompatBug2.ts(3,1): error TS2322: Type '{ a: number; }' is not assignable to type '{ b: number; }'.
Property 'b' is missing in type '{ a: number; }'.
Object literal may only specify known properties, and 'a' does not exist in type '{ b: number; }'.
tests/cases/compiler/assignmentCompatBug2.ts(5,1): error TS2322: Type '{ b: number; a: number; }' is not assignable to type '{ b: number; }'.
Object literal may only specify known properties, and 'a' does not exist in type '{ b: number; }'.
tests/cases/compiler/assignmentCompatBug2.ts(15,1): error TS2322: Type '{ f: (n: number) => number; g: (s: string) => number; }' is not assignable to type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'.
Property 'm' is missing in type '{ f: (n: number) => number; g: (s: string) => number; }'.
tests/cases/compiler/assignmentCompatBug2.ts(20,1): error TS2322: Type '{ f: (n: number) => number; m: number; }' is not assignable to type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'.
@@ -10,18 +12,21 @@ tests/cases/compiler/assignmentCompatBug2.ts(33,1): error TS2322: Type '{ f: (n:
Property 'm' is missing in type '{ f: (n: number) => number; g: (s: string) => number; n: number; k: (a: any) => any; }'.
==== tests/cases/compiler/assignmentCompatBug2.ts (5 errors) ====
==== tests/cases/compiler/assignmentCompatBug2.ts (6 errors) ====
var b2: { b: number;} = { a: 0 }; // error
~~
!!! error TS2322: Type '{ a: number; }' is not assignable to type '{ b: number; }'.
!!! error TS2322: Property 'b' is missing in type '{ a: number; }'.
!!! error TS2322: Object literal may only specify known properties, and 'a' does not exist in type '{ b: number; }'.
b2 = { a: 0 }; // error
~~
!!! error TS2322: Type '{ a: number; }' is not assignable to type '{ b: number; }'.
!!! error TS2322: Property 'b' is missing in type '{ a: number; }'.
!!! error TS2322: Object literal may only specify known properties, and 'a' does not exist in type '{ b: number; }'.
b2 = {b: 0, a: 0 };
~~
!!! error TS2322: Type '{ b: number; a: number; }' is not assignable to type '{ b: number; }'.
!!! error TS2322: Object literal may only specify known properties, and 'a' does not exist in type '{ b: number; }'.
var b3: { f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; };
@@ -1,5 +1,5 @@
tests/cases/compiler/assignmentCompatBug5.ts(2,6): error TS2345: Argument of type '{ b: number; }' is not assignable to parameter of type '{ a: number; }'.
Property 'a' is missing in type '{ b: number; }'.
Object literal may only specify known properties, and 'b' does not exist in type '{ a: number; }'.
tests/cases/compiler/assignmentCompatBug5.ts(5,6): error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'number[]'.
Type 'string' is not assignable to type 'number'.
tests/cases/compiler/assignmentCompatBug5.ts(8,6): error TS2345: Argument of type '(s: string) => void' is not assignable to parameter of type '(n: number) => number'.
@@ -14,7 +14,7 @@ tests/cases/compiler/assignmentCompatBug5.ts(9,6): error TS2345: Argument of typ
foo1({ b: 5 });
~~~~~~~~
!!! error TS2345: Argument of type '{ b: number; }' is not assignable to parameter of type '{ a: number; }'.
!!! error TS2345: Property 'a' is missing in type '{ b: number; }'.
!!! error TS2345: Object literal may only specify known properties, and 'b' does not exist in type '{ a: number; }'.
function foo2(x: number[]) { }
foo2(["s", "t"]);
@@ -1,6 +1,6 @@
=== tests/cases/conformance/async/es6/awaitUnion_es6.ts ===
declare let a: number | string;
>a : string | number
>a : number | string
declare let b: PromiseLike<number> | PromiseLike<string>;
>b : PromiseLike<number> | PromiseLike<string>
@@ -8,7 +8,7 @@ declare let b: PromiseLike<number> | PromiseLike<string>;
>PromiseLike : PromiseLike<T>
declare let c: PromiseLike<number | string>;
>c : PromiseLike<string | number>
>c : PromiseLike<number | string>
>PromiseLike : PromiseLike<T>
declare let d: number | PromiseLike<string>;
@@ -16,29 +16,29 @@ declare let d: number | PromiseLike<string>;
>PromiseLike : PromiseLike<T>
declare let e: number | PromiseLike<number | string>;
>e : number | PromiseLike<string | number>
>e : number | PromiseLike<number | string>
>PromiseLike : PromiseLike<T>
async function f() {
>f : () => Promise<void>
let await_a = await a;
>await_a : string | number
>await_a : number | string
>a : any
let await_b = await b;
>await_b : string | number
>await_b : number | string
>b : any
let await_c = await c;
>await_c : string | number
>await_c : number | string
>c : any
let await_d = await d;
>await_d : string | number
>await_d : number | string
>d : any
let await_e = await e;
>await_e : string | number
>await_e : number | string
>e : any
}
@@ -46,8 +46,8 @@ var r = true ? 1 : 2;
>2 : number
var r3 = true ? 1 : {};
>r3 : {}
>true ? 1 : {} : {}
>r3 : number | {}
>true ? 1 : {} : number | {}
>true : boolean
>1 : number
>{} : {}
@@ -60,15 +60,15 @@ var r4 = true ? a : b; // typeof a
>b : { x: number; z?: number; }
var r5 = true ? b : a; // typeof b
>r5 : { x: number; y?: number; } | { x: number; z?: number; }
>true ? b : a : { x: number; y?: number; } | { x: number; z?: number; }
>r5 : { x: number; z?: number; } | { x: number; y?: number; }
>true ? b : a : { x: number; z?: number; } | { x: number; y?: number; }
>true : boolean
>b : { x: number; z?: number; }
>a : { x: number; y?: number; }
var r6 = true ? (x: number) => { } : (x: Object) => { }; // returns number => void
>r6 : (x: number) => void
>true ? (x: number) => { } : (x: Object) => { } : (x: number) => void
>r6 : ((x: number) => void) | ((x: Object) => void)
>true ? (x: number) => { } : (x: Object) => { } : ((x: number) => void) | ((x: Object) => void)
>true : boolean
>(x: number) => { } : (x: number) => void
>x : number
@@ -80,7 +80,7 @@ var r7: (x: Object) => void = true ? (x: number) => { } : (x: Object) => { };
>r7 : (x: Object) => void
>x : Object
>Object : Object
>true ? (x: number) => { } : (x: Object) => { } : (x: number) => void
>true ? (x: number) => { } : (x: Object) => { } : ((x: number) => void) | ((x: Object) => void)
>true : boolean
>(x: number) => { } : (x: number) => void
>x : number
@@ -89,8 +89,8 @@ var r7: (x: Object) => void = true ? (x: number) => { } : (x: Object) => { };
>Object : Object
var r8 = true ? (x: Object) => { } : (x: number) => { }; // returns Object => void
>r8 : (x: Object) => void
>true ? (x: Object) => { } : (x: number) => { } : (x: Object) => void
>r8 : ((x: Object) => void) | ((x: number) => void)
>true ? (x: Object) => { } : (x: number) => { } : ((x: Object) => void) | ((x: number) => void)
>true : boolean
>(x: Object) => { } : (x: Object) => void
>x : Object
@@ -107,8 +107,8 @@ var r10: Base = true ? derived : derived2; // no error since we use the contextu
>derived2 : Derived2
var r11 = true ? base : derived2;
>r11 : Base
>true ? base : derived2 : Base
>r11 : Base | Derived2
>true ? base : derived2 : Base | Derived2
>true : boolean
>base : Base
>derived2 : Derived2
@@ -98,8 +98,8 @@ var e3 = t3[2]; // any
>2 : number
var e4 = t4[3]; // number
>e4 : number
>t4[3] : number
>e4 : E1 | E2 | number
>t4[3] : E1 | E2 | number
>t4 : [E1, E2, number]
>3 : number
@@ -66,8 +66,8 @@ var t5: [C1, F]
>F : F
var e11 = t1[4]; // base
>e11 : base
>t1[4] : base
>e11 : C | base
>t1[4] : C | base
>t1 : [C, base]
>4 : number
@@ -78,20 +78,20 @@ var e21 = t2[4]; // {}
>4 : number
var e31 = t3[4]; // C1
>e31 : C1
>t3[4] : C1
>e31 : C1 | D1
>t3[4] : C1 | D1
>t3 : [C1, D1]
>4 : number
var e41 = t4[2]; // base1
>e41 : base1
>t4[2] : base1
>e41 : base1 | C1
>t4[2] : base1 | C1
>t4 : [base1, C1]
>2 : number
var e51 = t5[2]; // {}
>e51 : F | C1
>t5[2] : F | C1
>e51 : C1 | F
>t5[2] : C1 | F
>t5 : [C1, F]
>2 : number
@@ -27,43 +27,43 @@ var z: Z;
// All these arrays should be X[]
var b1 = [x, y, z];
>b1 : X[]
>[x, y, z] : X[]
>b1 : (X | Y | Z)[]
>[x, y, z] : (X | Y | Z)[]
>x : X
>y : Y
>z : Z
var b2 = [x, z, y];
>b2 : X[]
>[x, z, y] : X[]
>b2 : (X | Z | Y)[]
>[x, z, y] : (X | Z | Y)[]
>x : X
>z : Z
>y : Y
var b3 = [y, x, z];
>b3 : X[]
>[y, x, z] : X[]
>b3 : (Y | X | Z)[]
>[y, x, z] : (Y | X | Z)[]
>y : Y
>x : X
>z : Z
var b4 = [y, z, x];
>b4 : X[]
>[y, z, x] : X[]
>b4 : (Y | Z | X)[]
>[y, z, x] : (Y | Z | X)[]
>y : Y
>z : Z
>x : X
var b5 = [z, x, y];
>b5 : X[]
>[z, x, y] : X[]
>b5 : (Z | X | Y)[]
>[z, x, y] : (Z | X | Y)[]
>z : Z
>x : X
>y : Y
var b6 = [z, y, x];
>b6 : X[]
>[z, y, x] : X[]
>b6 : (Z | Y | X)[]
>[z, y, x] : (Z | Y | X)[]
>z : Z
>y : Y
>x : X
@@ -163,8 +163,8 @@ xa[1].foo(1, 2, ...a, "abc");
>xa : X[]
>1 : number
>foo : (x: number, y: number, ...z: string[]) => any
>...[1, 2, "abc"] : string | number
>[1, 2, "abc"] : (string | number)[]
>...[1, 2, "abc"] : number | string
>[1, 2, "abc"] : (number | string)[]
>1 : number
>2 : number
>"abc" : string
@@ -164,8 +164,8 @@ xa[1].foo(1, 2, ...a, "abc");
>xa : X[]
>1 : number
>foo : (x: number, y: number, ...z: string[]) => any
>...[1, 2, "abc"] : string | number
>[1, 2, "abc"] : (string | number)[]
>...[1, 2, "abc"] : number | string
>[1, 2, "abc"] : (number | string)[]
>1 : number
>2 : number
>"abc" : string
@@ -8,11 +8,12 @@ tests/cases/conformance/types/tuple/castingTuple.ts(28,10): error TS2352: Neithe
tests/cases/conformance/types/tuple/castingTuple.ts(29,10): error TS2352: Neither type '[C, D]' nor type '[A, I]' is assignable to the other.
Types of property '0' are incompatible.
Type 'C' is not assignable to type 'A'.
Property 'a' is missing in type 'C'.
tests/cases/conformance/types/tuple/castingTuple.ts(30,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'array1' must be of type '{}[]', but here has type 'number[]'.
tests/cases/conformance/types/tuple/castingTuple.ts(30,14): error TS2352: Neither type '[number, string]' nor type 'number[]' is assignable to the other.
Types of property 'pop' are incompatible.
Type '() => string | number' is not assignable to type '() => number'.
Type 'string | number' is not assignable to type 'number'.
Type '() => number | string' is not assignable to type '() => number'.
Type 'number | string' is not assignable to type 'number'.
Type 'string' is not assignable to type 'number'.
tests/cases/conformance/types/tuple/castingTuple.ts(31,1): error TS2304: Cannot find name 't4'.
@@ -61,14 +62,15 @@ tests/cases/conformance/types/tuple/castingTuple.ts(31,1): error TS2304: Cannot
!!! error TS2352: Neither type '[C, D]' nor type '[A, I]' is assignable to the other.
!!! error TS2352: Types of property '0' are incompatible.
!!! error TS2352: Type 'C' is not assignable to type 'A'.
!!! error TS2352: Property 'a' is missing in type 'C'.
var array1 = <number[]>numStrTuple;
~~~~~~
!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'array1' must be of type '{}[]', but here has type 'number[]'.
~~~~~~~~~~~~~~~~~~~~~
!!! error TS2352: Neither type '[number, string]' nor type 'number[]' is assignable to the other.
!!! error TS2352: Types of property 'pop' are incompatible.
!!! error TS2352: Type '() => string | number' is not assignable to type '() => number'.
!!! error TS2352: Type 'string | number' is not assignable to type 'number'.
!!! error TS2352: Type '() => number | string' is not assignable to type '() => number'.
!!! error TS2352: Type 'number | string' is not assignable to type 'number'.
!!! error TS2352: Type 'string' is not assignable to type 'number'.
t4[2] = 10;
~~
@@ -17,9 +17,9 @@ declare function foo<T>(obj: I<T>): T
>T : T
foo({
>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : string | number | boolean | (() => void) | number[]
>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : string | (() => void) | boolean | number | number[]
>foo : <T>(obj: I<T>) => T
>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: string]: string | number | boolean | (() => void) | number[]; 0: () => void; p: string; }
>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: string]: string | (() => void) | boolean | number | number[]; 0: () => void; p: string; }
p: "",
>p : string
@@ -17,9 +17,9 @@ declare function foo<T>(obj: I<T>): T
>T : T
foo({
>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : string | number | boolean | (() => void) | number[]
>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : string | (() => void) | boolean | number | number[]
>foo : <T>(obj: I<T>) => T
>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: string]: string | number | boolean | (() => void) | number[]; 0: () => void; p: string; }
>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: string]: string | (() => void) | boolean | number | number[]; 0: () => void; p: string; }
p: "",
>p : string
@@ -17,9 +17,9 @@ declare function foo<T>(obj: I<T>): T
>T : T
foo({
>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : number | (() => void) | number[]
>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : (() => void) | number | number[]
>foo : <T>(obj: I<T>) => T
>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: number]: number | (() => void) | number[]; 0: () => void; p: string; }
>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: number]: (() => void) | number | number[]; 0: () => void; p: string; }
p: "",
>p : string
@@ -17,9 +17,9 @@ declare function foo<T>(obj: I<T>): T
>T : T
foo({
>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : number | (() => void) | number[]
>foo({ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]}) : (() => void) | number | number[]
>foo : <T>(obj: I<T>) => T
>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: number]: number | (() => void) | number[]; 0: () => void; p: string; }
>{ p: "", 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, [+"hi"]: [0]} : { [x: number]: (() => void) | number | number[]; 0: () => void; p: string; }
p: "",
>p : string
@@ -1,9 +1,9 @@
tests/cases/compiler/conditionalExpression1.ts(1,5): error TS2322: Type 'string | number' is not assignable to type 'boolean'.
Type 'string' is not assignable to type 'boolean'.
tests/cases/compiler/conditionalExpression1.ts(1,5): error TS2322: Type 'number | string' is not assignable to type 'boolean'.
Type 'number' is not assignable to type 'boolean'.
==== tests/cases/compiler/conditionalExpression1.ts (1 errors) ====
var x: boolean = (true ? 1 : ""); // should be an error
~
!!! error TS2322: Type 'string | number' is not assignable to type 'boolean'.
!!! error TS2322: Type 'string' is not assignable to type 'boolean'.
!!! error TS2322: Type 'number | string' is not assignable to type 'boolean'.
!!! error TS2322: Type 'number' is not assignable to type 'boolean'.
@@ -31,27 +31,27 @@ var b: B;
//Cond ? Expr1 : Expr2, Expr1 is supertype
//Be Not contextually typed
true ? x : a;
>true ? x : a : X
>true ? x : a : X | A
>true : boolean
>x : X
>a : A
var result1 = true ? x : a;
>result1 : X
>true ? x : a : X
>result1 : X | A
>true ? x : a : X | A
>true : boolean
>x : X
>a : A
//Expr1 and Expr2 are literals
true ? {} : 1;
>true ? {} : 1 : {}
>true ? {} : 1 : {} | number
>true : boolean
>{} : {}
>1 : number
true ? { a: 1 } : { a: 2, b: 'string' };
>true ? { a: 1 } : { a: 2, b: 'string' } : { a: number; }
>true ? { a: 1 } : { a: 2, b: 'string' } : { a: number; } | { a: number; b: string; }
>true : boolean
>{ a: 1 } : { a: number; }
>a : number
@@ -63,15 +63,15 @@ true ? { a: 1 } : { a: 2, b: 'string' };
>'string' : string
var result2 = true ? {} : 1;
>result2 : {}
>true ? {} : 1 : {}
>result2 : {} | number
>true ? {} : 1 : {} | number
>true : boolean
>{} : {}
>1 : number
var result3 = true ? { a: 1 } : { a: 2, b: 'string' };
>result3 : { a: number; }
>true ? { a: 1 } : { a: 2, b: 'string' } : { a: number; }
>result3 : { a: number; } | { a: number; b: string; }
>true ? { a: 1 } : { a: 2, b: 'string' } : { a: number; } | { a: number; b: string; }
>true : boolean
>{ a: 1 } : { a: number; }
>a : number
@@ -86,7 +86,7 @@ var result3 = true ? { a: 1 } : { a: 2, b: 'string' };
var resultIsX1: X = true ? x : a;
>resultIsX1 : X
>X : X
>true ? x : a : X
>true ? x : a : X | A
>true : boolean
>x : X
>a : A
@@ -95,7 +95,7 @@ var result4: (t: A) => any = true ? (m) => m.propertyX : (n) => n.propertyA;
>result4 : (t: A) => any
>t : A
>A : A
>true ? (m) => m.propertyX : (n) => n.propertyA : (m: A) => any
>true ? (m) => m.propertyX : (n) => n.propertyA : ((m: A) => any) | ((n: A) => number)
>true : boolean
>(m) => m.propertyX : (m: A) => any
>m : A
@@ -111,27 +111,27 @@ var result4: (t: A) => any = true ? (m) => m.propertyX : (n) => n.propertyA;
//Cond ? Expr1 : Expr2, Expr2 is supertype
//Be Not contextually typed
true ? a : x;
>true ? a : x : X
>true ? a : x : A | X
>true : boolean
>a : A
>x : X
var result5 = true ? a : x;
>result5 : X
>true ? a : x : X
>result5 : A | X
>true ? a : x : A | X
>true : boolean
>a : A
>x : X
//Expr1 and Expr2 are literals
true ? 1 : {};
>true ? 1 : {} : {}
>true ? 1 : {} : number | {}
>true : boolean
>1 : number
>{} : {}
true ? { a: 2, b: 'string' } : { a: 1 };
>true ? { a: 2, b: 'string' } : { a: 1 } : { a: number; }
>true ? { a: 2, b: 'string' } : { a: 1 } : { a: number; b: string; } | { a: number; }
>true : boolean
>{ a: 2, b: 'string' } : { a: number; b: string; }
>a : number
@@ -143,15 +143,15 @@ true ? { a: 2, b: 'string' } : { a: 1 };
>1 : number
var result6 = true ? 1 : {};
>result6 : {}
>true ? 1 : {} : {}
>result6 : number | {}
>true ? 1 : {} : number | {}
>true : boolean
>1 : number
>{} : {}
var result7 = true ? { a: 2, b: 'string' } : { a: 1 };
>result7 : { a: number; }
>true ? { a: 2, b: 'string' } : { a: 1 } : { a: number; }
>result7 : { a: number; b: string; } | { a: number; }
>true ? { a: 2, b: 'string' } : { a: 1 } : { a: number; b: string; } | { a: number; }
>true : boolean
>{ a: 2, b: 'string' } : { a: number; b: string; }
>a : number
@@ -166,7 +166,7 @@ var result7 = true ? { a: 2, b: 'string' } : { a: 1 };
var resultIsX2: X = true ? x : a;
>resultIsX2 : X
>X : X
>true ? x : a : X
>true ? x : a : X | A
>true : boolean
>x : X
>a : A
@@ -175,7 +175,7 @@ var result8: (t: A) => any = true ? (m) => m.propertyA : (n) => n.propertyX;
>result8 : (t: A) => any
>t : A
>A : A
>true ? (m) => m.propertyA : (n) => n.propertyX : (n: A) => any
>true ? (m) => m.propertyA : (n) => n.propertyX : ((m: A) => number) | ((n: A) => any)
>true : boolean
>(m) => m.propertyA : (m: A) => number
>m : A
@@ -218,7 +218,7 @@ var result10: (t: X) => any = true ? (m) => m.propertyX1 : (n) => n.propertyX2;
//Expr1 and Expr2 are literals
var result11: any = true ? 1 : 'string';
>result11 : any
>true ? 1 : 'string' : string | number
>true ? 1 : 'string' : number | string
>true : boolean
>1 : number
>'string' : string
@@ -0,0 +1,14 @@
//// [constEnumMergingWithValues1.ts]
function foo() {}
module foo {
const enum E { X }
}
export = foo
//// [constEnumMergingWithValues1.js]
define(["require", "exports"], function (require, exports) {
function foo() { }
return foo;
});
@@ -0,0 +1,16 @@
=== tests/cases/compiler/constEnumMergingWithValues1.ts ===
function foo() {}
>foo : Symbol(foo, Decl(constEnumMergingWithValues1.ts, 0, 0), Decl(constEnumMergingWithValues1.ts, 1, 17))
module foo {
>foo : Symbol(foo, Decl(constEnumMergingWithValues1.ts, 0, 0), Decl(constEnumMergingWithValues1.ts, 1, 17))
const enum E { X }
>E : Symbol(E, Decl(constEnumMergingWithValues1.ts, 2, 12))
>X : Symbol(E.X, Decl(constEnumMergingWithValues1.ts, 3, 18))
}
export = foo
>foo : Symbol(foo, Decl(constEnumMergingWithValues1.ts, 0, 0), Decl(constEnumMergingWithValues1.ts, 1, 17))
@@ -0,0 +1,16 @@
=== tests/cases/compiler/constEnumMergingWithValues1.ts ===
function foo() {}
>foo : typeof foo
module foo {
>foo : typeof foo
const enum E { X }
>E : E
>X : E
}
export = foo
>foo : typeof foo
@@ -0,0 +1,18 @@
//// [constEnumMergingWithValues2.ts]
class foo {}
module foo {
const enum E { X }
}
export = foo
//// [constEnumMergingWithValues2.js]
define(["require", "exports"], function (require, exports) {
var foo = (function () {
function foo() {
}
return foo;
})();
return foo;
});
@@ -0,0 +1,16 @@
=== tests/cases/compiler/constEnumMergingWithValues2.ts ===
class foo {}
>foo : Symbol(foo, Decl(constEnumMergingWithValues2.ts, 0, 0), Decl(constEnumMergingWithValues2.ts, 1, 12))
module foo {
>foo : Symbol(foo, Decl(constEnumMergingWithValues2.ts, 0, 0), Decl(constEnumMergingWithValues2.ts, 1, 12))
const enum E { X }
>E : Symbol(E, Decl(constEnumMergingWithValues2.ts, 2, 12))
>X : Symbol(E.X, Decl(constEnumMergingWithValues2.ts, 3, 18))
}
export = foo
>foo : Symbol(foo, Decl(constEnumMergingWithValues2.ts, 0, 0), Decl(constEnumMergingWithValues2.ts, 1, 12))
@@ -0,0 +1,16 @@
=== tests/cases/compiler/constEnumMergingWithValues2.ts ===
class foo {}
>foo : foo
module foo {
>foo : typeof foo
const enum E { X }
>E : E
>X : E
}
export = foo
>foo : foo
@@ -0,0 +1,17 @@
//// [constEnumMergingWithValues3.ts]
enum foo { A }
module foo {
const enum E { X }
}
export = foo
//// [constEnumMergingWithValues3.js]
define(["require", "exports"], function (require, exports) {
var foo;
(function (foo) {
foo[foo["A"] = 0] = "A";
})(foo || (foo = {}));
return foo;
});
@@ -0,0 +1,17 @@
=== tests/cases/compiler/constEnumMergingWithValues3.ts ===
enum foo { A }
>foo : Symbol(foo, Decl(constEnumMergingWithValues3.ts, 0, 0), Decl(constEnumMergingWithValues3.ts, 1, 14))
>A : Symbol(foo.A, Decl(constEnumMergingWithValues3.ts, 1, 10))
module foo {
>foo : Symbol(foo, Decl(constEnumMergingWithValues3.ts, 0, 0), Decl(constEnumMergingWithValues3.ts, 1, 14))
const enum E { X }
>E : Symbol(E, Decl(constEnumMergingWithValues3.ts, 2, 12))
>X : Symbol(E.X, Decl(constEnumMergingWithValues3.ts, 3, 18))
}
export = foo
>foo : Symbol(foo, Decl(constEnumMergingWithValues3.ts, 0, 0), Decl(constEnumMergingWithValues3.ts, 1, 14))
@@ -0,0 +1,17 @@
=== tests/cases/compiler/constEnumMergingWithValues3.ts ===
enum foo { A }
>foo : foo
>A : foo
module foo {
>foo : typeof foo
const enum E { X }
>E : E
>X : E
}
export = foo
>foo : foo
@@ -0,0 +1,21 @@
//// [constEnumMergingWithValues4.ts]
module foo {
const enum E { X }
}
module foo {
var x = 1;
}
export = foo
//// [constEnumMergingWithValues4.js]
define(["require", "exports"], function (require, exports) {
var foo;
(function (foo) {
var x = 1;
})(foo || (foo = {}));
return foo;
});
@@ -0,0 +1,21 @@
=== tests/cases/compiler/constEnumMergingWithValues4.ts ===
module foo {
>foo : Symbol(foo, Decl(constEnumMergingWithValues4.ts, 0, 0), Decl(constEnumMergingWithValues4.ts, 3, 1))
const enum E { X }
>E : Symbol(E, Decl(constEnumMergingWithValues4.ts, 1, 12))
>X : Symbol(E.X, Decl(constEnumMergingWithValues4.ts, 2, 18))
}
module foo {
>foo : Symbol(foo, Decl(constEnumMergingWithValues4.ts, 0, 0), Decl(constEnumMergingWithValues4.ts, 3, 1))
var x = 1;
>x : Symbol(x, Decl(constEnumMergingWithValues4.ts, 6, 7))
}
export = foo
>foo : Symbol(foo, Decl(constEnumMergingWithValues4.ts, 0, 0), Decl(constEnumMergingWithValues4.ts, 3, 1))
@@ -0,0 +1,22 @@
=== tests/cases/compiler/constEnumMergingWithValues4.ts ===
module foo {
>foo : typeof foo
const enum E { X }
>E : E
>X : E
}
module foo {
>foo : typeof foo
var x = 1;
>x : number
>1 : number
}
export = foo
>foo : typeof foo
@@ -0,0 +1,19 @@
//// [constEnumMergingWithValues5.ts]
module foo {
const enum E { X }
}
export = foo
//// [constEnumMergingWithValues5.js]
define(["require", "exports"], function (require, exports) {
var foo;
(function (foo) {
var E;
(function (E) {
E[E["X"] = 0] = "X";
})(E || (E = {}));
})(foo || (foo = {}));
return foo;
});
@@ -0,0 +1,13 @@
=== tests/cases/compiler/constEnumMergingWithValues5.ts ===
module foo {
>foo : Symbol(foo, Decl(constEnumMergingWithValues5.ts, 0, 0))
const enum E { X }
>E : Symbol(E, Decl(constEnumMergingWithValues5.ts, 1, 12))
>X : Symbol(E.X, Decl(constEnumMergingWithValues5.ts, 2, 18))
}
export = foo
>foo : Symbol(foo, Decl(constEnumMergingWithValues5.ts, 0, 0))
@@ -0,0 +1,13 @@
=== tests/cases/compiler/constEnumMergingWithValues5.ts ===
module foo {
>foo : typeof foo
const enum E { X }
>E : E
>X : E
}
export = foo
>foo : typeof foo
@@ -87,24 +87,24 @@ var a = baz(1, 1, g); // Should be number
>g : <T>(x: T, y: T) => T
var b: number | string;
>b : string | number
>b : number | string
var b = foo(g); // Should be number | string
>b : string | number
>foo(g) : string | number
>b : number | string
>foo(g) : number | string
>foo : <T>(cb: (x: number, y: string) => T) => T
>g : <T>(x: T, y: T) => T
var b = bar(1, "one", g); // Should be number | string
>b : string | number
>bar(1, "one", g) : string | number
>b : number | string
>bar(1, "one", g) : number | string
>bar : <T, U, V>(x: T, y: U, cb: (x: T, y: U) => V) => V
>1 : number
>"one" : string
>g : <T>(x: T, y: T) => T
var b = bar("one", 1, g); // Should be number | string
>b : string | number
>b : number | string
>bar("one", 1, g) : string | number
>bar : <T, U, V>(x: T, y: U, cb: (x: T, y: U) => V) => V
>"one" : string
@@ -112,11 +112,11 @@ var b = bar("one", 1, g); // Should be number | string
>g : <T>(x: T, y: T) => T
var b = baz(b, b, g); // Should be number | string
>b : string | number
>baz(b, b, g) : string | number
>b : number | string
>baz(b, b, g) : number | string
>baz : <T, U>(x: T, y: T, cb: (x: T, y: T) => U) => U
>b : string | number
>b : string | number
>b : number | string
>b : number | string
>g : <T>(x: T, y: T) => T
var d: number[] | string[];
@@ -138,7 +138,7 @@ var d = bar(1, "one", h); // Should be number[] | string[]
var d = bar("one", 1, h); // Should be number[] | string[]
>d : number[] | string[]
>bar("one", 1, h) : number[] | string[]
>bar("one", 1, h) : string[] | number[]
>bar : <T, U, V>(x: T, y: U, cb: (x: T, y: U) => V) => V
>"one" : string
>1 : number
@@ -1,9 +1,9 @@
tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(3,5): error TS2322: Type '[number, string, boolean]' is not assignable to type '[number, string]'.
Types of property 'pop' are incompatible.
Type '() => string | number | boolean' is not assignable to type '() => string | number'.
Type 'string | number | boolean' is not assignable to type 'string | number'.
Type 'boolean' is not assignable to type 'string | number'.
Type 'boolean' is not assignable to type 'number'.
Type '() => number | string | boolean' is not assignable to type '() => number | string'.
Type 'number | string | boolean' is not assignable to type 'number | string'.
Type 'boolean' is not assignable to type 'number | string'.
Type 'boolean' is not assignable to type 'string'.
tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(15,1): error TS2322: Type '[number, string, boolean]' is not assignable to type '[number, string]'.
tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(18,1): error TS2322: Type '[{}, number]' is not assignable to type '[{ a: string; }, number]'.
Types of property '0' are incompatible.
@@ -31,10 +31,10 @@ tests/cases/conformance/types/tuple/contextualTypeWithTuple.ts(25,1): error TS23
~~~~~~~~~~~~
!!! error TS2322: Type '[number, string, boolean]' is not assignable to type '[number, string]'.
!!! error TS2322: Types of property 'pop' are incompatible.
!!! error TS2322: Type '() => string | number | boolean' is not assignable to type '() => string | number'.
!!! error TS2322: Type 'string | number | boolean' is not assignable to type 'string | number'.
!!! error TS2322: Type 'boolean' is not assignable to type 'string | number'.
!!! error TS2322: Type 'boolean' is not assignable to type 'number'.
!!! error TS2322: Type '() => number | string | boolean' is not assignable to type '() => number | string'.
!!! error TS2322: Type 'number | string | boolean' is not assignable to type 'number | string'.
!!! error TS2322: Type 'boolean' is not assignable to type 'number | string'.
!!! error TS2322: Type 'boolean' is not assignable to type 'string'.
var numStrBoolTuple: [number, string, boolean] = [5, "foo", true];
var objNumTuple: [{ a: string }, number] = [{ a: "world" }, 5];
var strTupleTuple: [string, [number, {}]] = ["bar", [5, { x: 1, y: 1 }]];
@@ -82,7 +82,5 @@ var x4: IWithCallSignatures | IWithCallSignatures4 = a => /*here a should be any
>IWithCallSignatures : Symbol(IWithCallSignatures, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 9, 1))
>IWithCallSignatures4 : Symbol(IWithCallSignatures4, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 18, 1))
>a : Symbol(a, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 35, 52))
>a.toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18))
>a : Symbol(a, Decl(contextualTypeWithUnionTypeCallSignatures.ts, 35, 52))
>toString : Symbol(Number.toString, Decl(lib.d.ts, 458, 18))
@@ -90,10 +90,10 @@ var x4: IWithCallSignatures | IWithCallSignatures4 = a => /*here a should be any
>x4 : IWithCallSignatures | IWithCallSignatures4
>IWithCallSignatures : IWithCallSignatures
>IWithCallSignatures4 : IWithCallSignatures4
>a => /*here a should be any*/ a.toString() : (a: number) => string
>a : number
>a.toString() : string
>a.toString : (radix?: number) => string
>a : number
>toString : (radix?: number) => string
>a => /*here a should be any*/ a.toString() : (a: any) => any
>a : any
>a.toString() : any
>a.toString : any
>a : any
>toString : any

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