diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 57fe0e699c8..1a8b1d72833 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -1655,7 +1655,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg: any): Int8Array; + map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1922,7 +1922,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg: any): Uint8Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2189,7 +2189,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: any): Uint8ClampedArray; + map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2454,7 +2454,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg: any): Int16Array; + map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2722,7 +2722,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg: any): Uint16Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3255,7 +3255,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg: any): Uint32Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3522,7 +3522,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg: any): Float32Array; + map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 9abe5dce567..f628dc4fe84 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1655,7 +1655,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg: any): Int8Array; + map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1922,7 +1922,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg: any): Uint8Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2189,7 +2189,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: any): Uint8ClampedArray; + map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2454,7 +2454,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg: any): Int16Array; + map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2722,7 +2722,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg: any): Uint16Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3255,7 +3255,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg: any): Uint32Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3522,7 +3522,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg: any): Float32Array; + map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 9340f56fef3..588c609a164 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -1655,7 +1655,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg: any): Int8Array; + map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -1922,7 +1922,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg: any): Uint8Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2189,7 +2189,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: any): Uint8ClampedArray; + map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2454,7 +2454,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg: any): Int16Array; + map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2722,7 +2722,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg: any): Uint16Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3255,7 +3255,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg: any): Uint32Array; + map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3522,7 +3522,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg: any): Float32Array; + map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of diff --git a/lib/tsc.js b/lib/tsc.js index 056aa61e3b6..42ab1cd5dcf 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -142,7 +142,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.4.1"; + ts.version = "2.4.1-insiders.20170614"; })(ts || (ts = {})); (function (ts) { ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; @@ -3421,6 +3421,7 @@ var ts; Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, Declare_method_0: { code: 90023, category: ts.DiagnosticCategory.Message, key: "Declare_method_0_90023", message: "Declare method '{0}'." }, Declare_static_method_0: { code: 90024, category: ts.DiagnosticCategory.Message, key: "Declare_static_method_0_90024", message: "Declare static method '{0}'." }, + Prefix_0_with_an_underscore: { code: 90025, category: ts.DiagnosticCategory.Message, key: "Prefix_0_with_an_underscore_90025", message: "Prefix '{0}' with an underscore." }, Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, @@ -13554,7 +13555,7 @@ var ts; processReferenceComments(sourceFile); sourceFile.statements = parseList(0, parseStatement); ts.Debug.assert(token() === 1); - sourceFile.endOfFileToken = parseTokenNode(); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; sourceFile.identifierCount = identifierCount; @@ -24265,9 +24266,15 @@ var ts; writer.writeStringLiteral(literalTypeToString(type)); } else if (type.flags & 262144) { + if (flags & 128) { + writePunctuation(writer, 19); + } writer.writeKeyword("keyof"); writeSpace(writer); writeType(type.type, 128); + if (flags & 128) { + writePunctuation(writer, 20); + } } else if (type.flags & 524288) { writeType(type.objectType, 128); @@ -25571,11 +25578,8 @@ var ts; } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); - if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); - signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); - } - return signatures; + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { @@ -27987,7 +27991,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -28541,9 +28545,6 @@ var ts; function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); } - function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); - } function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } @@ -28965,8 +28966,7 @@ var ts; (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; + var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) { if (reportErrors) { ts.Debug.assert(!!errorNode); @@ -28974,14 +28974,21 @@ var ts; reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { - if (prop.valueDeclaration) { + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { errorNode = prop.valueDeclaration; } reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } } - return true; + return { value: true }; } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_4(prop); + if (typeof state_2 === "object") + return state_2.value; } } return false; @@ -29717,18 +29724,10 @@ var ts; function isRestParameterIndex(signature, parameterIndex) { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } - function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; - if (candidate !== t && !isTypeSubtypeOf(t, candidate)) - return false; - } - return true; - } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -29740,45 +29739,18 @@ var ts; return true; } function getSupertypeOrUnion(types) { - return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); } function getCommonSupertype(types) { if (!strictNullChecks) { return getSupertypeOrUnion(types); } var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); - if (!primaryTypes.length) { - return getUnionType(types, true); - } - var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); - } - function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { - var bestSupertype; - var bestSupertypeDownfallType; - var bestSupertypeScore = 0; - for (var i = 0; i < types.length; i++) { - var score = 0; - var downfallType = undefined; - for (var j = 0; j < types.length; j++) { - if (isTypeSubtypeOf(types[j], types[i])) { - score++; - } - else if (!downfallType) { - downfallType = types[j]; - } - } - ts.Debug.assert(!!downfallType, "If there is no common supertype, each type should have a downfallType"); - if (score > bestSupertypeScore) { - bestSupertype = types[i]; - bestSupertypeDownfallType = downfallType; - bestSupertypeScore = score; - } - if (bestSupertypeScore === types.length - 1) { - break; - } - } - checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144) : + getUnionType(types, true); } function isArrayType(type) { return getObjectFlags(type) & 4 && type.target === globalArrayType; @@ -29819,8 +29791,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; result |= getFalsyFlags(t); } return result; @@ -30341,8 +30313,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -30366,7 +30338,6 @@ var ts; function getInferredType(context, index) { var inference = context.inferences[index]; var inferredType = inference.inferredType; - var inferenceSucceeded; if (!inferredType) { if (inference.candidates) { var signature = context.signature; @@ -30376,37 +30347,28 @@ var ts; var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; var unionOrSuperType = context.flags & 1 || inference.priority & 4 ? getUnionType(baseCandidates, true) : getCommonSupertype(baseCandidates); - inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; - inferenceSucceeded = !!unionOrSuperType; + inferredType = getWidenedType(unionOrSuperType); + } + else if (context.flags & 2) { + inferredType = silentNeverType; } else { - if (context.flags & 2) { - inferredType = silentNeverType; + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - var defaultType = getDefaultFromTypeParameter(inference.typeParameter); - if (defaultType) { - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); - } - else { - inferredType = context.flags & 4 ? anyType : emptyObjectType; - } + inferredType = context.flags & 4 ? anyType : emptyObjectType; } - inferenceSucceeded = true; } inference.inferredType = inferredType; - if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); - if (constraint) { - var instantiatedConstraint = instantiateType(constraint, context); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; - } + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; } } - else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { - context.failedTypeParameterIndex = index; - } } return inferredType; } @@ -30555,8 +30517,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; result |= getTypeFacts(t); } return result; @@ -30806,8 +30768,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var current = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -30876,8 +30838,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -32291,8 +32253,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -33347,12 +33309,23 @@ var ts; var left = node.kind === 179 ? node.expression : node.left; - var type = checkExpression(left); + return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + } + function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type !== unknownType && !isTypeAny(type)) { - var prop = getPropertyOfType(getWidenedType(type), propertyName); + var prop = getPropertyOfType(type, propertyName); if (prop) { return checkPropertyAccessibility(node, left, type, prop); } + if (ts.isInJavaScriptFile(left) && (type.flags & 65536)) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var elementType = _a[_i]; + if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { + return true; + } + } + } + return false; } return true; } @@ -33602,9 +33575,6 @@ var ts; inferences[i].inferredType = undefined; } } - if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { - context.failedTypeParameterIndex = undefined; - } if (ts.isExpression(node)) { var contextualType = getContextualType(node); if (contextualType) { @@ -33926,16 +33896,12 @@ var ts; } var candidateForArgumentError; var candidateForTypeArgumentError; - var resultOfFailedInference; var result; var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } if (!result) { - candidateForArgumentError = undefined; - candidateForTypeArgumentError = undefined; - resultOfFailedInference = undefined; result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); } if (result) { @@ -33948,20 +33914,8 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && !isDecorator && typeArguments) { - var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); - } - else { - ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); - var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; - var inferenceCandidates = resultOfFailedInference.inferences[resultOfFailedInference.failedTypeParameterIndex].candidates; - var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (fallbackError) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); - } - reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); - } + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -34011,34 +33965,35 @@ var ts; return resolveErrorCall(node); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { var originalCandidate = candidates_2[_i]; if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; - var typeArgumentsAreValid = void 0; - var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) - : undefined; + var inferenceContext = originalCandidate.typeParameters ? + createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : + undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); - typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); + if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { + candidateForTypeArgumentError = originalCandidate; + break; + } } else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; - } - if (!typeArgumentsAreValid) { - break; } candidate = getSignatureInstantiation(candidate, typeArgumentTypes); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + candidateForArgumentError = candidate; break; } var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; @@ -34047,22 +34002,6 @@ var ts; } excludeArgument[index] = false; } - if (originalCandidate.typeParameters) { - var instantiatedCandidate = candidate; - if (typeArgumentsAreValid) { - candidateForArgumentError = instantiatedCandidate; - } - else { - candidateForTypeArgumentError = originalCandidate; - if (!typeArguments) { - resultOfFailedInference = inferenceContext; - } - } - } - else { - ts.Debug.assert(originalCandidate === candidate); - candidateForArgumentError = originalCandidate; - } } return undefined; } @@ -34265,8 +34204,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var type = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -34932,8 +34871,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -34947,8 +34886,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -34957,8 +34896,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { - var t = types_20[_a]; + for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { + var t = types_19[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -37924,7 +37863,7 @@ var ts; var staticBaseType = getApparentType(baseConstructorType); checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); - if (baseTypeNode.typeArguments) { + if (ts.some(baseTypeNode.typeArguments)) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { var constructor = _a[_i]; @@ -39212,13 +39151,9 @@ var ts; } return undefined; case 9: - if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && - ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 || node.parent.kind === 244) && - node.parent.moduleSpecifier === node)) { - return resolveExternalModuleName(node, node); - } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 238 || node.parent.kind === 244) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } case 8: @@ -39552,6 +39487,12 @@ var ts; parameter.initializer && !(ts.getModifierFlags(parameter) & 92); } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + !!(ts.getModifierFlags(parameter) & 92); + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags; } @@ -39727,6 +39668,7 @@ var ts; isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, @@ -40332,6 +40274,10 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } + return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); } function checkGrammarClassDeclarationHeritageClauses(node) { var seenExtendsClause = false; @@ -46643,10 +46589,9 @@ var ts; statements.push(extendsCall); classBodyStart++; } - statements.push(ts.updateVariableStatement(varStatement, undefined, ts.updateVariableDeclarationList(varStatement.declarationList, [ - ts.updateVariableDeclaration(variable, variable.name, undefined, ts.updateBinary(aliasAssignment, aliasAssignment.left, ts.convertFunctionDeclarationToExpression(ts.cast(funcStatements[classBodyStart], ts.isFunctionDeclaration)))) - ]))); + statements.push(funcStatements[classBodyStart]); classBodyStart++; + statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); } while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { classBodyEnd--; @@ -51401,7 +51346,8 @@ var ts; writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); var shouldUseResolverType = declaration.kind === 146 && - resolver.isRequiredInitializedParameter(declaration); + (resolver.isRequiredInitializedParameter(declaration) || + resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { emitType(type); } diff --git a/lib/tsserver.js b/lib/tsserver.js index a3479aba7b4..152a4169a38 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -1144,7 +1144,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.4.1"; + ts.version = "2.4.1-insiders.20170614"; })(ts || (ts = {})); (function (ts) { var Ternary; @@ -4454,6 +4454,7 @@ var ts; Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, Declare_method_0: { code: 90023, category: ts.DiagnosticCategory.Message, key: "Declare_method_0_90023", message: "Declare method '{0}'." }, Declare_static_method_0: { code: 90024, category: ts.DiagnosticCategory.Message, key: "Declare_static_method_0_90024", message: "Declare static method '{0}'." }, + Prefix_0_with_an_underscore: { code: 90025, category: ts.DiagnosticCategory.Message, key: "Prefix_0_with_an_underscore_90025", message: "Prefix '{0}' with an underscore." }, Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, @@ -15399,7 +15400,7 @@ var ts; processReferenceComments(sourceFile); sourceFile.statements = parseList(0, parseStatement); ts.Debug.assert(token() === 1); - sourceFile.endOfFileToken = parseTokenNode(); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; sourceFile.identifierCount = identifierCount; @@ -25467,9 +25468,15 @@ var ts; writer.writeStringLiteral(literalTypeToString(type)); } else if (type.flags & 262144) { + if (flags & 128) { + writePunctuation(writer, 19); + } writer.writeKeyword("keyof"); writeSpace(writer); writeType(type.type, 128); + if (flags & 128) { + writePunctuation(writer, 20); + } } else if (type.flags & 524288) { writeType(type.objectType, 128); @@ -26773,11 +26780,8 @@ var ts; } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); - if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); - signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); - } - return signatures; + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { @@ -29189,7 +29193,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -29743,9 +29747,6 @@ var ts; function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); } - function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); - } function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } @@ -30167,8 +30168,7 @@ var ts; (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; + var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) { if (reportErrors) { ts.Debug.assert(!!errorNode); @@ -30176,14 +30176,21 @@ var ts; reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { - if (prop.valueDeclaration) { + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { errorNode = prop.valueDeclaration; } reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } } - return true; + return { value: true }; } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_4(prop); + if (typeof state_2 === "object") + return state_2.value; } } return false; @@ -30919,18 +30926,10 @@ var ts; function isRestParameterIndex(signature, parameterIndex) { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } - function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; - if (candidate !== t && !isTypeSubtypeOf(t, candidate)) - return false; - } - return true; - } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -30942,45 +30941,18 @@ var ts; return true; } function getSupertypeOrUnion(types) { - return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); } function getCommonSupertype(types) { if (!strictNullChecks) { return getSupertypeOrUnion(types); } var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); - if (!primaryTypes.length) { - return getUnionType(types, true); - } - var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); - } - function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { - var bestSupertype; - var bestSupertypeDownfallType; - var bestSupertypeScore = 0; - for (var i = 0; i < types.length; i++) { - var score = 0; - var downfallType = undefined; - for (var j = 0; j < types.length; j++) { - if (isTypeSubtypeOf(types[j], types[i])) { - score++; - } - else if (!downfallType) { - downfallType = types[j]; - } - } - ts.Debug.assert(!!downfallType, "If there is no common supertype, each type should have a downfallType"); - if (score > bestSupertypeScore) { - bestSupertype = types[i]; - bestSupertypeDownfallType = downfallType; - bestSupertypeScore = score; - } - if (bestSupertypeScore === types.length - 1) { - break; - } - } - checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144) : + getUnionType(types, true); } function isArrayType(type) { return getObjectFlags(type) & 4 && type.target === globalArrayType; @@ -31021,8 +30993,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; result |= getFalsyFlags(t); } return result; @@ -31543,8 +31515,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -31568,7 +31540,6 @@ var ts; function getInferredType(context, index) { var inference = context.inferences[index]; var inferredType = inference.inferredType; - var inferenceSucceeded; if (!inferredType) { if (inference.candidates) { var signature = context.signature; @@ -31578,37 +31549,28 @@ var ts; var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; var unionOrSuperType = context.flags & 1 || inference.priority & 4 ? getUnionType(baseCandidates, true) : getCommonSupertype(baseCandidates); - inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; - inferenceSucceeded = !!unionOrSuperType; + inferredType = getWidenedType(unionOrSuperType); + } + else if (context.flags & 2) { + inferredType = silentNeverType; } else { - if (context.flags & 2) { - inferredType = silentNeverType; + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - var defaultType = getDefaultFromTypeParameter(inference.typeParameter); - if (defaultType) { - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); - } - else { - inferredType = context.flags & 4 ? anyType : emptyObjectType; - } + inferredType = context.flags & 4 ? anyType : emptyObjectType; } - inferenceSucceeded = true; } inference.inferredType = inferredType; - if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); - if (constraint) { - var instantiatedConstraint = instantiateType(constraint, context); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; - } + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; } } - else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { - context.failedTypeParameterIndex = index; - } } return inferredType; } @@ -31757,8 +31719,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; result |= getTypeFacts(t); } return result; @@ -32008,8 +31970,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var current = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -32078,8 +32040,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -33493,8 +33455,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -34549,12 +34511,23 @@ var ts; var left = node.kind === 179 ? node.expression : node.left; - var type = checkExpression(left); + return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + } + function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type !== unknownType && !isTypeAny(type)) { - var prop = getPropertyOfType(getWidenedType(type), propertyName); + var prop = getPropertyOfType(type, propertyName); if (prop) { return checkPropertyAccessibility(node, left, type, prop); } + if (ts.isInJavaScriptFile(left) && (type.flags & 65536)) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var elementType = _a[_i]; + if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { + return true; + } + } + } + return false; } return true; } @@ -34804,9 +34777,6 @@ var ts; inferences[i].inferredType = undefined; } } - if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { - context.failedTypeParameterIndex = undefined; - } if (ts.isExpression(node)) { var contextualType = getContextualType(node); if (contextualType) { @@ -35128,16 +35098,12 @@ var ts; } var candidateForArgumentError; var candidateForTypeArgumentError; - var resultOfFailedInference; var result; var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } if (!result) { - candidateForArgumentError = undefined; - candidateForTypeArgumentError = undefined; - resultOfFailedInference = undefined; result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); } if (result) { @@ -35150,20 +35116,8 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && !isDecorator && typeArguments) { - var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); - } - else { - ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); - var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; - var inferenceCandidates = resultOfFailedInference.inferences[resultOfFailedInference.failedTypeParameterIndex].candidates; - var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (fallbackError) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); - } - reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); - } + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -35213,34 +35167,35 @@ var ts; return resolveErrorCall(node); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { var originalCandidate = candidates_2[_i]; if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; - var typeArgumentsAreValid = void 0; - var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) - : undefined; + var inferenceContext = originalCandidate.typeParameters ? + createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : + undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); - typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); + if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { + candidateForTypeArgumentError = originalCandidate; + break; + } } else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; - } - if (!typeArgumentsAreValid) { - break; } candidate = getSignatureInstantiation(candidate, typeArgumentTypes); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + candidateForArgumentError = candidate; break; } var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; @@ -35249,22 +35204,6 @@ var ts; } excludeArgument[index] = false; } - if (originalCandidate.typeParameters) { - var instantiatedCandidate = candidate; - if (typeArgumentsAreValid) { - candidateForArgumentError = instantiatedCandidate; - } - else { - candidateForTypeArgumentError = originalCandidate; - if (!typeArguments) { - resultOfFailedInference = inferenceContext; - } - } - } - else { - ts.Debug.assert(originalCandidate === candidate); - candidateForArgumentError = originalCandidate; - } } return undefined; } @@ -35467,8 +35406,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var type = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -36134,8 +36073,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -36149,8 +36088,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -36159,8 +36098,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { - var t = types_20[_a]; + for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { + var t = types_19[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -39133,7 +39072,7 @@ var ts; var staticBaseType = getApparentType(baseConstructorType); checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); - if (baseTypeNode.typeArguments) { + if (ts.some(baseTypeNode.typeArguments)) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { var constructor = _a[_i]; @@ -40421,13 +40360,9 @@ var ts; } return undefined; case 9: - if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && - ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 || node.parent.kind === 244) && - node.parent.moduleSpecifier === node)) { - return resolveExternalModuleName(node, node); - } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 238 || node.parent.kind === 244) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } case 8: @@ -40761,6 +40696,12 @@ var ts; parameter.initializer && !(ts.getModifierFlags(parameter) & 92); } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + !!(ts.getModifierFlags(parameter) & 92); + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags; } @@ -40936,6 +40877,7 @@ var ts; isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, @@ -41541,6 +41483,10 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } + return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); } function checkGrammarClassDeclarationHeritageClauses(node) { var seenExtendsClause = false; @@ -47956,10 +47902,9 @@ var ts; statements.push(extendsCall); classBodyStart++; } - statements.push(ts.updateVariableStatement(varStatement, undefined, ts.updateVariableDeclarationList(varStatement.declarationList, [ - ts.updateVariableDeclaration(variable, variable.name, undefined, ts.updateBinary(aliasAssignment, aliasAssignment.left, ts.convertFunctionDeclarationToExpression(ts.cast(funcStatements[classBodyStart], ts.isFunctionDeclaration)))) - ]))); + statements.push(funcStatements[classBodyStart]); classBodyStart++; + statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); } while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { classBodyEnd--; @@ -52150,7 +52095,8 @@ var ts; writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); var shouldUseResolverType = declaration.kind === 146 && - resolver.isRequiredInitializedParameter(declaration); + (resolver.isRequiredInitializedParameter(declaration) || + resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { emitType(type); } @@ -59665,7 +59611,7 @@ var ts; else if (node.parent.kind === 243) { return 7; } - else if (isInRightSideOfImport(node)) { + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { return getMeaningFromRightHandSideOfImportEquals(node); } else if (ts.isDeclarationName(node)) { @@ -59695,12 +59641,13 @@ var ts; } return 4; } - function isInRightSideOfImport(node) { + function isInRightSideOfInternalImportEqualsDeclaration(node) { while (node.parent.kind === 143) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); } @@ -60204,7 +60151,7 @@ var ts; for (var i = 0; i < children.length; i++) { var child = children[i]; if (position < child.end && (nodeHasTokens(child) || child.kind === 10)) { - var start = (includeJsDoc && child.jsDoc ? child.jsDoc[0] : child).getStart(sourceFile); + var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || (child.kind === 10 && start === child.end); if (lookInPreviousChild) { @@ -62621,6 +62568,7 @@ var ts; start = ts.timestamp(); var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64) { @@ -62633,48 +62581,46 @@ var ts; } } } - var insideJsDocTagExpression = false; var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { request = { kind: "JsDocTagName" }; } - switch (tag.kind) { - case 289: - case 287: - case 288: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression && tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end) { - insideJsDocTagExpression = true; - } - else if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; - } - break; + if (isTagWithTypeExpression(tag) && tag.typeExpression) { + currentToken = ts.getTokenAtPosition(sourceFile, position, true); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 292 || + currentToken.parent.name !== currentToken))) { + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + request = { kind: "JsDocParameterName", tag: tag }; } } if (request) { return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, hasFilteredClassMemberKeywords: false }; } - if (!insideJsDocTagExpression) { + if (!insideJsDocTagTypeExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); return undefined; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile, undefined, true); + var previousToken = ts.findPrecedingToken(position, sourceFile, undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); var contextToken = previousToken; if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { var start_2 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, undefined, true); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); } var node = currentToken; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position, false); + var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); if (contextToken) { if (isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); @@ -62757,10 +62703,23 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 285: + case 287: + case 292: + case 288: + case 289: + case 291: + return true; + } + } function getTypeScriptMemberSymbols() { isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; + var isTypeLocation = ts.isPartOfTypeNode(node.parent) || insideJsDocTagTypeExpression; + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); if (node.kind === 71 || node.kind === 143 || node.kind === 179) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol && symbol.flags & 8388608) { @@ -62768,15 +62727,22 @@ var ts; } if (symbol && symbol.flags & 1952) { var exportedSymbols = typeChecker.getExportsOfModule(symbol); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanbeReferencedAtTypeLocation(symbol); }; + var isValidAccess_1 = isRhsOfImportDeclaration ? + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + if (isValidAccess_1(symbol)) { symbols.push(symbol); } }); } } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); + if (!isTypeLocation) { + var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } } function addTypeProperties(type) { if (type) { @@ -62839,9 +62805,64 @@ var ts; ts.isStatement(scopeNode); } var symbolMeanings = 793064 | 107455 | 1920 | 8388608; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); return true; } + function filterGlobalCompletion(symbols) { + return ts.filter(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + if (ts.isExportAssignment(location.parent)) { + return true; + } + if (symbol && symbol.flags & 8388608) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920); + } + if (insideJsDocTagTypeExpression || + (!isContextTokenValueLocation(contextToken) && + (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + return symbolCanbeReferencedAtTypeLocation(symbol); + } + } + return !!(symbol.flags & 107455); + }); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 103 && + contextToken.parent.kind === 162; + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 56: + return parentKind === 149 || + parentKind === 148 || + parentKind === 146 || + parentKind === 226 || + ts.isFunctionLikeKind(parentKind); + case 58: + return parentKind === 231; + case 118: + return parentKind === 202; + } + } + } + function symbolCanbeReferencedAtTypeLocation(symbol) { + if (symbol && symbol.flags & 8388608) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (symbol.flags & 793064) { + return true; + } + if (symbol.flags & (512 | 1024)) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + return ts.forEach(exportedSymbols, symbolCanbeReferencedAtTypeLocation); + } + } function getScopeNode(initialToken, position, sourceFile) { var scope = initialToken; while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { @@ -63129,19 +63150,6 @@ var ts; } return undefined; } - function isFunction(kind) { - if (!ts.isFunctionLikeKind(kind)) { - return false; - } - switch (kind) { - case 152: - case 161: - case 160: - return false; - default: - return true; - } - } function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { @@ -63150,7 +63158,7 @@ var ts; containingNodeKind === 227 || containingNodeKind === 208 || containingNodeKind === 232 || - isFunction(containingNodeKind) || + isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 229 || containingNodeKind === 199 || containingNodeKind === 230 || @@ -63164,7 +63172,7 @@ var ts; return containingNodeKind === 175; case 19: return containingNodeKind === 260 || - isFunction(containingNodeKind); + isFunctionLikeButNotConstructor(containingNodeKind); case 17: return containingNodeKind === 232 || containingNodeKind === 230 || @@ -63179,7 +63187,7 @@ var ts; containingNodeKind === 199 || containingNodeKind === 230 || containingNodeKind === 231 || - isFunction(containingNodeKind); + ts.isFunctionLikeKind(containingNodeKind); case 115: return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); case 24: @@ -63235,6 +63243,9 @@ var ts; } return false; } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 152; + } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8) { var text = contextToken.getFullText(); @@ -64777,7 +64788,7 @@ var ts; case 244: return true; case 181: - return ts.isRequireCall(node.parent, false); + return ts.isRequireCall(node.parent, false) || ts.isImportCall(node.parent); default: return false; } @@ -66419,7 +66430,7 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_4 = function (sourceFile) { + var _loop_5 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { return "continue"; @@ -66451,7 +66462,7 @@ var ts; }; for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_4(sourceFile); + _loop_5(sourceFile); } rawItems = ts.filter(rawItems, function (item) { var decl = item.declaration; @@ -68940,7 +68951,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); - var _loop_5 = function (opt) { + var _loop_6 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -68956,7 +68967,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_5(opt); + _loop_6(opt); } return options; } @@ -72383,12 +72394,12 @@ var ts; } switch (token.kind) { case 71: - return deleteIdentifier(); + return deleteIdentifierOrPrefixWithUnderscore(token); case 149: case 240: - return deleteNode(token.parent); + return [deleteNode(token.parent)]; default: - return deleteDefault(); + return [deleteDefault()]; } function deleteDefault() { if (ts.isDeclarationName(token)) { @@ -72401,105 +72412,109 @@ var ts; return undefined; } } - function deleteIdentifier() { - switch (token.parent.kind) { + function prefixIdentifierWithUnderscore(identifier) { + var startPosition = identifier.getStart(sourceFile, false); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), + changes: [{ + fileName: sourceFile.path, + textChanges: [{ + span: { start: startPosition, length: 0 }, + newText: "_" + }] + }] + }; + } + function deleteIdentifierOrPrefixWithUnderscore(identifier) { + var parent = identifier.parent; + switch (parent.kind) { case 226: - return deleteVariableDeclaration(token.parent); + return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); case 145: - var typeParameters = token.parent.parent.typeParameters; + var typeParameters = parent.parent.typeParameters; if (typeParameters.length === 1) { var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, false); - if (!previousToken || previousToken.kind !== 27) { - return deleteRange(typeParameters); - } var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, false); - if (!nextToken || nextToken.kind !== 29) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); + ts.Debug.assert(previousToken.kind === 27); + ts.Debug.assert(nextToken.kind === 29); + return [deleteNodeRange(previousToken, nextToken)]; } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 146: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } + var functionDeclaration = parent.parent; + return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), + prefixIdentifierWithUnderscore(identifier)]; case 237: - var importEquals = ts.getAncestor(token, 237); - return deleteNode(importEquals); + var importEquals = ts.getAncestor(identifier, 237); + return [deleteNode(importEquals)]; case 242: - var namedImports = token.parent.parent; + var namedImports = parent.parent; if (namedImports.elements.length === 1) { - var importSpec = ts.getAncestor(token, 238); - return deleteNode(importSpec); + var importSpec = ts.getAncestor(identifier, 238); + return [deleteNode(importSpec)]; } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 239: - var importClause = token.parent; + var importClause = parent; if (!importClause.namedBindings) { var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); + return [deleteNode(importDecl)]; } else { var start_4 = importClause.name.getStart(sourceFile); var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, false); if (nextToken && nextToken.kind === 26) { - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); + return [deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) })]; } else { - return deleteNode(importClause.name); + return [deleteNode(importClause.name)]; } } case 240: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { + var namespaceImport = parent; + if (namespaceImport.name === identifier && !namespaceImport.parent.name) { var importDecl = ts.getAncestor(namespaceImport, 238); - return deleteNode(importDecl); + return [deleteNode(importDecl)]; } else { var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1, false); if (previousToken && previousToken.kind === 26) { var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); + return [deleteRange({ pos: startPosition, end: namespaceImport.end })]; } - return deleteRange(namespaceImport); + return [deleteRange(namespaceImport)]; } default: - return deleteDefault(); + return [deleteDefault()]; } } - function deleteVariableDeclaration(varDecl) { + function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { switch (varDecl.parent.parent.kind) { case 214: var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(varDecl); - } + return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; case 216: var forOfStatement = varDecl.parent.parent; ts.Debug.assert(forOfStatement.initializer.kind === 227); var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + return [ + replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), + prefixIdentifierWithUnderscore(identifier) + ]; case 215: - return undefined; + return [prefixIdentifierWithUnderscore(identifier)]; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); + return [deleteNode(variableStatement)]; } else { - return deleteNodeInList(varDecl); + return [deleteNodeInList(varDecl)]; } } } @@ -72519,10 +72534,10 @@ var ts; return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() - }]; + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), + changes: changeTracker.getChanges() + }; } } }); @@ -73951,7 +73966,6 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; this.currentDirectory = host.getCurrentDirectory(); this.fileNameToEntry = ts.createFileMap(); var rootFileNames = host.getScriptFileNames(); @@ -73978,19 +73992,15 @@ var ts; this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (path) { + HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (path) { + HostCache.prototype.containsEntryByPath = function (path) { return this.fileNameToEntry.contains(path); }; - HostCache.prototype.getOrCreateEntry = function (fileName) { - var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); - return this.getOrCreateEntryByPath(fileName, path); - }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.contains(path) - ? this.getEntry(path) + return this.containsEntryByPath(path) + ? this.getEntryByPath(path) : this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { @@ -74003,11 +74013,11 @@ var ts; return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.scriptSnapshot; }; return HostCache; @@ -74202,11 +74212,18 @@ var ts; writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { - return hostCache.getOrCreateEntry(fileName) !== undefined; + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + return hostCache.containsEntryByPath(path) ? + !!hostCache.getEntryByPath(path) : + (host.fileExists && host.fileExists(fileName)); }, readFile: function (fileName) { - var entry = hostCache.getOrCreateEntry(fileName); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + if (hostCache.containsEntryByPath(path)) { + var entry = hostCache.getEntryByPath(path); + return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + } + return host.readFile && host.readFile(fileName); }, directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -74296,7 +74313,9 @@ var ts; ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); + program = undefined; } + host = undefined; } function getSyntacticDiagnostics(fileName) { synchronizeHostData(); @@ -76298,6 +76317,10 @@ var ts; this.realpath = function (path) { return _this.host.realpath(path); }; } } + LSHost.prototype.dispose = function () { + this.project = undefined; + this.resolveModuleName = undefined; + }; LSHost.prototype.startRecordingFilesWithChangedResolutions = function () { this.filesWithChangedSetOfUnresolvedImports = []; }; @@ -77062,7 +77085,13 @@ var ts; this.rootFiles = undefined; this.rootFilesMap = undefined; this.program = undefined; + this.builder = undefined; + this.cachedUnresolvedImportsPerFile = undefined; + this.projectErrors = undefined; + this.lsHost.dispose(); + this.lsHost = undefined; this.languageService.dispose(); + this.languageService = undefined; }; Project.prototype.getCompilerOptions = function () { return this.compilerOptions; @@ -77544,7 +77573,7 @@ var ts; } } if (this.projectService.globalPlugins) { - var _loop_6 = function (globalPluginName) { + var _loop_7 = function (globalPluginName) { if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths); @@ -77552,7 +77581,7 @@ var ts; var this_1 = this; for (var _b = 0, _c = this.projectService.globalPlugins; _b < _c.length; _b++) { var globalPluginName = _c[_b]; - _loop_6(globalPluginName); + _loop_7(globalPluginName); } } }; @@ -77666,6 +77695,7 @@ var ts; _super.prototype.close.call(this); if (this.projectFileWatcher) { this.projectFileWatcher.close(); + this.projectFileWatcher = undefined; } if (this.typeRootsWatchers) { for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { @@ -78058,8 +78088,14 @@ var ts; } else { if (info && (!info.isScriptOpen())) { - info.reloadFromFile(); - this.updateProjectGraphs(info.containingProjects); + if (info.containingProjects.length === 0) { + info.stopWatcher(); + this.filenameToScriptInfo.remove(info.path); + } + else { + info.reloadFromFile(); + this.updateProjectGraphs(info.containingProjects); + } } } }; @@ -78241,8 +78277,21 @@ var ts; } } } - if (info.containingProjects.length === 0) { - this.filenameToScriptInfo.remove(info.path); + if (this.host.fileExists(info.fileName)) { + this.watchClosedScriptInfo(info); + } + else { + this.handleDeletedFile(info); + } + }; + ProjectService.prototype.deleteOrphanScriptInfoNotInAnyProject = function () { + for (var _i = 0, _a = this.filenameToScriptInfo.getKeys(); _i < _a.length; _i++) { + var path = _a[_i]; + var info = this.filenameToScriptInfo.get(path); + if (!info.isScriptOpen() && info.containingProjects.length === 0) { + info.stopWatcher(); + this.filenameToScriptInfo.remove(info.path); + } } }; ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName, projectRootPath) { @@ -78609,8 +78658,14 @@ var ts; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; - ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; + if (!info.hasMixedContent) { + var fileName_2 = info.fileName; + info.setWatcher(this.host.watchFile(fileName_2, function (_) { return _this.onSourceFileChanged(fileName_2); })); + } + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { var info = this.getScriptInfoForNormalizedPath(fileName); if (!info) { if (openedByClient || this.host.fileExists(fileName)) { @@ -78622,14 +78677,13 @@ var ts; } } else { - if (!hasMixedContent) { - info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); - } + this.watchClosedScriptInfo(info); } } } if (info) { if (openedByClient && !info.isScriptOpen()) { + info.stopWatcher(); info.open(fileContent); if (hasMixedContent) { info.registerFileUpdate(); @@ -78729,6 +78783,7 @@ var ts; } var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.deleteOrphanScriptInfoNotInAnyProject(); this.printProjects(); return { configFileName: configFileName, configFileErrors: configFileErrors }; var _a; @@ -78741,13 +78796,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_7 = function (proj) { + var _loop_8 = function (proj) { var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_7(proj); + _loop_8(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -78866,7 +78921,7 @@ var ts; var types = (typeAcquisition && typeAcquisition.include) || []; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); - var _loop_8 = function (name) { + var _loop_9 = function (name) { var rule = ProjectService.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -78881,7 +78936,7 @@ var ts; } } if (rule.exclude) { - var _loop_9 = function (exclude) { + var _loop_10 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -78904,7 +78959,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_9(exclude); + _loop_10(exclude); } } else { @@ -78923,7 +78978,7 @@ var ts; var this_2 = this; for (var _i = 0, _a = Object.keys(ProjectService.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_8(name); + _loop_9(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); proj.rootFiles = proj.rootFiles.filter(function (_file, index) { return !excludeRegexes.some(function (re) { return re.test(normalizedNames[index]); }); }); @@ -79488,9 +79543,9 @@ var ts; var _this = this; switch (event.eventName) { case server.ContextEvent: - var _a = event.data, project_1 = _a.project, fileName_2 = _a.fileName; - this.projectService.logger.info("got context event, updating diagnostics for " + fileName_2); - this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, [{ fileName: fileName_2, project: project_1 }], _this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); }); + var _a = event.data, project_1 = _a.project, fileName_3 = _a.fileName; + this.projectService.logger.info("got context event, updating diagnostics for " + fileName_3); + this.errorCheck.startNew(function (next) { return _this.updateErrorCheck(next, [{ fileName: fileName_3, project: project_1 }], _this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); }); break; case server.ConfigFileDiagEvent: var _b = event.data, triggerFile = _b.triggerFile, configFileName = _b.configFileName, diagnostics = _b.diagnostics; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 18346bd4d02..bfee1a02aa1 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -2339,7 +2339,7 @@ declare namespace ts { } } declare namespace ts { - const version = "2.4.1"; + const version = "2.4.1-insiders.20170614"; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -5038,17 +5038,18 @@ declare namespace ts.server { declare namespace ts.server { class LSHost implements ts.LanguageServiceHost, ModuleResolutionHost { private readonly host; - private readonly project; + private project; private readonly cancellationToken; private compilationSettings; private readonly resolvedModuleNames; private readonly resolvedTypeReferenceDirectives; private readonly getCanonicalFileName; private filesWithChangedSetOfUnresolvedImports; - private readonly resolveModuleName; + private resolveModuleName; readonly trace: (s: string) => void; readonly realpath?: (path: string) => string; constructor(host: ServerHost, project: Project, cancellationToken: HostCancellationToken); + dispose(): void; startRecordingFilesWithChangedResolutions(): void; finishRecordingFilesWithChangedResolutions(): Path[]; private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult, getResultFileName, logChanges); @@ -5164,7 +5165,7 @@ declare namespace ts.server { private lastCachedUnresolvedImportsList; protected languageService: LanguageService; languageServiceEnabled: boolean; - protected readonly lsHost: LSHost; + protected lsHost: LSHost; builder: Builder; private updatedFileNames; private lastReportedFileNames; @@ -5428,6 +5429,7 @@ declare namespace ts.server { private removeProject(project); private assignScriptInfoToInferredProjectIfNecessary(info, addToListOfOpenFiles); private closeOpenFile(info); + private deleteOrphanScriptInfoNotInAnyProject(); private openOrUpdateConfiguredProjectForFile(fileName, projectRootPath?); private findConfigFile(searchPath, projectRootPath?); private printProjects(); @@ -5447,6 +5449,7 @@ declare namespace ts.server { createInferredProjectWithRootFileIfNecessary(root: ScriptInfo): InferredProject; getOrCreateScriptInfo(uncheckedFileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; getScriptInfo(uncheckedFileName: string): ScriptInfo; + watchClosedScriptInfo(info: ScriptInfo): void; getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): ScriptInfo; getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; getScriptInfoForPath(fileName: Path): ScriptInfo; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 42ef6180d2c..e9a8f715420 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -1144,7 +1144,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.4.1"; + ts.version = "2.4.1-insiders.20170614"; })(ts || (ts = {})); (function (ts) { var Ternary; @@ -4454,6 +4454,7 @@ var ts; Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, Declare_method_0: { code: 90023, category: ts.DiagnosticCategory.Message, key: "Declare_method_0_90023", message: "Declare method '{0}'." }, Declare_static_method_0: { code: 90024, category: ts.DiagnosticCategory.Message, key: "Declare_static_method_0_90024", message: "Declare static method '{0}'." }, + Prefix_0_with_an_underscore: { code: 90025, category: ts.DiagnosticCategory.Message, key: "Prefix_0_with_an_underscore_90025", message: "Prefix '{0}' with an underscore." }, Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, @@ -16796,7 +16797,7 @@ var ts; processReferenceComments(sourceFile); sourceFile.statements = parseList(0, parseStatement); ts.Debug.assert(token() === 1); - sourceFile.endOfFileToken = parseTokenNode(); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; sourceFile.identifierCount = identifierCount; @@ -26864,9 +26865,15 @@ var ts; writer.writeStringLiteral(literalTypeToString(type)); } else if (type.flags & 262144) { + if (flags & 128) { + writePunctuation(writer, 19); + } writer.writeKeyword("keyof"); writeSpace(writer); writeType(type.type, 128); + if (flags & 128) { + writePunctuation(writer, 20); + } } else if (type.flags & 524288) { writeType(type.objectType, 128); @@ -28170,11 +28177,8 @@ var ts; } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); - if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); - signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); - } - return signatures; + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); } function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { @@ -30586,7 +30590,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -31140,9 +31144,6 @@ var ts; function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); } - function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); - } function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } @@ -31564,8 +31565,7 @@ var ts; (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; + var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) { if (reportErrors) { ts.Debug.assert(!!errorNode); @@ -31573,14 +31573,21 @@ var ts; reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { - if (prop.valueDeclaration) { + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { errorNode = prop.valueDeclaration; } reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } } - return true; + return { value: true }; } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_4(prop); + if (typeof state_2 === "object") + return state_2.value; } } return false; @@ -32316,18 +32323,10 @@ var ts; function isRestParameterIndex(signature, parameterIndex) { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } - function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; - if (candidate !== t && !isTypeSubtypeOf(t, candidate)) - return false; - } - return true; - } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -32339,45 +32338,18 @@ var ts; return true; } function getSupertypeOrUnion(types) { - return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); } function getCommonSupertype(types) { if (!strictNullChecks) { return getSupertypeOrUnion(types); } var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144); }); - if (!primaryTypes.length) { - return getUnionType(types, true); - } - var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144); - } - function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { - var bestSupertype; - var bestSupertypeDownfallType; - var bestSupertypeScore = 0; - for (var i = 0; i < types.length; i++) { - var score = 0; - var downfallType = undefined; - for (var j = 0; j < types.length; j++) { - if (isTypeSubtypeOf(types[j], types[i])) { - score++; - } - else if (!downfallType) { - downfallType = types[j]; - } - } - ts.Debug.assert(!!downfallType, "If there is no common supertype, each type should have a downfallType"); - if (score > bestSupertypeScore) { - bestSupertype = types[i]; - bestSupertypeDownfallType = downfallType; - bestSupertypeScore = score; - } - if (bestSupertypeScore === types.length - 1) { - break; - } - } - checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144) : + getUnionType(types, true); } function isArrayType(type) { return getObjectFlags(type) & 4 && type.target === globalArrayType; @@ -32418,8 +32390,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; result |= getFalsyFlags(t); } return result; @@ -32940,8 +32912,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -32965,7 +32937,6 @@ var ts; function getInferredType(context, index) { var inference = context.inferences[index]; var inferredType = inference.inferredType; - var inferenceSucceeded; if (!inferredType) { if (inference.candidates) { var signature = context.signature; @@ -32975,37 +32946,28 @@ var ts; var baseCandidates = widenLiteralTypes ? ts.sameMap(inference.candidates, getWidenedLiteralType) : inference.candidates; var unionOrSuperType = context.flags & 1 || inference.priority & 4 ? getUnionType(baseCandidates, true) : getCommonSupertype(baseCandidates); - inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; - inferenceSucceeded = !!unionOrSuperType; + inferredType = getWidenedType(unionOrSuperType); + } + else if (context.flags & 2) { + inferredType = silentNeverType; } else { - if (context.flags & 2) { - inferredType = silentNeverType; + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - var defaultType = getDefaultFromTypeParameter(inference.typeParameter); - if (defaultType) { - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); - } - else { - inferredType = context.flags & 4 ? anyType : emptyObjectType; - } + inferredType = context.flags & 4 ? anyType : emptyObjectType; } - inferenceSucceeded = true; } inference.inferredType = inferredType; - if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); - if (constraint) { - var instantiatedConstraint = instantiateType(constraint, context); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; - } + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; } } - else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { - context.failedTypeParameterIndex = index; - } } return inferredType; } @@ -33154,8 +33116,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; result |= getTypeFacts(t); } return result; @@ -33405,8 +33367,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var current = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -33475,8 +33437,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (!(t.flags & 8192)) { if (!(getObjectFlags(t) & 256)) { return false; @@ -34890,8 +34852,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -35946,12 +35908,23 @@ var ts; var left = node.kind === 179 ? node.expression : node.left; - var type = checkExpression(left); + return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + } + function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type !== unknownType && !isTypeAny(type)) { - var prop = getPropertyOfType(getWidenedType(type), propertyName); + var prop = getPropertyOfType(type, propertyName); if (prop) { return checkPropertyAccessibility(node, left, type, prop); } + if (ts.isInJavaScriptFile(left) && (type.flags & 65536)) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var elementType = _a[_i]; + if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { + return true; + } + } + } + return false; } return true; } @@ -36201,9 +36174,6 @@ var ts; inferences[i].inferredType = undefined; } } - if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { - context.failedTypeParameterIndex = undefined; - } if (ts.isExpression(node)) { var contextualType = getContextualType(node); if (contextualType) { @@ -36525,16 +36495,12 @@ var ts; } var candidateForArgumentError; var candidateForTypeArgumentError; - var resultOfFailedInference; var result; var signatureHelpTrailingComma = candidatesOutArray && node.kind === 181 && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } if (!result) { - candidateForArgumentError = undefined; - candidateForTypeArgumentError = undefined; - resultOfFailedInference = undefined; result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); } if (result) { @@ -36547,20 +36513,8 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, undefined, true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && !isDecorator && typeArguments) { - var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), true, fallbackError); - } - else { - ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); - var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; - var inferenceCandidates = resultOfFailedInference.inferences[resultOfFailedInference.failedTypeParameterIndex].candidates; - var diagnosticChainHead = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (fallbackError) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); - } - reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); - } + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -36610,34 +36564,35 @@ var ts; return resolveErrorCall(node); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { var originalCandidate = candidates_2[_i]; if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; - var typeArgumentsAreValid = void 0; - var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) - : undefined; + var inferenceContext = originalCandidate.typeParameters ? + createInferenceContext(originalCandidate, ts.isInJavaScriptFile(node) ? 4 : 0) : + undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); - typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false); + if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, false)) { + candidateForTypeArgumentError = originalCandidate; + break; + } } else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; - } - if (!typeArgumentsAreValid) { - break; } candidate = getSignatureInstantiation(candidate, typeArgumentTypes); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, false)) { + candidateForArgumentError = candidate; break; } var index = excludeArgument ? ts.indexOf(excludeArgument, true) : -1; @@ -36646,22 +36601,6 @@ var ts; } excludeArgument[index] = false; } - if (originalCandidate.typeParameters) { - var instantiatedCandidate = candidate; - if (typeArgumentsAreValid) { - candidateForArgumentError = instantiatedCandidate; - } - else { - candidateForTypeArgumentError = originalCandidate; - if (!typeArguments) { - resultOfFailedInference = inferenceContext; - } - } - } - else { - ts.Debug.assert(originalCandidate === candidate); - candidateForArgumentError = originalCandidate; - } } return undefined; } @@ -36864,8 +36803,8 @@ var ts; if (elementType.flags & 65536) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var type = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -37531,8 +37470,8 @@ var ts; } if (type.flags & 196608) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -37546,8 +37485,8 @@ var ts; } if (type.flags & 65536) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -37556,8 +37495,8 @@ var ts; } if (type.flags & 131072) { var types = type.types; - for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { - var t = types_20[_a]; + for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { + var t = types_19[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -40530,7 +40469,7 @@ var ts; var staticBaseType = getApparentType(baseConstructorType); checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); - if (baseTypeNode.typeArguments) { + if (ts.some(baseTypeNode.typeArguments)) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { var constructor = _a[_i]; @@ -41818,13 +41757,9 @@ var ts; } return undefined; case 9: - if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && - ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 || node.parent.kind === 244) && - node.parent.moduleSpecifier === node)) { - return resolveExternalModuleName(node, node); - } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 238 || node.parent.kind === 244) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } case 8: @@ -42158,6 +42093,12 @@ var ts; parameter.initializer && !(ts.getModifierFlags(parameter) & 92); } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + !!(ts.getModifierFlags(parameter) & 92); + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags; } @@ -42333,6 +42274,7 @@ var ts; isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, @@ -42938,6 +42880,10 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } + return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); } function checkGrammarClassDeclarationHeritageClauses(node) { var seenExtendsClause = false; @@ -49353,10 +49299,9 @@ var ts; statements.push(extendsCall); classBodyStart++; } - statements.push(ts.updateVariableStatement(varStatement, undefined, ts.updateVariableDeclarationList(varStatement.declarationList, [ - ts.updateVariableDeclaration(variable, variable.name, undefined, ts.updateBinary(aliasAssignment, aliasAssignment.left, ts.convertFunctionDeclarationToExpression(ts.cast(funcStatements[classBodyStart], ts.isFunctionDeclaration)))) - ]))); + statements.push(funcStatements[classBodyStart]); classBodyStart++; + statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); } while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { classBodyEnd--; @@ -53547,7 +53492,8 @@ var ts; writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); var shouldUseResolverType = declaration.kind === 146 && - resolver.isRequiredInitializedParameter(declaration); + (resolver.isRequiredInitializedParameter(declaration) || + resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { emitType(type); } @@ -59665,7 +59611,7 @@ var ts; else if (node.parent.kind === 243) { return 7; } - else if (isInRightSideOfImport(node)) { + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { return getMeaningFromRightHandSideOfImportEquals(node); } else if (ts.isDeclarationName(node)) { @@ -59695,12 +59641,13 @@ var ts; } return 4; } - function isInRightSideOfImport(node) { + function isInRightSideOfInternalImportEqualsDeclaration(node) { while (node.parent.kind === 143) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); } @@ -60204,7 +60151,7 @@ var ts; for (var i = 0; i < children.length; i++) { var child = children[i]; if (position < child.end && (nodeHasTokens(child) || child.kind === 10)) { - var start = (includeJsDoc && child.jsDoc ? child.jsDoc[0] : child).getStart(sourceFile); + var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || (child.kind === 10 && start === child.end); if (lookInPreviousChild) { @@ -62621,6 +62568,7 @@ var ts; start = ts.timestamp(); var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64) { @@ -62633,48 +62581,46 @@ var ts; } } } - var insideJsDocTagExpression = false; var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { request = { kind: "JsDocTagName" }; } - switch (tag.kind) { - case 289: - case 287: - case 288: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression && tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end) { - insideJsDocTagExpression = true; - } - else if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; - } - break; + if (isTagWithTypeExpression(tag) && tag.typeExpression) { + currentToken = ts.getTokenAtPosition(sourceFile, position, true); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 292 || + currentToken.parent.name !== currentToken))) { + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + request = { kind: "JsDocParameterName", tag: tag }; } } if (request) { return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, hasFilteredClassMemberKeywords: false }; } - if (!insideJsDocTagExpression) { + if (!insideJsDocTagTypeExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); return undefined; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile, undefined, true); + var previousToken = ts.findPrecedingToken(position, sourceFile, undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); var contextToken = previousToken; if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { var start_2 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, undefined, true); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); } var node = currentToken; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position, false); + var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); if (contextToken) { if (isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); @@ -62757,10 +62703,23 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 285: + case 287: + case 292: + case 288: + case 289: + case 291: + return true; + } + } function getTypeScriptMemberSymbols() { isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; + var isTypeLocation = ts.isPartOfTypeNode(node.parent) || insideJsDocTagTypeExpression; + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); if (node.kind === 71 || node.kind === 143 || node.kind === 179) { var symbol = typeChecker.getSymbolAtLocation(node); if (symbol && symbol.flags & 8388608) { @@ -62768,15 +62727,22 @@ var ts; } if (symbol && symbol.flags & 1952) { var exportedSymbols = typeChecker.getExportsOfModule(symbol); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanbeReferencedAtTypeLocation(symbol); }; + var isValidAccess_1 = isRhsOfImportDeclaration ? + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + if (isValidAccess_1(symbol)) { symbols.push(symbol); } }); } } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); + if (!isTypeLocation) { + var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } } function addTypeProperties(type) { if (type) { @@ -62839,9 +62805,64 @@ var ts; ts.isStatement(scopeNode); } var symbolMeanings = 793064 | 107455 | 1920 | 8388608; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); return true; } + function filterGlobalCompletion(symbols) { + return ts.filter(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + if (ts.isExportAssignment(location.parent)) { + return true; + } + if (symbol && symbol.flags & 8388608) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920); + } + if (insideJsDocTagTypeExpression || + (!isContextTokenValueLocation(contextToken) && + (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + return symbolCanbeReferencedAtTypeLocation(symbol); + } + } + return !!(symbol.flags & 107455); + }); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 103 && + contextToken.parent.kind === 162; + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 56: + return parentKind === 149 || + parentKind === 148 || + parentKind === 146 || + parentKind === 226 || + ts.isFunctionLikeKind(parentKind); + case 58: + return parentKind === 231; + case 118: + return parentKind === 202; + } + } + } + function symbolCanbeReferencedAtTypeLocation(symbol) { + if (symbol && symbol.flags & 8388608) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (symbol.flags & 793064) { + return true; + } + if (symbol.flags & (512 | 1024)) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + return ts.forEach(exportedSymbols, symbolCanbeReferencedAtTypeLocation); + } + } function getScopeNode(initialToken, position, sourceFile) { var scope = initialToken; while (scope && !ts.positionBelongsToNode(scope, position, sourceFile)) { @@ -63129,19 +63150,6 @@ var ts; } return undefined; } - function isFunction(kind) { - if (!ts.isFunctionLikeKind(kind)) { - return false; - } - switch (kind) { - case 152: - case 161: - case 160: - return false; - default: - return true; - } - } function isSolelyIdentifierDefinitionLocation(contextToken) { var containingNodeKind = contextToken.parent.kind; switch (contextToken.kind) { @@ -63150,7 +63158,7 @@ var ts; containingNodeKind === 227 || containingNodeKind === 208 || containingNodeKind === 232 || - isFunction(containingNodeKind) || + isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 229 || containingNodeKind === 199 || containingNodeKind === 230 || @@ -63164,7 +63172,7 @@ var ts; return containingNodeKind === 175; case 19: return containingNodeKind === 260 || - isFunction(containingNodeKind); + isFunctionLikeButNotConstructor(containingNodeKind); case 17: return containingNodeKind === 232 || containingNodeKind === 230 || @@ -63179,7 +63187,7 @@ var ts; containingNodeKind === 199 || containingNodeKind === 230 || containingNodeKind === 231 || - isFunction(containingNodeKind); + ts.isFunctionLikeKind(containingNodeKind); case 115: return containingNodeKind === 149 && !ts.isClassLike(contextToken.parent.parent); case 24: @@ -63235,6 +63243,9 @@ var ts; } return false; } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 152; + } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8) { var text = contextToken.getFullText(); @@ -64777,7 +64788,7 @@ var ts; case 244: return true; case 181: - return ts.isRequireCall(node.parent, false); + return ts.isRequireCall(node.parent, false) || ts.isImportCall(node.parent); default: return false; } @@ -66419,7 +66430,7 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_4 = function (sourceFile) { + var _loop_5 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { return "continue"; @@ -66451,7 +66462,7 @@ var ts; }; for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_4(sourceFile); + _loop_5(sourceFile); } rawItems = ts.filter(rawItems, function (item) { var decl = item.declaration; @@ -68940,7 +68951,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); - var _loop_5 = function (opt) { + var _loop_6 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -68956,7 +68967,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_5(opt); + _loop_6(opt); } return options; } @@ -72383,12 +72394,12 @@ var ts; } switch (token.kind) { case 71: - return deleteIdentifier(); + return deleteIdentifierOrPrefixWithUnderscore(token); case 149: case 240: - return deleteNode(token.parent); + return [deleteNode(token.parent)]; default: - return deleteDefault(); + return [deleteDefault()]; } function deleteDefault() { if (ts.isDeclarationName(token)) { @@ -72401,105 +72412,109 @@ var ts; return undefined; } } - function deleteIdentifier() { - switch (token.parent.kind) { + function prefixIdentifierWithUnderscore(identifier) { + var startPosition = identifier.getStart(sourceFile, false); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), + changes: [{ + fileName: sourceFile.path, + textChanges: [{ + span: { start: startPosition, length: 0 }, + newText: "_" + }] + }] + }; + } + function deleteIdentifierOrPrefixWithUnderscore(identifier) { + var parent = identifier.parent; + switch (parent.kind) { case 226: - return deleteVariableDeclaration(token.parent); + return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); case 145: - var typeParameters = token.parent.parent.typeParameters; + var typeParameters = parent.parent.typeParameters; if (typeParameters.length === 1) { var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, false); - if (!previousToken || previousToken.kind !== 27) { - return deleteRange(typeParameters); - } var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, false); - if (!nextToken || nextToken.kind !== 29) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); + ts.Debug.assert(previousToken.kind === 27); + ts.Debug.assert(nextToken.kind === 29); + return [deleteNodeRange(previousToken, nextToken)]; } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 146: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } + var functionDeclaration = parent.parent; + return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), + prefixIdentifierWithUnderscore(identifier)]; case 237: - var importEquals = ts.getAncestor(token, 237); - return deleteNode(importEquals); + var importEquals = ts.getAncestor(identifier, 237); + return [deleteNode(importEquals)]; case 242: - var namedImports = token.parent.parent; + var namedImports = parent.parent; if (namedImports.elements.length === 1) { - var importSpec = ts.getAncestor(token, 238); - return deleteNode(importSpec); + var importSpec = ts.getAncestor(identifier, 238); + return [deleteNode(importSpec)]; } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 239: - var importClause = token.parent; + var importClause = parent; if (!importClause.namedBindings) { var importDecl = ts.getAncestor(importClause, 238); - return deleteNode(importDecl); + return [deleteNode(importDecl)]; } else { var start_4 = importClause.name.getStart(sourceFile); var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, false); if (nextToken && nextToken.kind === 26) { - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) }); + return [deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, false, true) })]; } else { - return deleteNode(importClause.name); + return [deleteNode(importClause.name)]; } } case 240: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { + var namespaceImport = parent; + if (namespaceImport.name === identifier && !namespaceImport.parent.name) { var importDecl = ts.getAncestor(namespaceImport, 238); - return deleteNode(importDecl); + return [deleteNode(importDecl)]; } else { var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1, false); if (previousToken && previousToken.kind === 26) { var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); + return [deleteRange({ pos: startPosition, end: namespaceImport.end })]; } - return deleteRange(namespaceImport); + return [deleteRange(namespaceImport)]; } default: - return deleteDefault(); + return [deleteDefault()]; } } - function deleteVariableDeclaration(varDecl) { + function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { switch (varDecl.parent.parent.kind) { case 214: var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(varDecl); - } + return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; case 216: var forOfStatement = varDecl.parent.parent; ts.Debug.assert(forOfStatement.initializer.kind === 227); var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + return [ + replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), + prefixIdentifierWithUnderscore(identifier) + ]; case 215: - return undefined; + return [prefixIdentifierWithUnderscore(identifier)]; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); + return [deleteNode(variableStatement)]; } else { - return deleteNodeInList(varDecl); + return [deleteNodeInList(varDecl)]; } } } @@ -72519,10 +72534,10 @@ var ts; return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() - }]; + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), + changes: changeTracker.getChanges() + }; } } }); @@ -73951,7 +73966,6 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; this.currentDirectory = host.getCurrentDirectory(); this.fileNameToEntry = ts.createFileMap(); var rootFileNames = host.getScriptFileNames(); @@ -73978,19 +73992,15 @@ var ts; this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (path) { + HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (path) { + HostCache.prototype.containsEntryByPath = function (path) { return this.fileNameToEntry.contains(path); }; - HostCache.prototype.getOrCreateEntry = function (fileName) { - var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); - return this.getOrCreateEntryByPath(fileName, path); - }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.contains(path) - ? this.getEntry(path) + return this.containsEntryByPath(path) + ? this.getEntryByPath(path) : this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { @@ -74003,11 +74013,11 @@ var ts; return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.scriptSnapshot; }; return HostCache; @@ -74202,11 +74212,18 @@ var ts; writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { - return hostCache.getOrCreateEntry(fileName) !== undefined; + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + return hostCache.containsEntryByPath(path) ? + !!hostCache.getEntryByPath(path) : + (host.fileExists && host.fileExists(fileName)); }, readFile: function (fileName) { - var entry = hostCache.getOrCreateEntry(fileName); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + if (hostCache.containsEntryByPath(path)) { + var entry = hostCache.getEntryByPath(path); + return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + } + return host.readFile && host.readFile(fileName); }, directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -74296,7 +74313,9 @@ var ts; ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); + program = undefined; } + host = undefined; } function getSyntacticDiagnostics(fileName) { synchronizeHostData(); @@ -78109,6 +78128,10 @@ var ts; this.realpath = function (path) { return _this.host.realpath(path); }; } } + LSHost.prototype.dispose = function () { + this.project = undefined; + this.resolveModuleName = undefined; + }; LSHost.prototype.startRecordingFilesWithChangedResolutions = function () { this.filesWithChangedSetOfUnresolvedImports = []; }; @@ -78873,7 +78896,13 @@ var ts; this.rootFiles = undefined; this.rootFilesMap = undefined; this.program = undefined; + this.builder = undefined; + this.cachedUnresolvedImportsPerFile = undefined; + this.projectErrors = undefined; + this.lsHost.dispose(); + this.lsHost = undefined; this.languageService.dispose(); + this.languageService = undefined; }; Project.prototype.getCompilerOptions = function () { return this.compilerOptions; @@ -79355,7 +79384,7 @@ var ts; } } if (this.projectService.globalPlugins) { - var _loop_6 = function (globalPluginName) { + var _loop_7 = function (globalPluginName) { if (options.plugins && options.plugins.some(function (p) { return p.name === globalPluginName; })) return "continue"; this_1.enablePlugin({ name: globalPluginName, global: true }, searchPaths); @@ -79363,7 +79392,7 @@ var ts; var this_1 = this; for (var _b = 0, _c = this.projectService.globalPlugins; _b < _c.length; _b++) { var globalPluginName = _c[_b]; - _loop_6(globalPluginName); + _loop_7(globalPluginName); } } }; @@ -79477,6 +79506,7 @@ var ts; _super.prototype.close.call(this); if (this.projectFileWatcher) { this.projectFileWatcher.close(); + this.projectFileWatcher = undefined; } if (this.typeRootsWatchers) { for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { @@ -79869,8 +79899,14 @@ var ts; } else { if (info && (!info.isScriptOpen())) { - info.reloadFromFile(); - this.updateProjectGraphs(info.containingProjects); + if (info.containingProjects.length === 0) { + info.stopWatcher(); + this.filenameToScriptInfo.remove(info.path); + } + else { + info.reloadFromFile(); + this.updateProjectGraphs(info.containingProjects); + } } } }; @@ -80052,8 +80088,21 @@ var ts; } } } - if (info.containingProjects.length === 0) { - this.filenameToScriptInfo.remove(info.path); + if (this.host.fileExists(info.fileName)) { + this.watchClosedScriptInfo(info); + } + else { + this.handleDeletedFile(info); + } + }; + ProjectService.prototype.deleteOrphanScriptInfoNotInAnyProject = function () { + for (var _i = 0, _a = this.filenameToScriptInfo.getKeys(); _i < _a.length; _i++) { + var path = _a[_i]; + var info = this.filenameToScriptInfo.get(path); + if (!info.isScriptOpen() && info.containingProjects.length === 0) { + info.stopWatcher(); + this.filenameToScriptInfo.remove(info.path); + } } }; ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName, projectRootPath) { @@ -80420,8 +80469,14 @@ var ts; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; - ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; + if (!info.hasMixedContent) { + var fileName_3 = info.fileName; + info.setWatcher(this.host.watchFile(fileName_3, function (_) { return _this.onSourceFileChanged(fileName_3); })); + } + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { var info = this.getScriptInfoForNormalizedPath(fileName); if (!info) { if (openedByClient || this.host.fileExists(fileName)) { @@ -80433,14 +80488,13 @@ var ts; } } else { - if (!hasMixedContent) { - info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); - } + this.watchClosedScriptInfo(info); } } } if (info) { if (openedByClient && !info.isScriptOpen()) { + info.stopWatcher(); info.open(fileContent); if (hasMixedContent) { info.registerFileUpdate(); @@ -80540,6 +80594,7 @@ var ts; } var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.deleteOrphanScriptInfoNotInAnyProject(); this.printProjects(); return { configFileName: configFileName, configFileErrors: configFileErrors }; var _a; @@ -80552,13 +80607,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_7 = function (proj) { + var _loop_8 = function (proj) { var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_7(proj); + _loop_8(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -80677,7 +80732,7 @@ var ts; var types = (typeAcquisition && typeAcquisition.include) || []; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); - var _loop_8 = function (name) { + var _loop_9 = function (name) { var rule = ProjectService.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -80692,7 +80747,7 @@ var ts; } } if (rule.exclude) { - var _loop_9 = function (exclude) { + var _loop_10 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -80715,7 +80770,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_9(exclude); + _loop_10(exclude); } } else { @@ -80734,7 +80789,7 @@ var ts; var this_2 = this; for (var _i = 0, _a = Object.keys(ProjectService.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_8(name); + _loop_9(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); proj.rootFiles = proj.rootFiles.filter(function (_file, index) { return !excludeRegexes.some(function (re) { return re.test(normalizedNames[index]); }); }); diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index fb5346c28aa..8eac7cb6ff1 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -2593,7 +2593,7 @@ declare namespace ts { } declare namespace ts { /** The version of the TypeScript compiler release */ - const version = "2.4.1"; + const version = "2.4.1-insiders.20170614"; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; diff --git a/lib/typescript.js b/lib/typescript.js index 96a530f4517..85e6fe12cc0 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -1317,7 +1317,7 @@ var ts; var ts; (function (ts) { /** The version of the TypeScript compiler release */ - ts.version = "2.4.1"; + ts.version = "2.4.1-insiders.20170614"; })(ts || (ts = {})); /* @internal */ (function (ts) { @@ -4973,6 +4973,7 @@ var ts; Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, Declare_method_0: { code: 90023, category: ts.DiagnosticCategory.Message, key: "Declare_method_0_90023", message: "Declare method '{0}'." }, Declare_static_method_0: { code: 90024, category: ts.DiagnosticCategory.Message, key: "Declare_static_method_0_90024", message: "Declare static method '{0}'." }, + Prefix_0_with_an_underscore: { code: 90025, category: ts.DiagnosticCategory.Message, key: "Prefix_0_with_an_underscore_90025", message: "Prefix '{0}' with an underscore." }, Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, @@ -16560,7 +16561,7 @@ var ts; processReferenceComments(sourceFile); sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); ts.Debug.assert(token() === 1 /* EndOfFileToken */); - sourceFile.endOfFileToken = parseTokenNode(); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; sourceFile.identifierCount = identifierCount; @@ -29589,9 +29590,15 @@ var ts; writer.writeStringLiteral(literalTypeToString(type)); } else if (type.flags & 262144 /* Index */) { + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 19 /* OpenParenToken */); + } writer.writeKeyword("keyof"); writeSpace(writer); writeType(type.type, 128 /* InElementType */); + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 20 /* CloseParenToken */); + } } else if (type.flags & 524288 /* IndexedAccess */) { writeType(type.objectType, 128 /* InElementType */); @@ -31054,11 +31061,8 @@ var ts; } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); - if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); - signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); - } - return signatures; + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); } /** * The base constructor of a class can resolve to @@ -33736,7 +33740,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 67108864 /* Optional */); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -34365,9 +34369,6 @@ var ts; function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); } - function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); - } function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } @@ -34857,8 +34858,7 @@ var ts; (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; + var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -34871,14 +34871,22 @@ var ts; reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { - if (prop.valueDeclaration) { + // use the property's value declaration if the property is assigned inside the literal itself + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { errorNode = prop.valueDeclaration; } reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } } - return true; + return { value: true }; } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_4(prop); + if (typeof state_2 === "object") + return state_2.value; } } return false; @@ -35717,18 +35725,10 @@ var ts; function isRestParameterIndex(signature, parameterIndex) { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } - function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; - if (candidate !== t && !isTypeSubtypeOf(t, candidate)) - return false; - } - return true; - } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -35739,55 +35739,22 @@ var ts; } return true; } - // When the candidate types are all literal types with the same base type, the common - // supertype is a union of those literal types. Otherwise, the common supertype is the - // first type that is a supertype of each of the other types. + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. function getSupertypeOrUnion(types) { - return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); } function getCommonSupertype(types) { if (!strictNullChecks) { return getSupertypeOrUnion(types); } var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (!primaryTypes.length) { - return getUnionType(types, /*subtypeReduction*/ true); - } - var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); - } - function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { - // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate - // to not be the common supertype. So if it weren't for this one downfallType (and possibly others), - // the type in question could have been the common supertype. - var bestSupertype; - var bestSupertypeDownfallType; - var bestSupertypeScore = 0; - for (var i = 0; i < types.length; i++) { - var score = 0; - var downfallType = undefined; - for (var j = 0; j < types.length; j++) { - if (isTypeSubtypeOf(types[j], types[i])) { - score++; - } - else if (!downfallType) { - downfallType = types[j]; - } - } - ts.Debug.assert(!!downfallType, "If there is no common supertype, each type should have a downfallType"); - if (score > bestSupertypeScore) { - bestSupertype = types[i]; - bestSupertypeDownfallType = downfallType; - bestSupertypeScore = score; - } - // types.length - 1 is the maximum score, given that getCommonSupertype returned false - if (bestSupertypeScore === types.length - 1) { - break; - } - } - // In the following errors, the {1} slot is before the {0} slot because checkTypeSubtypeOf supplies the - // subtype as the first argument to the error - checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144 /* Nullable */) : + getUnionType(types, /*subtypeReduction*/ true); } function isArrayType(type) { return getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; @@ -35834,8 +35801,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; result |= getFalsyFlags(t); } return result; @@ -36425,8 +36392,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -36454,7 +36421,6 @@ var ts; function getInferredType(context, index) { var inference = context.inferences[index]; var inferredType = inference.inferredType; - var inferenceSucceeded; if (!inferredType) { if (inference.candidates) { // We widen inferred literal types if @@ -36470,49 +36436,36 @@ var ts; // for inferences coming from return types in order to avoid common supertype failures. var unionOrSuperType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? getUnionType(baseCandidates, /*subtypeReduction*/ true) : getCommonSupertype(baseCandidates); - inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; - inferenceSucceeded = !!unionOrSuperType; + inferredType = getWidenedType(unionOrSuperType); + } + else if (context.flags & 2 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; } else { - if (context.flags & 2 /* NoDefault */) { - // We use silentNeverType as the wildcard that signals no inferences. - inferredType = silentNeverType; + // Infer either the default or the empty object type when no inferences were + // made. It is important to remember that in this case, inference still + // succeeds, meaning there is no error for not having inference candidates. An + // inference error only occurs when there are *conflicting* candidates, i.e. + // candidates with no common supertype. + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + // Instantiate the default type. Any forward reference to a type + // parameter should be instantiated to the empty object type. + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - // Infer either the default or the empty object type when no inferences were - // made. It is important to remember that in this case, inference still - // succeeds, meaning there is no error for not having inference candidates. An - // inference error only occurs when there are *conflicting* candidates, i.e. - // candidates with no common supertype. - var defaultType = getDefaultFromTypeParameter(inference.typeParameter); - if (defaultType) { - // Instantiate the default type. Any forward reference to a type - // parameter should be instantiated to the empty object type. - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); - } - else { - inferredType = context.flags & 4 /* AnyDefault */ ? anyType : emptyObjectType; - } + inferredType = context.flags & 4 /* AnyDefault */ ? anyType : emptyObjectType; } - inferenceSucceeded = true; } inference.inferredType = inferredType; - // Only do the constraint check if inference succeeded (to prevent cascading errors) - if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); - if (constraint) { - var instantiatedConstraint = instantiateType(constraint, context); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; - } + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; } } - else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { - // If inference failed, it is necessary to record the index of the failed type parameter (the one we are on). - // It might be that inference has already failed on a later type parameter on a previous call to inferTypeArguments. - // So if this failure is on preceding type parameter, this type parameter is the new failure index. - context.failedTypeParameterIndex = index; - } } return inferredType; } @@ -36678,8 +36631,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; result |= getTypeFacts(t); } return result; @@ -36939,8 +36892,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var current = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -37020,8 +36973,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (!(t.flags & 8192 /* Never */)) { if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -38770,8 +38723,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -40144,12 +40097,24 @@ var ts; var left = node.kind === 179 /* PropertyAccessExpression */ ? node.expression : node.left; - var type = checkExpression(left); + return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + } + function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type !== unknownType && !isTypeAny(type)) { - var prop = getPropertyOfType(getWidenedType(type), propertyName); + var prop = getPropertyOfType(type, propertyName); if (prop) { return checkPropertyAccessibility(node, left, type, prop); } + // In js files properties of unions are allowed in completion + if (ts.isInJavaScriptFile(left) && (type.flags & 65536 /* Union */)) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var elementType = _a[_i]; + if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { + return true; + } + } + } + return false; } return true; } @@ -40456,16 +40421,6 @@ var ts; inferences[i].inferredType = undefined; } } - // On this call to inferTypeArguments, we may get more inferences for certain type parameters that were not - // fixed last time. This means that a type parameter that failed inference last time may succeed this time, - // or vice versa. Therefore, the failedTypeParameterIndex is useless if it points to an unfixed type parameter, - // because it may change. So here we reset it. However, getInferredType will not revisit any type parameters - // that were previously fixed. So if a fixed type parameter failed previously, it will fail again because - // it will contain the exact same set of inferences. So if we reset the index from a fixed type parameter, - // we will lose information that we won't recover this time around. - if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { - context.failedTypeParameterIndex = undefined; - } // If a contextual type is available, infer from that type to the return type of the call expression. For // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the @@ -40975,9 +40930,9 @@ var ts; // was fine. So if there is any overload that is only incorrect because of an // argument, we will report an error on that one. // - // function foo(s: string) {} - // function foo(n: number) {} // Report argument error on this overload - // function foo() {} + // function foo(s: string): void; + // function foo(n: number): void; // Report argument error on this overload + // function foo(): void; // foo(true); // // If none of the overloads even made it that far, there are two possibilities. @@ -40985,13 +40940,12 @@ var ts; // report an error on that. Or none of the overloads even had correct arity, // in which case give an arity error. // - // function foo(x: T, y: T) {} // Report type argument inference error - // function foo() {} - // foo(0, true); + // function foo(x: T): void; // Report type argument error + // function foo(): void; + // foo(0); // var candidateForArgumentError; var candidateForTypeArgumentError; - var resultOfFailedInference; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. @@ -41010,10 +40964,6 @@ var ts; result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } if (!result) { - // Reinitialize these pointers for round two - candidateForArgumentError = undefined; - candidateForTypeArgumentError = undefined; - resultOfFailedInference = undefined; result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); } if (result) { @@ -41036,21 +40986,8 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && !isDecorator && typeArguments) { - var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); - } - else { - ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); - var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; - var inferenceCandidates = resultOfFailedInference.inferences[resultOfFailedInference.failedTypeParameterIndex].candidates; - var diagnosticChainHead = ts.chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError - ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (fallbackError) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); - } - reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); - } + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -41105,34 +41042,35 @@ var ts; return resolveErrorCall(node); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { var originalCandidate = candidates_2[_i]; if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; - var typeArgumentsAreValid = void 0; - var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0) - : undefined; + var inferenceContext = originalCandidate.typeParameters ? + createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0) : + undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); - typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); + if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false)) { + candidateForTypeArgumentError = originalCandidate; + break; + } } else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; - } - if (!typeArgumentsAreValid) { - break; } candidate = getSignatureInstantiation(candidate, typeArgumentTypes); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = candidate; break; } var index = excludeArgument ? ts.indexOf(excludeArgument, /*value*/ true) : -1; @@ -41141,27 +41079,6 @@ var ts; } excludeArgument[index] = false; } - // A post-mortem of this iteration of the loop. The signature was not applicable, - // so we want to track it as a candidate for reporting an error. If the candidate - // had no type parameters, or had no issues related to type arguments, we can - // report an error based on the arguments. If there was an issue with type - // arguments, then we can only report an error based on the type arguments. - if (originalCandidate.typeParameters) { - var instantiatedCandidate = candidate; - if (typeArgumentsAreValid) { - candidateForArgumentError = instantiatedCandidate; - } - else { - candidateForTypeArgumentError = originalCandidate; - if (!typeArguments) { - resultOfFailedInference = inferenceContext; - } - } - } - else { - ts.Debug.assert(originalCandidate === candidate); - candidateForArgumentError = originalCandidate; - } } return undefined; } @@ -41436,8 +41353,8 @@ var ts; if (elementType.flags & 65536 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var type = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -42217,8 +42134,8 @@ var ts; } if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -42235,8 +42152,8 @@ var ts; } if (type.flags & 65536 /* Union */) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -42245,8 +42162,8 @@ var ts; } if (type.flags & 131072 /* Intersection */) { var types = type.types; - for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { - var t = types_20[_a]; + for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { + var t = types_19[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -45857,7 +45774,7 @@ var ts; var staticBaseType = getApparentType(baseConstructorType); checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); - if (baseTypeNode.typeArguments) { + if (ts.some(baseTypeNode.typeArguments)) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { var constructor = _a[_i]; @@ -47308,14 +47225,12 @@ var ts; } return undefined; case 9 /* StringLiteral */: - // External module name in an import declaration - if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && - ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 /* ImportDeclaration */ || node.parent.kind === 244 /* ExportDeclaration */) && - node.parent.moduleSpecifier === node)) { - return resolveExternalModuleName(node, node); - } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { + // 1). import x = require("./mo/*gotToDefinitionHere*/d") + // 2). External module name in an import declaration + // 3). Dynamic import call or require in javascript + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 238 /* ImportDeclaration */ || node.parent.kind === 244 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } // falls through @@ -47743,6 +47658,12 @@ var ts; parameter.initializer && !(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + !!(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags; } @@ -47930,6 +47851,7 @@ var ts; isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, @@ -48564,6 +48486,10 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } + return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); } function checkGrammarClassDeclarationHeritageClauses(node) { var seenExtendsClause = false; @@ -57486,15 +57412,11 @@ var ts; statements.push(extendsCall); classBodyStart++; } - // We reuse the comment and source-map positions from the original variable statement - // and class alias, while converting the function declaration for the class constructor - // into an expression. - statements.push(ts.updateVariableStatement(varStatement, - /*modifiers*/ undefined, ts.updateVariableDeclarationList(varStatement.declarationList, [ - ts.updateVariableDeclaration(variable, variable.name, - /*type*/ undefined, ts.updateBinary(aliasAssignment, aliasAssignment.left, ts.convertFunctionDeclarationToExpression(ts.cast(funcStatements[classBodyStart], ts.isFunctionDeclaration)))) - ]))); + // The next statement is the function declaration. + statements.push(funcStatements[classBodyStart]); classBodyStart++; + // Add the class alias following the declaration. + statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); } // Find the trailing 'return' statement (4) while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { @@ -64853,9 +64775,12 @@ var ts; writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); // use the checker's type, not the declared type, - // for non-optional initialized parameters that aren't a parameter property + // for optional parameter properties + // and also for non-optional initialized parameters that aren't a parameter property + // these types may need to add `undefined`. var shouldUseResolverType = declaration.kind === 146 /* Parameter */ && - resolver.isRequiredInitializedParameter(declaration); + (resolver.isRequiredInitializedParameter(declaration) || + resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { // Write the type emitType(type); @@ -72635,7 +72560,7 @@ var ts; else if (node.parent.kind === 243 /* ExportAssignment */) { return 7 /* All */; } - else if (isInRightSideOfImport(node)) { + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { return getMeaningFromRightHandSideOfImportEquals(node); } else if (ts.isDeclarationName(node)) { @@ -72668,12 +72593,13 @@ var ts; } return 4 /* Namespace */; } - function isInRightSideOfImport(node) { + function isInRightSideOfInternalImportEqualsDeclaration(node) { while (node.parent.kind === 143 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); } @@ -73235,7 +73161,7 @@ var ts; // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). // if this is the case - then we should assume that token in question is located in previous child. if (position < child.end && (nodeHasTokens(child) || child.kind === 10 /* JsxText */)) { - var start = (includeJsDoc && child.jsDoc ? child.jsDoc[0] : child).getStart(sourceFile); + var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || (child.kind === 10 /* JsxText */ && start === child.end); // whitespace only JsxText if (lookInPreviousChild) { @@ -75515,6 +75441,7 @@ var ts; // Completion not allowed inside comments, bail out if this is the case var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { @@ -75548,30 +75475,29 @@ var ts; // Completion should work inside certain JsDoc tags. For example: // /** @type {number | string} */ // Completion should work in the brackets - var insideJsDocTagExpression = false; var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { request = { kind: "JsDocTagName" }; } - switch (tag.kind) { - case 289 /* JSDocTypeTag */: - case 287 /* JSDocParameterTag */: - case 288 /* JSDocReturnTag */: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression && tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end) { - insideJsDocTagExpression = true; - } - else if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; - } - break; + if (isTagWithTypeExpression(tag) && tag.typeExpression) { + currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 292 /* JSDocPropertyTag */ || + currentToken.parent.name !== currentToken))) { + // Use as type location if inside tag's type expression + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + request = { kind: "JsDocParameterName", tag: tag }; } } if (request) { return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, hasFilteredClassMemberKeywords: false }; } - if (!insideJsDocTagExpression) { + if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -75579,7 +75505,7 @@ var ts; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); // The decision to provide completion depends on the contextToken, which is determined through the previousToken. // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file @@ -75588,7 +75514,7 @@ var ts; // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { var start_2 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); } // Find the node where completion is requested on. @@ -75598,7 +75524,7 @@ var ts; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 + var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); // TODO: GH#15853 if (contextToken) { // Bail out if this is a known invalid completion location if (isCompletionListBlocker(contextToken)) { @@ -75692,11 +75618,25 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 285 /* JSDocAugmentsTag */: + case 287 /* JSDocParameterTag */: + case 292 /* JSDocPropertyTag */: + case 288 /* JSDocReturnTag */: + case 289 /* JSDocTypeTag */: + case 291 /* JSDocTypedefTag */: + return true; + } + } function getTypeScriptMemberSymbols() { // Right of dot member completion list isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; + // Since this is qualified name check its a type node location + var isTypeLocation = ts.isPartOfTypeNode(node.parent) || insideJsDocTagTypeExpression; + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); if (node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */ || node.kind === 179 /* PropertyAccessExpression */) { var symbol = typeChecker.getSymbolAtLocation(node); // This is an alias, follow what it aliases @@ -75706,15 +75646,23 @@ var ts; if (symbol && symbol.flags & 1952 /* HasExports */) { // Extract module or enum members var exportedSymbols = typeChecker.getExportsOfModule(symbol); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanbeReferencedAtTypeLocation(symbol); }; + var isValidAccess_1 = isRhsOfImportDeclaration ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + if (isValidAccess_1(symbol)) { symbols.push(symbol); } }); } } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); + if (!isTypeLocation) { + var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } } function addTypeProperties(type) { if (type) { @@ -75812,11 +75760,73 @@ var ts; scopeNode.kind === 256 /* JsxExpression */ || ts.isStatement(scopeNode); } - /// TODO filter meaning based on the current context var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 8388608 /* Alias */; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); return true; } + function filterGlobalCompletion(symbols) { + return ts.filter(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + // This is an alias, follow what it aliases + if (symbol && symbol.flags & 8388608 /* Alias */) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (insideJsDocTagTypeExpression || + (!isContextTokenValueLocation(contextToken) && + (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + // Its a type, but you can reach it by namespace.type as well + return symbolCanbeReferencedAtTypeLocation(symbol); + } + } + // expressions are value space (which includes the value namespaces) + return !!(symbol.flags & 107455 /* Value */); + }); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 103 /* TypeOfKeyword */ && + contextToken.parent.kind === 162 /* TypeQuery */; + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 56 /* ColonToken */: + return parentKind === 149 /* PropertyDeclaration */ || + parentKind === 148 /* PropertySignature */ || + parentKind === 146 /* Parameter */ || + parentKind === 226 /* VariableDeclaration */ || + ts.isFunctionLikeKind(parentKind); + case 58 /* EqualsToken */: + return parentKind === 231 /* TypeAliasDeclaration */; + case 118 /* AsKeyword */: + return parentKind === 202 /* AsExpression */; + } + } + } + function symbolCanbeReferencedAtTypeLocation(symbol) { + // This is an alias, follow what it aliases + if (symbol && symbol.flags & 8388608 /* Alias */) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (symbol.flags & 793064 /* Type */) { + return true; + } + if (symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */)) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + // If the exported symbols contains type, + // symbol can be referenced at locations where type is allowed + return ts.forEach(exportedSymbols, symbolCanbeReferencedAtTypeLocation); + } + } /** * Finds the first node that "embraces" the position, so that one may * accurately aggregate locals from the closest containing scope. @@ -76191,19 +76201,6 @@ var ts; } return undefined; } - function isFunction(kind) { - if (!ts.isFunctionLikeKind(kind)) { - return false; - } - switch (kind) { - case 152 /* Constructor */: - case 161 /* ConstructorType */: - case 160 /* FunctionType */: - return false; - default: - return true; - } - } /** * @returns true if we are certain that the currently edited location must define a new location; false otherwise. */ @@ -76215,7 +76212,7 @@ var ts; containingNodeKind === 227 /* VariableDeclarationList */ || containingNodeKind === 208 /* VariableStatement */ || containingNodeKind === 232 /* EnumDeclaration */ || - isFunction(containingNodeKind) || + isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 229 /* ClassDeclaration */ || containingNodeKind === 199 /* ClassExpression */ || containingNodeKind === 230 /* InterfaceDeclaration */ || @@ -76229,7 +76226,7 @@ var ts; return containingNodeKind === 175 /* ArrayBindingPattern */; // var [x| case 19 /* OpenParenToken */: return containingNodeKind === 260 /* CatchClause */ || - isFunction(containingNodeKind); + isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: return containingNodeKind === 232 /* EnumDeclaration */ || containingNodeKind === 230 /* InterfaceDeclaration */ || @@ -76244,7 +76241,7 @@ var ts; containingNodeKind === 199 /* ClassExpression */ || containingNodeKind === 230 /* InterfaceDeclaration */ || containingNodeKind === 231 /* TypeAliasDeclaration */ || - isFunction(containingNodeKind); + ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: @@ -76304,6 +76301,9 @@ var ts; } return false; } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 152 /* Constructor */; + } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { var text = contextToken.getFullText(); @@ -78026,7 +78026,7 @@ var ts; case 244 /* ExportDeclaration */: return true; case 181 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false); + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); default: return false; } @@ -80063,7 +80063,7 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_4 = function (sourceFile) { + var _loop_5 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; @@ -80100,7 +80100,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_4(sourceFile); + _loop_5(sourceFile); } // Remove imports when the imported declaration is already in the list and has the same name. rawItems = ts.filter(rawItems, function (item) { @@ -83050,7 +83050,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); - var _loop_5 = function (opt) { + var _loop_6 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -83069,7 +83069,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_5(opt); + _loop_6(opt); } return options; } @@ -87025,12 +87025,12 @@ var ts; } switch (token.kind) { case 71 /* Identifier */: - return deleteIdentifier(); + return deleteIdentifierOrPrefixWithUnderscore(token); case 149 /* PropertyDeclaration */: case 240 /* NamespaceImport */: - return deleteNode(token.parent); + return [deleteNode(token.parent)]; default: - return deleteDefault(); + return [deleteDefault()]; } function deleteDefault() { if (ts.isDeclarationName(token)) { @@ -87043,56 +87043,62 @@ var ts; return undefined; } } - function deleteIdentifier() { - switch (token.parent.kind) { + function prefixIdentifierWithUnderscore(identifier) { + var startPosition = identifier.getStart(sourceFile, /*includeJsDocComment*/ false); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), + changes: [{ + fileName: sourceFile.path, + textChanges: [{ + span: { start: startPosition, length: 0 }, + newText: "_" + }] + }] + }; + } + function deleteIdentifierOrPrefixWithUnderscore(identifier) { + var parent = identifier.parent; + switch (parent.kind) { case 226 /* VariableDeclaration */: - return deleteVariableDeclaration(token.parent); + return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); case 145 /* TypeParameter */: - var typeParameters = token.parent.parent.typeParameters; + var typeParameters = parent.parent.typeParameters; if (typeParameters.length === 1) { var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); - if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { - return deleteRange(typeParameters); - } var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); - if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); + ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); + ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); + return [deleteNodeRange(previousToken, nextToken)]; } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 146 /* Parameter */: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } + var functionDeclaration = parent.parent; + return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), + prefixIdentifierWithUnderscore(identifier)]; // handle case where 'import a = A;' case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); - return deleteNode(importEquals); + var importEquals = ts.getAncestor(identifier, 237 /* ImportEqualsDeclaration */); + return [deleteNode(importEquals)]; case 242 /* ImportSpecifier */: - var namedImports = token.parent.parent; + var namedImports = parent.parent; if (namedImports.elements.length === 1) { // Only 1 import and it is unused. So the entire declaration should be removed. - var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); - return deleteNode(importSpec); + var importSpec = ts.getAncestor(identifier, 238 /* ImportDeclaration */); + return [deleteNode(importSpec)]; } else { // delete import specifier - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } // handle case where "import d, * as ns from './file'" // or "'import {a, b as ns} from './file'" case 239 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' - var importClause = token.parent; + var importClause = parent; if (!importClause.namedBindings) { var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); - return deleteNode(importDecl); + return [deleteNode(importDecl)]; } else { // import |d,| * as ns from './file' @@ -87100,58 +87106,56 @@ var ts; var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); if (nextToken && nextToken.kind === 26 /* CommaToken */) { // shift first non-whitespace position after comma to the start position of the node - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); + return [deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) })]; } else { - return deleteNode(importClause.name); + return [deleteNode(importClause.name)]; } } case 240 /* NamespaceImport */: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { + var namespaceImport = parent; + if (namespaceImport.name === identifier && !namespaceImport.parent.name) { var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); - return deleteNode(importDecl); + return [deleteNode(importDecl)]; } else { var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1, /*includeJsDocComment*/ false); if (previousToken && previousToken.kind === 26 /* CommaToken */) { var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); + return [deleteRange({ pos: startPosition, end: namespaceImport.end })]; } - return deleteRange(namespaceImport); + return [deleteRange(namespaceImport)]; } default: - return deleteDefault(); + return [deleteDefault()]; } } // token.parent is a variableDeclaration - function deleteVariableDeclaration(varDecl) { + function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { switch (varDecl.parent.parent.kind) { case 214 /* ForStatement */: var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(varDecl); - } + return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; case 216 /* ForOfStatement */: var forOfStatement = varDecl.parent.parent; ts.Debug.assert(forOfStatement.initializer.kind === 227 /* VariableDeclarationList */); var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + return [ + replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), + prefixIdentifierWithUnderscore(identifier) + ]; case 215 /* ForInStatement */: // There is no valid fix in the case of: // for .. in - return undefined; + return [prefixIdentifierWithUnderscore(identifier)]; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); + return [deleteNode(variableStatement)]; } else { - return deleteNodeInList(varDecl); + return [deleteNodeInList(varDecl)]; } } } @@ -87171,10 +87175,10 @@ var ts; return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() - }]; + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), + changes: changeTracker.getChanges() + }; } } }); @@ -87992,7 +87996,7 @@ var ts; /// /// /// -/// +/// /// /// /// @@ -88816,7 +88820,6 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; // script id => script index this.currentDirectory = host.getCurrentDirectory(); this.fileNameToEntry = ts.createFileMap(); @@ -88846,19 +88849,15 @@ var ts; this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (path) { + HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (path) { + HostCache.prototype.containsEntryByPath = function (path) { return this.fileNameToEntry.contains(path); }; - HostCache.prototype.getOrCreateEntry = function (fileName) { - var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); - return this.getOrCreateEntryByPath(fileName, path); - }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.contains(path) - ? this.getEntry(path) + return this.containsEntryByPath(path) + ? this.getEntryByPath(path) : this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { @@ -88871,11 +88870,11 @@ var ts; return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.scriptSnapshot; }; return HostCache; @@ -89103,12 +89102,19 @@ var ts; getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { // stub missing host functionality - return hostCache.getOrCreateEntry(fileName) !== undefined; + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + return hostCache.containsEntryByPath(path) ? + !!hostCache.getEntryByPath(path) : + (host.fileExists && host.fileExists(fileName)); }, readFile: function (fileName) { // stub missing host functionality - var entry = hostCache.getOrCreateEntry(fileName); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + if (hostCache.containsEntryByPath(path)) { + var entry = hostCache.getEntryByPath(path); + return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + } + return host.readFile && host.readFile(fileName); }, directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -89241,7 +89247,9 @@ var ts; ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); + program = undefined; } + host = undefined; } /// Diagnostics function getSyntacticDiagnostics(fileName) { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 802f936d9de..b8fb040125c 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -2593,7 +2593,7 @@ declare namespace ts { } declare namespace ts { /** The version of the TypeScript compiler release */ - const version = "2.4.1"; + const version = "2.4.1-insiders.20170614"; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 96a530f4517..85e6fe12cc0 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -1317,7 +1317,7 @@ var ts; var ts; (function (ts) { /** The version of the TypeScript compiler release */ - ts.version = "2.4.1"; + ts.version = "2.4.1-insiders.20170614"; })(ts || (ts = {})); /* @internal */ (function (ts) { @@ -4973,6 +4973,7 @@ var ts; Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, Declare_method_0: { code: 90023, category: ts.DiagnosticCategory.Message, key: "Declare_method_0_90023", message: "Declare method '{0}'." }, Declare_static_method_0: { code: 90024, category: ts.DiagnosticCategory.Message, key: "Declare_static_method_0_90024", message: "Declare static method '{0}'." }, + Prefix_0_with_an_underscore: { code: 90025, category: ts.DiagnosticCategory.Message, key: "Prefix_0_with_an_underscore_90025", message: "Prefix '{0}' with an underscore." }, Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." }, @@ -16560,7 +16561,7 @@ var ts; processReferenceComments(sourceFile); sourceFile.statements = parseList(0 /* SourceElements */, parseStatement); ts.Debug.assert(token() === 1 /* EndOfFileToken */); - sourceFile.endOfFileToken = parseTokenNode(); + sourceFile.endOfFileToken = addJSDocComment(parseTokenNode()); setExternalModuleIndicator(sourceFile); sourceFile.nodeCount = nodeCount; sourceFile.identifierCount = identifierCount; @@ -29589,9 +29590,15 @@ var ts; writer.writeStringLiteral(literalTypeToString(type)); } else if (type.flags & 262144 /* Index */) { + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 19 /* OpenParenToken */); + } writer.writeKeyword("keyof"); writeSpace(writer); writeType(type.type, 128 /* InElementType */); + if (flags & 128 /* InElementType */) { + writePunctuation(writer, 20 /* CloseParenToken */); + } } else if (type.flags & 524288 /* IndexedAccess */) { writeType(type.objectType, 128 /* InElementType */); @@ -31054,11 +31061,8 @@ var ts; } function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) { var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); - if (typeArgumentNodes) { - var typeArguments_1 = ts.map(typeArgumentNodes, getTypeFromTypeNode); - signatures = ts.map(signatures, function (sig) { return getSignatureInstantiation(sig, typeArguments_1); }); - } - return signatures; + var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode); + return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments) : sig; }); } /** * The base constructor of a class can resolve to @@ -33736,7 +33740,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 67108864 /* Optional */); var result = createSymbol(flags, leftProp.name); - result.type = getUnionType([getTypeOfSymbol(leftProp), rightType]); + result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -34365,9 +34369,6 @@ var ts; function areTypesComparable(type1, type2) { return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1); } - function checkTypeSubtypeOf(source, target, errorNode, headMessage, containingMessageChain) { - return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain); - } function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain) { return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain); } @@ -34857,8 +34858,7 @@ var ts; (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } - for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { - var prop = _a[_i]; + var _loop_4 = function (prop) { if (!isKnownProperty(target, prop.name, isComparingJsxAttributes)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -34871,14 +34871,22 @@ var ts; reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { - if (prop.valueDeclaration) { + // use the property's value declaration if the property is assigned inside the literal itself + var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); + if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; })) { errorNode = prop.valueDeclaration; } reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); } } - return true; + return { value: true }; } + }; + for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var state_2 = _loop_4(prop); + if (typeof state_2 === "object") + return state_2.value; } } return false; @@ -35717,18 +35725,10 @@ var ts; function isRestParameterIndex(signature, parameterIndex) { return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } - function isSupertypeOfEach(candidate, types) { - for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { - var t = types_9[_i]; - if (candidate !== t && !isTypeSubtypeOf(t, candidate)) - return false; - } - return true; - } function literalTypesWithSameBaseType(types) { var commonBaseType; - for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { - var t = types_10[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var t = types_9[_i]; var baseType = getBaseTypeOfLiteralType(t); if (!commonBaseType) { commonBaseType = baseType; @@ -35739,55 +35739,22 @@ var ts; } return true; } - // When the candidate types are all literal types with the same base type, the common - // supertype is a union of those literal types. Otherwise, the common supertype is the - // first type that is a supertype of each of the other types. + // When the candidate types are all literal types with the same base type, return a union + // of those literal types. Otherwise, return the leftmost type for which no type to the + // right is a supertype. function getSupertypeOrUnion(types) { - return literalTypesWithSameBaseType(types) ? getUnionType(types) : ts.forEach(types, function (t) { return isSupertypeOfEach(t, types) ? t : undefined; }); + return literalTypesWithSameBaseType(types) ? + getUnionType(types) : + ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; }); } function getCommonSupertype(types) { if (!strictNullChecks) { return getSupertypeOrUnion(types); } var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 6144 /* Nullable */); }); - if (!primaryTypes.length) { - return getUnionType(types, /*subtypeReduction*/ true); - } - var supertype = getSupertypeOrUnion(primaryTypes); - return supertype && getNullableType(supertype, getFalsyFlagsOfTypes(types) & 6144 /* Nullable */); - } - function reportNoCommonSupertypeError(types, errorLocation, errorMessageChainHead) { - // The downfallType/bestSupertypeDownfallType is the first type that caused a particular candidate - // to not be the common supertype. So if it weren't for this one downfallType (and possibly others), - // the type in question could have been the common supertype. - var bestSupertype; - var bestSupertypeDownfallType; - var bestSupertypeScore = 0; - for (var i = 0; i < types.length; i++) { - var score = 0; - var downfallType = undefined; - for (var j = 0; j < types.length; j++) { - if (isTypeSubtypeOf(types[j], types[i])) { - score++; - } - else if (!downfallType) { - downfallType = types[j]; - } - } - ts.Debug.assert(!!downfallType, "If there is no common supertype, each type should have a downfallType"); - if (score > bestSupertypeScore) { - bestSupertype = types[i]; - bestSupertypeDownfallType = downfallType; - bestSupertypeScore = score; - } - // types.length - 1 is the maximum score, given that getCommonSupertype returned false - if (bestSupertypeScore === types.length - 1) { - break; - } - } - // In the following errors, the {1} slot is before the {0} slot because checkTypeSubtypeOf supplies the - // subtype as the first argument to the error - checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); + return primaryTypes.length ? + getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 6144 /* Nullable */) : + getUnionType(types, /*subtypeReduction*/ true); } function isArrayType(type) { return getObjectFlags(type) & 4 /* Reference */ && type.target === globalArrayType; @@ -35834,8 +35801,8 @@ var ts; } function getFalsyFlagsOfTypes(types) { var result = 0; - for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { - var t = types_11[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var t = types_10[_i]; result |= getFalsyFlags(t); } return result; @@ -36425,8 +36392,8 @@ var ts; } } function typeIdenticalToSomeType(type, types) { - for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { - var t = types_12[_i]; + for (var _i = 0, types_11 = types; _i < types_11.length; _i++) { + var t = types_11[_i]; if (isTypeIdenticalTo(t, type)) { return true; } @@ -36454,7 +36421,6 @@ var ts; function getInferredType(context, index) { var inference = context.inferences[index]; var inferredType = inference.inferredType; - var inferenceSucceeded; if (!inferredType) { if (inference.candidates) { // We widen inferred literal types if @@ -36470,49 +36436,36 @@ var ts; // for inferences coming from return types in order to avoid common supertype failures. var unionOrSuperType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? getUnionType(baseCandidates, /*subtypeReduction*/ true) : getCommonSupertype(baseCandidates); - inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; - inferenceSucceeded = !!unionOrSuperType; + inferredType = getWidenedType(unionOrSuperType); + } + else if (context.flags & 2 /* NoDefault */) { + // We use silentNeverType as the wildcard that signals no inferences. + inferredType = silentNeverType; } else { - if (context.flags & 2 /* NoDefault */) { - // We use silentNeverType as the wildcard that signals no inferences. - inferredType = silentNeverType; + // Infer either the default or the empty object type when no inferences were + // made. It is important to remember that in this case, inference still + // succeeds, meaning there is no error for not having inference candidates. An + // inference error only occurs when there are *conflicting* candidates, i.e. + // candidates with no common supertype. + var defaultType = getDefaultFromTypeParameter(inference.typeParameter); + if (defaultType) { + // Instantiate the default type. Any forward reference to a type + // parameter should be instantiated to the empty object type. + inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); } else { - // Infer either the default or the empty object type when no inferences were - // made. It is important to remember that in this case, inference still - // succeeds, meaning there is no error for not having inference candidates. An - // inference error only occurs when there are *conflicting* candidates, i.e. - // candidates with no common supertype. - var defaultType = getDefaultFromTypeParameter(inference.typeParameter); - if (defaultType) { - // Instantiate the default type. Any forward reference to a type - // parameter should be instantiated to the empty object type. - inferredType = instantiateType(defaultType, combineTypeMappers(createBackreferenceMapper(context.signature.typeParameters, index), context)); - } - else { - inferredType = context.flags & 4 /* AnyDefault */ ? anyType : emptyObjectType; - } + inferredType = context.flags & 4 /* AnyDefault */ ? anyType : emptyObjectType; } - inferenceSucceeded = true; } inference.inferredType = inferredType; - // Only do the constraint check if inference succeeded (to prevent cascading errors) - if (inferenceSucceeded) { - var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); - if (constraint) { - var instantiatedConstraint = instantiateType(constraint, context); - if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; - } + var constraint = getConstraintOfTypeParameter(context.signature.typeParameters[index]); + if (constraint) { + var instantiatedConstraint = instantiateType(constraint, context); + if (!isTypeAssignableTo(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { + inference.inferredType = inferredType = instantiatedConstraint; } } - else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { - // If inference failed, it is necessary to record the index of the failed type parameter (the one we are on). - // It might be that inference has already failed on a later type parameter on a previous call to inferTypeArguments. - // So if this failure is on preceding type parameter, this type parameter is the new failure index. - context.failedTypeParameterIndex = index; - } } return inferredType; } @@ -36678,8 +36631,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_12 = types; _i < types_12.length; _i++) { + var t = types_12[_i]; result |= getTypeFacts(t); } return result; @@ -36939,8 +36892,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var current = types_14[_i]; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var current = types_13[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -37020,8 +36973,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var t = types_15[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; if (!(t.flags & 8192 /* Never */)) { if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -38770,8 +38723,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var current = types_16[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var current = types_15[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -40144,12 +40097,24 @@ var ts; var left = node.kind === 179 /* PropertyAccessExpression */ ? node.expression : node.left; - var type = checkExpression(left); + return isValidPropertyAccessWithType(node, left, propertyName, getWidenedType(checkExpression(left))); + } + function isValidPropertyAccessWithType(node, left, propertyName, type) { if (type !== unknownType && !isTypeAny(type)) { - var prop = getPropertyOfType(getWidenedType(type), propertyName); + var prop = getPropertyOfType(type, propertyName); if (prop) { return checkPropertyAccessibility(node, left, type, prop); } + // In js files properties of unions are allowed in completion + if (ts.isInJavaScriptFile(left) && (type.flags & 65536 /* Union */)) { + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var elementType = _a[_i]; + if (isValidPropertyAccessWithType(node, left, propertyName, elementType)) { + return true; + } + } + } + return false; } return true; } @@ -40456,16 +40421,6 @@ var ts; inferences[i].inferredType = undefined; } } - // On this call to inferTypeArguments, we may get more inferences for certain type parameters that were not - // fixed last time. This means that a type parameter that failed inference last time may succeed this time, - // or vice versa. Therefore, the failedTypeParameterIndex is useless if it points to an unfixed type parameter, - // because it may change. So here we reset it. However, getInferredType will not revisit any type parameters - // that were previously fixed. So if a fixed type parameter failed previously, it will fail again because - // it will contain the exact same set of inferences. So if we reset the index from a fixed type parameter, - // we will lose information that we won't recover this time around. - if (context.failedTypeParameterIndex !== undefined && !context.inferences[context.failedTypeParameterIndex].isFixed) { - context.failedTypeParameterIndex = undefined; - } // If a contextual type is available, infer from that type to the return type of the call expression. For // example, given a 'function wrap(cb: (x: T) => U): (x: T) => U' and a call expression // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the @@ -40975,9 +40930,9 @@ var ts; // was fine. So if there is any overload that is only incorrect because of an // argument, we will report an error on that one. // - // function foo(s: string) {} - // function foo(n: number) {} // Report argument error on this overload - // function foo() {} + // function foo(s: string): void; + // function foo(n: number): void; // Report argument error on this overload + // function foo(): void; // foo(true); // // If none of the overloads even made it that far, there are two possibilities. @@ -40985,13 +40940,12 @@ var ts; // report an error on that. Or none of the overloads even had correct arity, // in which case give an arity error. // - // function foo(x: T, y: T) {} // Report type argument inference error - // function foo() {} - // foo(0, true); + // function foo(x: T): void; // Report type argument error + // function foo(): void; + // foo(0); // var candidateForArgumentError; var candidateForTypeArgumentError; - var resultOfFailedInference; var result; // If we are in signature help, a trailing comma indicates that we intend to provide another argument, // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments. @@ -41010,10 +40964,6 @@ var ts; result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma); } if (!result) { - // Reinitialize these pointers for round two - candidateForArgumentError = undefined; - candidateForTypeArgumentError = undefined; - resultOfFailedInference = undefined; result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma); } if (result) { @@ -41036,21 +40986,8 @@ var ts; checkApplicableSignature(node, args, candidateForArgumentError, assignableRelation, /*excludeArgument*/ undefined, /*reportErrors*/ true); } else if (candidateForTypeArgumentError) { - if (!isTaggedTemplate && !isDecorator && typeArguments) { - var typeArguments_2 = node.typeArguments; - checkTypeArguments(candidateForTypeArgumentError, typeArguments_2, ts.map(typeArguments_2, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); - } - else { - ts.Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); - var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; - var inferenceCandidates = resultOfFailedInference.inferences[resultOfFailedInference.failedTypeParameterIndex].candidates; - var diagnosticChainHead = ts.chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError - ts.Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, typeToString(failedTypeParameter)); - if (fallbackError) { - diagnosticChainHead = ts.chainDiagnosticMessages(diagnosticChainHead, fallbackError); - } - reportNoCommonSupertypeError(inferenceCandidates, node.tagName || node.expression || node.tag, diagnosticChainHead); - } + var typeArguments_1 = node.typeArguments; + checkTypeArguments(candidateForTypeArgumentError, typeArguments_1, ts.map(typeArguments_1, getTypeFromTypeNode), /*reportErrors*/ true, fallbackError); } else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; @@ -41105,34 +41042,35 @@ var ts; return resolveErrorCall(node); function chooseOverload(candidates, relation, signatureHelpTrailingComma) { if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; } + candidateForArgumentError = undefined; + candidateForTypeArgumentError = undefined; for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { var originalCandidate = candidates_2[_i]; if (!hasCorrectArity(node, args, originalCandidate, signatureHelpTrailingComma)) { continue; } var candidate = void 0; - var typeArgumentsAreValid = void 0; - var inferenceContext = originalCandidate.typeParameters - ? createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0) - : undefined; + var inferenceContext = originalCandidate.typeParameters ? + createInferenceContext(originalCandidate, /*flags*/ ts.isInJavaScriptFile(node) ? 4 /* AnyDefault */ : 0) : + undefined; while (true) { candidate = originalCandidate; if (candidate.typeParameters) { var typeArgumentTypes = void 0; if (typeArguments) { typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArguments, getTypeFromTypeNode), candidate.typeParameters, getMinTypeArgumentCount(candidate.typeParameters)); - typeArgumentsAreValid = checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false); + if (!checkTypeArguments(candidate, typeArguments, typeArgumentTypes, /*reportErrors*/ false)) { + candidateForTypeArgumentError = originalCandidate; + break; + } } else { typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - typeArgumentsAreValid = inferenceContext.failedTypeParameterIndex === undefined; - } - if (!typeArgumentsAreValid) { - break; } candidate = getSignatureInstantiation(candidate, typeArgumentTypes); } if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { + candidateForArgumentError = candidate; break; } var index = excludeArgument ? ts.indexOf(excludeArgument, /*value*/ true) : -1; @@ -41141,27 +41079,6 @@ var ts; } excludeArgument[index] = false; } - // A post-mortem of this iteration of the loop. The signature was not applicable, - // so we want to track it as a candidate for reporting an error. If the candidate - // had no type parameters, or had no issues related to type arguments, we can - // report an error based on the arguments. If there was an issue with type - // arguments, then we can only report an error based on the type arguments. - if (originalCandidate.typeParameters) { - var instantiatedCandidate = candidate; - if (typeArgumentsAreValid) { - candidateForArgumentError = instantiatedCandidate; - } - else { - candidateForTypeArgumentError = originalCandidate; - if (!typeArguments) { - resultOfFailedInference = inferenceContext; - } - } - } - else { - ts.Debug.assert(originalCandidate === candidate); - candidateForArgumentError = originalCandidate; - } } return undefined; } @@ -41436,8 +41353,8 @@ var ts; if (elementType.flags & 65536 /* Union */) { var types = elementType.types; var result = void 0; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var type = types_17[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var type = types_16[_i]; result = result || resolveStatelessJsxOpeningLikeElement(openingLikeElement, type, candidatesOutArray); } return result; @@ -42217,8 +42134,8 @@ var ts; } if (type.flags & 196608 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var t = types_18[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var t = types_17[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -42235,8 +42152,8 @@ var ts; } if (type.flags & 65536 /* Union */) { var types = type.types; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var t = types_19[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (!isTypeOfKind(t, kind)) { return false; } @@ -42245,8 +42162,8 @@ var ts; } if (type.flags & 131072 /* Intersection */) { var types = type.types; - for (var _a = 0, types_20 = types; _a < types_20.length; _a++) { - var t = types_20[_a]; + for (var _a = 0, types_19 = types; _a < types_19.length; _a++) { + var t = types_19[_a]; if (isTypeOfKind(t, kind)) { return true; } @@ -45857,7 +45774,7 @@ var ts; var staticBaseType = getApparentType(baseConstructorType); checkBaseTypeAccessibility(staticBaseType, baseTypeNode); checkSourceElement(baseTypeNode.expression); - if (baseTypeNode.typeArguments) { + if (ts.some(baseTypeNode.typeArguments)) { ts.forEach(baseTypeNode.typeArguments, checkSourceElement); for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) { var constructor = _a[_i]; @@ -47308,14 +47225,12 @@ var ts; } return undefined; case 9 /* StringLiteral */: - // External module name in an import declaration - if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && - ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || - ((node.parent.kind === 238 /* ImportDeclaration */ || node.parent.kind === 244 /* ExportDeclaration */) && - node.parent.moduleSpecifier === node)) { - return resolveExternalModuleName(node, node); - } - if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { + // 1). import x = require("./mo/*gotToDefinitionHere*/d") + // 2). External module name in an import declaration + // 3). Dynamic import call or require in javascript + if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || + ((node.parent.kind === 238 /* ImportDeclaration */ || node.parent.kind === 244 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) || + ((ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) || ts.isImportCall(node.parent))) { return resolveExternalModuleName(node, node); } // falls through @@ -47743,6 +47658,12 @@ var ts; parameter.initializer && !(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); } + function isOptionalUninitializedParameterProperty(parameter) { + return strictNullChecks && + isOptionalParameter(parameter) && + !parameter.initializer && + !!(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + } function getNodeCheckFlags(node) { return getNodeLinks(node).flags; } @@ -47930,6 +47851,7 @@ var ts; isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, + isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, @@ -48564,6 +48486,10 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); return grammarErrorAtPos(sourceFile, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType); } + return ts.forEach(types, checkGrammarExpressionWithTypeArguments); + } + function checkGrammarExpressionWithTypeArguments(node) { + return checkGrammarTypeArguments(node, node.typeArguments); } function checkGrammarClassDeclarationHeritageClauses(node) { var seenExtendsClause = false; @@ -57486,15 +57412,11 @@ var ts; statements.push(extendsCall); classBodyStart++; } - // We reuse the comment and source-map positions from the original variable statement - // and class alias, while converting the function declaration for the class constructor - // into an expression. - statements.push(ts.updateVariableStatement(varStatement, - /*modifiers*/ undefined, ts.updateVariableDeclarationList(varStatement.declarationList, [ - ts.updateVariableDeclaration(variable, variable.name, - /*type*/ undefined, ts.updateBinary(aliasAssignment, aliasAssignment.left, ts.convertFunctionDeclarationToExpression(ts.cast(funcStatements[classBodyStart], ts.isFunctionDeclaration)))) - ]))); + // The next statement is the function declaration. + statements.push(funcStatements[classBodyStart]); classBodyStart++; + // Add the class alias following the declaration. + statements.push(ts.createStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier)))); } // Find the trailing 'return' statement (4) while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) { @@ -64853,9 +64775,12 @@ var ts; writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); // use the checker's type, not the declared type, - // for non-optional initialized parameters that aren't a parameter property + // for optional parameter properties + // and also for non-optional initialized parameters that aren't a parameter property + // these types may need to add `undefined`. var shouldUseResolverType = declaration.kind === 146 /* Parameter */ && - resolver.isRequiredInitializedParameter(declaration); + (resolver.isRequiredInitializedParameter(declaration) || + resolver.isOptionalUninitializedParameterProperty(declaration)); if (type && !shouldUseResolverType) { // Write the type emitType(type); @@ -72635,7 +72560,7 @@ var ts; else if (node.parent.kind === 243 /* ExportAssignment */) { return 7 /* All */; } - else if (isInRightSideOfImport(node)) { + else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { return getMeaningFromRightHandSideOfImportEquals(node); } else if (ts.isDeclarationName(node)) { @@ -72668,12 +72593,13 @@ var ts; } return 4 /* Namespace */; } - function isInRightSideOfImport(node) { + function isInRightSideOfInternalImportEqualsDeclaration(node) { while (node.parent.kind === 143 /* QualifiedName */) { node = node.parent; } return ts.isInternalModuleImportEqualsDeclaration(node.parent) && node.parent.moduleReference === node; } + ts.isInRightSideOfInternalImportEqualsDeclaration = isInRightSideOfInternalImportEqualsDeclaration; function isNamespaceReference(node) { return isQualifiedNameNamespaceReference(node) || isPropertyAccessNamespaceReference(node); } @@ -73235,7 +73161,7 @@ var ts; // NOTE: JsxText is a weird kind of node that can contain only whitespaces (since they are not counted as trivia). // if this is the case - then we should assume that token in question is located in previous child. if (position < child.end && (nodeHasTokens(child) || child.kind === 10 /* JsxText */)) { - var start = (includeJsDoc && child.jsDoc ? child.jsDoc[0] : child).getStart(sourceFile); + var start = child.getStart(sourceFile, includeJsDoc); var lookInPreviousChild = (start >= position) || (child.kind === 10 /* JsxText */ && start === child.end); // whitespace only JsxText if (lookInPreviousChild) { @@ -75515,6 +75441,7 @@ var ts; // Completion not allowed inside comments, bail out if this is the case var insideComment = ts.isInComment(sourceFile, position, currentToken); log("getCompletionData: Is inside comment: " + (ts.timestamp() - start)); + var insideJsDocTagTypeExpression = false; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { @@ -75548,30 +75475,29 @@ var ts; // Completion should work inside certain JsDoc tags. For example: // /** @type {number | string} */ // Completion should work in the brackets - var insideJsDocTagExpression = false; var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { request = { kind: "JsDocTagName" }; } - switch (tag.kind) { - case 289 /* JSDocTypeTag */: - case 287 /* JSDocParameterTag */: - case 288 /* JSDocReturnTag */: - var tagWithExpression = tag; - if (tagWithExpression.typeExpression && tagWithExpression.typeExpression.pos < position && position < tagWithExpression.typeExpression.end) { - insideJsDocTagExpression = true; - } - else if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; - } - break; + if (isTagWithTypeExpression(tag) && tag.typeExpression) { + currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); + if (!currentToken || + (!ts.isDeclarationName(currentToken) && + (currentToken.parent.kind !== 292 /* JSDocPropertyTag */ || + currentToken.parent.name !== currentToken))) { + // Use as type location if inside tag's type expression + insideJsDocTagTypeExpression = isCurrentlyEditingNode(tag.typeExpression); + } + } + if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { + request = { kind: "JsDocParameterName", tag: tag }; } } if (request) { return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, request: request, hasFilteredClassMemberKeywords: false }; } - if (!insideJsDocTagExpression) { + if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -75579,7 +75505,7 @@ var ts; } } start = ts.timestamp(); - var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true); + var previousToken = ts.findPrecedingToken(position, sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 1: " + (ts.timestamp() - start)); // The decision to provide completion depends on the contextToken, which is determined through the previousToken. // Note: 'previousToken' (and thus 'contextToken') can be undefined if we are the beginning of the file @@ -75588,7 +75514,7 @@ var ts; // Skip this partial identifier and adjust the contextToken to the token that precedes it. if (contextToken && position <= contextToken.end && ts.isWord(contextToken.kind)) { var start_2 = ts.timestamp(); - contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, /*includeJsDoc*/ true); + contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined, insideJsDocTagTypeExpression); log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_2)); } // Find the node where completion is requested on. @@ -75598,7 +75524,7 @@ var ts; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; - var location = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 + var location = ts.getTouchingPropertyName(sourceFile, position, insideJsDocTagTypeExpression); // TODO: GH#15853 if (contextToken) { // Bail out if this is a known invalid completion location if (isCompletionListBlocker(contextToken)) { @@ -75692,11 +75618,25 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, hasFilteredClassMemberKeywords: hasFilteredClassMemberKeywords }; + function isTagWithTypeExpression(tag) { + switch (tag.kind) { + case 285 /* JSDocAugmentsTag */: + case 287 /* JSDocParameterTag */: + case 292 /* JSDocPropertyTag */: + case 288 /* JSDocReturnTag */: + case 289 /* JSDocTypeTag */: + case 291 /* JSDocTypedefTag */: + return true; + } + } function getTypeScriptMemberSymbols() { // Right of dot member completion list isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; + // Since this is qualified name check its a type node location + var isTypeLocation = ts.isPartOfTypeNode(node.parent) || insideJsDocTagTypeExpression; + var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); if (node.kind === 71 /* Identifier */ || node.kind === 143 /* QualifiedName */ || node.kind === 179 /* PropertyAccessExpression */) { var symbol = typeChecker.getSymbolAtLocation(node); // This is an alias, follow what it aliases @@ -75706,15 +75646,23 @@ var ts; if (symbol && symbol.flags & 1952 /* HasExports */) { // Extract module or enum members var exportedSymbols = typeChecker.getExportsOfModule(symbol); + var isValidValueAccess_1 = function (symbol) { return typeChecker.isValidPropertyAccess((node.parent), symbol.name); }; + var isValidTypeAccess_1 = function (symbol) { return symbolCanbeReferencedAtTypeLocation(symbol); }; + var isValidAccess_1 = isRhsOfImportDeclaration ? + // Any kind is allowed when dotting off namespace in internal import equals declaration + function (symbol) { return isValidTypeAccess_1(symbol) || isValidValueAccess_1(symbol); } : + isTypeLocation ? isValidTypeAccess_1 : isValidValueAccess_1; ts.forEach(exportedSymbols, function (symbol) { - if (typeChecker.isValidPropertyAccess((node.parent), symbol.name)) { + if (isValidAccess_1(symbol)) { symbols.push(symbol); } }); } } - var type = typeChecker.getTypeAtLocation(node); - addTypeProperties(type); + if (!isTypeLocation) { + var type = typeChecker.getTypeAtLocation(node); + addTypeProperties(type); + } } function addTypeProperties(type) { if (type) { @@ -75812,11 +75760,73 @@ var ts; scopeNode.kind === 256 /* JsxExpression */ || ts.isStatement(scopeNode); } - /// TODO filter meaning based on the current context var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 8388608 /* Alias */; - symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + symbols = filterGlobalCompletion(typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); return true; } + function filterGlobalCompletion(symbols) { + return ts.filter(symbols, function (symbol) { + if (!ts.isSourceFile(location)) { + // export = /**/ here we want to get all meanings, so any symbol is ok + if (ts.isExportAssignment(location.parent)) { + return true; + } + // This is an alias, follow what it aliases + if (symbol && symbol.flags & 8388608 /* Alias */) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) + if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { + return !!(symbol.flags & 1920 /* Namespace */); + } + if (insideJsDocTagTypeExpression || + (!isContextTokenValueLocation(contextToken) && + (ts.isPartOfTypeNode(location) || isContextTokenTypeLocation(contextToken)))) { + // Its a type, but you can reach it by namespace.type as well + return symbolCanbeReferencedAtTypeLocation(symbol); + } + } + // expressions are value space (which includes the value namespaces) + return !!(symbol.flags & 107455 /* Value */); + }); + } + function isContextTokenValueLocation(contextToken) { + return contextToken && + contextToken.kind === 103 /* TypeOfKeyword */ && + contextToken.parent.kind === 162 /* TypeQuery */; + } + function isContextTokenTypeLocation(contextToken) { + if (contextToken) { + var parentKind = contextToken.parent.kind; + switch (contextToken.kind) { + case 56 /* ColonToken */: + return parentKind === 149 /* PropertyDeclaration */ || + parentKind === 148 /* PropertySignature */ || + parentKind === 146 /* Parameter */ || + parentKind === 226 /* VariableDeclaration */ || + ts.isFunctionLikeKind(parentKind); + case 58 /* EqualsToken */: + return parentKind === 231 /* TypeAliasDeclaration */; + case 118 /* AsKeyword */: + return parentKind === 202 /* AsExpression */; + } + } + } + function symbolCanbeReferencedAtTypeLocation(symbol) { + // This is an alias, follow what it aliases + if (symbol && symbol.flags & 8388608 /* Alias */) { + symbol = typeChecker.getAliasedSymbol(symbol); + } + if (symbol.flags & 793064 /* Type */) { + return true; + } + if (symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */)) { + var exportedSymbols = typeChecker.getExportsOfModule(symbol); + // If the exported symbols contains type, + // symbol can be referenced at locations where type is allowed + return ts.forEach(exportedSymbols, symbolCanbeReferencedAtTypeLocation); + } + } /** * Finds the first node that "embraces" the position, so that one may * accurately aggregate locals from the closest containing scope. @@ -76191,19 +76201,6 @@ var ts; } return undefined; } - function isFunction(kind) { - if (!ts.isFunctionLikeKind(kind)) { - return false; - } - switch (kind) { - case 152 /* Constructor */: - case 161 /* ConstructorType */: - case 160 /* FunctionType */: - return false; - default: - return true; - } - } /** * @returns true if we are certain that the currently edited location must define a new location; false otherwise. */ @@ -76215,7 +76212,7 @@ var ts; containingNodeKind === 227 /* VariableDeclarationList */ || containingNodeKind === 208 /* VariableStatement */ || containingNodeKind === 232 /* EnumDeclaration */ || - isFunction(containingNodeKind) || + isFunctionLikeButNotConstructor(containingNodeKind) || containingNodeKind === 229 /* ClassDeclaration */ || containingNodeKind === 199 /* ClassExpression */ || containingNodeKind === 230 /* InterfaceDeclaration */ || @@ -76229,7 +76226,7 @@ var ts; return containingNodeKind === 175 /* ArrayBindingPattern */; // var [x| case 19 /* OpenParenToken */: return containingNodeKind === 260 /* CatchClause */ || - isFunction(containingNodeKind); + isFunctionLikeButNotConstructor(containingNodeKind); case 17 /* OpenBraceToken */: return containingNodeKind === 232 /* EnumDeclaration */ || containingNodeKind === 230 /* InterfaceDeclaration */ || @@ -76244,7 +76241,7 @@ var ts; containingNodeKind === 199 /* ClassExpression */ || containingNodeKind === 230 /* InterfaceDeclaration */ || containingNodeKind === 231 /* TypeAliasDeclaration */ || - isFunction(containingNodeKind); + ts.isFunctionLikeKind(containingNodeKind); case 115 /* StaticKeyword */: return containingNodeKind === 149 /* PropertyDeclaration */ && !ts.isClassLike(contextToken.parent.parent); case 24 /* DotDotDotToken */: @@ -76304,6 +76301,9 @@ var ts; } return false; } + function isFunctionLikeButNotConstructor(kind) { + return ts.isFunctionLikeKind(kind) && kind !== 152 /* Constructor */; + } function isDotOfNumericLiteral(contextToken) { if (contextToken.kind === 8 /* NumericLiteral */) { var text = contextToken.getFullText(); @@ -78026,7 +78026,7 @@ var ts; case 244 /* ExportDeclaration */: return true; case 181 /* CallExpression */: - return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false); + return ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent); default: return false; } @@ -80063,7 +80063,7 @@ var ts; function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var _loop_4 = function (sourceFile) { + var _loop_5 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts" /* Dts */)) { return "continue"; @@ -80100,7 +80100,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_8 = sourceFiles; _i < sourceFiles_8.length; _i++) { var sourceFile = sourceFiles_8[_i]; - _loop_4(sourceFile); + _loop_5(sourceFile); } // Remove imports when the imported declaration is already in the list and has the same name. rawItems = ts.filter(rawItems, function (item) { @@ -83050,7 +83050,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.clone(options); - var _loop_5 = function (opt) { + var _loop_6 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -83069,7 +83069,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_5(opt); + _loop_6(opt); } return options; } @@ -87025,12 +87025,12 @@ var ts; } switch (token.kind) { case 71 /* Identifier */: - return deleteIdentifier(); + return deleteIdentifierOrPrefixWithUnderscore(token); case 149 /* PropertyDeclaration */: case 240 /* NamespaceImport */: - return deleteNode(token.parent); + return [deleteNode(token.parent)]; default: - return deleteDefault(); + return [deleteDefault()]; } function deleteDefault() { if (ts.isDeclarationName(token)) { @@ -87043,56 +87043,62 @@ var ts; return undefined; } } - function deleteIdentifier() { - switch (token.parent.kind) { + function prefixIdentifierWithUnderscore(identifier) { + var startPosition = identifier.getStart(sourceFile, /*includeJsDocComment*/ false); + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Prefix_0_with_an_underscore), { 0: token.getText() }), + changes: [{ + fileName: sourceFile.path, + textChanges: [{ + span: { start: startPosition, length: 0 }, + newText: "_" + }] + }] + }; + } + function deleteIdentifierOrPrefixWithUnderscore(identifier) { + var parent = identifier.parent; + switch (parent.kind) { case 226 /* VariableDeclaration */: - return deleteVariableDeclaration(token.parent); + return deleteVariableDeclarationOrPrefixWithUnderscore(identifier, parent); case 145 /* TypeParameter */: - var typeParameters = token.parent.parent.typeParameters; + var typeParameters = parent.parent.typeParameters; if (typeParameters.length === 1) { var previousToken = ts.getTokenAtPosition(sourceFile, typeParameters.pos - 1, /*includeJsDocComment*/ false); - if (!previousToken || previousToken.kind !== 27 /* LessThanToken */) { - return deleteRange(typeParameters); - } var nextToken = ts.getTokenAtPosition(sourceFile, typeParameters.end, /*includeJsDocComment*/ false); - if (!nextToken || nextToken.kind !== 29 /* GreaterThanToken */) { - return deleteRange(typeParameters); - } - return deleteNodeRange(previousToken, nextToken); + ts.Debug.assert(previousToken.kind === 27 /* LessThanToken */); + ts.Debug.assert(nextToken.kind === 29 /* GreaterThanToken */); + return [deleteNodeRange(previousToken, nextToken)]; } else { - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } case 146 /* Parameter */: - var functionDeclaration = token.parent.parent; - if (functionDeclaration.parameters.length === 1) { - return deleteNode(token.parent); - } - else { - return deleteNodeInList(token.parent); - } + var functionDeclaration = parent.parent; + return [functionDeclaration.parameters.length === 1 ? deleteNode(parent) : deleteNodeInList(parent), + prefixIdentifierWithUnderscore(identifier)]; // handle case where 'import a = A;' case 237 /* ImportEqualsDeclaration */: - var importEquals = ts.getAncestor(token, 237 /* ImportEqualsDeclaration */); - return deleteNode(importEquals); + var importEquals = ts.getAncestor(identifier, 237 /* ImportEqualsDeclaration */); + return [deleteNode(importEquals)]; case 242 /* ImportSpecifier */: - var namedImports = token.parent.parent; + var namedImports = parent.parent; if (namedImports.elements.length === 1) { // Only 1 import and it is unused. So the entire declaration should be removed. - var importSpec = ts.getAncestor(token, 238 /* ImportDeclaration */); - return deleteNode(importSpec); + var importSpec = ts.getAncestor(identifier, 238 /* ImportDeclaration */); + return [deleteNode(importSpec)]; } else { // delete import specifier - return deleteNodeInList(token.parent); + return [deleteNodeInList(parent)]; } // handle case where "import d, * as ns from './file'" // or "'import {a, b as ns} from './file'" case 239 /* ImportClause */:// this covers both 'import |d|' and 'import |d,| *' - var importClause = token.parent; + var importClause = parent; if (!importClause.namedBindings) { var importDecl = ts.getAncestor(importClause, 238 /* ImportDeclaration */); - return deleteNode(importDecl); + return [deleteNode(importDecl)]; } else { // import |d,| * as ns from './file' @@ -87100,58 +87106,56 @@ var ts; var nextToken = ts.getTokenAtPosition(sourceFile, importClause.name.end, /*includeJsDocComment*/ false); if (nextToken && nextToken.kind === 26 /* CommaToken */) { // shift first non-whitespace position after comma to the start position of the node - return deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) }); + return [deleteRange({ pos: start_4, end: ts.skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) })]; } else { - return deleteNode(importClause.name); + return [deleteNode(importClause.name)]; } } case 240 /* NamespaceImport */: - var namespaceImport = token.parent; - if (namespaceImport.name === token && !namespaceImport.parent.name) { + var namespaceImport = parent; + if (namespaceImport.name === identifier && !namespaceImport.parent.name) { var importDecl = ts.getAncestor(namespaceImport, 238 /* ImportDeclaration */); - return deleteNode(importDecl); + return [deleteNode(importDecl)]; } else { var previousToken = ts.getTokenAtPosition(sourceFile, namespaceImport.pos - 1, /*includeJsDocComment*/ false); if (previousToken && previousToken.kind === 26 /* CommaToken */) { var startPosition = ts.textChanges.getAdjustedStartPosition(sourceFile, previousToken, {}, ts.textChanges.Position.FullStart); - return deleteRange({ pos: startPosition, end: namespaceImport.end }); + return [deleteRange({ pos: startPosition, end: namespaceImport.end })]; } - return deleteRange(namespaceImport); + return [deleteRange(namespaceImport)]; } default: - return deleteDefault(); + return [deleteDefault()]; } } // token.parent is a variableDeclaration - function deleteVariableDeclaration(varDecl) { + function deleteVariableDeclarationOrPrefixWithUnderscore(identifier, varDecl) { switch (varDecl.parent.parent.kind) { case 214 /* ForStatement */: var forStatement = varDecl.parent.parent; var forInitializer = forStatement.initializer; - if (forInitializer.declarations.length === 1) { - return deleteNode(forInitializer); - } - else { - return deleteNodeInList(varDecl); - } + return [forInitializer.declarations.length === 1 ? deleteNode(forInitializer) : deleteNodeInList(varDecl)]; case 216 /* ForOfStatement */: var forOfStatement = varDecl.parent.parent; ts.Debug.assert(forOfStatement.initializer.kind === 227 /* VariableDeclarationList */); var forOfInitializer = forOfStatement.initializer; - return replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()); + return [ + replaceNode(forOfInitializer.declarations[0], ts.createObjectLiteral()), + prefixIdentifierWithUnderscore(identifier) + ]; case 215 /* ForInStatement */: // There is no valid fix in the case of: // for .. in - return undefined; + return [prefixIdentifierWithUnderscore(identifier)]; default: var variableStatement = varDecl.parent.parent; if (variableStatement.declarationList.declarations.length === 1) { - return deleteNode(variableStatement); + return [deleteNode(variableStatement)]; } else { - return deleteNodeInList(varDecl); + return [deleteNodeInList(varDecl)]; } } } @@ -87171,10 +87175,10 @@ var ts; return makeChange(ts.textChanges.ChangeTracker.fromCodeFixContext(context).replaceNode(sourceFile, n, newNode)); } function makeChange(changeTracker) { - return [{ - description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), - changes: changeTracker.getChanges() - }]; + return { + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Remove_declaration_for_Colon_0), { 0: token.getText() }), + changes: changeTracker.getChanges() + }; } } }); @@ -87992,7 +87996,7 @@ var ts; /// /// /// -/// +/// /// /// /// @@ -88816,7 +88820,6 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.getCanonicalFileName = getCanonicalFileName; // script id => script index this.currentDirectory = host.getCurrentDirectory(); this.fileNameToEntry = ts.createFileMap(); @@ -88846,19 +88849,15 @@ var ts; this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (path) { + HostCache.prototype.getEntryByPath = function (path) { return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (path) { + HostCache.prototype.containsEntryByPath = function (path) { return this.fileNameToEntry.contains(path); }; - HostCache.prototype.getOrCreateEntry = function (fileName) { - var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); - return this.getOrCreateEntryByPath(fileName, path); - }; HostCache.prototype.getOrCreateEntryByPath = function (fileName, path) { - return this.contains(path) - ? this.getEntry(path) + return this.containsEntryByPath(path) + ? this.getEntryByPath(path) : this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { @@ -88871,11 +88870,11 @@ var ts; return fileNames; }; HostCache.prototype.getVersion = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.version; }; HostCache.prototype.getScriptSnapshot = function (path) { - var file = this.getEntry(path); + var file = this.getEntryByPath(path); return file && file.scriptSnapshot; }; return HostCache; @@ -89103,12 +89102,19 @@ var ts; getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { // stub missing host functionality - return hostCache.getOrCreateEntry(fileName) !== undefined; + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + return hostCache.containsEntryByPath(path) ? + !!hostCache.getEntryByPath(path) : + (host.fileExists && host.fileExists(fileName)); }, readFile: function (fileName) { // stub missing host functionality - var entry = hostCache.getOrCreateEntry(fileName); - return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + if (hostCache.containsEntryByPath(path)) { + var entry = hostCache.getEntryByPath(path); + return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + } + return host.readFile && host.readFile(fileName); }, directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -89241,7 +89247,9 @@ var ts; ts.forEach(program.getSourceFiles(), function (f) { return documentRegistry.releaseDocument(f.fileName, program.getCompilerOptions()); }); + program = undefined; } + host = undefined; } /// Diagnostics function getSyntacticDiagnostics(fileName) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 415649d053f..ec70cd031cf 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -152,7 +152,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.4.1"; + ts.version = "2.4.1-insiders.20170614"; })(ts || (ts = {})); (function (ts) { ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; @@ -3431,6 +3431,7 @@ var ts; Change_spelling_to_0: { code: 90022, category: ts.DiagnosticCategory.Message, key: "Change_spelling_to_0_90022", message: "Change spelling to '{0}'." }, Declare_method_0: { code: 90023, category: ts.DiagnosticCategory.Message, key: "Declare_method_0_90023", message: "Declare method '{0}'." }, Declare_static_method_0: { code: 90024, category: ts.DiagnosticCategory.Message, key: "Declare_static_method_0_90024", message: "Declare static method '{0}'." }, + Prefix_0_with_an_underscore: { code: 90025, category: ts.DiagnosticCategory.Message, key: "Prefix_0_with_an_underscore_90025", message: "Prefix '{0}' with an underscore." }, Convert_function_to_an_ES2015_class: { code: 95001, category: ts.DiagnosticCategory.Message, key: "Convert_function_to_an_ES2015_class_95001", message: "Convert function to an ES2015 class" }, Convert_function_0_to_class: { code: 95002, category: ts.DiagnosticCategory.Message, key: "Convert_function_0_to_class_95002", message: "Convert function '{0}' to class" }, Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0: { code: 8017, category: ts.DiagnosticCategory.Error, key: "Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0_8017", message: "Octal literal types must use ES2015 syntax. Use the syntax '{0}'." },