diff --git a/debug.log b/debug.log deleted file mode 100644 index e4f3ee33ba2..00000000000 --- a/debug.log +++ /dev/null @@ -1,8 +0,0 @@ -[0405/094221:ERROR:tcp_listen_socket.cc(76)] Could not bind socket to 127.0.0.1:5959 -[0405/094221:ERROR:node_debugger.cc(86)] Cannot start debugger server -[0405/094221:ERROR:tcp_listen_socket.cc(76)] Could not bind socket to 127.0.0.1:5960 -[0405/094221:ERROR:node_debugger.cc(86)] Cannot start debugger server -[0413/114447:ERROR:tcp_listen_socket.cc(76)] Could not bind socket to 127.0.0.1:5959 -[0413/114447:ERROR:node_debugger.cc(86)] Cannot start debugger server -[0413/114448:ERROR:tcp_listen_socket.cc(76)] Could not bind socket to 127.0.0.1:5960 -[0413/114448:ERROR:node_debugger.cc(86)] Cannot start debugger server diff --git a/lib/tsc.js b/lib/tsc.js index dd08ef17873..b5a10171633 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -142,7 +142,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.3.1"; + ts.version = "2.3.3"; })(ts || (ts = {})); (function (ts) { ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; @@ -6407,6 +6407,36 @@ var ts; return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0: + case 2: + return undefined; + case 1: + if (lhs.kind === 71) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4: + case 5: + return lhs.name; + case 3: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 144 && @@ -6544,6 +6574,9 @@ var ts; } ts.isTrivia = isTrivia; function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -6588,7 +6621,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -9340,7 +9374,7 @@ var ts; var node = createSynthesizedNode(179); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); - setEmitFlags(node, 65536); + setEmitFlags(node, 131072); return node; } ts.createPropertyAccess = createPropertyAccess; @@ -11208,6 +11242,14 @@ var ts; function createExpressionForMethodDeclaration(method, receiver) { return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body), method), method)), method), method)); } + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 | 32768); + } + ts.getInternalName = getInternalName; + function isInternalName(node) { + return (ts.getEmitFlags(node) & 32768) !== 0; + } + ts.isInternalName = isInternalName; function getLocalName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 16384); } @@ -11229,9 +11271,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -11302,7 +11345,7 @@ var ts; var numStatements = source.length; while (statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 524288) { + if (ts.getEmitFlags(statement) & 1048576) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -17420,19 +17463,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -17528,9 +17572,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -21131,16 +21175,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -21251,7 +21295,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -21612,13 +21657,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -22828,8 +22873,9 @@ var ts; function getNameOfSymbol(symbol) { var declaration = ts.firstOrUndefined(symbol.declarations); if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -22910,8 +22956,9 @@ var ts; function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -25740,8 +25787,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -27661,24 +27709,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -28127,23 +28157,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -28681,7 +28722,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -30233,7 +30274,7 @@ var ts; if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -31230,6 +31271,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -31247,6 +31292,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -31256,31 +31304,34 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); - } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { - if (!filter || filter(attr)) { - attributesTable.set(attr.name, attr); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + attributesArray = []; + attributesTable = ts.createMap(); } - }); + attributesArray = getPropertiesOfType(spread); + } + attributesTable = ts.createMap(); + if (attributesArray) { + ts.forEach(attributesArray, function (attr) { + if (!filter || filter(attr)) { + attributesTable.set(attr.name, attr); + } + }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { @@ -31296,9 +31347,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -31308,11 +31358,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -31367,7 +31421,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -31401,6 +31466,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -31410,6 +31489,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -31435,6 +31515,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -31638,6 +31719,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -31649,7 +31748,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -31988,8 +32096,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -32625,7 +32733,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -32961,10 +33069,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -33848,12 +33956,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -34246,17 +34354,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -34279,7 +34384,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -34393,7 +34498,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -34467,7 +34572,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -34694,16 +34800,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -34714,7 +34820,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -34822,7 +34928,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -34835,8 +34941,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) { + var signature = signatures_5[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -34885,11 +34991,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -35251,15 +35358,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -35337,7 +35445,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -35399,7 +35507,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -35413,7 +35521,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -35609,7 +35717,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -35715,11 +35823,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -36169,11 +36278,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -36447,7 +36559,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -36715,7 +36827,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -38071,15 +38183,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -38158,7 +38261,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -38305,7 +38407,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -38332,9 +38434,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -40800,7 +40903,7 @@ var ts; } if (statements.length > 1) { statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 2097152); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304); } return ts.singleOrMany(statements); } @@ -40846,7 +40949,7 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - ts.setEmitFlags(classExpression, 32768 | ts.getEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -41684,13 +41787,13 @@ var ts; ts.setSourceMapRange(statement, node); } ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 | 2097152); + ts.setEmitFlags(statement, 1024 | 4194304); statements.push(statement); return true; } else { var mergeMarker = ts.createMergeDeclarationMarker(statement); - ts.setEmitFlags(mergeMarker, 1536 | 2097152); + ts.setEmitFlags(mergeMarker, 1536 | 4194304); statements.push(mergeMarker); return false; } @@ -42318,7 +42421,7 @@ var ts; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(39), undefined, undefined, [], undefined, body); - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__awaiter"), undefined, [ ts.createThis(), hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), @@ -42421,19 +42524,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -42560,6 +42658,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -42567,19 +42668,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 1048576), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -42588,12 +42687,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -42718,7 +42812,7 @@ var ts; var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); if (ts.some(declarations)) { var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(declarations)); - ts.setEmitFlags(statement, 524288); + ts.setEmitFlags(statement, 1048576); statements = ts.append(statements, statement); } } @@ -42825,14 +42919,24 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ ts.createThis(), ts.createIdentifier("arguments"), @@ -42842,11 +42946,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -43659,9 +43763,9 @@ var ts; statements.push(exportStatement); } var emitFlags = ts.getEmitFlags(node); - if ((emitFlags & 2097152) === 0) { + if ((emitFlags & 4194304) === 0) { statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(statement, emitFlags | 2097152); + ts.setEmitFlags(statement, emitFlags | 4194304); } return ts.singleOrMany(statements); } @@ -43674,8 +43778,8 @@ var ts; } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter(undefined, undefined, undefined, "_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (ts.getEmitFlags(node) & 32768) { - ts.setEmitFlags(classFunction, 32768); + if (ts.getEmitFlags(node) & 65536) { + ts.setEmitFlags(classFunction, 65536); } var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; @@ -43694,7 +43798,7 @@ var ts; addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18); - var localName = ts.getLocalName(node); + var localName = ts.getInternalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; ts.setEmitFlags(outer, 1536); @@ -43718,7 +43822,7 @@ var ts; var ancestorFacts = enterSubtree(16278, 73); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getInternalName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); ts.setTextRange(constructorFunction, constructor || node); if (extendsClauseElement) { ts.setEmitFlags(constructorFunction, 8); @@ -43882,10 +43986,10 @@ var ts; function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); if (name.elements.length > 0) { - statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 524288)); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 1048576)); } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 524288)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576)); } } function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { @@ -43895,7 +43999,7 @@ var ts; ]), parameter), 1 | 32 | 384)); statement.startsOnNewLine = true; ts.setTextRange(statement, parameter); - ts.setEmitFlags(statement, 384 | 32 | 524288); + ts.setEmitFlags(statement, 384 | 32 | 1048576); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { @@ -43913,7 +44017,7 @@ var ts; var temp = ts.createLoopVariable(); statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) - ])), parameter), 524288)); + ])), parameter), 1048576)); var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ @@ -43921,7 +44025,7 @@ var ts; ? temp : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), parameter)) ])); - ts.setEmitFlags(forStatement, 524288); + ts.setEmitFlags(forStatement, 1048576); ts.startOnNewLine(forStatement); statements.push(forStatement); } @@ -43935,7 +44039,7 @@ var ts; var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration("_this", undefined, initializer) ])); - ts.setEmitFlags(captureThisStatement, 1536 | 524288); + ts.setEmitFlags(captureThisStatement, 1536 | 1048576); ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); @@ -44075,7 +44179,7 @@ var ts; return func; } function visitFunctionExpression(node) { - var ancestorFacts = ts.getEmitFlags(node) & 131072 + var ancestorFacts = ts.getEmitFlags(node) & 262144 ? enterSubtree(16278, 69) : enterSubtree(16286, 65); var savedConvertedLoopState = convertedLoopState; @@ -44424,7 +44528,7 @@ var ts; var forStatement = ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), ts.setTextRange(ts.createVariableDeclaration(rhsReference, undefined, expression), node.expression) - ]), node.expression), 1048576), ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), node); + ]), node.expression), 2097152), ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), node); ts.setEmitFlags(forStatement, 256); ts.setTextRange(forStatement, node); return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); @@ -44443,7 +44547,7 @@ var ts; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 1048576), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), node), 256); + ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -44480,7 +44584,7 @@ var ts; } var temp = ts.createTempVariable(hoistVariableDeclaration); var expressions = []; - var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 32768)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -44587,11 +44691,11 @@ var ts; loopBodyFlags |= 8; } if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 131072; + loopBodyFlags |= 262144; } var convertedLoopVariable = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(39) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) - ]), 1048576)); + ]), 2097152)); var statements = [convertedLoopVariable]; var extraVariableDeclarations; if (currentState.argumentsName) { @@ -44672,7 +44776,7 @@ var ts; !state.labeledNonLocalContinues; var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 4194304)) + ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 8388608)) : call; if (isSimpleLoop) { statements.push(ts.createStatement(callResult)); @@ -44843,7 +44947,20 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286, 65); - var updated = ts.visitEachChild(node, visitor, context); + var updated; + if (node.transformFlags & 32768) { + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = transformFunctionBody(node); + if (node.kind === 153) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + } + else { + updated = ts.visitEachChild(node, visitor, context); + } exitSubtree(ancestorFacts, 49152, 0); convertedLoopState = savedConvertedLoopState; return updated; @@ -45086,7 +45203,7 @@ var ts; return node; } function substituteIdentifier(node) { - if (enabledSubstitutions & 2) { + if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var original = ts.getParseTreeNode(node, ts.isIdentifier); if (original && isNameOfDeclarationWithCollidingName(original)) { return ts.setTextRange(ts.getGeneratedNameForNode(original), node); @@ -45116,14 +45233,32 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (enabledSubstitutions & 2) { + if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; } + function isPartOfClassBody(declaration, node) { + var currentNode = ts.getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + return false; + } + var blockScope = ts.getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + return false; + } + if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { + return currentNode.kind !== 149 + || (ts.getModifierFlags(currentNode) & 32) === 0; + } + currentNode = currentNode.parent; + } + return false; + } function substituteThisKeyword(node) { if (enabledSubstitutions & 1 && hierarchyFacts & 16) { @@ -45132,8 +45267,9 @@ var ts; return node; } function getClassMemberPrefix(node, member) { - var expression = ts.getLocalName(node); - return ts.hasModifier(member, 32) ? expression : ts.createPropertyAccess(expression, "prototype"); + return ts.hasModifier(member, 32) + ? ts.getInternalName(node) + : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); } function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { if (!constructor || !hasExtendsClause) { @@ -45502,7 +45638,7 @@ var ts; return undefined; } else { - if (ts.getEmitFlags(node) & 524288) { + if (ts.getEmitFlags(node) & 1048576) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -45638,7 +45774,7 @@ var ts; var resumeLabel = defineLabel(); var expression = ts.visitNode(node.expression, visitor, ts.isExpression); if (node.asteriskToken) { - var iterator = (ts.getEmitFlags(node.expression) & 4194304) === 0 + var iterator = (ts.getEmitFlags(node.expression) & 8388608) === 0 ? ts.createValuesHelper(context, expression, node) : expression; emitYieldStar(iterator, node); @@ -46603,7 +46739,7 @@ var ts; currentExceptionBlock = undefined; withBlockStack = undefined; var buildResult = buildStatements(); - return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, state)], undefined, ts.createBlock(buildResult, buildResult.length > 0)), 262144)); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, state)], undefined, ts.createBlock(buildResult, buildResult.length > 0)), 524288)); } function buildStatements() { if (operations) { @@ -47280,7 +47416,7 @@ var ts; return node; } function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 2097152) !== 0; + return (ts.getEmitFlags(node) & 4194304) !== 0; } function visitEndOfDeclarationMarker(node) { var id = ts.getOriginalNodeId(node); @@ -47393,7 +47529,7 @@ var ts; ]) ])); } - ts.setEmitFlags(statement, 524288); + ts.setEmitFlags(statement, 1048576); return statement; } function createExportStatement(name, value, location, allowComments) { @@ -47902,7 +48038,7 @@ var ts; } } function shouldHoistVariableDeclarationList(node) { - return (ts.getEmitFlags(node) & 1048576) === 0 + return (ts.getEmitFlags(node) & 2097152) === 0 && (enclosingBlockScopedContainer.kind === 265 || (ts.getOriginalNode(node).flags & 3) === 0); } @@ -47933,7 +48069,7 @@ var ts; return node; } function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 2097152) !== 0; + return (ts.getEmitFlags(node) & 4194304) !== 0; } function visitEndOfDeclarationMarker(node) { var id = ts.getOriginalNodeId(node); @@ -49323,7 +49459,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -49348,11 +49484,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -49756,8 +49892,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -49770,23 +49905,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -49796,12 +49938,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -49871,7 +50007,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -50196,7 +50332,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -50208,12 +50344,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -50227,7 +50357,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -50242,6 +50372,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -50249,15 +50392,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -50278,7 +50428,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -51687,7 +51837,7 @@ var ts; write("{}"); } else { - var indentedFlag = ts.getEmitFlags(node) & 32768; + var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } @@ -51702,7 +51852,7 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; - if (!(ts.getEmitFlags(node) & 65536)) { + if (!(ts.getEmitFlags(node) & 131072)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; var dotToken = { kind: 23, pos: dotRangeStart, end: dotRangeEnd }; @@ -52077,11 +52227,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = ts.getEmitFlags(node) & 32768; + var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } - if (ts.getEmitFlags(node) & 262144) { + if (ts.getEmitFlags(node) & 524288) { emitSignatureHead(node); if (onEmitNode) { onEmitNode(3, body, emitBlockCallback); @@ -52184,7 +52334,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = ts.getEmitFlags(node) & 32768; + var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } diff --git a/lib/tsserver.js b/lib/tsserver.js index dd7c057693e..5f4effd9e22 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -1002,14 +1002,15 @@ var ts; EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; - EmitFlags[EmitFlags["Indented"] = 32768] = "Indented"; - EmitFlags[EmitFlags["NoIndentation"] = 65536] = "NoIndentation"; - EmitFlags[EmitFlags["AsyncFunctionBody"] = 131072] = "AsyncFunctionBody"; - EmitFlags[EmitFlags["ReuseTempVariableScope"] = 262144] = "ReuseTempVariableScope"; - EmitFlags[EmitFlags["CustomPrologue"] = 524288] = "CustomPrologue"; - EmitFlags[EmitFlags["NoHoisting"] = 1048576] = "NoHoisting"; - EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 2097152] = "HasEndOfDeclarationMarker"; - EmitFlags[EmitFlags["Iterator"] = 4194304] = "Iterator"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1024,14 +1025,17 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1102,7 +1106,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.3.1"; + ts.version = "2.3.3"; })(ts || (ts = {})); (function (ts) { var Ternary; @@ -6594,6 +6598,36 @@ var ts; return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0: + case 2: + return undefined; + case 1: + if (lhs.kind === 71) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4: + case 5: + return lhs.name; + case 3: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 144 && @@ -6735,12 +6769,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -6785,7 +6820,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -11119,7 +11155,7 @@ var ts; var node = createSynthesizedNode(179); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); - setEmitFlags(node, 65536); + setEmitFlags(node, 131072); return node; } ts.createPropertyAccess = createPropertyAccess; @@ -12987,6 +13023,14 @@ var ts; function createExpressionForMethodDeclaration(method, receiver) { return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body), method), method)), method), method)); } + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 | 32768); + } + ts.getInternalName = getInternalName; + function isInternalName(node) { + return (ts.getEmitFlags(node) & 32768) !== 0; + } + ts.isInternalName = isInternalName; function getLocalName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 16384); } @@ -13008,9 +13052,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -13081,7 +13126,7 @@ var ts; var numStatements = source.length; while (statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 524288) { + if (ts.getEmitFlags(statement) & 1048576) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -19271,19 +19316,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -19379,9 +19425,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -22293,16 +22339,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -22413,7 +22459,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -22774,13 +22821,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -23990,8 +24037,9 @@ var ts; function getNameOfSymbol(symbol) { var declaration = ts.firstOrUndefined(symbol.declarations); if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -24072,8 +24120,9 @@ var ts; function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -26902,8 +26951,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -28823,24 +28873,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -29289,23 +29321,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -29843,7 +29886,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -31395,7 +31438,7 @@ var ts; if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -32392,6 +32435,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -32409,6 +32456,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -32418,31 +32468,34 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); - } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { - if (!filter || filter(attr)) { - attributesTable.set(attr.name, attr); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + attributesArray = []; + attributesTable = ts.createMap(); } - }); + attributesArray = getPropertiesOfType(spread); + } + attributesTable = ts.createMap(); + if (attributesArray) { + ts.forEach(attributesArray, function (attr) { + if (!filter || filter(attr)) { + attributesTable.set(attr.name, attr); + } + }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { @@ -32458,9 +32511,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -32470,11 +32522,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -32529,7 +32585,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -32563,6 +32630,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -32572,6 +32653,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -32597,6 +32679,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -32800,6 +32883,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -32811,7 +32912,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -33150,8 +33260,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -33787,7 +33897,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -34123,10 +34233,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -35010,12 +35120,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -35408,17 +35518,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -35441,7 +35548,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -35562,7 +35669,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -35636,7 +35743,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -35863,16 +35971,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -35883,7 +35991,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -35991,7 +36099,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -36004,8 +36112,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) { + var signature = signatures_5[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -36054,11 +36162,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -36420,15 +36529,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -36506,7 +36616,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -36568,7 +36678,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -36582,7 +36692,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -36778,7 +36888,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -36884,11 +36994,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -37338,11 +37449,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -37616,7 +37730,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -37884,7 +37998,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -39240,15 +39354,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -39327,7 +39432,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -39474,7 +39578,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -39501,9 +39605,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -41980,7 +42085,7 @@ var ts; } if (statements.length > 1) { statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 2097152); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304); } return ts.singleOrMany(statements); } @@ -42026,7 +42131,7 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - ts.setEmitFlags(classExpression, 32768 | ts.getEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -42864,13 +42969,13 @@ var ts; ts.setSourceMapRange(statement, node); } ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 | 2097152); + ts.setEmitFlags(statement, 1024 | 4194304); statements.push(statement); return true; } else { var mergeMarker = ts.createMergeDeclarationMarker(statement); - ts.setEmitFlags(mergeMarker, 1536 | 2097152); + ts.setEmitFlags(mergeMarker, 1536 | 4194304); statements.push(mergeMarker); return false; } @@ -43502,7 +43607,7 @@ var ts; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(39), undefined, undefined, [], undefined, body); - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__awaiter"), undefined, [ ts.createThis(), hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), @@ -43609,19 +43714,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -43748,6 +43848,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -43755,19 +43858,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 1048576), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -43776,12 +43877,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -43906,7 +44002,7 @@ var ts; var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); if (ts.some(declarations)) { var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(declarations)); - ts.setEmitFlags(statement, 524288); + ts.setEmitFlags(statement, 1048576); statements = ts.append(statements, statement); } } @@ -44013,14 +44109,24 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ ts.createThis(), ts.createIdentifier("arguments"), @@ -44030,11 +44136,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -44916,9 +45022,9 @@ var ts; statements.push(exportStatement); } var emitFlags = ts.getEmitFlags(node); - if ((emitFlags & 2097152) === 0) { + if ((emitFlags & 4194304) === 0) { statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(statement, emitFlags | 2097152); + ts.setEmitFlags(statement, emitFlags | 4194304); } return ts.singleOrMany(statements); } @@ -44931,8 +45037,8 @@ var ts; } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter(undefined, undefined, undefined, "_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (ts.getEmitFlags(node) & 32768) { - ts.setEmitFlags(classFunction, 32768); + if (ts.getEmitFlags(node) & 65536) { + ts.setEmitFlags(classFunction, 65536); } var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; @@ -44951,7 +45057,7 @@ var ts; addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18); - var localName = ts.getLocalName(node); + var localName = ts.getInternalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; ts.setEmitFlags(outer, 1536); @@ -44975,7 +45081,7 @@ var ts; var ancestorFacts = enterSubtree(16278, 73); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getInternalName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); ts.setTextRange(constructorFunction, constructor || node); if (extendsClauseElement) { ts.setEmitFlags(constructorFunction, 8); @@ -45139,10 +45245,10 @@ var ts; function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); if (name.elements.length > 0) { - statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 524288)); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 1048576)); } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 524288)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576)); } } function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { @@ -45152,7 +45258,7 @@ var ts; ]), parameter), 1 | 32 | 384)); statement.startsOnNewLine = true; ts.setTextRange(statement, parameter); - ts.setEmitFlags(statement, 384 | 32 | 524288); + ts.setEmitFlags(statement, 384 | 32 | 1048576); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { @@ -45170,7 +45276,7 @@ var ts; var temp = ts.createLoopVariable(); statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) - ])), parameter), 524288)); + ])), parameter), 1048576)); var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ @@ -45178,7 +45284,7 @@ var ts; ? temp : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), parameter)) ])); - ts.setEmitFlags(forStatement, 524288); + ts.setEmitFlags(forStatement, 1048576); ts.startOnNewLine(forStatement); statements.push(forStatement); } @@ -45192,7 +45298,7 @@ var ts; var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration("_this", undefined, initializer) ])); - ts.setEmitFlags(captureThisStatement, 1536 | 524288); + ts.setEmitFlags(captureThisStatement, 1536 | 1048576); ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); @@ -45332,7 +45438,7 @@ var ts; return func; } function visitFunctionExpression(node) { - var ancestorFacts = ts.getEmitFlags(node) & 131072 + var ancestorFacts = ts.getEmitFlags(node) & 262144 ? enterSubtree(16278, 69) : enterSubtree(16286, 65); var savedConvertedLoopState = convertedLoopState; @@ -45681,7 +45787,7 @@ var ts; var forStatement = ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), ts.setTextRange(ts.createVariableDeclaration(rhsReference, undefined, expression), node.expression) - ]), node.expression), 1048576), ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), node); + ]), node.expression), 2097152), ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), node); ts.setEmitFlags(forStatement, 256); ts.setTextRange(forStatement, node); return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); @@ -45700,7 +45806,7 @@ var ts; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 1048576), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), node), 256); + ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -45737,7 +45843,7 @@ var ts; } var temp = ts.createTempVariable(hoistVariableDeclaration); var expressions = []; - var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 32768)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -45844,11 +45950,11 @@ var ts; loopBodyFlags |= 8; } if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 131072; + loopBodyFlags |= 262144; } var convertedLoopVariable = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(39) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) - ]), 1048576)); + ]), 2097152)); var statements = [convertedLoopVariable]; var extraVariableDeclarations; if (currentState.argumentsName) { @@ -45929,7 +46035,7 @@ var ts; !state.labeledNonLocalContinues; var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 4194304)) + ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 8388608)) : call; if (isSimpleLoop) { statements.push(ts.createStatement(callResult)); @@ -46100,7 +46206,20 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286, 65); - var updated = ts.visitEachChild(node, visitor, context); + var updated; + if (node.transformFlags & 32768) { + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = transformFunctionBody(node); + if (node.kind === 153) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + } + else { + updated = ts.visitEachChild(node, visitor, context); + } exitSubtree(ancestorFacts, 49152, 0); convertedLoopState = savedConvertedLoopState; return updated; @@ -46343,7 +46462,7 @@ var ts; return node; } function substituteIdentifier(node) { - if (enabledSubstitutions & 2) { + if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var original = ts.getParseTreeNode(node, ts.isIdentifier); if (original && isNameOfDeclarationWithCollidingName(original)) { return ts.setTextRange(ts.getGeneratedNameForNode(original), node); @@ -46373,14 +46492,32 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (enabledSubstitutions & 2) { + if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; } + function isPartOfClassBody(declaration, node) { + var currentNode = ts.getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + return false; + } + var blockScope = ts.getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + return false; + } + if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { + return currentNode.kind !== 149 + || (ts.getModifierFlags(currentNode) & 32) === 0; + } + currentNode = currentNode.parent; + } + return false; + } function substituteThisKeyword(node) { if (enabledSubstitutions & 1 && hierarchyFacts & 16) { @@ -46389,8 +46526,9 @@ var ts; return node; } function getClassMemberPrefix(node, member) { - var expression = ts.getLocalName(node); - return ts.hasModifier(member, 32) ? expression : ts.createPropertyAccess(expression, "prototype"); + return ts.hasModifier(member, 32) + ? ts.getInternalName(node) + : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); } function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { if (!constructor || !hasExtendsClause) { @@ -46734,7 +46872,7 @@ var ts; return undefined; } else { - if (ts.getEmitFlags(node) & 524288) { + if (ts.getEmitFlags(node) & 1048576) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -46870,7 +47008,7 @@ var ts; var resumeLabel = defineLabel(); var expression = ts.visitNode(node.expression, visitor, ts.isExpression); if (node.asteriskToken) { - var iterator = (ts.getEmitFlags(node.expression) & 4194304) === 0 + var iterator = (ts.getEmitFlags(node.expression) & 8388608) === 0 ? ts.createValuesHelper(context, expression, node) : expression; emitYieldStar(iterator, node); @@ -47835,7 +47973,7 @@ var ts; currentExceptionBlock = undefined; withBlockStack = undefined; var buildResult = buildStatements(); - return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, state)], undefined, ts.createBlock(buildResult, buildResult.length > 0)), 262144)); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, state)], undefined, ts.createBlock(buildResult, buildResult.length > 0)), 524288)); } function buildStatements() { if (operations) { @@ -48582,7 +48720,7 @@ var ts; return node; } function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 2097152) !== 0; + return (ts.getEmitFlags(node) & 4194304) !== 0; } function visitEndOfDeclarationMarker(node) { var id = ts.getOriginalNodeId(node); @@ -48695,7 +48833,7 @@ var ts; ]) ])); } - ts.setEmitFlags(statement, 524288); + ts.setEmitFlags(statement, 1048576); return statement; } function createExportStatement(name, value, location, allowComments) { @@ -49204,7 +49342,7 @@ var ts; } } function shouldHoistVariableDeclarationList(node) { - return (ts.getEmitFlags(node) & 1048576) === 0 + return (ts.getEmitFlags(node) & 2097152) === 0 && (enclosingBlockScopedContainer.kind === 265 || (ts.getOriginalNode(node).flags & 3) === 0); } @@ -49235,7 +49373,7 @@ var ts; return node; } function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 2097152) !== 0; + return (ts.getEmitFlags(node) & 4194304) !== 0; } function visitEndOfDeclarationMarker(node) { var id = ts.getOriginalNodeId(node); @@ -50032,7 +50170,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -50057,11 +50195,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -50465,8 +50603,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -50479,23 +50616,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -50505,12 +50649,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -50580,7 +50718,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -50905,7 +51043,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -50917,12 +51055,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -50936,7 +51068,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -50951,6 +51083,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -50958,15 +51103,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -50987,7 +51139,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -53001,7 +53153,7 @@ var ts; write("{}"); } else { - var indentedFlag = ts.getEmitFlags(node) & 32768; + var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } @@ -53016,7 +53168,7 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; - if (!(ts.getEmitFlags(node) & 65536)) { + if (!(ts.getEmitFlags(node) & 131072)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; var dotToken = { kind: 23, pos: dotRangeStart, end: dotRangeEnd }; @@ -53391,11 +53543,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = ts.getEmitFlags(node) & 32768; + var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } - if (ts.getEmitFlags(node) & 262144) { + if (ts.getEmitFlags(node) & 524288) { emitSignatureHead(node); if (onEmitNode) { onEmitNode(3, body, emitBlockCallback); @@ -53498,7 +53650,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = ts.getEmitFlags(node) & 32768; + var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } @@ -57635,7 +57787,7 @@ var ts; case 153: case 154: case 233: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180: return node.parent.argumentExpression === node; case 144: @@ -61079,7 +61231,7 @@ var ts; } } else { - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } @@ -61889,6 +62041,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { @@ -62144,8 +62299,8 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + var name = ts.forEach(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 && name.text; }); ts.Debug.assert(!!name); @@ -62797,7 +62952,7 @@ var ts; var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); if (!(flags & 134217728) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -63546,7 +63701,7 @@ var ts; } } function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { var sourceFile = name.getSourceFile(); @@ -64069,16 +64224,19 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144) { - return tryAddComputedPropertyName(declaration.name.expression, containers, true); - } - else { - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144) { + return tryAddComputedPropertyName(name.expression, containers, true); + } + else { + return false; + } } } return true; @@ -64102,8 +64260,9 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 144) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144) { + if (!tryAddComputedPropertyName(name.expression, containers, false)) { return undefined; } } @@ -64136,6 +64295,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -64144,8 +64304,8 @@ var ts; isCaseSensitive: rawItem.isCaseSensitive, fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -64359,8 +64519,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { return true; } @@ -64438,9 +64598,9 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186: @@ -64457,7 +64617,7 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -68085,7 +68245,7 @@ var ts; } case 149: case 146: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -70563,7 +70723,7 @@ var ts; return undefined; } var declaration = declarations[0]; - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -71051,13 +71211,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_7 = getTextOfIdentifierOrLiteral(name); if (result_7 !== undefined) { return result_7; } - if (declaration.name.kind === 144) { - var expr = declaration.name.expression; + if (name.kind === 144) { + var expr = name.expression; if (expr.kind === 179) { return expr.name.text; } @@ -72669,6 +72830,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations @@ -76291,7 +76455,7 @@ var ts; return MultistepOperation; }()); var Session = (function () { - function Session(opts) { + function Session(optsOrArg) { var _this = this; this.changeSeq = 0; this.handlers = ts.createMapFromTemplate((_a = {}, @@ -76532,6 +76696,24 @@ var ts; return _this.requiredResponse(_this.getSupportedCodeFixes()); }, _a)); + var opts; + if (arguments.length === 1) { + opts = optsOrArg; + } + else { + opts = { + host: arguments[0], + cancellationToken: arguments[1], + useSingleInferredProject: arguments[2], + typingsInstaller: arguments[3], + byteLength: arguments[4], + hrtime: arguments[5], + logger: arguments[6], + canUseEvents: arguments[7], + eventHandler: arguments[8], + throttleWaitMilliseconds: arguments[9] + }; + } this.host = opts.host; this.cancellationToken = opts.cancellationToken; this.typingsInstaller = opts.typingsInstaller; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 756d8e4d625..a002578c086 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -482,9 +482,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -495,7 +497,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -503,7 +505,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -516,7 +518,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -528,7 +530,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -537,7 +539,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -559,7 +561,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -581,7 +583,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -589,7 +591,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -926,7 +928,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1172,7 +1174,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1185,11 +1187,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1213,7 +1215,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1266,13 +1268,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1298,13 +1300,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1435,7 +1437,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -2195,14 +2197,15 @@ declare namespace ts { HelperName = 4096, ExportName = 8192, LocalName = 16384, - Indented = 32768, - NoIndentation = 65536, - AsyncFunctionBody = 131072, - ReuseTempVariableScope = 262144, - CustomPrologue = 524288, - NoHoisting = 1048576, - HasEndOfDeclarationMarker = 2097152, - Iterator = 4194304, + InternalName = 32768, + Indented = 65536, + NoIndentation = 131072, + AsyncFunctionBody = 262144, + ReuseTempVariableScope = 524288, + CustomPrologue = 1048576, + NoHoisting = 2097152, + HasEndOfDeclarationMarker = 4194304, + Iterator = 8388608, } interface EmitHelper { readonly name: string; @@ -2271,7 +2274,7 @@ declare namespace ts { } } declare namespace ts { - const version = "2.3.1"; + const version = "2.3.3"; } declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; @@ -4483,6 +4486,7 @@ declare namespace ts.server { protected logger: Logger; private canUseEvents; constructor(opts: SessionOptions); + constructor(host: ServerHost, cancellationToken: ServerCancellationToken, useSingleInferredProject: boolean, typingsInstaller: ITypingsInstaller, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: server.Logger, canUseEvents: boolean, eventHandler?: ProjectServiceEventHandler, throttleWaitMilliseconds?: number); private sendRequestCompletedEvent(requestId); private defaultEventHandler(event); logError(err: Error, cmd: string): void; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index d4c391f8d3a..9ea92256e2b 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -1002,14 +1002,15 @@ var ts; EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; - EmitFlags[EmitFlags["Indented"] = 32768] = "Indented"; - EmitFlags[EmitFlags["NoIndentation"] = 65536] = "NoIndentation"; - EmitFlags[EmitFlags["AsyncFunctionBody"] = 131072] = "AsyncFunctionBody"; - EmitFlags[EmitFlags["ReuseTempVariableScope"] = 262144] = "ReuseTempVariableScope"; - EmitFlags[EmitFlags["CustomPrologue"] = 524288] = "CustomPrologue"; - EmitFlags[EmitFlags["NoHoisting"] = 1048576] = "NoHoisting"; - EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 2097152] = "HasEndOfDeclarationMarker"; - EmitFlags[EmitFlags["Iterator"] = 4194304] = "Iterator"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1024,14 +1025,17 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1102,7 +1106,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.3.1"; + ts.version = "2.3.3"; })(ts || (ts = {})); (function (ts) { var Ternary; @@ -9517,6 +9521,36 @@ var ts; return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0: + case 2: + return undefined; + case 1: + if (lhs.kind === 71) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4: + case 5: + return lhs.name; + case 3: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 || node.kind === 8) && node.parent.kind === 144 && @@ -9658,12 +9692,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4; + } var flags = 0; switch (node.kind) { case 228: @@ -9708,7 +9743,8 @@ var ts; } ts.isStringOrNumericLiteral = isStringOrNumericLiteral; function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -12465,7 +12501,7 @@ var ts; var node = createSynthesizedNode(179); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); - setEmitFlags(node, 65536); + setEmitFlags(node, 131072); return node; } ts.createPropertyAccess = createPropertyAccess; @@ -14333,6 +14369,14 @@ var ts; function createExpressionForMethodDeclaration(method, receiver) { return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, undefined, undefined, method.parameters, undefined, method.body), method), method)), method), method)); } + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 | 32768); + } + ts.getInternalName = getInternalName; + function isInternalName(node) { + return (ts.getEmitFlags(node) & 32768) !== 0; + } + ts.isInternalName = isInternalName; function getLocalName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 16384); } @@ -14354,9 +14398,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48; if (!allowComments) @@ -14427,7 +14472,7 @@ var ts; var numStatements = source.length; while (statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 524288) { + if (ts.getEmitFlags(statement) & 1048576) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -20617,19 +20662,20 @@ var ts; } } function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144) { - var nameExpression = node.name.expression; + if (name.kind === 144) { + var nameExpression = name.expression; if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; } ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152: @@ -20725,9 +20771,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0, name); } } @@ -23639,16 +23685,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 || source.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -23759,7 +23805,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { @@ -24120,13 +24167,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 384) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -25336,8 +25383,9 @@ var ts; function getNameOfSymbol(symbol) { var declaration = ts.firstOrUndefined(symbol.declarations); if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -25418,8 +25466,9 @@ var ts; function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226) { return ts.declarationNameToString(declaration.parent.name); @@ -28248,8 +28297,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -30169,24 +30219,6 @@ var ts; } return 0; } - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - return true; - } - } - else if (type.flags & 196608) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768) && !(getObjectFlags(target) & 512)) { var isComparingJsxAttributes = !!(source.flags & 33554432); @@ -30635,23 +30667,34 @@ var ts; } var result = -1; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 && getObjectFlags(target) & 64 && source.symbol === target.symbol) { + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, undefined, undefined, kind)); + } + return 0; } - return 0; } return result; } @@ -31189,7 +31232,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152) { @@ -32741,7 +32784,7 @@ var ts; if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -33738,6 +33781,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -33755,6 +33802,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255); @@ -33764,31 +33814,34 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); - } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { - if (!filter || filter(attr)) { - attributesTable.set(attr.name, attr); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + attributesArray = []; + attributesTable = ts.createMap(); } - }); + attributesArray = getPropertiesOfType(spread); + } + attributesTable = ts.createMap(); + if (attributesArray) { + ts.forEach(attributesArray, function (attr) { + if (!filter || filter(attr)) { + attributesTable.set(attr.name, attr); + } + }); + } } var parent = openingLikeElement.parent.kind === 249 ? openingLikeElement.parent : undefined; if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) { @@ -33804,9 +33857,8 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } var childrenPropSymbol = createSymbol(4 | 134217728, jsxChildrenPropertyName); @@ -33816,11 +33868,15 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, undefined, undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576; - result.flags |= 33554432 | 4194304 | freshObjectLiteralFlag; + result.flags |= 33554432 | 4194304; result.objectFlags |= 128; return result; } @@ -33875,7 +33931,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(undefined, signature.typeParameters, 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), true); } function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer) { var jsxNamespace = getGlobalSymbol(JsxNames.JSX, 1920, undefined); @@ -33909,6 +33976,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } function defaultTryGetJsxStatelessFunctionAttributesType(openingLikeElement, elementType, elemInstanceType, elementClassType) { ts.Debug.assert(!(elementType.flags & 65536)); if (!elementClassType || !isTypeAssignableTo(elemInstanceType, elementClassType)) { @@ -33918,6 +33999,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); if (intrinsicAttributes !== unknownType) { @@ -33943,6 +34025,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -34146,6 +34229,24 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + return true; + } + } + else if (targetType.flags & 196608) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } function checkJsxAttributesAssignableToTagNameAttributes(openingLikeElement) { var targetAttributesType = isJsxIntrinsicIdentifier(openingLikeElement.tagName) ? getIntrinsicAttributesTypeFromJsxOpeningLikeElement(openingLikeElement) : @@ -34157,7 +34258,16 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -34496,8 +34606,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -35133,7 +35243,7 @@ var ts; } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } if (isTypeAny(expressionType)) { @@ -35469,10 +35579,10 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 || - parameter.valueDeclaration.name.kind === 175)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 || name.kind === 175)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -36356,12 +36466,12 @@ var ts; var func = ts.getContainingFunction(node); var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 4096); - } + if ((functionFlags & 3) === 3 && + languageVersion < 5) { + checkExternalEmitHelpers(node, 26624); } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + if ((functionFlags & 3) === 1 && + languageVersion < 2 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256); } } @@ -36754,17 +36864,14 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7) === 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 64); - if (languageVersion < 2) { - checkExternalEmitHelpers(node, 128); + if (!(functionFlags & 4)) { + if ((functionFlags & 3) === 3 && languageVersion < 5) { + checkExternalEmitHelpers(node, 6144); } - } - if ((functionFlags & 5) === 1) { - if (functionFlags & 2 && languageVersion < 4) { - checkExternalEmitHelpers(node, 2048); + if ((functionFlags & 3) === 2 && languageVersion < 4) { + checkExternalEmitHelpers(node, 64); } - else if (languageVersion < 2) { + if ((functionFlags & 3) !== 0 && languageVersion < 2) { checkExternalEmitHelpers(node, 128); } } @@ -36787,7 +36894,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5) === 1) { + if ((functionFlags_1 & (4 | 1)) === 1) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -36908,7 +37015,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -36982,7 +37089,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -37209,16 +37317,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 | 16)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -37229,7 +37337,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -37337,7 +37445,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && @@ -37350,8 +37458,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) { + var signature = signatures_5[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -37400,11 +37508,12 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -37766,15 +37875,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -37852,7 +37962,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -37914,7 +38024,7 @@ var ts; if (getNodeCheckFlags(current) & 4) { var isDeclaration_1 = node.kind !== 71; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -37928,7 +38038,7 @@ var ts; if (getNodeCheckFlags(current) & 8) { var isDeclaration_2 = node.kind !== 71; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -38124,7 +38234,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -38230,11 +38340,12 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216) { if (node.awaitModifier) { - if (languageVersion < 4) { - checkExternalEmitHelpers(node, 8192); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 | 2)) === 2 && languageVersion < 5) { + checkExternalEmitHelpers(node, 16384); } } - else if (languageVersion < 2 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2) { checkExternalEmitHelpers(node, 256); } } @@ -38684,11 +38795,14 @@ var ts; return; } var propDeclaration = prop.valueDeclaration; - if (indexKind === 1 && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 || + ts.getNameOfDeclaration(propDeclaration).kind === 144 || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -38962,7 +39076,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -39230,7 +39344,7 @@ var ts; if (enumSymbol.declarations.length > 1) { ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -40586,15 +40700,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -40673,7 +40778,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -40820,7 +40924,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1; helper <= 8192; helper <<= 1) { + for (var helper = 1; helper <= 16384; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455); @@ -40847,9 +40951,10 @@ var ts; case 256: return "__values"; case 512: return "__read"; case 1024: return "__spread"; - case 2048: return "__asyncGenerator"; - case 4096: return "__asyncDelegator"; - case 8192: return "__asyncValues"; + case 2048: return "__await"; + case 4096: return "__asyncGenerator"; + case 8192: return "__asyncDelegator"; + case 16384: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -43326,7 +43431,7 @@ var ts; } if (statements.length > 1) { statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 2097152); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304); } return ts.singleOrMany(statements); } @@ -43372,7 +43477,7 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - ts.setEmitFlags(classExpression, 32768 | ts.getEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -44210,13 +44315,13 @@ var ts; ts.setSourceMapRange(statement, node); } ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 | 2097152); + ts.setEmitFlags(statement, 1024 | 4194304); statements.push(statement); return true; } else { var mergeMarker = ts.createMergeDeclarationMarker(statement); - ts.setEmitFlags(mergeMarker, 1536 | 2097152); + ts.setEmitFlags(mergeMarker, 1536 | 4194304); statements.push(mergeMarker); return false; } @@ -44848,7 +44953,7 @@ var ts; function createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, body) { context.requestEmitHelper(awaiterHelper); var generatorFunc = ts.createFunctionExpression(undefined, ts.createToken(39), undefined, undefined, [], undefined, body); - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__awaiter"), undefined, [ ts.createThis(), hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(), @@ -44955,19 +45060,14 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), node), node); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1) { + if (enclosingFunctionFlags & 2 && enclosingFunctionFlags & 1 && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -45094,6 +45194,9 @@ var ts; } return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), true), bodyLocation), 48 | 384); } + function awaitAsYield(expression) { + return ts.createYield(undefined, enclosingFunctionFlags & 1 ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(undefined); @@ -45101,19 +45204,17 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(undefined); - var values = createAsyncValuesHelper(context, expression, node.expression); - var next = ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), - ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 1048576), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), node), 256); + ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152), ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), undefined, convertForOfStatementHead(node, awaitAsYield(getValue))), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -45122,12 +45223,7 @@ var ts; ]))) ]), 1)), ts.createBlock([ ts.createTry(ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield(undefined, enclosingFunctionFlags & 1 - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1) ]), undefined, ts.setEmitFlags(ts.createBlock([ ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1) ]), 1)) @@ -45252,7 +45348,7 @@ var ts; var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1, temp, false, true); if (ts.some(declarations)) { var statement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList(declarations)); - ts.setEmitFlags(statement, 524288); + ts.setEmitFlags(statement, 1048576); statements = ts.append(statements, statement); } } @@ -45359,14 +45455,24 @@ var ts; return ts.createCall(ts.getHelperName("__assign"), undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144; return ts.createCall(ts.getHelperName("__asyncGenerator"), undefined, [ ts.createThis(), ts.createIdentifier("arguments"), @@ -45376,11 +45482,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), undefined, [expression]), location); } var asyncValues = { @@ -46262,9 +46368,9 @@ var ts; statements.push(exportStatement); } var emitFlags = ts.getEmitFlags(node); - if ((emitFlags & 2097152) === 0) { + if ((emitFlags & 4194304) === 0) { statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(statement, emitFlags | 2097152); + ts.setEmitFlags(statement, emitFlags | 4194304); } return ts.singleOrMany(statements); } @@ -46277,8 +46383,8 @@ var ts; } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter(undefined, undefined, undefined, "_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (ts.getEmitFlags(node) & 32768) { - ts.setEmitFlags(classFunction, 32768); + if (ts.getEmitFlags(node) & 65536) { + ts.setEmitFlags(classFunction, 65536); } var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; @@ -46297,7 +46403,7 @@ var ts; addConstructor(statements, node, extendsClauseElement); addClassMembers(statements, node); var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18); - var localName = ts.getLocalName(node); + var localName = ts.getInternalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; ts.setEmitFlags(outer, 1536); @@ -46321,7 +46427,7 @@ var ts; var ancestorFacts = enterSubtree(16278, 73); var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, ts.getInternalName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); ts.setTextRange(constructorFunction, constructor || node); if (extendsClauseElement) { ts.setEmitFlags(constructorFunction, 8); @@ -46485,10 +46591,10 @@ var ts; function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); if (name.elements.length > 0) { - statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 524288)); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, temp))), 1048576)); } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 524288)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576)); } } function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { @@ -46498,7 +46604,7 @@ var ts; ]), parameter), 1 | 32 | 384)); statement.startsOnNewLine = true; ts.setTextRange(statement, parameter); - ts.setEmitFlags(statement, 384 | 32 | 524288); + ts.setEmitFlags(statement, 384 | 32 | 1048576); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { @@ -46516,7 +46622,7 @@ var ts; var temp = ts.createLoopVariable(); statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) - ])), parameter), 524288)); + ])), parameter), 1048576)); var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([ ts.createVariableDeclaration(temp, undefined, ts.createLiteral(restIndex)) ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([ @@ -46524,7 +46630,7 @@ var ts; ? temp : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), parameter)) ])); - ts.setEmitFlags(forStatement, 524288); + ts.setEmitFlags(forStatement, 1048576); ts.startOnNewLine(forStatement); statements.push(forStatement); } @@ -46538,7 +46644,7 @@ var ts; var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration("_this", undefined, initializer) ])); - ts.setEmitFlags(captureThisStatement, 1536 | 524288); + ts.setEmitFlags(captureThisStatement, 1536 | 1048576); ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); @@ -46678,7 +46784,7 @@ var ts; return func; } function visitFunctionExpression(node) { - var ancestorFacts = ts.getEmitFlags(node) & 131072 + var ancestorFacts = ts.getEmitFlags(node) & 262144 ? enterSubtree(16278, 69) : enterSubtree(16286, 65); var savedConvertedLoopState = convertedLoopState; @@ -47027,7 +47133,7 @@ var ts; var forStatement = ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), ts.setTextRange(ts.createVariableDeclaration(rhsReference, undefined, expression), node.expression) - ]), node.expression), 1048576), ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), node); + ]), node.expression), 2097152), ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), node); ts.setEmitFlags(forStatement, 256); ts.setTextRange(forStatement, node); return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel); @@ -47046,7 +47152,7 @@ var ts; var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(iterator, undefined, values), node.expression), ts.createVariableDeclaration(result, undefined, next) - ]), node.expression), 1048576), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), node), 256); + ]), node.expression), 2097152), ts.createLogicalNot(ts.createPropertyAccess(result, "done")), ts.createAssignment(result, next), convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), node), 256); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel) ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([ @@ -47083,7 +47189,7 @@ var ts; } var temp = ts.createTempVariable(hoistVariableDeclaration); var expressions = []; - var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 32768)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -47190,11 +47296,11 @@ var ts; loopBodyFlags |= 8; } if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 131072; + loopBodyFlags |= 262144; } var convertedLoopVariable = ts.createVariableStatement(undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(undefined, containsYield ? ts.createToken(39) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) - ]), 1048576)); + ]), 2097152)); var statements = [convertedLoopVariable]; var extraVariableDeclarations; if (currentState.argumentsName) { @@ -47275,7 +47381,7 @@ var ts; !state.labeledNonLocalContinues; var call = ts.createCall(loopFunctionExpressionName, undefined, ts.map(parameters, function (p) { return p.name; })); var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 4194304)) + ? ts.createYield(ts.createToken(39), ts.setEmitFlags(call, 8388608)) : call; if (isSimpleLoop) { statements.push(ts.createStatement(callResult)); @@ -47446,7 +47552,20 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286, 65); - var updated = ts.visitEachChild(node, visitor, context); + var updated; + if (node.transformFlags & 32768) { + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = transformFunctionBody(node); + if (node.kind === 153) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + } + else { + updated = ts.visitEachChild(node, visitor, context); + } exitSubtree(ancestorFacts, 49152, 0); convertedLoopState = savedConvertedLoopState; return updated; @@ -47689,7 +47808,7 @@ var ts; return node; } function substituteIdentifier(node) { - if (enabledSubstitutions & 2) { + if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var original = ts.getParseTreeNode(node, ts.isIdentifier); if (original && isNameOfDeclarationWithCollidingName(original)) { return ts.setTextRange(ts.getGeneratedNameForNode(original), node); @@ -47719,14 +47838,32 @@ var ts; return node; } function substituteExpressionIdentifier(node) { - if (enabledSubstitutions & 2) { + if (enabledSubstitutions & 2 && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; } + function isPartOfClassBody(declaration, node) { + var currentNode = ts.getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + return false; + } + var blockScope = ts.getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + return false; + } + if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { + return currentNode.kind !== 149 + || (ts.getModifierFlags(currentNode) & 32) === 0; + } + currentNode = currentNode.parent; + } + return false; + } function substituteThisKeyword(node) { if (enabledSubstitutions & 1 && hierarchyFacts & 16) { @@ -47735,8 +47872,9 @@ var ts; return node; } function getClassMemberPrefix(node, member) { - var expression = ts.getLocalName(node); - return ts.hasModifier(member, 32) ? expression : ts.createPropertyAccess(expression, "prototype"); + return ts.hasModifier(member, 32) + ? ts.getInternalName(node) + : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); } function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { if (!constructor || !hasExtendsClause) { @@ -48080,7 +48218,7 @@ var ts; return undefined; } else { - if (ts.getEmitFlags(node) & 524288) { + if (ts.getEmitFlags(node) & 1048576) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -48216,7 +48354,7 @@ var ts; var resumeLabel = defineLabel(); var expression = ts.visitNode(node.expression, visitor, ts.isExpression); if (node.asteriskToken) { - var iterator = (ts.getEmitFlags(node.expression) & 4194304) === 0 + var iterator = (ts.getEmitFlags(node.expression) & 8388608) === 0 ? ts.createValuesHelper(context, expression, node) : expression; emitYieldStar(iterator, node); @@ -49181,7 +49319,7 @@ var ts; currentExceptionBlock = undefined; withBlockStack = undefined; var buildResult = buildStatements(); - return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, state)], undefined, ts.createBlock(buildResult, buildResult.length > 0)), 262144)); + return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ts.createParameter(undefined, undefined, undefined, state)], undefined, ts.createBlock(buildResult, buildResult.length > 0)), 524288)); } function buildStatements() { if (operations) { @@ -49928,7 +50066,7 @@ var ts; return node; } function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 2097152) !== 0; + return (ts.getEmitFlags(node) & 4194304) !== 0; } function visitEndOfDeclarationMarker(node) { var id = ts.getOriginalNodeId(node); @@ -50041,7 +50179,7 @@ var ts; ]) ])); } - ts.setEmitFlags(statement, 524288); + ts.setEmitFlags(statement, 1048576); return statement; } function createExportStatement(name, value, location, allowComments) { @@ -50550,7 +50688,7 @@ var ts; } } function shouldHoistVariableDeclarationList(node) { - return (ts.getEmitFlags(node) & 1048576) === 0 + return (ts.getEmitFlags(node) & 2097152) === 0 && (enclosingBlockScopedContainer.kind === 265 || (ts.getOriginalNode(node).flags & 3) === 0); } @@ -50581,7 +50719,7 @@ var ts; return node; } function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 2097152) !== 0; + return (ts.getEmitFlags(node) & 4194304) !== 0; } function visitEndOfDeclarationMarker(node) { var id = ts.getOriginalNodeId(node); @@ -51378,7 +51516,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; var referencesOutput = ""; @@ -51403,11 +51541,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -51811,8 +51949,7 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -51825,23 +51962,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 | 1024, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -51851,12 +51995,6 @@ var ts; var nodes = resolver.collectLinkedAliases(node.expression); writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -51926,7 +52064,7 @@ var ts; if (modifiers & 512) { write("default "); } - else if (node.kind !== 230 && !noDeclare) { + else if (node.kind !== 230 && needsDeclare) { write("declare "); } } @@ -52251,7 +52389,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -52263,12 +52401,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; if (node.parent.parent.kind === 229) { @@ -52282,7 +52414,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -52297,6 +52429,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128)) { @@ -52304,15 +52449,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), true); write(" {"); writeLine(); increaseIndent(); @@ -52333,7 +52485,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, false); + emitHeritageClause(interfaceExtendsTypes, false); } write(" {"); writeLine(); @@ -54347,7 +54499,7 @@ var ts; write("{}"); } else { - var indentedFlag = ts.getEmitFlags(node) & 32768; + var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } @@ -54362,7 +54514,7 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; - if (!(ts.getEmitFlags(node) & 65536)) { + if (!(ts.getEmitFlags(node) & 131072)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; var dotToken = { kind: 23, pos: dotRangeStart, end: dotRangeEnd }; @@ -54737,11 +54889,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = ts.getEmitFlags(node) & 32768; + var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } - if (ts.getEmitFlags(node) & 262144) { + if (ts.getEmitFlags(node) & 524288) { emitSignatureHead(node); if (onEmitNode) { onEmitNode(3, body, emitBlockCallback); @@ -54844,7 +54996,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = ts.getEmitFlags(node) & 32768; + var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } @@ -57635,7 +57787,7 @@ var ts; case 153: case 154: case 233: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180: return node.parent.argumentExpression === node; case 144: @@ -61079,7 +61231,7 @@ var ts; } } else { - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } @@ -61889,6 +62041,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240) { @@ -62144,8 +62299,8 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + var name = ts.forEach(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 && name.text; }); ts.Debug.assert(!!name); @@ -62797,7 +62952,7 @@ var ts; var flags = _a.flags, valueDeclaration = _a.valueDeclaration; var shorthandValueSymbol = state.checker.getShorthandAssignmentValueSymbol(valueDeclaration); if (!(flags & 134217728) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -63546,7 +63701,7 @@ var ts; } } function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { var sourceFile = name.getSourceFile(); @@ -64069,16 +64224,19 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144) { - return tryAddComputedPropertyName(declaration.name.expression, containers, true); - } - else { - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144) { + return tryAddComputedPropertyName(name.expression, containers, true); + } + else { + return false; + } } } return true; @@ -64102,8 +64260,9 @@ var ts; } function getContainers(declaration) { var containers = []; - if (declaration.name.kind === 144) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144) { + if (!tryAddComputedPropertyName(name.expression, containers, false)) { return undefined; } } @@ -64136,6 +64295,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -64144,8 +64304,8 @@ var ts; isCaseSensitive: rawItem.isCaseSensitive, fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -64359,8 +64519,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { return true; } @@ -64438,9 +64598,9 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186: @@ -64457,7 +64617,7 @@ var ts; if (node.kind === 233) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -68085,7 +68245,7 @@ var ts; } case 149: case 146: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -70563,7 +70723,7 @@ var ts; return undefined; } var declaration = declarations[0]; - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -71051,13 +71211,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_7 = getTextOfIdentifierOrLiteral(name); if (result_7 !== undefined) { return result_7; } - if (declaration.name.kind === 144) { - var expr = declaration.name.expression; + if (name.kind === 144) { + var expr = name.expression; if (expr.kind === 179) { return expr.name.text; } @@ -72610,7 +72771,7 @@ var ts; return MultistepOperation; }()); var Session = (function () { - function Session(opts) { + function Session(optsOrArg) { var _this = this; this.changeSeq = 0; this.handlers = ts.createMapFromTemplate((_a = {}, @@ -72851,6 +73012,24 @@ var ts; return _this.requiredResponse(_this.getSupportedCodeFixes()); }, _a)); + var opts; + if (arguments.length === 1) { + opts = optsOrArg; + } + else { + opts = { + host: arguments[0], + cancellationToken: arguments[1], + useSingleInferredProject: arguments[2], + typingsInstaller: arguments[3], + byteLength: arguments[4], + hrtime: arguments[5], + logger: arguments[6], + canUseEvents: arguments[7], + eventHandler: arguments[8], + throttleWaitMilliseconds: arguments[9] + }; + } this.host = opts.host; this.cancellationToken = opts.cancellationToken; this.typingsInstaller = opts.typingsInstaller; @@ -78364,6 +78543,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index ee2e3241196..75b1947e355 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -491,9 +491,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -504,7 +506,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -512,7 +514,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -525,7 +527,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -537,7 +539,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -546,7 +548,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -568,7 +570,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -590,7 +592,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -598,7 +600,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -950,7 +952,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1197,7 +1199,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1210,11 +1212,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1238,7 +1240,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1297,13 +1299,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1330,13 +1332,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1467,7 +1469,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -2320,14 +2322,15 @@ declare namespace ts { HelperName = 4096, ExportName = 8192, LocalName = 16384, - Indented = 32768, - NoIndentation = 65536, - AsyncFunctionBody = 131072, - ReuseTempVariableScope = 262144, - CustomPrologue = 524288, - NoHoisting = 1048576, - HasEndOfDeclarationMarker = 2097152, - Iterator = 4194304, + InternalName = 32768, + Indented = 65536, + NoIndentation = 131072, + AsyncFunctionBody = 262144, + ReuseTempVariableScope = 524288, + CustomPrologue = 1048576, + NoHoisting = 2097152, + HasEndOfDeclarationMarker = 4194304, + Iterator = 8388608, } interface EmitHelper { readonly name: string; @@ -2515,7 +2518,7 @@ declare namespace ts { } declare namespace ts { /** The version of the TypeScript compiler release */ - const version = "2.3.1"; + const version = "2.3.3"; } 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 ee99953790c..b06a1d92700 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -1110,14 +1110,15 @@ var ts; EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; - EmitFlags[EmitFlags["Indented"] = 32768] = "Indented"; - EmitFlags[EmitFlags["NoIndentation"] = 65536] = "NoIndentation"; - EmitFlags[EmitFlags["AsyncFunctionBody"] = 131072] = "AsyncFunctionBody"; - EmitFlags[EmitFlags["ReuseTempVariableScope"] = 262144] = "ReuseTempVariableScope"; - EmitFlags[EmitFlags["CustomPrologue"] = 524288] = "CustomPrologue"; - EmitFlags[EmitFlags["NoHoisting"] = 1048576] = "NoHoisting"; - EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 2097152] = "HasEndOfDeclarationMarker"; - EmitFlags[EmitFlags["Iterator"] = 4194304] = "Iterator"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1137,17 +1138,22 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1256,7 +1262,7 @@ var ts; var ts; (function (ts) { /** The version of the TypeScript compiler release */ - ts.version = "2.3.1"; + ts.version = "2.3.3"; })(ts || (ts = {})); /* @internal */ (function (ts) { @@ -8243,6 +8249,36 @@ var ts; return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194 /* BinaryExpression */) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0 /* None */: + case 2 /* ModuleExports */: + return undefined; + case 1 /* ExportsProperty */: + if (lhs.kind === 71 /* Identifier */) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4 /* ThisProperty */: + case 5 /* Property */: + return lhs.name; + case 3 /* PrototypeProperty */: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 144 /* ComputedPropertyName */ && @@ -8397,12 +8433,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } var flags = 0 /* Normal */; switch (node.kind) { case 228 /* FunctionDeclaration */: @@ -8455,7 +8492,8 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -11582,7 +11620,7 @@ var ts; var node = createSynthesizedNode(179 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); - setEmitFlags(node, 65536 /* NoIndentation */); + setEmitFlags(node, 131072 /* NoIndentation */); return node; } ts.createPropertyAccess = createPropertyAccess; @@ -13595,6 +13633,28 @@ var ts; /*location*/ method), /*original*/ method)); } + /** + * Gets the internal name of a declaration. This is primarily used for declarations that can be + * referred to by name in the body of an ES5 class function body. An internal name will *never* + * be prefixed with an module or namespace export modifier like "exports." when emitted as an + * expression. An internal name will also *never* be renamed due to a collision with a block + * scoped variable. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */); + } + ts.getInternalName = getInternalName; + /** + * Gets whether an identifier should only be referred to by its internal name. + */ + function isInternalName(node) { + return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0; + } + ts.isInternalName = isInternalName; /** * Gets the local name of a declaration. This is primarily used for declarations that can be * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A @@ -13650,9 +13710,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -13765,7 +13826,7 @@ var ts; var numStatements = source.length; while (statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 524288 /* CustomPrologue */) { + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -21481,12 +21542,13 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -21494,7 +21556,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152 /* Constructor */: @@ -21638,9 +21700,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -25936,16 +25998,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -26073,7 +26135,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { // nodes are in different files and order cannot be determined return true; } @@ -26537,13 +26600,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 384 /* Enum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -27919,8 +27982,9 @@ var ts; function getNameOfSymbol(symbol) { var declaration = ts.firstOrUndefined(symbol.declarations); if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -28001,8 +28065,9 @@ var ts; function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -31193,8 +31258,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -33321,29 +33387,6 @@ var ts; } return 0 /* False */; } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. - return true; - } - } - else if (type.flags & 196608 /* UnionOrIntersection */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); @@ -33844,24 +33887,38 @@ var ts; } var result = -1 /* True */; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - // Only elaborate errors from the first failure - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We instantiations of the same anonymous type (which typically will be the type of a method). + // Simply do a pairwise comparison of the signatures in the two signature lists instead of the + // much more expensive N * M comparison matrix we explore below. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0 /* False */; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; } - return 0 /* False */; } return result; } @@ -34480,7 +34537,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { @@ -36260,7 +36317,7 @@ var ts; if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -37537,6 +37594,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -37554,6 +37615,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); @@ -37563,31 +37627,34 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); - } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { - if (!filter || filter(attr)) { - attributesTable.set(attr.name, attr); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + attributesArray = []; + attributesTable = ts.createMap(); } - }); + attributesArray = getPropertiesOfType(spread); + } + attributesTable = ts.createMap(); + if (attributesArray) { + ts.forEach(attributesArray, function (attr) { + if (!filter || filter(attr)) { + attributesTable.set(attr.name, attr); + } + }); + } } // Handle children attribute var parent = openingLikeElement.parent.kind === 249 /* JsxElement */ ? openingLikeElement.parent : undefined; @@ -37607,11 +37674,11 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - // Error if there is a attribute named "children" and children element. - // This is because children element will overwrite the value from attributes - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process @@ -37622,7 +37689,12 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -37630,8 +37702,7 @@ var ts; */ function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag; + result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; } @@ -37709,7 +37780,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -37761,6 +37843,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072 /* Intersection */) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } /** * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. * Return only attributes type of successfully resolved call signature. @@ -37781,6 +37877,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -37819,6 +37916,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -38093,6 +38191,34 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if the object type is empty and the check is for assignability, if the object type has + * index signatures, or if the property is actually declared in the object type. In a union or intersection + * type, a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 196608 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" @@ -38121,7 +38247,20 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -38520,8 +38659,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -39450,7 +39589,7 @@ var ts; // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128 /* Abstract */) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } // TS 1.0 spec: 4.11 @@ -39861,11 +40000,11 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 /* ObjectBindingPattern */ || - parameter.valueDeclaration.name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -39996,7 +40135,7 @@ var ts; // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + return (functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? createPromiseReturnType(func, widenedType) // Async function : widenedType; // Generator function, AsyncGenerator function, or normal function } @@ -40192,7 +40331,7 @@ var ts; ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = node.type && - ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ ? + ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function if ((functionFlags & 1 /* Generator */) === 0) { @@ -40219,7 +40358,7 @@ var ts; // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -40902,12 +41041,15 @@ var ts; // we are in a yield context. var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2 /* Async */) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 4096 /* AsyncDelegator */); - } + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256 /* Values */); } } @@ -41365,17 +41507,18 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7 /* InvalidAsyncOrAsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 64 /* Awaiter */); - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(node, 128 /* Generator */); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } - } - if ((functionFlags & 5 /* InvalidGenerator */) === 1 /* Generator */) { - if (functionFlags & 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 2048 /* AsyncGenerator */); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); } - else if (languageVersion < 2 /* ES2015 */) { + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 128 /* Generator */); } } @@ -41398,7 +41541,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5 /* InvalidGenerator */) === 1 /* Generator */) { + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -41417,7 +41560,7 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } - else if ((functionFlags_1 & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { checkAsyncFunctionReturnType(node); } } @@ -41536,7 +41679,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -41624,7 +41767,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -41884,16 +42028,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1 /* Export */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2 /* Ambient */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 /* Private */ | 16 /* Protected */)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128 /* Abstract */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -41904,7 +42048,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -42028,7 +42172,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -42042,8 +42186,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) { + var signature = signatures_5[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -42101,12 +42245,13 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -42612,15 +42757,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146 /* Parameter */) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -42700,7 +42846,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -42768,7 +42914,7 @@ var ts; if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { var isDeclaration_1 = node.kind !== 71 /* Identifier */; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -42782,7 +42928,7 @@ var ts; if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { var isDeclaration_2 = node.kind !== 71 /* Identifier */; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -43048,7 +43194,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -43163,11 +43309,14 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216 /* ForOfStatement */) { if (node.awaitModifier) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 8192 /* ForAwaitOfIncludes */); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 5 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); } } @@ -43550,7 +43699,7 @@ var ts; return !!(node.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); @@ -43772,13 +43921,16 @@ var ts; } var propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } // perform property check if property or indexer is declared in 'type' - // this allows to rule out cases when both property and indexer are inherited from the base class + // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -44101,7 +44253,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -44396,7 +44548,7 @@ var ts; // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -45963,15 +46115,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -46057,7 +46200,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -46225,7 +46367,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1 /* FirstEmitHelper */; helper <= 8192 /* LastEmitHelper */; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 16384 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455 /* Value */); @@ -46252,9 +46394,10 @@ var ts; case 256 /* Values */: return "__values"; case 512 /* Read */: return "__read"; case 1024 /* Spread */: return "__spread"; - case 2048 /* AsyncGenerator */: return "__asyncGenerator"; - case 4096 /* AsyncDelegator */: return "__asyncDelegator"; - case 8192 /* AsyncValues */: return "__asyncValues"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -49214,7 +49357,7 @@ var ts; if (statements.length > 1) { // Add a DeclarationMarker as a marker for the end of the declaration statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 2097152 /* HasEndOfDeclarationMarker */); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */); } return ts.singleOrMany(statements); } @@ -49390,7 +49533,7 @@ var ts; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. - ts.setEmitFlags(classExpression, 32768 /* Indented */ | ts.getEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -50868,7 +51011,7 @@ var ts; // })(m1 || (m1 = {})); // trailing comment module // ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 2097152 /* HasEndOfDeclarationMarker */); + ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); statements.push(statement); return true; } @@ -50878,7 +51021,7 @@ var ts; // begin/end semantics of the declararation and to properly handle exports // we wrap the leading variable declaration in a `MergeDeclarationMarker`. var mergeMarker = ts.createMergeDeclarationMarker(statement); - ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 2097152 /* HasEndOfDeclarationMarker */); + ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */); statements.push(mergeMarker); return false; } @@ -51816,7 +51959,7 @@ var ts; /*parameters*/ [], /*type*/ undefined, body); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; return ts.createCall(ts.getHelperName("__awaiter"), /*typeArguments*/ undefined, [ ts.createThis(), @@ -51929,21 +52072,15 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield( - /*asteriskToken*/ undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -52093,6 +52230,9 @@ var ts; return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } + function awaitAsYield(expression) { + return ts.createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -52100,24 +52240,21 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); - var values = createAsyncValuesHelper(context, expression, /*location*/ node.expression); - var next = ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), - ts.createVariableDeclaration(result, /*type*/ undefined, next) - ]), node.expression), 1048576 /* NoHoisting */), - /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), - /*incrementor*/ ts.createAssignment(result, next), - /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -52128,13 +52265,7 @@ var ts; ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -52290,7 +52421,7 @@ var ts; if (ts.some(declarations)) { var statement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations)); - ts.setEmitFlags(statement, 524288 /* CustomPrologue */); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); statements = ts.append(statements, statement); } } @@ -52420,15 +52551,25 @@ var ts; /*typeArguments*/ undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; return ts.createCall(ts.getHelperName("__asyncGenerator"), /*typeArguments*/ undefined, [ ts.createThis(), @@ -52439,11 +52580,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), /*typeArguments*/ undefined, [expression]), location); } @@ -53483,10 +53624,10 @@ var ts; statements.push(exportStatement); } var emitFlags = ts.getEmitFlags(node); - if ((emitFlags & 2097152 /* HasEndOfDeclarationMarker */) === 0) { + if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) { // Add a DeclarationMarker as a marker for the end of the declaration statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(statement, emitFlags | 2097152 /* HasEndOfDeclarationMarker */); + ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */); } return ts.singleOrMany(statements); } @@ -53548,8 +53689,8 @@ var ts; // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier // transformation. - if (ts.getEmitFlags(node) & 32768 /* Indented */) { - ts.setEmitFlags(classFunction, 32768 /* Indented */); + if (ts.getEmitFlags(node) & 65536 /* Indented */) { + ts.setEmitFlags(classFunction, 65536 /* Indented */); } // "inner" and "outer" below are added purely to preserve source map locations from // the old emitter @@ -53578,7 +53719,7 @@ var ts; addClassMembers(statements, node); // Create a synthetic text range for the return statement. var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18 /* CloseBraceToken */); - var localName = ts.getLocalName(node); + var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. var outer = ts.createPartiallyEmittedExpression(localName); @@ -53622,7 +53763,7 @@ var ts; var constructorFunction = ts.createFunctionDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, - /*asteriskToken*/ undefined, ts.getDeclarationName(node), + /*asteriskToken*/ undefined, ts.getInternalName(node), /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); ts.setTextRange(constructorFunction, constructor || node); @@ -53912,10 +54053,10 @@ var ts; // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { statements.push(ts.setEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 524288 /* CustomPrologue */)); + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 524288 /* CustomPrologue */)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); } } /** @@ -53933,7 +54074,7 @@ var ts; ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */)); statement.startsOnNewLine = true; ts.setTextRange(statement, parameter); - ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 524288 /* CustomPrologue */); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */); statements.push(statement); } /** @@ -53974,7 +54115,7 @@ var ts; ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) ])), - /*location*/ parameter), 524288 /* CustomPrologue */)); + /*location*/ parameter), 1048576 /* CustomPrologue */)); // for (var _i = restIndex; _i < arguments.length; _i++) { // param[_i - restIndex] = arguments[_i]; // } @@ -53986,7 +54127,7 @@ var ts; : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), /*location*/ parameter)) ])); - ts.setEmitFlags(forStatement, 524288 /* CustomPrologue */); + ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); } @@ -54008,7 +54149,7 @@ var ts; ts.createVariableDeclaration("_this", /*type*/ undefined, initializer) ])); - ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 524288 /* CustomPrologue */); + ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); @@ -54212,7 +54353,7 @@ var ts; * @param node a FunctionExpression node. */ function visitFunctionExpression(node) { - var ancestorFacts = ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */ + var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var savedConvertedLoopState = convertedLoopState; @@ -54736,7 +54877,7 @@ var ts; /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression) - ]), node.expression), 1048576 /* NoHoisting */), + ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), @@ -54761,7 +54902,7 @@ var ts; /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), ts.createVariableDeclaration(result, /*type*/ undefined, next) - ]), node.expression), 1048576 /* NoHoisting */), + ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), /*incrementor*/ ts.createAssignment(result, next), /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), @@ -54816,7 +54957,7 @@ var ts; var temp = ts.createTempVariable(hoistVariableDeclaration); // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. var expressions = []; - var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 32768 /* Indented */)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -54940,7 +55081,7 @@ var ts; loopBodyFlags |= 8 /* CapturesThis */; } if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 131072 /* AsyncFunctionBody */; + loopBodyFlags |= 262144 /* AsyncFunctionBody */; } var convertedLoopVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ @@ -54950,7 +55091,7 @@ var ts; /*name*/ undefined, /*typeParameters*/ undefined, loopParameters, /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 1048576 /* NoHoisting */)); + ]), 2097152 /* NoHoisting */)); var statements = [convertedLoopVariable]; var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary @@ -55056,7 +55197,7 @@ var ts; !state.labeledNonLocalContinues; var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 4194304 /* Iterator */)) + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createStatement(callResult)); @@ -55276,7 +55417,20 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); - var updated = ts.visitEachChild(node, visitor, context); + var updated; + if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) { + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = transformFunctionBody(node); + if (node.kind === 153 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + } + else { + updated = ts.visitEachChild(node, visitor, context); + } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return updated; @@ -55721,7 +55875,7 @@ var ts; function substituteIdentifier(node) { // Only substitute the identifier if we have enabled substitutions for block-scoped // bindings. - if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var original = ts.getParseTreeNode(node, ts.isIdentifier); if (original && isNameOfDeclarationWithCollidingName(original)) { return ts.setTextRange(ts.getGeneratedNameForNode(original), node); @@ -55767,14 +55921,39 @@ var ts; * @param node An Identifier node. */ function substituteExpressionIdentifier(node) { - if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; } + function isPartOfClassBody(declaration, node) { + var currentNode = ts.getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + // if the node has no correlation to a parse tree node, its definitely not + // part of the body. + // if the node is outside of the document range of the declaration, its + // definitely not part of the body. + return false; + } + var blockScope = ts.getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + // if we are in the enclosing block scope of the declaration, we are definitely + // not inside the class body. + return false; + } + if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { + // we are in the class body, but we treat static fields as outside of the class body + return currentNode.kind !== 149 /* PropertyDeclaration */ + || (ts.getModifierFlags(currentNode) & 32 /* Static */) === 0; + } + currentNode = currentNode.parent; + } + return false; + } /** * Substitutes `this` when contained within an arrow function. * @@ -55788,8 +55967,9 @@ var ts; return node; } function getClassMemberPrefix(node, member) { - var expression = ts.getLocalName(node); - return ts.hasModifier(member, 32 /* Static */) ? expression : ts.createPropertyAccess(expression, "prototype"); + return ts.hasModifier(member, 32 /* Static */) + ? ts.getInternalName(node) + : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); } function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { if (!constructor || !hasExtendsClause) { @@ -56470,7 +56650,7 @@ var ts; } else { // Do not hoist custom prologues. - if (ts.getEmitFlags(node) & 524288 /* CustomPrologue */) { + if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -56728,7 +56908,7 @@ var ts; var resumeLabel = defineLabel(); var expression = ts.visitNode(node.expression, visitor, ts.isExpression); if (node.asteriskToken) { - var iterator = (ts.getEmitFlags(node.expression) & 4194304 /* Iterator */) === 0 + var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 ? ts.createValuesHelper(context, expression, /*location*/ node) : expression; emitYieldStar(iterator, /*location*/ node); @@ -58148,7 +58328,7 @@ var ts; /*name*/ undefined, /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], /*type*/ undefined, ts.createBlock(buildResult, - /*multiLine*/ buildResult.length > 0)), 262144 /* ReuseTempVariableScope */)); + /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */)); } /** * Builds the statements for the generator function body. @@ -59243,7 +59423,7 @@ var ts; * @param node The node to test. */ function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 2097152 /* HasEndOfDeclarationMarker */) !== 0; + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; } /** * Visits a DeclarationMarker used as a placeholder for the end of a transformed @@ -59431,7 +59611,7 @@ var ts; ]) ])); } - ts.setEmitFlags(statement, 524288 /* CustomPrologue */); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); return statement; } /** @@ -60281,7 +60461,7 @@ var ts; */ function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file - return (ts.getEmitFlags(node) & 1048576 /* NoHoisting */) === 0 + return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 && (enclosingBlockScopedContainer.kind === 265 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } @@ -60359,7 +60539,7 @@ var ts; * @param node The node to test. */ function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 2097152 /* HasEndOfDeclarationMarker */) !== 0; + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; } /** * Visits a DeclarationMarker used as a placeholder for the end of a transformed @@ -62279,7 +62459,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. @@ -62315,11 +62495,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -62746,12 +62926,11 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComents*/ true); emitLines(node.statements); } - // Return a temp variable name to be used in `export default` statements. + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. // The temp name will be of the form _default_counter. // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -62764,24 +62943,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - // Expression - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -62793,12 +62978,6 @@ var ts; // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -62871,7 +63050,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 230 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 230 /* InterfaceDeclaration */ && needsDeclare) { write("declare "); } } @@ -63207,7 +63386,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -63219,12 +63398,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named @@ -63241,7 +63414,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -63256,6 +63429,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233 /* ModuleDeclaration */; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128 /* Abstract */)) { @@ -63263,15 +63449,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -63292,7 +63485,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); @@ -64864,7 +65057,7 @@ var ts; write("{}"); } else { - var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -64879,7 +65072,7 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; - if (!(ts.getEmitFlags(node) & 65536 /* NoIndentation */)) { + if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; var dotToken = { kind: 23 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; @@ -65281,11 +65474,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } - if (ts.getEmitFlags(node) & 262144 /* ReuseTempVariableScope */) { + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { emitSignatureHead(node); if (onEmitNode) { onEmitNode(3 /* Unspecified */, body, emitBlockCallback); @@ -65395,7 +65588,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -70143,7 +70336,7 @@ var ts; case 153 /* GetAccessor */: case 154 /* SetAccessor */: case 233 /* ModuleDeclaration */: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180 /* ElementAccessExpression */: return node.parent.argumentExpression === node; case 144 /* ComputedPropertyName */: @@ -73692,7 +73885,7 @@ var ts; // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } @@ -74595,6 +74788,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { @@ -74885,8 +75081,8 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + var name = ts.forEach(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.text; }); ts.Debug.assert(!!name); @@ -75640,7 +75836,7 @@ var ts; * position of property accessing, the referenceEntry of such position will be handled in the first case. */ if (!(flags & 134217728 /* Transient */) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -76565,7 +76761,7 @@ var ts; } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { @@ -77203,17 +77399,20 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; + } } } return true; @@ -77242,8 +77441,9 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -77281,6 +77481,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -77290,8 +77491,8 @@ var ts; fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -77543,8 +77744,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. return true; @@ -77633,9 +77834,9 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186 /* FunctionExpression */: @@ -77652,7 +77853,7 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -82073,7 +82274,7 @@ var ts; // falls through case 149 /* PropertyDeclaration */: case 146 /* Parameter */: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -84912,7 +85113,7 @@ var ts; } var declaration = declarations[0]; // Clone name to remove leading trivia. - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -85473,13 +85674,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_7 = getTextOfIdentifierOrLiteral(name); if (result_7 !== undefined) { return result_7; } - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - var expr = declaration.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var expr = name.expression; if (expr.kind === 179 /* PropertyAccessExpression */) { return expr.name.text; } @@ -88032,6 +88234,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index e6dab7293ab..22a06d46f97 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -491,9 +491,11 @@ declare namespace ts { type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern; interface Declaration extends Node { _declarationBrand: any; + } + interface NamedDeclaration extends Declaration { name?: DeclarationName; } - interface DeclarationStatement extends Declaration, Statement { + interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { @@ -504,7 +506,7 @@ declare namespace ts { kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } - interface TypeParameterDeclaration extends Declaration { + interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -512,7 +514,7 @@ declare namespace ts { default?: TypeNode; expression?: Expression; } - interface SignatureDeclaration extends Declaration { + interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -525,7 +527,7 @@ declare namespace ts { kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; - interface VariableDeclaration extends Declaration { + interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; @@ -537,7 +539,7 @@ declare namespace ts { parent?: VariableStatement | ForStatement | ForOfStatement | ForInStatement; declarations: NodeArray; } - interface ParameterDeclaration extends Declaration { + interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; @@ -546,7 +548,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface BindingElement extends Declaration { + interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; @@ -568,7 +570,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface ObjectLiteralElement extends Declaration { + interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -590,7 +592,7 @@ declare namespace ts { kind: SyntaxKind.SpreadAssignment; expression: Expression; } - interface VariableLikeDeclaration extends Declaration { + interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -598,7 +600,7 @@ declare namespace ts { type?: TypeNode; initializer?: Expression; } - interface PropertyLikeDeclaration extends Declaration { + interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } interface ObjectBindingPattern extends Node { @@ -950,7 +952,7 @@ declare namespace ts { } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - interface PropertyAccessExpression extends MemberExpression, Declaration { + interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1197,7 +1199,7 @@ declare namespace ts { block: Block; } type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - interface ClassLikeDeclaration extends Declaration { + interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1210,11 +1212,11 @@ declare namespace ts { interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { kind: SyntaxKind.ClassExpression; } - interface ClassElement extends Declaration { + interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - interface TypeElement extends Declaration { + interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1238,7 +1240,7 @@ declare namespace ts { typeParameters?: NodeArray; type: TypeNode; } - interface EnumMember extends Declaration { + interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; name: PropertyName; @@ -1297,13 +1299,13 @@ declare namespace ts { moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; - interface ImportClause extends Declaration { + interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; namedBindings?: NamedImportBindings; } - interface NamespaceImport extends Declaration { + interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1330,13 +1332,13 @@ declare namespace ts { elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; - interface ImportSpecifier extends Declaration { + interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; name: Identifier; } - interface ExportSpecifier extends Declaration { + interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; @@ -1467,7 +1469,7 @@ declare namespace ts { kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } - interface JSDocTypedefTag extends JSDocTag, Declaration { + interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -2320,14 +2322,15 @@ declare namespace ts { HelperName = 4096, ExportName = 8192, LocalName = 16384, - Indented = 32768, - NoIndentation = 65536, - AsyncFunctionBody = 131072, - ReuseTempVariableScope = 262144, - CustomPrologue = 524288, - NoHoisting = 1048576, - HasEndOfDeclarationMarker = 2097152, - Iterator = 4194304, + InternalName = 32768, + Indented = 65536, + NoIndentation = 131072, + AsyncFunctionBody = 262144, + ReuseTempVariableScope = 524288, + CustomPrologue = 1048576, + NoHoisting = 2097152, + HasEndOfDeclarationMarker = 4194304, + Iterator = 8388608, } interface EmitHelper { readonly name: string; @@ -2515,7 +2518,7 @@ declare namespace ts { } declare namespace ts { /** The version of the TypeScript compiler release */ - const version = "2.3.1"; + const version = "2.3.3"; } 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 ee99953790c..b06a1d92700 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -1110,14 +1110,15 @@ var ts; EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName"; EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName"; EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName"; - EmitFlags[EmitFlags["Indented"] = 32768] = "Indented"; - EmitFlags[EmitFlags["NoIndentation"] = 65536] = "NoIndentation"; - EmitFlags[EmitFlags["AsyncFunctionBody"] = 131072] = "AsyncFunctionBody"; - EmitFlags[EmitFlags["ReuseTempVariableScope"] = 262144] = "ReuseTempVariableScope"; - EmitFlags[EmitFlags["CustomPrologue"] = 524288] = "CustomPrologue"; - EmitFlags[EmitFlags["NoHoisting"] = 1048576] = "NoHoisting"; - EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 2097152] = "HasEndOfDeclarationMarker"; - EmitFlags[EmitFlags["Iterator"] = 4194304] = "Iterator"; + EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName"; + EmitFlags[EmitFlags["Indented"] = 65536] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue"; + EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting"; + EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker"; + EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1137,17 +1138,22 @@ var ts; ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values"; ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read"; ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 2048] = "AsyncGenerator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 4096] = "AsyncDelegator"; - ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 8192] = "AsyncValues"; + ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator"; + ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues"; // Helpers included by ES2015 for..of ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes"; // Helpers included by ES2017 for..await..of - ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 8192] = "ForAwaitOfIncludes"; + ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes"; + // Helpers included by ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes"; + // Helpers included by yield* in ES2017 async generators + ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes"; // Helpers included by ES2015 spread ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes"; ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper"; - ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 8192] = "LastEmitHelper"; + ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 16384] = "LastEmitHelper"; })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {})); var EmitHint; (function (EmitHint) { @@ -1256,7 +1262,7 @@ var ts; var ts; (function (ts) { /** The version of the TypeScript compiler release */ - ts.version = "2.3.1"; + ts.version = "2.3.3"; })(ts || (ts = {})); /* @internal */ (function (ts) { @@ -8243,6 +8249,36 @@ var ts; return false; } ts.isDeclarationName = isDeclarationName; + function getNameOfDeclaration(declaration) { + if (!declaration) { + return undefined; + } + if (declaration.kind === 194 /* BinaryExpression */) { + var kind = getSpecialPropertyAssignmentKind(declaration); + var lhs = declaration.left; + switch (kind) { + case 0 /* None */: + case 2 /* ModuleExports */: + return undefined; + case 1 /* ExportsProperty */: + if (lhs.kind === 71 /* Identifier */) { + return lhs.name; + } + else { + return lhs.expression.name; + } + case 4 /* ThisProperty */: + case 5 /* Property */: + return lhs.name; + case 3 /* PrototypeProperty */: + return lhs.expression.name; + } + } + else { + return declaration.name; + } + } + ts.getNameOfDeclaration = getNameOfDeclaration; function isLiteralComputedPropertyDeclarationName(node) { return (node.kind === 9 /* StringLiteral */ || node.kind === 8 /* NumericLiteral */) && node.parent.kind === 144 /* ComputedPropertyName */ && @@ -8397,12 +8433,13 @@ var ts; FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal"; FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator"; FunctionFlags[FunctionFlags["Async"] = 2] = "Async"; - FunctionFlags[FunctionFlags["AsyncOrAsyncGenerator"] = 3] = "AsyncOrAsyncGenerator"; FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid"; - FunctionFlags[FunctionFlags["InvalidAsyncOrAsyncGenerator"] = 7] = "InvalidAsyncOrAsyncGenerator"; - FunctionFlags[FunctionFlags["InvalidGenerator"] = 5] = "InvalidGenerator"; + FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator"; })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {})); function getFunctionFlags(node) { + if (!node) { + return 4 /* Invalid */; + } var flags = 0 /* Normal */; switch (node.kind) { case 228 /* FunctionDeclaration */: @@ -8455,7 +8492,8 @@ var ts; * Symbol. */ function hasDynamicName(declaration) { - return declaration.name && isDynamicName(declaration.name); + var name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } ts.hasDynamicName = hasDynamicName; function isDynamicName(name) { @@ -11582,7 +11620,7 @@ var ts; var node = createSynthesizedNode(179 /* PropertyAccessExpression */); node.expression = ts.parenthesizeForAccess(expression); node.name = asName(name); - setEmitFlags(node, 65536 /* NoIndentation */); + setEmitFlags(node, 131072 /* NoIndentation */); return node; } ts.createPropertyAccess = createPropertyAccess; @@ -13595,6 +13633,28 @@ var ts; /*location*/ method), /*original*/ method)); } + /** + * Gets the internal name of a declaration. This is primarily used for declarations that can be + * referred to by name in the body of an ES5 class function body. An internal name will *never* + * be prefixed with an module or namespace export modifier like "exports." when emitted as an + * expression. An internal name will also *never* be renamed due to a collision with a block + * scoped variable. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + function getInternalName(node, allowComments, allowSourceMaps) { + return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */); + } + ts.getInternalName = getInternalName; + /** + * Gets whether an identifier should only be referred to by its internal name. + */ + function isInternalName(node) { + return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0; + } + ts.isInternalName = isInternalName; /** * Gets the local name of a declaration. This is primarily used for declarations that can be * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A @@ -13650,9 +13710,10 @@ var ts; } ts.getDeclarationName = getDeclarationName; function getName(node, allowComments, allowSourceMaps, emitFlags) { - if (node.name && ts.isIdentifier(node.name) && !ts.isGeneratedIdentifier(node.name)) { - var name = ts.getMutableClone(node.name); - emitFlags |= ts.getEmitFlags(node.name); + var nodeName = ts.getNameOfDeclaration(node); + if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) { + var name = ts.getMutableClone(nodeName); + emitFlags |= ts.getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= 48 /* NoSourceMap */; if (!allowComments) @@ -13765,7 +13826,7 @@ var ts; var numStatements = source.length; while (statementOffset < numStatements) { var statement = source[statementOffset]; - if (ts.getEmitFlags(statement) & 524288 /* CustomPrologue */) { + if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -21481,12 +21542,13 @@ var ts; // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node) { - if (node.name) { + var name = ts.getNameOfDeclaration(node); + if (name) { if (ts.isAmbientModule(node)) { - return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + node.name.text + "\""; + return ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + name.text + "\""; } - if (node.name.kind === 144 /* ComputedPropertyName */) { - var nameExpression = node.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var nameExpression = name.expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (ts.isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -21494,7 +21556,7 @@ var ts; ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression)); return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text); } - return node.name.text; + return name.text; } switch (node.kind) { case 152 /* Constructor */: @@ -21638,9 +21700,9 @@ var ts; } } ts.forEach(symbol.declarations, function (declaration) { - file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(declaration) || declaration, message_1, getDisplayName(declaration))); }); - file.bindDiagnostics.push(ts.createDiagnosticForNode(node.name || node, message_1, getDisplayName(node))); + file.bindDiagnostics.push(ts.createDiagnosticForNode(ts.getNameOfDeclaration(node) || node, message_1, getDisplayName(node))); symbol = createSymbol(0 /* None */, name); } } @@ -25936,16 +25998,16 @@ var ts; recordMergedSymbol(target, source); } else if (target.flags & 1024 /* NamespaceModule */) { - error(source.declarations[0].name, ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { var message_2 = target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(source.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); ts.forEach(target.declarations, function (node) { - error(node.name ? node.name : node, message_2, symbolToString(source)); + error(ts.getNameOfDeclaration(node) || node, message_2, symbolToString(source)); }); } } @@ -26073,7 +26135,8 @@ var ts; var useFile = ts.getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + ts.isInAmbientContext(declaration)) { // nodes are in different files and order cannot be determined return true; } @@ -26537,13 +26600,13 @@ var ts; ts.Debug.assert(declaration !== undefined, "Declaration to checkResolvedBlockScopedVariable is undefined"); if (!ts.isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & 2 /* BlockScopedVariable */) { - error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 32 /* Class */) { - error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } else if (result.flags & 384 /* Enum */) { - error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); + error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, ts.declarationNameToString(ts.getNameOfDeclaration(declaration))); } } } @@ -27919,8 +27982,9 @@ var ts; function getNameOfSymbol(symbol) { var declaration = ts.firstOrUndefined(symbol.declarations); if (declaration) { - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -28001,8 +28065,9 @@ var ts; function getNameOfSymbol(symbol) { if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - if (declaration.name) { - return ts.declarationNameToString(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + return ts.declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === 226 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -31193,8 +31258,9 @@ var ts; type = anyType; if (noImplicitAny) { var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + error(name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(name)); } else { error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -33321,29 +33387,6 @@ var ts; } return 0 /* False */; } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type, name, isComparingJsxAttributes) { - if (type.flags & 32768 /* Object */) { - var resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. - return true; - } - } - else if (type.flags & 196608 /* UnionOrIntersection */) { - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } function hasExcessProperties(source, target, reportErrors) { if (maybeTypeOfKind(target, 32768 /* Object */) && !(getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { var isComparingJsxAttributes = !!(source.flags & 33554432 /* JsxAttributes */); @@ -33844,24 +33887,38 @@ var ts; } var result = -1 /* True */; var saveErrorInfo = errorInfo; - outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { - var t = targetSignatures_1[_i]; - // Only elaborate errors from the first failure - var shouldElaborateErrors = reportErrors; - for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { - var s = sourceSignatures_1[_a]; - var related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & 64 /* Instantiated */ && getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) { + // We instantiations of the same anonymous type (which typically will be the type of a method). + // Simply do a pairwise comparison of the signatures in the two signature lists instead of the + // much more expensive N * M comparison matrix we explore below. + for (var i = 0; i < targetSignatures.length; i++) { + var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return 0 /* False */; } - shouldElaborateErrors = false; + result &= related; } - if (shouldElaborateErrors) { - reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + else { + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; + // Only elaborate errors from the first failure + var shouldElaborateErrors = reportErrors; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; + var related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } + if (shouldElaborateErrors) { + reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return 0 /* False */; } - return 0 /* False */; } return result; } @@ -34480,7 +34537,7 @@ var ts; default: diagnostic = ts.Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration, type) { if (produceDiagnostics && noImplicitAny && type.flags & 2097152 /* ContainsWideningType */) { @@ -36260,7 +36317,7 @@ var ts; if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -37537,6 +37594,10 @@ var ts; var attributesTable = ts.createMap(); var spread = emptyObjectType; var attributesArray = []; + var hasSpreadAnyType = false; + var typeToIntersect; + var explicitlySpecifyChildrenAttribute = false; + var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) { var attributeDecl = _a[_i]; var member = attributeDecl.symbol; @@ -37554,6 +37615,9 @@ var ts; attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { ts.Debug.assert(attributeDecl.kind === 255 /* JsxSpreadAttribute */); @@ -37563,31 +37627,34 @@ var ts; attributesTable = ts.createMap(); } var exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = ts.createMap(); - } - attributesArray = getPropertiesOfType(spread); - } - attributesTable = ts.createMap(); - if (attributesArray) { - ts.forEach(attributesArray, function (attr) { - if (!filter || filter(attr)) { - attributesTable.set(attr.name, attr); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + attributesArray = []; + attributesTable = ts.createMap(); } - }); + attributesArray = getPropertiesOfType(spread); + } + attributesTable = ts.createMap(); + if (attributesArray) { + ts.forEach(attributesArray, function (attr) { + if (!filter || filter(attr)) { + attributesTable.set(attr.name, attr); + } + }); + } } // Handle children attribute var parent = openingLikeElement.parent.kind === 249 /* JsxElement */ ? openingLikeElement.parent : undefined; @@ -37607,11 +37674,11 @@ var ts; childrenTypes.push(checkExpression(child, checkMode)); } } - // Error if there is a attribute named "children" and children element. - // This is because children element will overwrite the value from attributes - var jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } // If there are children in the body of JSX element, create dummy attribute "children" with anyType so that it will pass the attribute checking process @@ -37622,7 +37689,12 @@ var ts; attributesTable.set(jsxChildrenPropertyName, childrenPropSymbol); } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + var attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; /** * Create anonymous type from given attributes symbol table. * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable @@ -37630,8 +37702,7 @@ var ts; */ function createJsxAttributesType(symbol, attributesTable) { var result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 1048576 /* FreshLiteral */; - result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */ | freshObjectLiteralFlag; + result.flags |= 33554432 /* JsxAttributes */ | 4194304 /* ContainsObjectLiteral */; result.objectFlags |= 128 /* ObjectLiteral */; return result; } @@ -37709,7 +37780,18 @@ var ts; return unknownType; } } - return getUnionType(ts.map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + var instantiatedSignatures = []; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; + if (signature.typeParameters) { + var typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + return getUnionType(ts.map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer. @@ -37761,6 +37843,20 @@ var ts; } return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType) { + if (!propsType) { + return undefined; + } + if (propsType.flags & 131072 /* Intersection */) { + var propsApparentType = []; + for (var _i = 0, _a = propsType.types; _i < _a.length; _i++) { + var t = _a[_i]; + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } /** * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. * Return only attributes type of successfully resolved call signature. @@ -37781,6 +37877,7 @@ var ts; if (callSignature !== unknownSignature) { var callReturnType = callSignature && getReturnTypeOfSignature(callSignature); var paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -37819,6 +37916,7 @@ var ts; var candidate = candidatesOutArray_1[_i]; var callReturnType = getReturnTypeOfSignature(candidate); var paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { var shouldBeCandidate = true; for (var _a = 0, _b = openingLikeElement.attributes.properties; _a < _b.length; _a++) { @@ -38093,6 +38191,34 @@ var ts; } checkJsxAttributesAssignableToTagNameAttributes(node); } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if the object type is empty and the check is for assignability, if the object type has + * index signatures, or if the property is actually declared in the object type. In a union or intersection + * type, a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType, name, isComparingJsxAttributes) { + if (targetType.flags & 32768 /* Object */) { + var resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & 196608 /* UnionOrIntersection */) { + for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" @@ -38121,7 +38247,20 @@ var ts; error(openingLikeElement, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + var isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (var _i = 0, _a = openingLikeElement.attributes.properties; _i < _a.length; _i++) { + var attribute = _a[_i]; + if (ts.isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { + error(attribute, ts.Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } } } function checkJsxExpression(node, checkMode) { @@ -38520,8 +38659,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var signature = signatures_3[_i]; + for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { + var signature = signatures_4[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -39450,7 +39589,7 @@ var ts; // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && ts.getModifierFlags(valueDecl) & 128 /* Abstract */) { - error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); + error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(ts.getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } // TS 1.0 spec: 4.11 @@ -39861,11 +40000,11 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + var name = ts.getNameOfDeclaration(parameter.valueDeclaration); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === 174 /* ObjectBindingPattern */ || - parameter.valueDeclaration.name.kind === 175 /* ArrayBindingPattern */)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === 174 /* ObjectBindingPattern */ || name.kind === 175 /* ArrayBindingPattern */)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -39996,7 +40135,7 @@ var ts; // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + return (functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? createPromiseReturnType(func, widenedType) // Async function : widenedType; // Generator function, AsyncGenerator function, or normal function } @@ -40192,7 +40331,7 @@ var ts; ts.Debug.assert(node.kind !== 151 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); var functionFlags = ts.getFunctionFlags(node); var returnOrPromisedType = node.type && - ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ ? + ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ ? checkAsyncFunctionReturnType(node) : getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function if ((functionFlags & 1 /* Generator */) === 0) { @@ -40219,7 +40358,7 @@ var ts; // its return type annotation. var exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -40902,12 +41041,15 @@ var ts; // we are in a yield context. var functionFlags = func && ts.getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & 2 /* Async */) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 4096 /* AsyncDelegator */); - } + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && + languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & 3 /* AsyncGenerator */) === 1 /* Generator */ && + languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256 /* Values */); } } @@ -41365,17 +41507,18 @@ var ts; checkGrammarFunctionLikeDeclaration(node); } var functionFlags = ts.getFunctionFlags(node); - if ((functionFlags & 7 /* InvalidAsyncOrAsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 64 /* Awaiter */); - if (languageVersion < 2 /* ES2015 */) { - checkExternalEmitHelpers(node, 128 /* Generator */); + if (!(functionFlags & 4 /* Invalid */)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 5 /* ESNext */) { + checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } - } - if ((functionFlags & 5 /* InvalidGenerator */) === 1 /* Generator */) { - if (functionFlags & 2 /* Async */ && languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 2048 /* AsyncGenerator */); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) { + checkExternalEmitHelpers(node, 64 /* Awaiter */); } - else if (languageVersion < 2 /* ES2015 */) { + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) { checkExternalEmitHelpers(node, 128 /* Generator */); } } @@ -41398,7 +41541,7 @@ var ts; } if (node.type) { var functionFlags_1 = ts.getFunctionFlags(node); - if ((functionFlags_1 & 5 /* InvalidGenerator */) === 1 /* Generator */) { + if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) { var returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -41417,7 +41560,7 @@ var ts; checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } - else if ((functionFlags_1 & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */) { + else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) { checkAsyncFunctionReturnType(node); } } @@ -41536,7 +41679,7 @@ var ts; continue; } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, ts.Diagnostics.Duplicate_identifier_0, memberName); + error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName); error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -41624,7 +41767,8 @@ var ts; return; } function containsSuperCallAsComputedPropertyName(n) { - return n.name && containsSuperCall(n.name); + var name = ts.getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n) { if (ts.isSuperCall(n)) { @@ -41884,16 +42028,16 @@ var ts; ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1; if (deviation & 1 /* Export */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & 2 /* Ambient */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (8 /* Private */ | 16 /* Protected */)) { - error(o.name || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & 128 /* Abstract */) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -41904,7 +42048,7 @@ var ts; ts.forEach(overloads, function (o) { var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1; if (deviation) { - error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -42028,7 +42172,7 @@ var ts; } if (duplicateFunctionDeclaration) { ts.forEach(declarations, function (declaration) { - error(declaration.name, ts.Diagnostics.Duplicate_function_implementation); + error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation); }); } // Abstract methods can't have an implementation -- in particular, they don't need one. @@ -42042,8 +42186,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_4 = signatures; _a < signatures_4.length; _a++) { - var signature = signatures_4[_a]; + for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) { + var signature = signatures_5[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -42101,12 +42245,13 @@ var ts; for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) { var d = _c[_b]; var declarationSpaces = getDeclarationSpaces(d); + var name = ts.getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, ts.declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(d.name)); + error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name)); } } } @@ -42612,15 +42757,16 @@ var ts; if (!local.isReferenced) { if (local.valueDeclaration && ts.getRootDeclaration(local.valueDeclaration).kind === 146 /* Parameter */) { var parameter = ts.getRootDeclaration(local.valueDeclaration); + var name = ts.getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && !ts.parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - ts.forEach(local.declarations, function (d) { return errorUnusedLocal(d.name || d, local.name); }); + ts.forEach(local.declarations, function (d) { return errorUnusedLocal(ts.getNameOfDeclaration(d) || d, local.name); }); } } }); @@ -42700,7 +42846,7 @@ var ts; for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (!ts.isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(ts.getNameOfDeclaration(declaration), local.name); } } } @@ -42768,7 +42914,7 @@ var ts; if (getNodeCheckFlags(current) & 4 /* CaptureThis */) { var isDeclaration_1 = node.kind !== 71 /* Identifier */; if (isDeclaration_1) { - error(node.name, ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -42782,7 +42928,7 @@ var ts; if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) { var isDeclaration_2 = node.kind !== 71 /* Identifier */; if (isDeclaration_2) { - error(node.name, ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -43048,7 +43194,7 @@ var ts; checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); + error(ts.getNameOfDeclaration(symbol.valueDeclaration), ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name)); } } @@ -43163,11 +43309,14 @@ var ts; checkGrammarForInOrForOfStatement(node); if (node.kind === 216 /* ForOfStatement */) { if (node.awaitModifier) { - if (languageVersion < 4 /* ES2017 */) { - checkExternalEmitHelpers(node, 8192 /* ForAwaitOfIncludes */); + var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node)); + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 5 /* ESNext */) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper + checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } - else if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); } } @@ -43550,7 +43699,7 @@ var ts; return !!(node.kind === 153 /* GetAccessor */ && ts.getSetAccessorTypeAnnotationNode(ts.getDeclarationOfKind(node.symbol, 154 /* SetAccessor */))); } function isUnwrappedReturnTypeVoidOrAny(func, returnType) { - var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncOrAsyncGenerator */) === 2 /* Async */ + var unwrappedReturnType = (ts.getFunctionFlags(func) & 3 /* AsyncGenerator */) === 2 /* Async */ ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 1024 /* Void */ | 1 /* Any */); @@ -43772,13 +43921,16 @@ var ts; } var propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === 1 /* Number */ && !(propDeclaration ? isNumericName(ts.getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } // perform property check if property or indexer is declared in 'type' - // this allows to rule out cases when both property and indexer are inherited from the base class + // this allows us to rule out cases when both property and indexer are inherited from the base class var errorNode; - if (propDeclaration && (propDeclaration.name.kind === 144 /* ComputedPropertyName */ || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === 194 /* BinaryExpression */ || + ts.getNameOfDeclaration(propDeclaration).kind === 144 /* ComputedPropertyName */ || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -44101,7 +44253,7 @@ var ts; else { errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -44396,7 +44548,7 @@ var ts; // check that const is placed\omitted on all enum declarations ts.forEach(enumSymbol.declarations, function (decl) { if (ts.isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -45963,15 +46115,6 @@ var ts; var type = getWidenedType(getRegularTypeOfExpression(expr)); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node, enclosingDeclaration, flags, writer) { - var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - var baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } function hasGlobalName(name) { return globals.has(name); } @@ -46057,7 +46200,6 @@ var ts; writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, - writeBaseConstructorTypeOfClass: writeBaseConstructorTypeOfClass, isSymbolAccessible: isSymbolAccessible, isEntityNameVisible: isEntityNameVisible, getConstantValue: function (node) { @@ -46225,7 +46367,7 @@ var ts; var helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (var helper = 1 /* FirstEmitHelper */; helper <= 8192 /* LastEmitHelper */; helper <<= 1) { + for (var helper = 1 /* FirstEmitHelper */; helper <= 16384 /* LastEmitHelper */; helper <<= 1) { if (uncheckedHelpers & helper) { var name = getHelperName(helper); var symbol = getSymbol(helpersModule.exports, ts.escapeIdentifier(name), 107455 /* Value */); @@ -46252,9 +46394,10 @@ var ts; case 256 /* Values */: return "__values"; case 512 /* Read */: return "__read"; case 1024 /* Spread */: return "__spread"; - case 2048 /* AsyncGenerator */: return "__asyncGenerator"; - case 4096 /* AsyncDelegator */: return "__asyncDelegator"; - case 8192 /* AsyncValues */: return "__asyncValues"; + case 2048 /* Await */: return "__await"; + case 4096 /* AsyncGenerator */: return "__asyncGenerator"; + case 8192 /* AsyncDelegator */: return "__asyncDelegator"; + case 16384 /* AsyncValues */: return "__asyncValues"; default: ts.Debug.fail("Unrecognized helper."); } } @@ -49214,7 +49357,7 @@ var ts; if (statements.length > 1) { // Add a DeclarationMarker as a marker for the end of the declaration statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 2097152 /* HasEndOfDeclarationMarker */); + ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */); } return ts.singleOrMany(statements); } @@ -49390,7 +49533,7 @@ var ts; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. - ts.setEmitFlags(classExpression, 32768 /* Indented */ | ts.getEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -50868,7 +51011,7 @@ var ts; // })(m1 || (m1 = {})); // trailing comment module // ts.setCommentRange(statement, node); - ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 2097152 /* HasEndOfDeclarationMarker */); + ts.setEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */); statements.push(statement); return true; } @@ -50878,7 +51021,7 @@ var ts; // begin/end semantics of the declararation and to properly handle exports // we wrap the leading variable declaration in a `MergeDeclarationMarker`. var mergeMarker = ts.createMergeDeclarationMarker(statement); - ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 2097152 /* HasEndOfDeclarationMarker */); + ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */); statements.push(mergeMarker); return false; } @@ -51816,7 +51959,7 @@ var ts; /*parameters*/ [], /*type*/ undefined, body); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; return ts.createCall(ts.getHelperName("__awaiter"), /*typeArguments*/ undefined, [ ts.createThis(), @@ -51929,21 +52072,15 @@ var ts; } function visitAwaitExpression(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { - var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.setOriginalNode(ts.setTextRange(ts.createYield( - /*asteriskToken*/ undefined, ts.createArrayLiteral([ts.createLiteral("await"), expression])), + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), /*location*/ node), node); } return ts.visitEachChild(node, visitor, context); } function visitYieldExpression(node) { - if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { + if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ && node.asteriskToken) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); - return ts.updateYield(node, node.asteriskToken, node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : ts.createArrayLiteral(expression - ? [ts.createLiteral("yield"), expression] - : [ts.createLiteral("yield")])); + return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node); } return ts.visitEachChild(node, visitor, context); } @@ -52093,6 +52230,9 @@ var ts; return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */); } + function awaitAsYield(expression) { + return ts.createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? createAwaitHelper(context, expression) : expression); + } function transformForAwaitOfStatement(node, outermostLabeledStatement) { var expression = ts.visitNode(node.expression, visitor, ts.isExpression); var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -52100,24 +52240,21 @@ var ts; var errorRecord = ts.createUniqueName("e"); var catchVariable = ts.getGeneratedNameForNode(errorRecord); var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined); - var values = createAsyncValuesHelper(context, expression, /*location*/ node.expression); - var next = ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []) - ]) - : ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, [])); + var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []); + var getDone = ts.createPropertyAccess(result, "done"); + var getValue = ts.createPropertyAccess(result, "value"); + var callReturn = ts.createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor( /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ - ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), - ts.createVariableDeclaration(result, /*type*/ undefined, next) - ]), node.expression), 1048576 /* NoHoisting */), - /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), - /*incrementor*/ ts.createAssignment(result, next), - /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"))), + ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + ts.createVariableDeclaration(result) + ]), node.expression), 2097152 /* NoHoisting */), + /*condition*/ ts.createComma(ts.createAssignment(result, awaitAsYield(callNext)), ts.createLogicalNot(getDone)), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue))), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); return ts.createTry(ts.createBlock([ ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement) @@ -52128,13 +52265,7 @@ var ts; ]), 1 /* SingleLine */)), ts.createBlock([ ts.createTry( /*tryBlock*/ ts.createBlock([ - ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(ts.createYield( - /*asteriskToken*/ undefined, enclosingFunctionFlags & 1 /* Generator */ - ? ts.createArrayLiteral([ - ts.createLiteral("await"), - ts.createFunctionCall(returnMethod, iterator, []) - ]) - : ts.createFunctionCall(returnMethod, iterator, [])))), 1 /* SingleLine */) + ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createStatement(awaitAsYield(callReturn))), 1 /* SingleLine */) ]), /*catchClause*/ undefined, /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([ @@ -52290,7 +52421,7 @@ var ts; if (ts.some(declarations)) { var statement = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations)); - ts.setEmitFlags(statement, 524288 /* CustomPrologue */); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); statements = ts.append(statements, statement); } } @@ -52420,15 +52551,25 @@ var ts; /*typeArguments*/ undefined, attributesSegments); } ts.createAssignHelper = createAssignHelper; + var awaitHelper = { + name: "typescript:await", + scoped: false, + text: "\n var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }\n " + }; + function createAwaitHelper(context, expression) { + context.requestEmitHelper(awaitHelper); + return ts.createCall(ts.getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } var asyncGeneratorHelper = { name: "typescript:asyncGenerator", scoped: false, - text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), q = [], c, i;\n return i = { next: verb(\"next\"), \"throw\": verb(\"throw\"), \"return\": verb(\"return\") }, i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }\n function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }\n function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === \"yield\" ? send : fulfill, reject); }\n function send(value) { settle(c[2], { value: value, done: false }); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { c = void 0, f(v), next(); }\n };\n " + text: "\n var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n };\n " }; function createAsyncGeneratorHelper(context, generatorFunc) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); // Mark this node as originally an async function - (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 131072 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */; return ts.createCall(ts.getHelperName("__asyncGenerator"), /*typeArguments*/ undefined, [ ts.createThis(), @@ -52439,11 +52580,11 @@ var ts; var asyncDelegator = { name: "typescript:asyncDelegator", scoped: false, - text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i = { next: verb(\"next\"), \"throw\": verb(\"throw\", function (e) { throw e; }), \"return\": verb(\"return\", function (v) { return { value: v, done: true }; }) }, p;\n return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { return function (v) { return v = p && n === \"throw\" ? f(v) : p && v.done ? v : { value: p ? [\"yield\", v.value] : [\"await\", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; }\n };\n " + text: "\n var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; }; }\n };\n " }; function createAsyncDelegatorHelper(context, expression, location) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return ts.setTextRange(ts.createCall(ts.getHelperName("__asyncDelegator"), /*typeArguments*/ undefined, [expression]), location); } @@ -53483,10 +53624,10 @@ var ts; statements.push(exportStatement); } var emitFlags = ts.getEmitFlags(node); - if ((emitFlags & 2097152 /* HasEndOfDeclarationMarker */) === 0) { + if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) { // Add a DeclarationMarker as a marker for the end of the declaration statements.push(ts.createEndOfDeclarationMarker(node)); - ts.setEmitFlags(statement, emitFlags | 2097152 /* HasEndOfDeclarationMarker */); + ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */); } return ts.singleOrMany(statements); } @@ -53548,8 +53689,8 @@ var ts; // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier // transformation. - if (ts.getEmitFlags(node) & 32768 /* Indented */) { - ts.setEmitFlags(classFunction, 32768 /* Indented */); + if (ts.getEmitFlags(node) & 65536 /* Indented */) { + ts.setEmitFlags(classFunction, 65536 /* Indented */); } // "inner" and "outer" below are added purely to preserve source map locations from // the old emitter @@ -53578,7 +53719,7 @@ var ts; addClassMembers(statements, node); // Create a synthetic text range for the return statement. var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 18 /* CloseBraceToken */); - var localName = ts.getLocalName(node); + var localName = ts.getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. var outer = ts.createPartiallyEmittedExpression(localName); @@ -53622,7 +53763,7 @@ var ts; var constructorFunction = ts.createFunctionDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, - /*asteriskToken*/ undefined, ts.getDeclarationName(node), + /*asteriskToken*/ undefined, ts.getInternalName(node), /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper)); ts.setTextRange(constructorFunction, constructor || node); @@ -53912,10 +54053,10 @@ var ts; // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { statements.push(ts.setEmitFlags(ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 524288 /* CustomPrologue */)); + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, temp))), 1048576 /* CustomPrologue */)); } else if (initializer) { - statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 524288 /* CustomPrologue */)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */)); } } /** @@ -53933,7 +54074,7 @@ var ts; ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */)); statement.startsOnNewLine = true; ts.setTextRange(statement, parameter); - ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 524288 /* CustomPrologue */); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */); statements.push(statement); } /** @@ -53974,7 +54115,7 @@ var ts; ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) ])), - /*location*/ parameter), 524288 /* CustomPrologue */)); + /*location*/ parameter), 1048576 /* CustomPrologue */)); // for (var _i = restIndex; _i < arguments.length; _i++) { // param[_i - restIndex] = arguments[_i]; // } @@ -53986,7 +54127,7 @@ var ts; : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), /*location*/ parameter)) ])); - ts.setEmitFlags(forStatement, 524288 /* CustomPrologue */); + ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); } @@ -54008,7 +54149,7 @@ var ts; ts.createVariableDeclaration("_this", /*type*/ undefined, initializer) ])); - ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 524288 /* CustomPrologue */); + ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */); ts.setTextRange(captureThisStatement, originalStatement); ts.setSourceMapRange(captureThisStatement, node); statements.push(captureThisStatement); @@ -54212,7 +54353,7 @@ var ts; * @param node a FunctionExpression node. */ function visitFunctionExpression(node) { - var ancestorFacts = ts.getEmitFlags(node) & 131072 /* AsyncFunctionBody */ + var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */ ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */) : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); var savedConvertedLoopState = convertedLoopState; @@ -54736,7 +54877,7 @@ var ts; /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)), ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression) - ]), node.expression), 1048576 /* NoHoisting */), + ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), @@ -54761,7 +54902,7 @@ var ts; /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([ ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), ts.createVariableDeclaration(result, /*type*/ undefined, next) - ]), node.expression), 1048576 /* NoHoisting */), + ]), node.expression), 2097152 /* NoHoisting */), /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), /*incrementor*/ ts.createAssignment(result, next), /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), @@ -54816,7 +54957,7 @@ var ts; var temp = ts.createTempVariable(hoistVariableDeclaration); // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. var expressions = []; - var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 32768 /* Indented */)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -54940,7 +55081,7 @@ var ts; loopBodyFlags |= 8 /* CapturesThis */; } if (isAsyncBlockContainingAwait) { - loopBodyFlags |= 131072 /* AsyncFunctionBody */; + loopBodyFlags |= 262144 /* AsyncFunctionBody */; } var convertedLoopVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([ @@ -54950,7 +55091,7 @@ var ts; /*name*/ undefined, /*typeParameters*/ undefined, loopParameters, /*type*/ undefined, loopBody), loopBodyFlags)) - ]), 1048576 /* NoHoisting */)); + ]), 2097152 /* NoHoisting */)); var statements = [convertedLoopVariable]; var extraVariableDeclarations; // propagate state from the inner loop to the outer loop if necessary @@ -55056,7 +55197,7 @@ var ts; !state.labeledNonLocalContinues; var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(parameters, function (p) { return p.name; })); var callResult = isAsyncBlockContainingAwait - ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 4194304 /* Iterator */)) + ? ts.createYield(ts.createToken(39 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */)) : call; if (isSimpleLoop) { statements.push(ts.createStatement(callResult)); @@ -55276,7 +55417,20 @@ var ts; var savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */); - var updated = ts.visitEachChild(node, visitor, context); + var updated; + if (node.transformFlags & 32768 /* ContainsCapturedLexicalThis */) { + var parameters = ts.visitParameterList(node.parameters, visitor, context); + var body = transformFunctionBody(node); + if (node.kind === 153 /* GetAccessor */) { + updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + } + else { + updated = ts.visitEachChild(node, visitor, context); + } exitSubtree(ancestorFacts, 49152 /* PropagateNewTargetMask */, 0 /* None */); convertedLoopState = savedConvertedLoopState; return updated; @@ -55721,7 +55875,7 @@ var ts; function substituteIdentifier(node) { // Only substitute the identifier if we have enabled substitutions for block-scoped // bindings. - if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var original = ts.getParseTreeNode(node, ts.isIdentifier); if (original && isNameOfDeclarationWithCollidingName(original)) { return ts.setTextRange(ts.getGeneratedNameForNode(original), node); @@ -55767,14 +55921,39 @@ var ts; * @param node An Identifier node. */ function substituteExpressionIdentifier(node) { - if (enabledSubstitutions & 2 /* BlockScopedBindings */) { + if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) { var declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - return ts.setTextRange(ts.getGeneratedNameForNode(declaration.name), node); + if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node); } } return node; } + function isPartOfClassBody(declaration, node) { + var currentNode = ts.getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + // if the node has no correlation to a parse tree node, its definitely not + // part of the body. + // if the node is outside of the document range of the declaration, its + // definitely not part of the body. + return false; + } + var blockScope = ts.getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + // if we are in the enclosing block scope of the declaration, we are definitely + // not inside the class body. + return false; + } + if (ts.isClassElement(currentNode) && currentNode.parent === declaration) { + // we are in the class body, but we treat static fields as outside of the class body + return currentNode.kind !== 149 /* PropertyDeclaration */ + || (ts.getModifierFlags(currentNode) & 32 /* Static */) === 0; + } + currentNode = currentNode.parent; + } + return false; + } /** * Substitutes `this` when contained within an arrow function. * @@ -55788,8 +55967,9 @@ var ts; return node; } function getClassMemberPrefix(node, member) { - var expression = ts.getLocalName(node); - return ts.hasModifier(member, 32 /* Static */) ? expression : ts.createPropertyAccess(expression, "prototype"); + return ts.hasModifier(member, 32 /* Static */) + ? ts.getInternalName(node) + : ts.createPropertyAccess(ts.getInternalName(node), "prototype"); } function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) { if (!constructor || !hasExtendsClause) { @@ -56470,7 +56650,7 @@ var ts; } else { // Do not hoist custom prologues. - if (ts.getEmitFlags(node) & 524288 /* CustomPrologue */) { + if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -56728,7 +56908,7 @@ var ts; var resumeLabel = defineLabel(); var expression = ts.visitNode(node.expression, visitor, ts.isExpression); if (node.asteriskToken) { - var iterator = (ts.getEmitFlags(node.expression) & 4194304 /* Iterator */) === 0 + var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 ? ts.createValuesHelper(context, expression, /*location*/ node) : expression; emitYieldStar(iterator, /*location*/ node); @@ -58148,7 +58328,7 @@ var ts; /*name*/ undefined, /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], /*type*/ undefined, ts.createBlock(buildResult, - /*multiLine*/ buildResult.length > 0)), 262144 /* ReuseTempVariableScope */)); + /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */)); } /** * Builds the statements for the generator function body. @@ -59243,7 +59423,7 @@ var ts; * @param node The node to test. */ function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 2097152 /* HasEndOfDeclarationMarker */) !== 0; + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; } /** * Visits a DeclarationMarker used as a placeholder for the end of a transformed @@ -59431,7 +59611,7 @@ var ts; ]) ])); } - ts.setEmitFlags(statement, 524288 /* CustomPrologue */); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); return statement; } /** @@ -60281,7 +60461,7 @@ var ts; */ function shouldHoistVariableDeclarationList(node) { // hoist only non-block scoped declarations or block scoped declarations parented by source file - return (ts.getEmitFlags(node) & 1048576 /* NoHoisting */) === 0 + return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0 && (enclosingBlockScopedContainer.kind === 265 /* SourceFile */ || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0); } @@ -60359,7 +60539,7 @@ var ts; * @param node The node to test. */ function hasAssociatedEndOfDeclarationMarker(node) { - return (ts.getEmitFlags(node) & 2097152 /* HasEndOfDeclarationMarker */) !== 0; + return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0; } /** * Visits a DeclarationMarker used as a placeholder for the end of a transformed @@ -62279,7 +62459,7 @@ var ts; var errorNameNode; var emitJsDocComments = compilerOptions.removeComments ? ts.noop : writeJsDocComments; var emit = compilerOptions.stripInternal ? stripInternal : emitNode; - var noDeclare; + var needsDeclare = true; var moduleElementDeclarationEmitInfo = []; var asynchronousSubModuleDeclarationEmitInfo; // Contains the reference paths that needs to go in the declaration file. @@ -62315,11 +62495,11 @@ var ts; } resultHasExternalModuleIndicator = false; if (!isBundledEmit || !ts.isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (ts.isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write("declare module \"" + ts.getResolvedExternalModuleName(host, sourceFile) + "\" {"); writeLine(); increaseIndent(); @@ -62746,12 +62926,11 @@ var ts; ts.emitDetachedComments(currentText, currentLineMap, writer, ts.writeCommentRange, node, newLine, /*removeComents*/ true); emitLines(node.statements); } - // Return a temp variable name to be used in `export default` statements. + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. // The temp name will be of the form _default_counter. // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. - function getExportDefaultTempVariableName() { - var baseName = "_default"; + function getExportTempVariableName(baseName) { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -62764,24 +62943,30 @@ var ts; } } } + function emitTempVariableDeclaration(expr, baseName, diagnostic, needsDeclare) { + var tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + write(";"); + writeLine(); + return tempVarName; + } function emitExportAssignment(node) { if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - // Expression - var tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - write(";"); - writeLine(); + var tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -62793,12 +62978,6 @@ var ts; // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - function getDefaultExportAccessibilityDiagnostic() { - return { - diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node) { return resolver.isDeclarationVisible(node); @@ -62871,7 +63050,7 @@ var ts; if (modifiers & 512 /* Default */) { write("default "); } - else if (node.kind !== 230 /* InterfaceDeclaration */ && !noDeclare) { + else if (node.kind !== 230 /* InterfaceDeclaration */ && needsDeclare) { write("declare "); } } @@ -63207,7 +63386,7 @@ var ts; write(">"); } } - function emitHeritageClause(className, typeReferences, isImplementsList) { + function emitHeritageClause(typeReferences, isImplementsList) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -63219,12 +63398,6 @@ var ts; else if (!isImplementsList && node.expression.kind === 95 /* NullKeyword */) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError() { var diagnosticMessage; // Heritage clause is written by user so it can always be named @@ -63241,7 +63414,7 @@ var ts; return { diagnosticMessage: diagnosticMessage, errorNode: node, - typeName: node.parent.parent.name + typeName: ts.getNameOfDeclaration(node.parent.parent) }; } } @@ -63256,6 +63429,19 @@ var ts; }); } } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); + var tempVarName; + if (baseTypeNode && !ts.isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === 95 /* NullKeyword */ ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, node.name.text + "_base", { + diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !ts.findAncestor(node, function (n) { return n.kind === 233 /* ModuleDeclaration */; })); + } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (ts.hasModifier(node, 128 /* Abstract */)) { @@ -63263,15 +63449,22 @@ var ts; } write("class "); writeTextOfNode(currentText, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + if (!ts.isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); + } } - emitHeritageClause(node.name, ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + emitHeritageClause(ts.getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -63292,7 +63485,7 @@ var ts; emitTypeParameters(node.typeParameters); var interfaceExtendsTypes = ts.filter(ts.getInterfaceBaseTypeNodes(node), function (base) { return ts.isEntityNameExpression(base.expression); }); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); @@ -64864,7 +65057,7 @@ var ts; write("{}"); } else { - var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -64879,7 +65072,7 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; - if (!(ts.getEmitFlags(node) & 65536 /* NoIndentation */)) { + if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; var dotToken = { kind: 23 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; @@ -65281,11 +65474,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } - if (ts.getEmitFlags(node) & 262144 /* ReuseTempVariableScope */) { + if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) { emitSignatureHead(node); if (onEmitNode) { onEmitNode(3 /* Unspecified */, body, emitBlockCallback); @@ -65395,7 +65588,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = ts.getEmitFlags(node) & 32768 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -70143,7 +70336,7 @@ var ts; case 153 /* GetAccessor */: case 154 /* SetAccessor */: case 233 /* ModuleDeclaration */: - return node.parent.name === node; + return ts.getNameOfDeclaration(node.parent) === node; case 180 /* ElementAccessExpression */: return node.parent.argumentExpression === node; case 144 /* ComputedPropertyName */: @@ -73692,7 +73885,7 @@ var ts; // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - existingName = m.name.text; + existingName = ts.getNameOfDeclaration(m).text; } existingMemberNames.set(existingName, true); } @@ -74595,6 +74788,9 @@ var ts; searchForNamedImport(decl.exportClause); return; } + if (!decl.importClause) { + return; + } var importClause = decl.importClause; var namedBindings = importClause.namedBindings; if (namedBindings && namedBindings.kind === 240 /* NamespaceImport */) { @@ -74885,8 +75081,8 @@ var ts; if (symbol.name !== "default") { return symbol.name; } - var name = ts.forEach(symbol.declarations, function (_a) { - var name = _a.name; + var name = ts.forEach(symbol.declarations, function (decl) { + var name = ts.getNameOfDeclaration(decl); return name && name.kind === 71 /* Identifier */ && name.text; }); ts.Debug.assert(!!name); @@ -75640,7 +75836,7 @@ var ts; * position of property accessing, the referenceEntry of such position will be handled in the first case. */ if (!(flags & 134217728 /* Transient */) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(ts.getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } function addReference(referenceLocation, relatedSymbol, searchLocation, state) { @@ -76565,7 +76761,7 @@ var ts; } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node, symbolKind, symbolName, containerName) { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(ts.getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ function createDefinitionInfoFromName(name, symbolKind, symbolName, containerName) { @@ -77203,17 +77399,20 @@ var ts; return undefined; } function tryAddSingleDeclarationName(declaration, containers) { - if (declaration && declaration.name) { - var text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === 144 /* ComputedPropertyName */) { - return tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; + if (declaration) { + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === 144 /* ComputedPropertyName */) { + return tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; + } } } return true; @@ -77242,8 +77441,9 @@ var ts; var containers = []; // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - if (!tryAddComputedPropertyName(declaration.name.expression, containers, /*includeLastPortion*/ false)) { + var name = ts.getNameOfDeclaration(declaration); + if (name.kind === 144 /* ComputedPropertyName */) { + if (!tryAddComputedPropertyName(name.expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -77281,6 +77481,7 @@ var ts; function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; var container = ts.getContainerNode(declaration); + var containerName = container && ts.getNameOfDeclaration(container); return { name: rawItem.name, kind: ts.getNodeKind(declaration), @@ -77290,8 +77491,8 @@ var ts; fileName: rawItem.fileName, textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: container && container.name ? container.name.text : "", - containerKind: container && container.name ? ts.getNodeKind(container) : "" + containerName: containerName ? containerName.text : "", + containerKind: containerName ? ts.getNodeKind(container) : "" }; } } @@ -77543,8 +77744,8 @@ var ts; function mergeChildren(children) { var nameToItems = ts.createMap(); ts.filterMutate(children, function (child) { - var decl = child.node; - var name = decl.name && nodeText(decl.name); + var declName = ts.getNameOfDeclaration(child.node); + var name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. return true; @@ -77633,9 +77834,9 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var decl = node; - if (decl.name) { - return ts.getPropertyNameForPropertyNameNode(decl.name); + var declName = ts.getNameOfDeclaration(node); + if (declName) { + return ts.getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case 186 /* FunctionExpression */: @@ -77652,7 +77853,7 @@ var ts; if (node.kind === 233 /* ModuleDeclaration */) { return getModuleName(node); } - var name = node.name; + var name = ts.getNameOfDeclaration(node); if (name) { var text = nodeText(name); if (text.length > 0) { @@ -82073,7 +82274,7 @@ var ts; // falls through case 149 /* PropertyDeclaration */: case 146 /* Parameter */: - return node.name.kind; + return ts.getNameOfDeclaration(node).kind; } } function getDynamicIndentation(node, nodeStartLine, indentation, delta) { @@ -84912,7 +85113,7 @@ var ts; } var declaration = declarations[0]; // Clone name to remove leading trivia. - var name = ts.getSynthesizedClone(declaration.name); + var name = ts.getSynthesizedClone(ts.getNameOfDeclaration(declaration)); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); var modifiers = visibilityModifier ? ts.createNodeArray([visibilityModifier]) : undefined; var type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -85473,13 +85674,14 @@ var ts; return declarations; } function getDeclarationName(declaration) { - if (declaration.name) { - var result_7 = getTextOfIdentifierOrLiteral(declaration.name); + var name = ts.getNameOfDeclaration(declaration); + if (name) { + var result_7 = getTextOfIdentifierOrLiteral(name); if (result_7 !== undefined) { return result_7; } - if (declaration.name.kind === 144 /* ComputedPropertyName */) { - var expr = declaration.name.expression; + if (name.kind === 144 /* ComputedPropertyName */) { + var expr = name.expression; if (expr.kind === 179 /* PropertyAccessExpression */) { return expr.name.text; } @@ -88032,6 +88234,9 @@ var ts; var compilerOptions = JSON.parse(compilerOptionsJson); var result = ts.resolveModuleName(moduleName, ts.normalizeSlashes(fileName), compilerOptions, _this.host); var resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== ts.Extension.Ts && result.resolvedModule.extension !== ts.Extension.Tsx && result.resolvedModule.extension !== ts.Extension.Dts) { + resolvedFileName = undefined; + } return { resolvedFileName: resolvedFileName, failedLookupLocations: result.failedLookupLocations diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index df228288c22..290b2235863 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -152,7 +152,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.version = "2.3.1"; + ts.version = "2.3.3"; })(ts || (ts = {})); (function (ts) { ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator(undefined, { usage: "sort", sensitivity: "accent" }) : undefined; diff --git a/package.json b/package.json index 7dc1ccc3c86..4e13a1f4320 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "http://typescriptlang.org/", - "version": "2.3.1", + "version": "2.3.3", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 27b3067278c..bdcdf9b0aa3 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -227,12 +227,13 @@ namespace ts { // Should not be called on a declaration with a computed property name, // unless it is a well known Symbol. function getDeclarationName(node: Declaration): string { - if (node.name) { + const name = getNameOfDeclaration(node); + if (name) { if (isAmbientModule(node)) { - return isGlobalScopeAugmentation(node) ? "__global" : `"${(node.name).text}"`; + return isGlobalScopeAugmentation(node) ? "__global" : `"${(name).text}"`; } - if (node.name.kind === SyntaxKind.ComputedPropertyName) { - const nameExpression = (node.name).expression; + if (name.kind === SyntaxKind.ComputedPropertyName) { + const nameExpression = (name).expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (isStringOrNumericLiteral(nameExpression)) { return nameExpression.text; @@ -241,7 +242,7 @@ namespace ts { Debug.assert(isWellKnownSymbolSyntactically(nameExpression)); return getPropertyNameForKnownSymbolName((nameExpression).name.text); } - return (node.name).text; + return (name).text; } switch (node.kind) { case SyntaxKind.Constructor: @@ -303,7 +304,7 @@ namespace ts { } function getDisplayName(node: Declaration): string { - return node.name ? declarationNameToString(node.name) : getDeclarationName(node); + return (node as NamedDeclaration).name ? declarationNameToString((node as NamedDeclaration).name) : getDeclarationName(node); } /** @@ -366,8 +367,8 @@ namespace ts { symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name)); } else { - if (node.name) { - node.name.parent = node; + if ((node as NamedDeclaration).name) { + (node as NamedDeclaration).name.parent = node; } // Report errors every position with duplicate declaration @@ -396,9 +397,9 @@ namespace ts { } forEach(symbol.declarations, declaration => { - file.bindDiagnostics.push(createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration))); + file.bindDiagnostics.push(createDiagnosticForNode(getNameOfDeclaration(declaration) || declaration, message, getDisplayName(declaration))); }); - file.bindDiagnostics.push(createDiagnosticForNode(node.name || node, message, getDisplayName(node))); + file.bindDiagnostics.push(createDiagnosticForNode(getNameOfDeclaration(node) || node, message, getDisplayName(node))); symbol = createSymbol(SymbolFlags.None, name); } @@ -439,9 +440,9 @@ namespace ts { // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. const isJSDocTypedefInJSDocNamespace = node.kind === SyntaxKind.JSDocTypedefTag && - node.name && - node.name.kind === SyntaxKind.Identifier && - (node.name).isInJSDocNamespace; + (node as JSDocTypedefTag).name && + (node as JSDocTypedefTag).name.kind === SyntaxKind.Identifier && + ((node as JSDocTypedefTag).name as Identifier).isInJSDocNamespace; if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypedefInJSDocNamespace) { const exportKind = (symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fea692a1dce..013c5b6f2f4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -580,16 +580,16 @@ namespace ts { recordMergedSymbol(target, source); } else if (target.flags & SymbolFlags.NamespaceModule) { - error(source.declarations[0].name, Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); + error(getNameOfDeclaration(source.declarations[0]), Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target)); } else { const message = target.flags & SymbolFlags.BlockScopedVariable || source.flags & SymbolFlags.BlockScopedVariable ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; forEach(source.declarations, node => { - error(node.name ? node.name : node, message, symbolToString(source)); + error(getNameOfDeclaration(node) || node, message, symbolToString(source)); }); forEach(target.declarations, node => { - error(node.name ? node.name : node, message, symbolToString(source)); + error(getNameOfDeclaration(node) || node, message, symbolToString(source)); }); } } @@ -732,7 +732,8 @@ namespace ts { const useFile = getSourceFileOfNode(usage); if (declarationFile !== useFile) { if ((modulekind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) || - (!compilerOptions.outFile && !compilerOptions.out)) { + (!compilerOptions.outFile && !compilerOptions.out) || + isInAmbientContext(declaration)) { // nodes are in different files and order cannot be determined return true; } @@ -1240,13 +1241,13 @@ namespace ts { if (!isInAmbientContext(declaration) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { if (result.flags & SymbolFlags.BlockScopedVariable) { - error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(declaration.name)); + error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration))); } else if (result.flags & SymbolFlags.Class) { - error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationNameToString(declaration.name)); + error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration))); } else if (result.flags & SymbolFlags.Enum) { - error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationNameToString(declaration.name)); + error(errorLocation, Diagnostics.Enum_0_used_before_its_declaration, declarationNameToString(getNameOfDeclaration(declaration))); } } } @@ -2805,8 +2806,9 @@ namespace ts { function getNameOfSymbol(symbol: Symbol): string { const declaration = firstOrUndefined(symbol.declarations); if (declaration) { - if (declaration.name) { - return declarationNameToString(declaration.name); + const name = getNameOfDeclaration(declaration); + if (name) { + return declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { return declarationNameToString((declaration.parent).name); @@ -2893,8 +2895,9 @@ namespace ts { function getNameOfSymbol(symbol: Symbol): string { if (symbol.declarations && symbol.declarations.length) { const declaration = symbol.declarations[0]; - if (declaration.name) { - return declarationNameToString(declaration.name); + const name = getNameOfDeclaration(declaration); + if (name) { + return declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { return declarationNameToString((declaration.parent).name); @@ -3631,8 +3634,8 @@ namespace ts { case SyntaxKind.BindingElement: return isDeclarationVisible(node.parent.parent); case SyntaxKind.VariableDeclaration: - if (isBindingPattern(node.name) && - !(node.name).elements.length) { + if (isBindingPattern((node as VariableDeclaration).name) && + !((node as VariableDeclaration).name as BindingPattern).elements.length) { // If the binding pattern is empty, this variable declaration is not visible return false; } @@ -6233,8 +6236,8 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - return (node).name.kind === SyntaxKind.ComputedPropertyName - && traverse((node).name); + return (node).name.kind === SyntaxKind.ComputedPropertyName + && traverse((node).name); default: return !nodeStartsNewLexicalEnvironment(node) && !isPartOfTypeNode(node) && forEachChild(node, traverse); @@ -6314,8 +6317,9 @@ namespace ts { type = anyType; if (noImplicitAny) { const declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(declaration.name)); + const name = getNameOfDeclaration(declaration); + if (name) { + error(name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(name)); } else { error(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); @@ -8667,29 +8671,6 @@ namespace ts { return Ternary.False; } - // Check if a property with the given name is known anywhere in the given type. In an object type, a property - // is considered known if the object type is empty and the check is for assignability, if the object type has - // index signatures, or if the property is actually declared in the object type. In a union or intersection - // type, a property is considered known if it is known in any constituent type. - function isKnownProperty(type: Type, name: string, isComparingJsxAttributes: boolean): boolean { - if (type.flags & TypeFlags.Object) { - const resolved = resolveStructuredTypeMembers(type); - if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || - getPropertyOfType(type, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { - // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. - return true; - } - } - else if (type.flags & TypeFlags.UnionOrIntersection) { - for (const t of (type).types) { - if (isKnownProperty(t, name, isComparingJsxAttributes)) { - return true; - } - } - } - return false; - } - function hasExcessProperties(source: FreshObjectLiteralType, target: Type, reportErrors: boolean): boolean { if (maybeTypeOfKind(target, TypeFlags.Object) && !(getObjectFlags(target) & ObjectFlags.ObjectLiteralPatternWithComputedProperties)) { const isComparingJsxAttributes = !!(source.flags & TypeFlags.JsxAttributes); @@ -9204,25 +9185,39 @@ namespace ts { let result = Ternary.True; const saveErrorInfo = errorInfo; - outer: for (const t of targetSignatures) { - // Only elaborate errors from the first failure - let shouldElaborateErrors = reportErrors; - for (const s of sourceSignatures) { - const related = signatureRelatedTo(s, t, shouldElaborateErrors); - if (related) { - result &= related; - errorInfo = saveErrorInfo; - continue outer; + if (getObjectFlags(source) & ObjectFlags.Instantiated && getObjectFlags(target) & ObjectFlags.Instantiated && source.symbol === target.symbol) { + // We instantiations of the same anonymous type (which typically will be the type of a method). + // Simply do a pairwise comparison of the signatures in the two signature lists instead of the + // much more expensive N * M comparison matrix we explore below. + for (let i = 0; i < targetSignatures.length; i++) { + const related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], reportErrors); + if (!related) { + return Ternary.False; } - shouldElaborateErrors = false; + result &= related; } + } + else { + outer: for (const t of targetSignatures) { + // Only elaborate errors from the first failure + let shouldElaborateErrors = reportErrors; + for (const s of sourceSignatures) { + const related = signatureRelatedTo(s, t, shouldElaborateErrors); + if (related) { + result &= related; + errorInfo = saveErrorInfo; + continue outer; + } + shouldElaborateErrors = false; + } - if (shouldElaborateErrors) { - reportError(Diagnostics.Type_0_provides_no_match_for_the_signature_1, - typeToString(source), - signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + if (shouldElaborateErrors) { + reportError(Diagnostics.Type_0_provides_no_match_for_the_signature_1, + typeToString(source), + signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind)); + } + return Ternary.False; } - return Ternary.False; } return result; } @@ -9885,7 +9880,7 @@ namespace ts { case SyntaxKind.SetAccessor: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - if (!declaration.name) { + if (!(declaration as NamedDeclaration).name) { error(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); return; } @@ -9894,7 +9889,7 @@ namespace ts { default: diagnostic = Diagnostics.Variable_0_implicitly_has_an_1_type; } - error(declaration, diagnostic, declarationNameToString(declaration.name), typeAsString); + error(declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); } function reportErrorsFromWidening(declaration: Declaration, type: Type) { @@ -11799,7 +11794,7 @@ namespace ts { if (type === autoType || type === autoArrayType) { if (flowType === autoType || flowType === autoArrayType) { if (noImplicitAny) { - error(declaration.name, Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(getNameOfDeclaration(declaration), Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } return convertAutoToAny(flowType); @@ -13211,6 +13206,11 @@ namespace ts { let attributesTable = createMap(); let spread: Type = emptyObjectType; let attributesArray: Symbol[] = []; + let hasSpreadAnyType = false; + let typeToIntersect: Type; + let explicitlySpecifyChildrenAttribute = false; + const jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); + for (const attributeDecl of attributes.properties) { const member = attributeDecl.symbol; if (isJsxAttribute(attributeDecl)) { @@ -13228,6 +13228,9 @@ namespace ts { attributeSymbol.target = member; attributesTable.set(attributeSymbol.name, attributeSymbol); attributesArray.push(attributeSymbol); + if (attributeDecl.name.text === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } } else { Debug.assert(attributeDecl.kind === SyntaxKind.JsxSpreadAttribute); @@ -13237,33 +13240,36 @@ namespace ts { attributesTable = createMap(); } const exprType = checkExpression(attributeDecl.expression); - if (!isValidSpreadType(exprType)) { - error(attributeDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); - return anyType; - } if (isTypeAny(exprType)) { - return anyType; + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType(spread, exprType); + } + else { + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } - spread = getSpreadType(spread, exprType); } } - if (spread !== emptyObjectType) { - if (attributesArray.length > 0) { - spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); - attributesArray = []; - attributesTable = createMap(); - } - attributesArray = getPropertiesOfType(spread); - } - - attributesTable = createMap(); - if (attributesArray) { - forEach(attributesArray, (attr) => { - if (!filter || filter(attr)) { - attributesTable.set(attr.name, attr); + if (!hasSpreadAnyType) { + if (spread !== emptyObjectType) { + if (attributesArray.length > 0) { + spread = getSpreadType(spread, createJsxAttributesType(attributes.symbol, attributesTable)); + attributesArray = []; + attributesTable = createMap(); } - }); + attributesArray = getPropertiesOfType(spread); + } + + attributesTable = createMap(); + if (attributesArray) { + forEach(attributesArray, (attr) => { + if (!filter || filter(attr)) { + attributesTable.set(attr.name, attr); + } + }); + } } // Handle children attribute @@ -13284,11 +13290,11 @@ namespace ts { } } - // Error if there is a attribute named "children" and children element. - // This is because children element will overwrite the value from attributes - const jsxChildrenPropertyName = getJsxElementChildrenPropertyname(); - if (jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { - if (attributesTable.has(jsxChildrenPropertyName)) { + if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { + // Error if there is a attribute named "children" explicitly specified and children element. + // This is because children element will overwrite the value from attributes. + // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread. + if (explicitlySpecifyChildrenAttribute) { error(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, jsxChildrenPropertyName); } @@ -13301,7 +13307,13 @@ namespace ts { } } - return createJsxAttributesType(attributes.symbol, attributesTable); + if (hasSpreadAnyType) { + return anyType; + } + + const attributeType = createJsxAttributesType(attributes.symbol, attributesTable); + return typeToIntersect && attributesTable.size ? getIntersectionType([typeToIntersect, attributeType]) : + typeToIntersect ? typeToIntersect : attributeType; /** * Create anonymous type from given attributes symbol table. @@ -13310,8 +13322,7 @@ namespace ts { */ function createJsxAttributesType(symbol: Symbol, attributesTable: Map) { const result = createAnonymousType(symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral; - result.flags |= TypeFlags.JsxAttributes | TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag; + result.flags |= TypeFlags.JsxAttributes | TypeFlags.ContainsObjectLiteral; result.objectFlags |= ObjectFlags.ObjectLiteral; return result; } @@ -13397,7 +13408,18 @@ namespace ts { } } - return getUnionType(map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); + const instantiatedSignatures = []; + for (const signature of signatures) { + if (signature.typeParameters) { + const typeArguments = fillMissingTypeArguments(/*typeArguments*/ undefined, signature.typeParameters, /*minTypeArgumentCount*/ 0); + instantiatedSignatures.push(getSignatureInstantiation(signature, typeArguments)); + } + else { + instantiatedSignatures.push(signature); + } + } + + return getUnionType(map(instantiatedSignatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /** @@ -13457,6 +13479,20 @@ namespace ts { return _jsxElementChildrenPropertyName; } + function getApparentTypeOfJsxPropsType(propsType: Type): Type { + if (!propsType) { + return undefined; + } + if (propsType.flags & TypeFlags.Intersection) { + const propsApparentType: Type[] = []; + for (const t of (propsType).types) { + propsApparentType.push(getApparentType(t)); + } + return getIntersectionType(propsApparentType); + } + return getApparentType(propsType); + } + /** * Get JSX attributes type by trying to resolve openingLikeElement as a stateless function component. * Return only attributes type of successfully resolved call signature. @@ -13477,6 +13513,7 @@ namespace ts { if (callSignature !== unknownSignature) { const callReturnType = callSignature && getReturnTypeOfSignature(callSignature); let paramType = callReturnType && (callSignature.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(callSignature.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { // Intersect in JSX.IntrinsicAttributes if it exists const intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes); @@ -13514,7 +13551,8 @@ namespace ts { let allMatchingAttributesType: Type; for (const candidate of candidatesOutArray) { const callReturnType = getReturnTypeOfSignature(candidate); - const paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + let paramType = callReturnType && (candidate.parameters.length === 0 ? emptyObjectType : getTypeOfSymbol(candidate.parameters[0])); + paramType = getApparentTypeOfJsxPropsType(paramType); if (callReturnType && isTypeAssignableTo(callReturnType, jsxStatelessElementType)) { let shouldBeCandidate = true; for (const attribute of openingLikeElement.attributes.properties) { @@ -13819,6 +13857,34 @@ namespace ts { checkJsxAttributesAssignableToTagNameAttributes(node); } + /** + * Check if a property with the given name is known anywhere in the given type. In an object type, a property + * is considered known if the object type is empty and the check is for assignability, if the object type has + * index signatures, or if the property is actually declared in the object type. In a union or intersection + * type, a property is considered known if it is known in any constituent type. + * @param targetType a type to search a given name in + * @param name a property name to search + * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType + */ + function isKnownProperty(targetType: Type, name: string, isComparingJsxAttributes: boolean): boolean { + if (targetType.flags & TypeFlags.Object) { + const resolved = resolveStructuredTypeMembers(targetType); + if (resolved.stringIndexInfo || resolved.numberIndexInfo && isNumericLiteralName(name) || + getPropertyOfType(targetType, name) || isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) { + // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known. + return true; + } + } + else if (targetType.flags & TypeFlags.UnionOrIntersection) { + for (const t of (targetType).types) { + if (isKnownProperty(t, name, isComparingJsxAttributes)) { + return true; + } + } + } + return false; + } + /** * Check whether the given attributes of JSX opening-like element is assignable to the tagName attributes. * Get the attributes type of the opening-like element through resolving the tagName, "target attributes" @@ -13851,7 +13917,19 @@ namespace ts { error(openingLikeElement, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else { - checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // Check if sourceAttributesType assignable to targetAttributesType though this check will allow excess properties + const isSourceAttributeTypeAssignableToTarget = checkTypeAssignableTo(sourceAttributesType, targetAttributesType, openingLikeElement.attributes.properties.length > 0 ? openingLikeElement.attributes : openingLikeElement); + // After we check for assignability, we will do another pass to check that all explicitly specified attributes have correct name corresponding in targetAttributeType. + // This will allow excess properties in spread type as it is very common pattern to spread outter attributes into React component in its render method. + if (isSourceAttributeTypeAssignableToTarget && !isTypeAny(sourceAttributesType) && !isTypeAny(targetAttributesType)) { + for (const attribute of openingLikeElement.attributes.properties) { + if (isJsxAttribute(attribute) && !isKnownProperty(targetAttributesType, attribute.name.text, /*isComparingJsxAttributes*/ true)) { + error(attribute, Diagnostics.Property_0_does_not_exist_on_type_1, attribute.name.text, typeToString(targetAttributesType)); + // We break here so that errors won't be cascading + break; + } + } + } } } @@ -15334,7 +15412,7 @@ namespace ts { // only the class declaration node will have the Abstract flag set. const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && getModifierFlags(valueDecl) & ModifierFlags.Abstract) { - error(node, Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, declarationNameToString(valueDecl.name)); + error(node, Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, declarationNameToString(getNameOfDeclaration(valueDecl))); return resolveErrorCall(node); } @@ -15798,11 +15876,11 @@ namespace ts { const links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); + const name = getNameOfDeclaration(parameter.valueDeclaration); // if inference didn't come up with anything but {}, fall back to the binding pattern if present. if (links.type === emptyObjectType && - (parameter.valueDeclaration.name.kind === SyntaxKind.ObjectBindingPattern || - parameter.valueDeclaration.name.kind === SyntaxKind.ArrayBindingPattern)) { - links.type = getTypeFromBindingPattern(parameter.valueDeclaration.name); + (name.kind === SyntaxKind.ObjectBindingPattern || name.kind === SyntaxKind.ArrayBindingPattern)) { + links.type = getTypeFromBindingPattern(name); } assignBindingElementTypes(parameter.valueDeclaration); } @@ -15947,7 +16025,7 @@ namespace ts { // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - return (functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async + return (functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async ? createPromiseReturnType(func, widenedType) // Async function : widenedType; // Generator function, AsyncGenerator function, or normal function } @@ -16163,7 +16241,7 @@ namespace ts { const functionFlags = getFunctionFlags(node); const returnOrPromisedType = node.type && - ((functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async ? + ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async ? checkAsyncFunctionReturnType(node) : // Async function getTypeFromTypeNode(node.type)); // AsyncGenerator function, Generator function, or normal function @@ -16193,7 +16271,7 @@ namespace ts { // its return type annotation. const exprType = checkExpression(node.body); if (returnOrPromisedType) { - if ((functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async) { // Async function + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async) { // Async function const awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); checkTypeAssignableTo(awaitedType, returnOrPromisedType, node.body); } @@ -16933,12 +17011,16 @@ namespace ts { // we are in a yield context. const functionFlags = func && getFunctionFlags(func); if (node.asteriskToken) { - if (functionFlags & FunctionFlags.Async) { - if (languageVersion < ScriptTarget.ES2017) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncDelegator); - } + // Async generator functions prior to ESNext require the __await, __asyncDelegator, + // and __asyncValues helpers + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.AsyncGenerator && + languageVersion < ScriptTarget.ESNext) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncDelegatorIncludes); } - else if (languageVersion < ScriptTarget.ES2015 && compilerOptions.downlevelIteration) { + + // Generator functions prior to ES2015 require the __values helper + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Generator && + languageVersion < ScriptTarget.ES2015 && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, ExternalEmitHelpers.Values); } } @@ -17457,18 +17539,20 @@ namespace ts { } const functionFlags = getFunctionFlags(node); - if ((functionFlags & FunctionFlags.InvalidAsyncOrAsyncGenerator) === FunctionFlags.Async && languageVersion < ScriptTarget.ES2017) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.Awaiter); - if (languageVersion < ScriptTarget.ES2015) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.Generator); + if (!(functionFlags & FunctionFlags.Invalid)) { + // Async generators prior to ESNext require the __await and __asyncGenerator helpers + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.AsyncGenerator && languageVersion < ScriptTarget.ESNext) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncGeneratorIncludes); } - } - if ((functionFlags & FunctionFlags.InvalidGenerator) === FunctionFlags.Generator) { - if (functionFlags & FunctionFlags.Async && languageVersion < ScriptTarget.ES2017) { - checkExternalEmitHelpers(node, ExternalEmitHelpers.AsyncGenerator); + // Async functions prior to ES2017 require the __awaiter helper + if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async && languageVersion < ScriptTarget.ES2017) { + checkExternalEmitHelpers(node, ExternalEmitHelpers.Awaiter); } - else if (languageVersion < ScriptTarget.ES2015) { + + // Generator functions, Async functions, and Async Generator functions prior to + // ES2015 require the __generator helper + if ((functionFlags & FunctionFlags.AsyncGenerator) !== FunctionFlags.Normal && languageVersion < ScriptTarget.ES2015) { checkExternalEmitHelpers(node, ExternalEmitHelpers.Generator); } } @@ -17496,7 +17580,7 @@ namespace ts { if (node.type) { const functionFlags = getFunctionFlags(node); - if ((functionFlags & FunctionFlags.InvalidGenerator) === FunctionFlags.Generator) { + if ((functionFlags & (FunctionFlags.Invalid | FunctionFlags.Generator)) === FunctionFlags.Generator) { const returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -17516,7 +17600,7 @@ namespace ts { checkTypeAssignableTo(iterableIteratorInstantiation, returnType, node.type); } } - else if ((functionFlags & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async) { + else if ((functionFlags & FunctionFlags.AsyncGenerator) === FunctionFlags.Async) { checkAsyncFunctionReturnType(node); } } @@ -17640,7 +17724,7 @@ namespace ts { } if (names.get(memberName)) { - error(member.symbol.valueDeclaration.name, Diagnostics.Duplicate_identifier_0, memberName); + error(getNameOfDeclaration(member.symbol.valueDeclaration), Diagnostics.Duplicate_identifier_0, memberName); error(member.name, Diagnostics.Duplicate_identifier_0, memberName); } else { @@ -17741,7 +17825,8 @@ namespace ts { } function containsSuperCallAsComputedPropertyName(n: Declaration): boolean { - return n.name && containsSuperCall(n.name); + const name = getNameOfDeclaration(n); + return name && containsSuperCall(name); } function containsSuperCall(n: Node): boolean { @@ -18036,16 +18121,16 @@ namespace ts { forEach(overloads, o => { const deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; if (deviation & ModifierFlags.Export) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); } else if (deviation & ModifierFlags.Ambient) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } else if (deviation & (ModifierFlags.Private | ModifierFlags.Protected)) { - error(o.name || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + error(getNameOfDeclaration(o) || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } else if (deviation & ModifierFlags.Abstract) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); } }); } @@ -18057,7 +18142,7 @@ namespace ts { forEach(overloads, o => { const deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; if (deviation) { - error(o.name, Diagnostics.Overload_signatures_must_all_be_optional_or_required); + error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_optional_or_required); } }); } @@ -18193,7 +18278,7 @@ namespace ts { if (duplicateFunctionDeclaration) { forEach(declarations, declaration => { - error(declaration.name, Diagnostics.Duplicate_function_implementation); + error(getNameOfDeclaration(declaration), Diagnostics.Duplicate_function_implementation); }); } @@ -18275,12 +18360,13 @@ namespace ts { for (const d of symbol.declarations) { const declarationSpaces = getDeclarationSpaces(d); + const name = getNameOfDeclaration(d); // Only error on the declarations that contributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { - error(d.name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(d.name)); + error(name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(name)); } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { - error(d.name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(d.name)); + error(name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(name)); } } } @@ -18861,15 +18947,16 @@ namespace ts { if (!local.isReferenced) { if (local.valueDeclaration && getRootDeclaration(local.valueDeclaration).kind === SyntaxKind.Parameter) { const parameter = getRootDeclaration(local.valueDeclaration); + const name = getNameOfDeclaration(local.valueDeclaration); if (compilerOptions.noUnusedParameters && !isParameterPropertyDeclaration(parameter) && !parameterIsThisKeyword(parameter) && - !parameterNameStartsWithUnderscore(local.valueDeclaration.name)) { - error(local.valueDeclaration.name, Diagnostics._0_is_declared_but_never_used, local.name); + !parameterNameStartsWithUnderscore(name)) { + error(name, Diagnostics._0_is_declared_but_never_used, local.name); } } else if (compilerOptions.noUnusedLocals) { - forEach(local.declarations, d => errorUnusedLocal(d.name || d, local.name)); + forEach(local.declarations, d => errorUnusedLocal(getNameOfDeclaration(d) || d, local.name)); } } }); @@ -18953,7 +19040,7 @@ namespace ts { if (!local.isReferenced && !local.exportSymbol) { for (const declaration of local.declarations) { if (!isAmbientModule(declaration)) { - errorUnusedLocal(declaration.name, local.name); + errorUnusedLocal(getNameOfDeclaration(declaration), local.name); } } } @@ -19032,7 +19119,7 @@ namespace ts { if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureThis) { const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { - error((node).name, Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); + error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } else { error(node, Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference); @@ -19047,7 +19134,7 @@ namespace ts { if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureNewTarget) { const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { - error((node).name, Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); + error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference); } else { error(node, Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference); @@ -19346,7 +19433,7 @@ namespace ts { checkTypeAssignableTo(checkExpressionCached(node.initializer), declarationType, node, /*headMessage*/ undefined); } if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) { - error(symbol.valueDeclaration.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); + error(getNameOfDeclaration(symbol.valueDeclaration), Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name)); } } @@ -19483,11 +19570,14 @@ namespace ts { if (node.kind === SyntaxKind.ForOfStatement) { if ((node).awaitModifier) { - if (languageVersion < ScriptTarget.ES2017) { + const functionFlags = getFunctionFlags(getContainingFunction(node)); + if ((functionFlags & (FunctionFlags.Invalid | FunctionFlags.Async)) === FunctionFlags.Async && languageVersion < ScriptTarget.ESNext) { + // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper checkExternalEmitHelpers(node, ExternalEmitHelpers.ForAwaitOfIncludes); } } - else if (languageVersion < ScriptTarget.ES2015 && compilerOptions.downlevelIteration) { + else if (compilerOptions.downlevelIteration && languageVersion < ScriptTarget.ES2015) { + // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled checkExternalEmitHelpers(node, ExternalEmitHelpers.ForOfIncludes); } } @@ -19917,7 +20007,7 @@ namespace ts { } function isUnwrappedReturnTypeVoidOrAny(func: FunctionLikeDeclaration, returnType: Type): boolean { - const unwrappedReturnType = (getFunctionFlags(func) & FunctionFlags.AsyncOrAsyncGenerator) === FunctionFlags.Async + const unwrappedReturnType = (getFunctionFlags(func) & FunctionFlags.AsyncGenerator) === FunctionFlags.Async ? getPromisedTypeOfPromise(returnType) // Async function : returnType; // AsyncGenerator function, Generator function, or normal function return unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, TypeFlags.Void | TypeFlags.Any); @@ -20174,14 +20264,17 @@ namespace ts { const propDeclaration = prop.valueDeclaration; // index is numeric and property name is not valid numeric literal - if (indexKind === IndexKind.Number && !(propDeclaration ? isNumericName(propDeclaration.name) : isNumericLiteralName(prop.name))) { + if (indexKind === IndexKind.Number && !(propDeclaration ? isNumericName(getNameOfDeclaration(propDeclaration)) : isNumericLiteralName(prop.name))) { return; } // perform property check if property or indexer is declared in 'type' - // this allows to rule out cases when both property and indexer are inherited from the base class + // this allows us to rule out cases when both property and indexer are inherited from the base class let errorNode: Node; - if (propDeclaration && (propDeclaration.name.kind === SyntaxKind.ComputedPropertyName || prop.parent === containingType.symbol)) { + if (propDeclaration && + (propDeclaration.kind === SyntaxKind.BinaryExpression || + getNameOfDeclaration(propDeclaration).kind === SyntaxKind.ComputedPropertyName || + prop.parent === containingType.symbol)) { errorNode = propDeclaration; } else if (indexDeclaration) { @@ -20544,7 +20637,7 @@ namespace ts { errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } - error(derived.valueDeclaration.name || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } } } @@ -20875,7 +20968,7 @@ namespace ts { // check that const is placed\omitted on all enum declarations forEach(enumSymbol.declarations, decl => { if (isConstEnumDeclaration(decl) !== enumIsConst) { - error(decl.name, Diagnostics.Enum_declarations_must_all_be_const_or_non_const); + error(getNameOfDeclaration(decl), Diagnostics.Enum_declarations_must_all_be_const_or_non_const); } }); } @@ -21768,7 +21861,7 @@ namespace ts { function isTypeDeclarationName(name: Node): boolean { return name.kind === SyntaxKind.Identifier && isTypeDeclaration(name.parent) && - (name.parent).name === name; + (name.parent).name === name; } function isTypeDeclaration(node: Node): boolean { @@ -22615,16 +22708,6 @@ namespace ts { getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } - function writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { - const classType = getDeclaredTypeOfSymbol(getSymbolOfNode(node)); - resolveBaseTypesOfClass(classType); - const baseType = classType.resolvedBaseTypes.length ? classType.resolvedBaseTypes[0] : unknownType; - if (!baseType.symbol) { - writer.reportIllegalExtends(); - } - getSymbolDisplayBuilder().buildTypeDisplay(baseType, writer, enclosingDeclaration, flags); - } - function hasGlobalName(name: string): boolean { return globals.has(name); } @@ -22718,7 +22801,6 @@ namespace ts { writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression, - writeBaseConstructorTypeOfClass, isSymbolAccessible, isEntityNameVisible, getConstantValue: node => { @@ -22924,6 +23006,7 @@ namespace ts { case ExternalEmitHelpers.Values: return "__values"; case ExternalEmitHelpers.Read: return "__read"; case ExternalEmitHelpers.Spread: return "__spread"; + case ExternalEmitHelpers.Await: return "__await"; case ExternalEmitHelpers.AsyncGenerator: return "__asyncGenerator"; case ExternalEmitHelpers.AsyncDelegator: return "__asyncDelegator"; case ExternalEmitHelpers.AsyncValues: return "__asyncValues"; diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 358b910f2f2..8d4ed6a214e 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -3,7 +3,7 @@ namespace ts { /** The version of the TypeScript compiler release */ - export const version = "2.3.1"; + export const version = "2.3.3"; } /* @internal */ diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 2bd8d5971fb..1b048fe897e 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -67,7 +67,7 @@ namespace ts { let errorNameNode: DeclarationName; const emitJsDocComments = compilerOptions.removeComments ? noop : writeJsDocComments; const emit = compilerOptions.stripInternal ? stripInternal : emitNode; - let noDeclare: boolean; + let needsDeclare = true; let moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; let asynchronousSubModuleDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]; @@ -110,11 +110,11 @@ namespace ts { resultHasExternalModuleIndicator = false; if (!isBundledEmit || !isExternalModule(sourceFile)) { - noDeclare = false; + needsDeclare = true; emitSourceFile(sourceFile); } else if (isExternalModule(sourceFile)) { - noDeclare = true; + needsDeclare = false; write(`declare module "${getResolvedExternalModuleName(host, sourceFile)}" {`); writeLine(); increaseIndent(); @@ -594,12 +594,11 @@ namespace ts { emitLines(node.statements); } - // Return a temp variable name to be used in `export default` statements. + // Return a temp variable name to be used in `export default`/`export class ... extends` statements. // The temp name will be of the form _default_counter. // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. - function getExportDefaultTempVariableName(): string { - const baseName = "_default"; + function getExportTempVariableName(baseName: string): string { if (!currentIdentifiers.has(baseName)) { return baseName; } @@ -613,24 +612,31 @@ namespace ts { } } + function emitTempVariableDeclaration(expr: Expression, baseName: string, diagnostic: SymbolAccessibilityDiagnostic, needsDeclare: boolean): string { + const tempVarName = getExportTempVariableName(baseName); + if (needsDeclare) { + write("declare "); + } + write("const "); + write(tempVarName); + write(": "); + writer.getSymbolAccessibilityDiagnostic = () => diagnostic; + resolver.writeTypeOfExpression(expr, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); + write(";"); + writeLine(); + return tempVarName; + } + function emitExportAssignment(node: ExportAssignment) { if (node.expression.kind === SyntaxKind.Identifier) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); } else { - // Expression - const tempVarName = getExportDefaultTempVariableName(); - if (!noDeclare) { - write("declare "); - } - write("var "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); - write(";"); - writeLine(); + const tempVarName = emitTempVariableDeclaration(node.expression, "_default", { + diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: node + }, needsDeclare); write(node.isExportEquals ? "export = " : "export default "); write(tempVarName); } @@ -644,13 +650,6 @@ namespace ts { // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); } - - function getDefaultExportAccessibilityDiagnostic(): SymbolAccessibilityDiagnostic { - return { - diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }; - } } function isModuleElementVisible(node: Declaration) { @@ -729,7 +728,7 @@ namespace ts { if (modifiers & ModifierFlags.Default) { write("default "); } - else if (node.kind !== SyntaxKind.InterfaceDeclaration && !noDeclare) { + else if (node.kind !== SyntaxKind.InterfaceDeclaration && needsDeclare) { write("declare "); } } @@ -1097,7 +1096,7 @@ namespace ts { } } - function emitHeritageClause(className: Identifier, typeReferences: ExpressionWithTypeArguments[], isImplementsList: boolean) { + function emitHeritageClause(typeReferences: ExpressionWithTypeArguments[], isImplementsList: boolean) { if (typeReferences) { write(isImplementsList ? " implements " : " extends "); emitCommaList(typeReferences, emitTypeOfTypeReference); @@ -1110,12 +1109,6 @@ namespace ts { else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) { write("null"); } - else { - writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - errorNameNode = className; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseTypeAliasValue, writer); - errorNameNode = undefined; - } function getHeritageClauseVisibilityError(): SymbolAccessibilityDiagnostic { let diagnosticMessage: DiagnosticMessage; @@ -1134,7 +1127,7 @@ namespace ts { return { diagnosticMessage, errorNode: node, - typeName: (node.parent.parent).name + typeName: getNameOfDeclaration(node.parent.parent) }; } } @@ -1151,23 +1144,43 @@ namespace ts { } } + const prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + const baseTypeNode = getClassExtendsHeritageClauseElement(node); + let tempVarName: string; + if (baseTypeNode && !isEntityNameExpression(baseTypeNode.expression)) { + tempVarName = baseTypeNode.expression.kind === SyntaxKind.NullKeyword ? + "null" : + emitTempVariableDeclaration(baseTypeNode.expression, `${node.name.text}_base`, { + diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: baseTypeNode, + typeName: node.name + }, !findAncestor(node, n => n.kind === SyntaxKind.ModuleDeclaration)); + } + emitJsDocComments(node); emitModuleElementDeclarationFlags(node); if (hasModifier(node, ModifierFlags.Abstract)) { write("abstract "); } - write("class "); writeTextOfNode(currentText, node.name); - const prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { - node.name; - emitHeritageClause(node.name, [baseTypeNode], /*isImplementsList*/ false); + if (!isEntityNameExpression(baseTypeNode.expression)) { + write(" extends "); + write(tempVarName); + if (baseTypeNode.typeArguments) { + write("<"); + emitCommaList(baseTypeNode.typeArguments, emitType); + write(">"); + } + } + else { + emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); + } } - emitHeritageClause(node.name, getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); + emitHeritageClause(getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); write(" {"); writeLine(); increaseIndent(); @@ -1189,7 +1202,7 @@ namespace ts { emitTypeParameters(node.typeParameters); const interfaceExtendsTypes = filter(getInterfaceBaseTypeNodes(node), base => isEntityNameExpression(base.expression)); if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(node.name, interfaceExtendsTypes, /*isImplementsList*/ false); + emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); } write(" {"); writeLine(); diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 5c7486debe3..b425381a82b 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2937,6 +2937,28 @@ namespace ts { ); } + /** + * Gets the internal name of a declaration. This is primarily used for declarations that can be + * referred to by name in the body of an ES5 class function body. An internal name will *never* + * be prefixed with an module or namespace export modifier like "exports." when emitted as an + * expression. An internal name will also *never* be renamed due to a collision with a block + * scoped variable. + * + * @param node The declaration. + * @param allowComments A value indicating whether comments may be emitted for the name. + * @param allowSourceMaps A value indicating whether source maps may be emitted for the name. + */ + export function getInternalName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean) { + return getName(node, allowComments, allowSourceMaps, EmitFlags.LocalName | EmitFlags.InternalName); + } + + /** + * Gets whether an identifier should only be referred to by its internal name. + */ + export function isInternalName(node: Identifier) { + return (getEmitFlags(node) & EmitFlags.InternalName) !== 0; + } + /** * Gets the local name of a declaration. This is primarily used for declarations that can be * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A @@ -2992,9 +3014,10 @@ namespace ts { } function getName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean, emitFlags?: EmitFlags) { - if (node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name)) { - const name = getMutableClone(node.name); - emitFlags |= getEmitFlags(node.name); + const nodeName = getNameOfDeclaration(node); + if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { + const name = getMutableClone(nodeName); + emitFlags |= getEmitFlags(nodeName); if (!allowSourceMaps) emitFlags |= EmitFlags.NoSourceMap; if (!allowComments) emitFlags |= EmitFlags.NoComments; if (emitFlags) setEmitFlags(name, emitFlags); diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index 3ac5dc5d878..cd3f1310100 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -813,7 +813,7 @@ namespace ts { // Create a synthetic text range for the return statement. const closingBraceLocation = createTokenRange(skipTrivia(currentText, node.members.end), SyntaxKind.CloseBraceToken); - const localName = getLocalName(node); + const localName = getInternalName(node); // The following partially-emitted expression exists purely to align our sourcemap // emit with the original emitter. @@ -870,7 +870,7 @@ namespace ts { /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, - getDeclarationName(node), + getInternalName(node), /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), /*type*/ undefined, @@ -3180,7 +3180,20 @@ namespace ts { const savedConvertedLoopState = convertedLoopState; convertedLoopState = undefined; const ancestorFacts = enterSubtree(HierarchyFacts.FunctionExcludes, HierarchyFacts.FunctionIncludes); - const updated = visitEachChild(node, visitor, context); + let updated: AccessorDeclaration; + if (node.transformFlags & TransformFlags.ContainsCapturedLexicalThis) { + const parameters = visitParameterList(node.parameters, visitor, context); + const body = transformFunctionBody(node); + if (node.kind === SyntaxKind.GetAccessor) { + updated = updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body); + } + else { + updated = updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body); + } + } + else { + updated = visitEachChild(node, visitor, context); + } exitSubtree(ancestorFacts, HierarchyFacts.PropagateNewTargetMask, HierarchyFacts.None); convertedLoopState = savedConvertedLoopState; return updated; @@ -3712,7 +3725,7 @@ namespace ts { function substituteIdentifier(node: Identifier) { // Only substitute the identifier if we have enabled substitutions for block-scoped // bindings. - if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) { + if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings && !isInternalName(node)) { const original = getParseTreeNode(node, isIdentifier); if (original && isNameOfDeclarationWithCollidingName(original)) { return setTextRange(getGeneratedNameForNode(original), node); @@ -3735,7 +3748,7 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.VariableDeclaration: - return (parent).name === node + return (parent).name === node && resolver.isDeclarationWithCollidingName(parent); } @@ -3765,16 +3778,42 @@ namespace ts { * @param node An Identifier node. */ function substituteExpressionIdentifier(node: Identifier): Identifier { - if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) { + if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings && !isInternalName(node)) { const declaration = resolver.getReferencedDeclarationWithCollidingName(node); - if (declaration) { - return setTextRange(getGeneratedNameForNode(declaration.name), node); + if (declaration && !(isClassLike(declaration) && isPartOfClassBody(declaration, node))) { + return setTextRange(getGeneratedNameForNode(getNameOfDeclaration(declaration)), node); } } return node; } + function isPartOfClassBody(declaration: ClassLikeDeclaration, node: Identifier) { + let currentNode = getParseTreeNode(node); + if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) { + // if the node has no correlation to a parse tree node, its definitely not + // part of the body. + // if the node is outside of the document range of the declaration, its + // definitely not part of the body. + return false; + } + const blockScope = getEnclosingBlockScopeContainer(declaration); + while (currentNode) { + if (currentNode === blockScope || currentNode === declaration) { + // if we are in the enclosing block scope of the declaration, we are definitely + // not inside the class body. + return false; + } + if (isClassElement(currentNode) && currentNode.parent === declaration) { + // we are in the class body, but we treat static fields as outside of the class body + return currentNode.kind !== SyntaxKind.PropertyDeclaration + || (getModifierFlags(currentNode) & ModifierFlags.Static) === 0; + } + currentNode = currentNode.parent; + } + return false; + } + /** * Substitutes `this` when contained within an arrow function. * @@ -3789,8 +3828,9 @@ namespace ts { } function getClassMemberPrefix(node: ClassExpression | ClassDeclaration, member: ClassElement) { - const expression = getLocalName(node); - return hasModifier(member, ModifierFlags.Static) ? expression : createPropertyAccess(expression, "prototype"); + return hasModifier(member, ModifierFlags.Static) + ? getInternalName(node) + : createPropertyAccess(getInternalName(node), "prototype"); } function hasSynthesizedDefaultSuperCall(constructor: ConstructorDeclaration, hasExtendsClause: boolean) { diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 3aa5be551a6..81ebd0b8f5b 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -106,15 +106,11 @@ namespace ts { } } - function visitAwaitExpression(node: AwaitExpression) { + function visitAwaitExpression(node: AwaitExpression): Expression { if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { - const expression = visitNode(node.expression, visitor, isExpression); return setOriginalNode( setTextRange( - createYield( - /*asteriskToken*/ undefined, - createArrayLiteral([createLiteral("await"), expression]) - ), + createYield(createAwaitHelper(context, visitNode(node.expression, visitor, isExpression))), /*location*/ node ), node @@ -124,18 +120,26 @@ namespace ts { } function visitYieldExpression(node: YieldExpression) { - if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) { + if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator && node.asteriskToken) { const expression = visitNode(node.expression, visitor, isExpression); - return updateYield( - node, - node.asteriskToken, - node.asteriskToken - ? createAsyncDelegatorHelper(context, expression, expression) - : createArrayLiteral( - expression - ? [createLiteral("yield"), expression] - : [createLiteral("yield")] - ) + return setOriginalNode( + setTextRange( + createYield( + createAwaitHelper(context, + updateYield( + node, + node.asteriskToken, + createAsyncDelegatorHelper( + context, + createAsyncValuesHelper(context, expression, expression), + expression + ) + ) + ) + ), + node + ), + node ); } return visitEachChild(node, visitor, context); @@ -347,6 +351,10 @@ namespace ts { ); } + function awaitAsYield(expression: Expression) { + return createYield(/*asteriskToken*/ undefined, enclosingFunctionFlags & FunctionFlags.Generator ? createAwaitHelper(context, expression) : expression); + } + function transformForAwaitOfStatement(node: ForOfStatement, outermostLabeledStatement: LabeledStatement) { const expression = visitNode(node.expression, visitor, isExpression); const iterator = isIdentifier(expression) ? getGeneratedNameForNode(expression) : createTempVariable(/*recordTempVariable*/ undefined); @@ -354,16 +362,11 @@ namespace ts { const errorRecord = createUniqueName("e"); const catchVariable = getGeneratedNameForNode(errorRecord); const returnMethod = createTempVariable(/*recordTempVariable*/ undefined); - const values = createAsyncValuesHelper(context, expression, /*location*/ node.expression); - const next = createYield( - /*asteriskToken*/ undefined, - enclosingFunctionFlags & FunctionFlags.Generator - ? createArrayLiteral([ - createLiteral("await"), - createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, []) - ]) - : createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, []) - ); + const callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression); + const callNext = createCall(createPropertyAccess(iterator, "next" ), /*typeArguments*/ undefined, []); + const getDone = createPropertyAccess(result, "done"); + const getValue = createPropertyAccess(result, "value"); + const callReturn = createFunctionCall(returnMethod, iterator, []); hoistVariableDeclaration(errorRecord); hoistVariableDeclaration(returnMethod); @@ -374,16 +377,19 @@ namespace ts { /*initializer*/ setEmitFlags( setTextRange( createVariableDeclarationList([ - setTextRange(createVariableDeclaration(iterator, /*type*/ undefined, values), node.expression), - createVariableDeclaration(result, /*type*/ undefined, next) + setTextRange(createVariableDeclaration(iterator, /*type*/ undefined, callValues), node.expression), + createVariableDeclaration(result) ]), node.expression ), EmitFlags.NoHoisting ), - /*condition*/ createLogicalNot(createPropertyAccess(result, "done")), - /*incrementor*/ createAssignment(result, next), - /*statement*/ convertForOfStatementHead(node, createPropertyAccess(result, "value")) + /*condition*/ createComma( + createAssignment(result, awaitAsYield(callNext)), + createLogicalNot(getDone) + ), + /*incrementor*/ undefined, + /*statement*/ convertForOfStatementHead(node, awaitAsYield(getValue)) ), /*location*/ node ), @@ -421,26 +427,14 @@ namespace ts { createLogicalAnd( createLogicalAnd( result, - createLogicalNot( - createPropertyAccess(result, "done") - ) + createLogicalNot(getDone) ), createAssignment( returnMethod, createPropertyAccess(iterator, "return") ) ), - createStatement( - createYield( - /*asteriskToken*/ undefined, - enclosingFunctionFlags & FunctionFlags.Generator - ? createArrayLiteral([ - createLiteral("await"), - createFunctionCall(returnMethod, iterator, []) - ]) - : createFunctionCall(returnMethod, iterator, []) - ) - ) + createStatement(awaitAsYield(callReturn)) ), EmitFlags.SingleLine ) @@ -880,27 +874,39 @@ namespace ts { ); } + const awaitHelper: EmitHelper = { + name: "typescript:await", + scoped: false, + text: ` + var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } + ` + }; + + function createAwaitHelper(context: TransformationContext, expression: Expression) { + context.requestEmitHelper(awaitHelper); + return createCall(getHelperName("__await"), /*typeArguments*/ undefined, [expression]); + } + const asyncGeneratorHelper: EmitHelper = { name: "typescript:asyncGenerator", scoped: false, text: ` var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), q = [], c, i; - return i = { next: verb("next"), "throw": verb("throw"), "return": verb("return") }, i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; } - function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } } - function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? send : fulfill, reject); } - function send(value) { settle(c[2], { value: value, done: false }); } + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } - function settle(f, v) { c = void 0, f(v), next(); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; ` }; function createAsyncGeneratorHelper(context: TransformationContext, generatorFunc: FunctionExpression) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncGeneratorHelper); // Mark this node as originally an async function @@ -922,16 +928,16 @@ namespace ts { scoped: false, text: ` var __asyncDelegator = (this && this.__asyncDelegator) || function (o) { - var i = { next: verb("next"), "throw": verb("throw", function (e) { throw e; }), "return": verb("return", function (v) { return { value: v, done: true }; }) }, p; - return o = __asyncValues(o), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { return function (v) { return v = p && n === "throw" ? f(v) : p && v.done ? v : { value: p ? ["yield", v.value] : ["await", (o[n] || f).call(o, v)], done: false }, p = !p, v; }; } + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; ` }; function createAsyncDelegatorHelper(context: TransformationContext, expression: Expression, location?: TextRange) { + context.requestEmitHelper(awaitHelper); context.requestEmitHelper(asyncDelegator); - context.requestEmitHelper(asyncValues); return setTextRange( createCall( getHelperName("__asyncDelegator"), diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 2389ba80753..cc177730c8e 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -605,10 +605,13 @@ namespace ts { export interface Declaration extends Node { _declarationBrand: any; + } + + export interface NamedDeclaration extends Declaration { name?: DeclarationName; } - export interface DeclarationStatement extends Declaration, Statement { + export interface DeclarationStatement extends NamedDeclaration, Statement { name?: Identifier | StringLiteral | NumericLiteral; } @@ -622,7 +625,7 @@ namespace ts { expression: LeftHandSideExpression; } - export interface TypeParameterDeclaration extends Declaration { + export interface TypeParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.TypeParameter; parent?: DeclarationWithTypeParameters; name: Identifier; @@ -633,7 +636,7 @@ namespace ts { expression?: Expression; } - export interface SignatureDeclaration extends Declaration { + export interface SignatureDeclaration extends NamedDeclaration { name?: PropertyName; typeParameters?: NodeArray; parameters: NodeArray; @@ -650,7 +653,7 @@ namespace ts { export type BindingName = Identifier | BindingPattern; - export interface VariableDeclaration extends Declaration { + export interface VariableDeclaration extends NamedDeclaration { kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList | CatchClause; name: BindingName; // Declared variable name @@ -664,7 +667,7 @@ namespace ts { declarations: NodeArray; } - export interface ParameterDeclaration extends Declaration { + export interface ParameterDeclaration extends NamedDeclaration { kind: SyntaxKind.Parameter; parent?: SignatureDeclaration; dotDotDotToken?: DotDotDotToken; // Present on rest parameter @@ -674,7 +677,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface BindingElement extends Declaration { + export interface BindingElement extends NamedDeclaration { kind: SyntaxKind.BindingElement; parent?: BindingPattern; propertyName?: PropertyName; // Binding property name (in object binding pattern) @@ -699,7 +702,7 @@ namespace ts { initializer?: Expression; // Optional initializer } - export interface ObjectLiteralElement extends Declaration { + export interface ObjectLiteralElement extends NamedDeclaration { _objectLiteralBrandBrand: any; name?: PropertyName; } @@ -743,7 +746,7 @@ namespace ts { // SyntaxKind.ShorthandPropertyAssignment // SyntaxKind.EnumMember // SyntaxKind.JSDocPropertyTag - export interface VariableLikeDeclaration extends Declaration { + export interface VariableLikeDeclaration extends NamedDeclaration { propertyName?: PropertyName; dotDotDotToken?: DotDotDotToken; name: DeclarationName; @@ -752,7 +755,7 @@ namespace ts { initializer?: Expression; } - export interface PropertyLikeDeclaration extends Declaration { + export interface PropertyLikeDeclaration extends NamedDeclaration { name: PropertyName; } @@ -1216,8 +1219,7 @@ namespace ts { export type BinaryOperatorToken = Token; - // Binary expressions can be declarations if they are 'exports.foo = bar' expressions in JS files - export interface BinaryExpression extends Expression, Declaration { + export interface BinaryExpression extends Expression, Declaration { kind: SyntaxKind.BinaryExpression; left: Expression; operatorToken: BinaryOperatorToken; @@ -1417,7 +1419,7 @@ namespace ts { export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression; export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; - export interface PropertyAccessExpression extends MemberExpression, Declaration { + export interface PropertyAccessExpression extends MemberExpression, NamedDeclaration { kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; @@ -1762,7 +1764,7 @@ namespace ts { export type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration; - export interface ClassLikeDeclaration extends Declaration { + export interface ClassLikeDeclaration extends NamedDeclaration { name?: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; @@ -1778,12 +1780,12 @@ namespace ts { kind: SyntaxKind.ClassExpression; } - export interface ClassElement extends Declaration { + export interface ClassElement extends NamedDeclaration { _classElementBrand: any; name?: PropertyName; } - export interface TypeElement extends Declaration { + export interface TypeElement extends NamedDeclaration { _typeElementBrand: any; name?: PropertyName; questionToken?: QuestionToken; @@ -1811,7 +1813,7 @@ namespace ts { type: TypeNode; } - export interface EnumMember extends Declaration { + export interface EnumMember extends NamedDeclaration { kind: SyntaxKind.EnumMember; parent?: EnumDeclaration; // This does include ComputedPropertyName, but the parser will give an error @@ -1900,14 +1902,14 @@ namespace ts { // import d, * as ns from "mod" => name = d, namedBinding: NamespaceImport = { name: ns } // import { a, b as x } from "mod" => name = undefined, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} // import d, { a, b as x } from "mod" => name = d, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]} - export interface ImportClause extends Declaration { + export interface ImportClause extends NamedDeclaration { kind: SyntaxKind.ImportClause; parent?: ImportDeclaration; name?: Identifier; // Default binding namedBindings?: NamedImportBindings; } - export interface NamespaceImport extends Declaration { + export interface NamespaceImport extends NamedDeclaration { kind: SyntaxKind.NamespaceImport; parent?: ImportClause; name: Identifier; @@ -1940,14 +1942,14 @@ namespace ts { export type NamedImportsOrExports = NamedImports | NamedExports; - export interface ImportSpecifier extends Declaration { + export interface ImportSpecifier extends NamedDeclaration { kind: SyntaxKind.ImportSpecifier; parent?: NamedImports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) name: Identifier; // Declared name } - export interface ExportSpecifier extends Declaration { + export interface ExportSpecifier extends NamedDeclaration { kind: SyntaxKind.ExportSpecifier; parent?: NamedExports; propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent) @@ -2113,7 +2115,7 @@ namespace ts { typeExpression: JSDocTypeExpression; } - export interface JSDocTypedefTag extends JSDocTag, Declaration { + export interface JSDocTypedefTag extends JSDocTag, NamedDeclaration { kind: SyntaxKind.JSDocTypedefTag; fullName?: JSDocNamespaceDeclaration | Identifier; name?: Identifier; @@ -2727,7 +2729,6 @@ namespace ts { writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; - writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; // Returns the constant value this property access resolves to, or 'undefined' for a non-constant @@ -3940,14 +3941,15 @@ namespace ts { HelperName = 1 << 12, ExportName = 1 << 13, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal). LocalName = 1 << 14, // Ensure an export prefix is not added for an identifier that points to an exported declaration. - Indented = 1 << 15, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter). - NoIndentation = 1 << 16, // Do not indent the node. - AsyncFunctionBody = 1 << 17, - ReuseTempVariableScope = 1 << 18, // Reuse the existing temp variable scope during emit. - CustomPrologue = 1 << 19, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed). - NoHoisting = 1 << 20, // Do not hoist this declaration in --module system - HasEndOfDeclarationMarker = 1 << 21, // Declaration has an associated NotEmittedStatement to mark the end of the declaration - Iterator = 1 << 22, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable. + InternalName = 1 << 15, // The name is internal to an ES5 class body function. + Indented = 1 << 16, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter). + NoIndentation = 1 << 17, // Do not indent the node. + AsyncFunctionBody = 1 << 18, + ReuseTempVariableScope = 1 << 19, // Reuse the existing temp variable scope during emit. + CustomPrologue = 1 << 20, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed). + NoHoisting = 1 << 21, // Do not hoist this declaration in --module system + HasEndOfDeclarationMarker = 1 << 22, // Declaration has an associated NotEmittedStatement to mark the end of the declaration + Iterator = 1 << 23, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable. } export interface EmitHelper { @@ -3972,11 +3974,12 @@ namespace ts { Awaiter = 1 << 6, // __awaiter (used by ES2017 async functions transformation) Generator = 1 << 7, // __generator (used by ES2015 generator transformation) Values = 1 << 8, // __values (used by ES2015 for..of and yield* transformations) - Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation) + Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation) Spread = 1 << 10, // __spread (used by ES2015 array spread and argument list spread transformations) - AsyncGenerator = 1 << 11, // __asyncGenerator (used by ES2017 async generator transformation) - AsyncDelegator = 1 << 12, // __asyncDelegator (used by ES2017 async generator yield* transformation) - AsyncValues = 1 << 13, // __asyncValues (used by ES2017 for..await..of transformation) + Await = 1 << 11, // __await (used by ES2017 async generator transformation) + AsyncGenerator = 1 << 12, // __asyncGenerator (used by ES2017 async generator transformation) + AsyncDelegator = 1 << 13, // __asyncDelegator (used by ES2017 async generator yield* transformation) + AsyncValues = 1 << 14, // __asyncValues (used by ES2017 for..await..of transformation) // Helpers included by ES2015 for..of ForOfIncludes = Values, @@ -3984,6 +3987,12 @@ namespace ts { // Helpers included by ES2017 for..await..of ForAwaitOfIncludes = AsyncValues, + // Helpers included by ES2017 async generators + AsyncGeneratorIncludes = Await | AsyncGenerator, + + // Helpers included by yield* in ES2017 async generators + AsyncDelegatorIncludes = Await | AsyncDelegator | AsyncValues, + // Helpers included by ES2015 spread SpreadIncludes = Read | Spread, diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 646a7b22e3f..53553f3915c 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -567,7 +567,7 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.TypeAliasDeclaration: - errorNode = (node).name; + errorNode = (node).name; break; case SyntaxKind.ArrowFunction: return getErrorSpanForArrowFunction(sourceFile, node); @@ -1767,12 +1767,42 @@ namespace ts { } if (isDeclaration(parent)) { - return (parent).name === name; + return parent.name === name; } return false; } + export function getNameOfDeclaration(declaration: Declaration): DeclarationName { + if (!declaration) { + return undefined; + } + if (declaration.kind === SyntaxKind.BinaryExpression) { + const kind = getSpecialPropertyAssignmentKind(declaration as BinaryExpression); + const lhs = (declaration as BinaryExpression).left; + switch (kind) { + case SpecialPropertyAssignmentKind.None: + case SpecialPropertyAssignmentKind.ModuleExports: + return undefined; + case SpecialPropertyAssignmentKind.ExportsProperty: + if (lhs.kind === SyntaxKind.Identifier) { + return (lhs as PropertyAccessExpression).name; + } + else { + return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; + } + case SpecialPropertyAssignmentKind.ThisProperty: + case SpecialPropertyAssignmentKind.Property: + return (lhs as PropertyAccessExpression).name; + case SpecialPropertyAssignmentKind.PrototypeProperty: + return ((lhs as PropertyAccessExpression).expression as PropertyAccessExpression).name; + } + } + else { + return (declaration as NamedDeclaration).name; + } + } + export function isLiteralComputedPropertyDeclarationName(node: Node) { return (node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NumericLiteral) && node.parent.kind === SyntaxKind.ComputedPropertyName && @@ -1793,7 +1823,7 @@ namespace ts { case SyntaxKind.PropertyAssignment: case SyntaxKind.PropertyAccessExpression: // Name in member declaration or property name in property access - return (parent).name === node; + return (parent).name === node; case SyntaxKind.QualifiedName: // Name on right hand side of dot in a type query if ((parent).right === node) { @@ -1925,16 +1955,18 @@ namespace ts { } export const enum FunctionFlags { - Normal = 0, - Generator = 1 << 0, - Async = 1 << 1, - AsyncOrAsyncGenerator = Async | Generator, - Invalid = 1 << 2, - InvalidAsyncOrAsyncGenerator = AsyncOrAsyncGenerator | Invalid, - InvalidGenerator = Generator | Invalid, + Normal = 0, // Function is a normal function + Generator = 1 << 0, // Function is a generator function or async generator function + Async = 1 << 1, // Function is an async function or an async generator function + Invalid = 1 << 2, // Function is a signature or overload and does not have a body. + AsyncGenerator = Async | Generator, // Function is an async generator function } - export function getFunctionFlags(node: FunctionLikeDeclaration) { + export function getFunctionFlags(node: FunctionLikeDeclaration | undefined) { + if (!node) { + return FunctionFlags.Invalid; + } + let flags = FunctionFlags.Normal; switch (node.kind) { case SyntaxKind.FunctionDeclaration: @@ -1989,7 +2021,8 @@ namespace ts { * Symbol. */ export function hasDynamicName(declaration: Declaration): boolean { - return declaration.name && isDynamicName(declaration.name); + const name = getNameOfDeclaration(declaration); + return name && isDynamicName(name); } export function isDynamicName(name: DeclarationName): boolean { @@ -2754,7 +2787,7 @@ namespace ts { forEach(declarations, (member: Declaration) => { if ((member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor) && hasModifier(member, ModifierFlags.Static) === hasModifier(accessor, ModifierFlags.Static)) { - const memberName = getPropertyNameForPropertyNameNode(member.name); + const memberName = getPropertyNameForPropertyNameNode((member as NamedDeclaration).name); const accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { if (!firstAccessor) { @@ -4070,7 +4103,7 @@ namespace ts { || kind === SyntaxKind.MergeDeclarationMarker; } - export function isDeclaration(node: Node): node is Declaration { + export function isDeclaration(node: Node): node is NamedDeclaration { return isDeclarationKind(node.kind); } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index a56d21ae345..83d27c951be 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -655,7 +655,7 @@ namespace FourSlash { ts.zipWith(endMarkers, definitions, (endMarker, definition, i) => { const marker = this.getMarkerByName(endMarker); if (marker.fileName !== definition.fileName || marker.position !== definition.textSpan.start) { - this.raiseError(`goToDefinition failed for definition ${i}: expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`); + this.raiseError(`goToDefinition failed for definition ${endMarker} (${i}): expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`); } }); } diff --git a/src/server/session.ts b/src/server/session.ts index 7be33f8bd2a..cee9698d6d9 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -369,7 +369,41 @@ namespace ts.server { protected logger: Logger; private canUseEvents: boolean; - constructor(opts: SessionOptions) { + // New ctor + constructor(opts: SessionOptions); + // Back-compat ctor, remove / deprecate + constructor( + /*0*/ host: ServerHost, + /*1*/ cancellationToken: ServerCancellationToken, + /*2*/ useSingleInferredProject: boolean, + /*3*/ typingsInstaller: ITypingsInstaller, + /*4*/ byteLength: (buf: string, encoding?: string) => number, + /*5*/ hrtime: (start?: number[]) => number[], + /*6*/ logger: server.Logger, + /*7*/ canUseEvents: boolean, + /*8*/ eventHandler?: ProjectServiceEventHandler, + /*9*/ throttleWaitMilliseconds?: number); + // Implementation + constructor(optsOrArg: SessionOptions | ServerHost) { + let opts: SessionOptions; + if (arguments.length === 1) { + opts = optsOrArg as SessionOptions; + } + else { + opts = { + host: arguments[0], + cancellationToken: arguments[1], + useSingleInferredProject: arguments[2], + typingsInstaller: arguments[3], + byteLength: arguments[4], + hrtime: arguments[5], + logger: arguments[6], + canUseEvents: arguments[7], + eventHandler: arguments[8], + throttleWaitMilliseconds: arguments[9] + }; + } + this.host = opts.host; this.cancellationToken = opts.cancellationToken; this.typingsInstaller = opts.typingsInstaller; diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 0de04d7a9b9..6585e994543 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -63,7 +63,7 @@ namespace ts.codefix { const declaration = declarations[0] as Declaration; // Clone name to remove leading trivia. - const name = getSynthesizedClone(declaration.name); + const name = getSynthesizedClone(getNameOfDeclaration(declaration)) as PropertyName; const visibilityModifier = createVisibilityModifier(getModifierFlags(declaration)); const modifiers = visibilityModifier ? createNodeArray([visibilityModifier]) : undefined; const type = checker.getWidenedType(checker.getTypeOfSymbolAtLocation(symbol, enclosingDeclaration)); @@ -231,4 +231,4 @@ namespace ts.codefix { } return undefined; } -} \ No newline at end of file +} diff --git a/src/services/completions.ts b/src/services/completions.ts index 6ac3762b4c7..b9d62df751e 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1214,7 +1214,7 @@ namespace ts.Completions { // TODO(jfreeman): Account for computed property name // NOTE: if one only performs this step when m.name is an identifier, // things like '__proto__' are not filtered out. - existingName = (m.name).text; + existingName = (getNameOfDeclaration(m) as Identifier).text; } existingMemberNames.set(existingName, true); diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index fd717fc546e..9ca90cfd5ef 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -908,7 +908,7 @@ namespace ts.FindAllReferences.Core { * position of property accessing, the referenceEntry of such position will be handled in the first case. */ if (!(flags & SymbolFlags.Transient) && search.includes(shorthandValueSymbol)) { - addReference(valueDeclaration.name, shorthandValueSymbol, search.location, state); + addReference(getNameOfDeclaration(valueDeclaration), shorthandValueSymbol, search.location, state); } } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index d7c32da5e8d..bc077ad6651 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -487,7 +487,7 @@ namespace ts.formatting { // falls through case SyntaxKind.PropertyDeclaration: case SyntaxKind.Parameter: - return (node).name.kind; + return getNameOfDeclaration(node).kind; } } diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index f2602903be3..09d1f2a248c 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -235,7 +235,7 @@ namespace ts.GoToDefinition { /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node: Declaration, symbolKind: string, symbolName: string, containerName: string): DefinitionInfo { - return createDefinitionInfoFromName(node.name || node, symbolKind, symbolName, containerName); + return createDefinitionInfoFromName(getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index 0108d830dd1..6e9a12a4c4d 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -212,6 +212,10 @@ namespace ts.FindAllReferences { return; } + if (!decl.importClause) { + return; + } + const { importClause } = decl; const { namedBindings } = importClause; @@ -533,7 +537,10 @@ namespace ts.FindAllReferences { return symbol.name; } - const name = forEach(symbol.declarations, ({ name }) => name && name.kind === SyntaxKind.Identifier && name.text); + const name = forEach(symbol.declarations, decl => { + const name = getNameOfDeclaration(decl); + return name && name.kind === SyntaxKind.Identifier && name.text; + }); Debug.assert(!!name); return name; } diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 2c8d43b535b..2fdc567b9bb 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -52,7 +52,7 @@ namespace ts.NavigateTo { rawItems = filter(rawItems, item => { const decl = item.declaration; if (decl.kind === SyntaxKind.ImportClause || decl.kind === SyntaxKind.ImportSpecifier || decl.kind === SyntaxKind.ImportEqualsDeclaration) { - const importer = checker.getSymbolAtLocation(decl.name); + const importer = checker.getSymbolAtLocation((decl as NamedDeclaration).name); const imported = checker.getAliasedSymbol(importer); return importer.name !== imported.name; } @@ -97,17 +97,20 @@ namespace ts.NavigateTo { } function tryAddSingleDeclarationName(declaration: Declaration, containers: string[]) { - if (declaration && declaration.name) { - const text = getTextOfIdentifierOrLiteral(declaration.name); - if (text !== undefined) { - containers.unshift(text); - } - else if (declaration.name.kind === SyntaxKind.ComputedPropertyName) { - return tryAddComputedPropertyName((declaration.name).expression, containers, /*includeLastPortion*/ true); - } - else { - // Don't know how to add this. - return false; + if (declaration) { + const name = getNameOfDeclaration(declaration); + if (name) { + const text = getTextOfIdentifierOrLiteral(name); + if (text !== undefined) { + containers.unshift(text); + } + else if (name.kind === SyntaxKind.ComputedPropertyName) { + return tryAddComputedPropertyName((name).expression, containers, /*includeLastPortion*/ true); + } + else { + // Don't know how to add this. + return false; + } } } @@ -143,8 +146,9 @@ namespace ts.NavigateTo { // First, if we started with a computed property name, then add all but the last // portion into the container array. - if (declaration.name.kind === SyntaxKind.ComputedPropertyName) { - if (!tryAddComputedPropertyName((declaration.name).expression, containers, /*includeLastPortion*/ false)) { + const name = getNameOfDeclaration(declaration); + if (name.kind === SyntaxKind.ComputedPropertyName) { + if (!tryAddComputedPropertyName((name).expression, containers, /*includeLastPortion*/ false)) { return undefined; } } @@ -190,6 +194,7 @@ namespace ts.NavigateTo { function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem { const declaration = rawItem.declaration; const container = getContainerNode(declaration); + const containerName = container && getNameOfDeclaration(container); return { name: rawItem.name, kind: getNodeKind(declaration), @@ -199,9 +204,9 @@ namespace ts.NavigateTo { fileName: rawItem.fileName, textSpan: createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? - containerName: container && container.name ? (container.name).text : "", - containerKind: container && container.name ? getNodeKind(container) : "" + containerName: containerName ? (containerName).text : "", + containerKind: containerName ? getNodeKind(container) : "" }; } } -} \ No newline at end of file +} diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 7a2508fcfd6..819202ff6f4 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -279,8 +279,8 @@ namespace ts.NavigationBar { function mergeChildren(children: NavigationBarNode[]): void { const nameToItems = createMap(); filterMutate(children, child => { - const decl = child.node; - const name = decl.name && nodeText(decl.name); + const declName = getNameOfDeclaration(child.node); + const name = declName && nodeText(declName); if (!name) { // Anonymous items are never merged. return true; @@ -378,9 +378,9 @@ namespace ts.NavigationBar { return getModuleName(node); } - const decl = node; - if (decl.name) { - return getPropertyNameForPropertyNameNode(decl.name); + const declName = getNameOfDeclaration(node); + if (declName) { + return getPropertyNameForPropertyNameNode(declName); } switch (node.kind) { case SyntaxKind.FunctionExpression: @@ -399,7 +399,7 @@ namespace ts.NavigationBar { return getModuleName(node); } - const name = (node).name; + const name = getNameOfDeclaration(node); if (name) { const text = nodeText(name); if (text.length > 0) { diff --git a/src/services/services.ts b/src/services/services.ts index 8f2cbb22379..f2d0482606e 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -575,14 +575,15 @@ namespace ts { } function getDeclarationName(declaration: Declaration) { - if (declaration.name) { - const result = getTextOfIdentifierOrLiteral(declaration.name); + const name = getNameOfDeclaration(declaration); + if (name) { + const result = getTextOfIdentifierOrLiteral(name); if (result !== undefined) { return result; } - if (declaration.name.kind === SyntaxKind.ComputedPropertyName) { - const expr = (declaration.name).expression; + if (name.kind === SyntaxKind.ComputedPropertyName) { + const expr = (name).expression; if (expr.kind === SyntaxKind.PropertyAccessExpression) { return (expr).name.text; } diff --git a/src/services/shims.ts b/src/services/shims.ts index 7588e16f3dc..c6d19f125eb 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -1038,7 +1038,11 @@ namespace ts { return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => { const compilerOptions = JSON.parse(compilerOptionsJson); const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host); - const resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + let resolvedFileName = result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined; + if (result.resolvedModule && result.resolvedModule.extension !== Extension.Ts && result.resolvedModule.extension !== Extension.Tsx && result.resolvedModule.extension !== Extension.Dts) { + resolvedFileName = undefined; + } + return { resolvedFileName, failedLookupLocations: result.failedLookupLocations diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 1e9d4c52654..80562c2950d 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -238,7 +238,7 @@ namespace ts { case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: case SyntaxKind.ModuleDeclaration: - return (node.parent).name === node; + return getNameOfDeclaration(node.parent) === node; case SyntaxKind.ElementAccessExpression: return (node.parent).argumentExpression === node; case SyntaxKind.ComputedPropertyName: diff --git a/tests/baselines/reference/blockScopedNamespaceDifferentFile.js b/tests/baselines/reference/blockScopedNamespaceDifferentFile.js new file mode 100644 index 00000000000..3eab7477c09 --- /dev/null +++ b/tests/baselines/reference/blockScopedNamespaceDifferentFile.js @@ -0,0 +1,35 @@ +//// [tests/cases/compiler/blockScopedNamespaceDifferentFile.ts] //// + +//// [test.ts] +// #15734 failed when test.ts comes before typings.d.ts +namespace C { + export class Name { + static funcData = A.AA.func(); + static someConst = A.AA.foo; + + constructor(parameters) {} + } +} + +//// [typings.d.ts] +declare namespace A { + namespace AA { + function func(): number; + const foo = ""; + } +} + + +//// [out.js] +// #15734 failed when test.ts comes before typings.d.ts +var C; +(function (C) { + var Name = (function () { + function Name(parameters) { + } + return Name; + }()); + Name.funcData = A.AA.func(); + Name.someConst = A.AA.foo; + C.Name = Name; +})(C || (C = {})); diff --git a/tests/baselines/reference/blockScopedNamespaceDifferentFile.symbols b/tests/baselines/reference/blockScopedNamespaceDifferentFile.symbols new file mode 100644 index 00000000000..b7192d0e12b --- /dev/null +++ b/tests/baselines/reference/blockScopedNamespaceDifferentFile.symbols @@ -0,0 +1,44 @@ +=== tests/cases/compiler/test.ts === +// #15734 failed when test.ts comes before typings.d.ts +namespace C { +>C : Symbol(C, Decl(test.ts, 0, 0)) + + export class Name { +>Name : Symbol(Name, Decl(test.ts, 1, 13)) + + static funcData = A.AA.func(); +>funcData : Symbol(Name.funcData, Decl(test.ts, 2, 23)) +>A.AA.func : Symbol(A.AA.func, Decl(typings.d.ts, 1, 18)) +>A.AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>A : Symbol(A, Decl(typings.d.ts, 0, 0)) +>AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>func : Symbol(A.AA.func, Decl(typings.d.ts, 1, 18)) + + static someConst = A.AA.foo; +>someConst : Symbol(Name.someConst, Decl(test.ts, 3, 38)) +>A.AA.foo : Symbol(A.AA.foo, Decl(typings.d.ts, 3, 13)) +>A.AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>A : Symbol(A, Decl(typings.d.ts, 0, 0)) +>AA : Symbol(A.AA, Decl(typings.d.ts, 0, 21)) +>foo : Symbol(A.AA.foo, Decl(typings.d.ts, 3, 13)) + + constructor(parameters) {} +>parameters : Symbol(parameters, Decl(test.ts, 6, 20)) + } +} + +=== tests/cases/compiler/typings.d.ts === +declare namespace A { +>A : Symbol(A, Decl(typings.d.ts, 0, 0)) + + namespace AA { +>AA : Symbol(AA, Decl(typings.d.ts, 0, 21)) + + function func(): number; +>func : Symbol(func, Decl(typings.d.ts, 1, 18)) + + const foo = ""; +>foo : Symbol(foo, Decl(typings.d.ts, 3, 13)) + } +} + diff --git a/tests/baselines/reference/blockScopedNamespaceDifferentFile.types b/tests/baselines/reference/blockScopedNamespaceDifferentFile.types new file mode 100644 index 00000000000..c03d51d2bc4 --- /dev/null +++ b/tests/baselines/reference/blockScopedNamespaceDifferentFile.types @@ -0,0 +1,46 @@ +=== tests/cases/compiler/test.ts === +// #15734 failed when test.ts comes before typings.d.ts +namespace C { +>C : typeof C + + export class Name { +>Name : Name + + static funcData = A.AA.func(); +>funcData : number +>A.AA.func() : number +>A.AA.func : () => number +>A.AA : typeof A.AA +>A : typeof A +>AA : typeof A.AA +>func : () => number + + static someConst = A.AA.foo; +>someConst : string +>A.AA.foo : "" +>A.AA : typeof A.AA +>A : typeof A +>AA : typeof A.AA +>foo : "" + + constructor(parameters) {} +>parameters : any + } +} + +=== tests/cases/compiler/typings.d.ts === +declare namespace A { +>A : typeof A + + namespace AA { +>AA : typeof AA + + function func(): number; +>func : () => number + + const foo = ""; +>foo : "" +>"" : "" + } +} + diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt new file mode 100644 index 00000000000..d90e6d506ff --- /dev/null +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.errors.txt @@ -0,0 +1,29 @@ +tests/cases/compiler/weird.js(1,1): error TS2304: Cannot find name 'someFunction'. +tests/cases/compiler/weird.js(1,23): error TS7006: Parameter 'BaseClass' implicitly has an 'any' type. +tests/cases/compiler/weird.js(6,13): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/weird.js(9,17): error TS7006: Parameter 'error' implicitly has an 'any' type. + + +==== tests/cases/compiler/weird.js (4 errors) ==== + someFunction(function(BaseClass) { + ~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'someFunction'. + ~~~~~~~~~ +!!! error TS7006: Parameter 'BaseClass' implicitly has an 'any' type. + 'use strict'; + const DEFAULT_MESSAGE = "nop!"; + class Hello extends BaseClass { + constructor() { + super(); + ~~~~~~~ +!!! error TS2346: Supplied parameters do not match any signature of call target. + this.foo = "bar"; + } + _render(error) { + ~~~~~ +!!! error TS7006: Parameter 'error' implicitly has an 'any' type. + const message = error.message || DEFAULT_MESSAGE; + } + } + }); + \ No newline at end of file diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.symbols b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.symbols new file mode 100644 index 00000000000..c9ee830a9a5 --- /dev/null +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/weird.js === +someFunction(function(BaseClass) { +>BaseClass : Symbol(BaseClass, Decl(weird.js, 0, 22)) + + class Hello extends BaseClass { +>Hello : Symbol(Hello, Decl(weird.js, 0, 34)) +>BaseClass : Symbol(BaseClass, Decl(weird.js, 0, 22)) + + constructor() { + this.foo = "bar"; +>this.foo : Symbol(Hello.foo, Decl(weird.js, 2, 17)) +>this : Symbol(Hello, Decl(weird.js, 0, 34)) +>foo : Symbol(Hello.foo, Decl(weird.js, 2, 17)) + } + } +}); + diff --git a/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.types b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.types new file mode 100644 index 00000000000..6a0a5ad1479 --- /dev/null +++ b/tests/baselines/reference/checkIndexConstraintOfJavascriptClassExpression.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/weird.js === +someFunction(function(BaseClass) { +>someFunction(function(BaseClass) { class Hello extends BaseClass { constructor() { this.foo = "bar"; } }}) : any +>someFunction : any +>function(BaseClass) { class Hello extends BaseClass { constructor() { this.foo = "bar"; } }} : (BaseClass: any) => void +>BaseClass : any + + class Hello extends BaseClass { +>Hello : Hello +>BaseClass : any + + constructor() { + this.foo = "bar"; +>this.foo = "bar" : "bar" +>this.foo : string +>this : this +>foo : string +>"bar" : "bar" + } + } +}); + diff --git a/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt b/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt index 758b295a49d..d9104608284 100644 --- a/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt +++ b/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/a.js(14,5): error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property. +tests/cases/compiler/a.js(14,10): error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property. ==== tests/cases/compiler/a.js (1 errors) ==== @@ -16,7 +16,7 @@ tests/cases/compiler/a.js(14,5): error TS2424: Class 'A' defines instance member constructor() { super(); this.foo = () => 3; - ~~~~~~~~~~~~~~~~~~ + ~~~ !!! error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property. } } diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.js b/tests/baselines/reference/checkJsxChildrenProperty12.js new file mode 100644 index 00000000000..0030d87483f --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty12.js @@ -0,0 +1,76 @@ +//// [file.tsx] +import React = require('react'); + +interface ButtonProp { + a: number, + b: string, + children: Button; +} + +class Button extends React.Component { + render() { + let condition: boolean; + if (condition) { + return + } + else { + return ( +
Hello World
+
); + } + } +} + +interface InnerButtonProp { + a: number +} + +class InnerButton extends React.Component { + render() { + return (); + } +} + + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var Button = (function (_super) { + __extends(Button, _super); + function Button() { + return _super !== null && _super.apply(this, arguments) || this; + } + Button.prototype.render = function () { + var condition; + if (condition) { + return ; + } + else { + return ( +
Hello World
+
); + } + }; + return Button; +}(React.Component)); +var InnerButton = (function (_super) { + __extends(InnerButton, _super); + function InnerButton() { + return _super !== null && _super.apply(this, arguments) || this; + } + InnerButton.prototype.render = function () { + return (); + }; + return InnerButton; +}(React.Component)); diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.symbols b/tests/baselines/reference/checkJsxChildrenProperty12.symbols new file mode 100644 index 00000000000..ccfb4b18875 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty12.symbols @@ -0,0 +1,80 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : Symbol(React, Decl(file.tsx, 0, 0)) + +interface ButtonProp { +>ButtonProp : Symbol(ButtonProp, Decl(file.tsx, 0, 32)) + + a: number, +>a : Symbol(ButtonProp.a, Decl(file.tsx, 2, 22)) + + b: string, +>b : Symbol(ButtonProp.b, Decl(file.tsx, 3, 14)) + + children: Button; +>children : Symbol(ButtonProp.children, Decl(file.tsx, 4, 14)) +>Button : Symbol(Button, Decl(file.tsx, 6, 1)) +} + +class Button extends React.Component { +>Button : Symbol(Button, Decl(file.tsx, 6, 1)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>ButtonProp : Symbol(ButtonProp, Decl(file.tsx, 0, 32)) + + render() { +>render : Symbol(Button.render, Decl(file.tsx, 8, 55)) + + let condition: boolean; +>condition : Symbol(condition, Decl(file.tsx, 10, 5)) + + if (condition) { +>condition : Symbol(condition, Decl(file.tsx, 10, 5)) + + return +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) +>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>this : Symbol(Button, Decl(file.tsx, 6, 1)) +>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) + } + else { + return ( +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) +>this.props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) +>this : Symbol(Button, Decl(file.tsx, 6, 1)) +>props : Symbol(React.Component.props, Decl(react.d.ts, 166, 37)) + +
Hello World
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) +>div : Symbol(JSX.IntrinsicElements.div, Decl(react.d.ts, 2399, 45)) + +
); +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) + } + } +} + +interface InnerButtonProp { +>InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 20, 1)) + + a: number +>a : Symbol(InnerButtonProp.a, Decl(file.tsx, 22, 27)) +} + +class InnerButton extends React.Component { +>InnerButton : Symbol(InnerButton, Decl(file.tsx, 24, 1)) +>React.Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>React : Symbol(React, Decl(file.tsx, 0, 0)) +>Component : Symbol(React.Component, Decl(react.d.ts, 158, 55)) +>InnerButtonProp : Symbol(InnerButtonProp, Decl(file.tsx, 20, 1)) + + render() { +>render : Symbol(InnerButton.render, Decl(file.tsx, 26, 65)) + + return (); +>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43)) +>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43)) + } +} + diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.types b/tests/baselines/reference/checkJsxChildrenProperty12.types new file mode 100644 index 00000000000..93a7d0f9be1 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty12.types @@ -0,0 +1,86 @@ +=== tests/cases/conformance/jsx/file.tsx === +import React = require('react'); +>React : typeof React + +interface ButtonProp { +>ButtonProp : ButtonProp + + a: number, +>a : number + + b: string, +>b : string + + children: Button; +>children : Button +>Button : Button +} + +class Button extends React.Component { +>Button : Button +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>ButtonProp : ButtonProp + + render() { +>render : () => JSX.Element + + let condition: boolean; +>condition : boolean + + if (condition) { +>condition : boolean + + return +> : JSX.Element +>InnerButton : typeof InnerButton +>this.props : ButtonProp & { children?: React.ReactNode; } +>this : this +>props : ButtonProp & { children?: React.ReactNode; } + } + else { + return ( +>(
Hello World
) : JSX.Element +>
Hello World
: JSX.Element +>InnerButton : typeof InnerButton +>this.props : ButtonProp & { children?: React.ReactNode; } +>this : this +>props : ButtonProp & { children?: React.ReactNode; } + +
Hello World
+>
Hello World
: JSX.Element +>div : any +>div : any + +
); +>InnerButton : typeof InnerButton + } + } +} + +interface InnerButtonProp { +>InnerButtonProp : InnerButtonProp + + a: number +>a : number +} + +class InnerButton extends React.Component { +>InnerButton : InnerButton +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component +>InnerButtonProp : InnerButtonProp + + render() { +>render : () => JSX.Element + + return (); +>() : JSX.Element +> : JSX.Element +>button : any +>button : any + } +} + diff --git a/tests/baselines/reference/checkJsxChildrenProperty13.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty13.errors.txt new file mode 100644 index 00000000000..c926980cab1 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty13.errors.txt @@ -0,0 +1,33 @@ +tests/cases/conformance/jsx/file.tsx(12,30): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. + + +==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== + import React = require('react'); + + interface ButtonProp { + a: number, + b: string, + children: Button; + } + + class Button extends React.Component { + render() { + // Error children are specified twice + return ( + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. +
Hello World
+
); + } + } + + interface InnerButtonProp { + a: number + } + + class InnerButton extends React.Component { + render() { + return (); + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/checkJsxChildrenProperty13.js b/tests/baselines/reference/checkJsxChildrenProperty13.js new file mode 100644 index 00000000000..8947e6b211f --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenProperty13.js @@ -0,0 +1,66 @@ +//// [file.tsx] +import React = require('react'); + +interface ButtonProp { + a: number, + b: string, + children: Button; +} + +class Button extends React.Component { + render() { + // Error children are specified twice + return ( +
Hello World
+
); + } +} + +interface InnerButtonProp { + a: number +} + +class InnerButton extends React.Component { + render() { + return (); + } +} + + +//// [file.jsx] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var React = require("react"); +var Button = (function (_super) { + __extends(Button, _super); + function Button() { + return _super !== null && _super.apply(this, arguments) || this; + } + Button.prototype.render = function () { + // Error children are specified twice + return ( +
Hello World
+
); + }; + return Button; +}(React.Component)); +var InnerButton = (function (_super) { + __extends(InnerButton, _super); + function InnerButton() { + return _super !== null && _super.apply(this, arguments) || this; + } + InnerButton.prototype.render = function () { + return (); + }; + return InnerButton; +}(React.Component)); diff --git a/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt index 6bb91bd6385..aeeceb8652e 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt @@ -2,7 +2,6 @@ tests/cases/conformance/jsx/file.tsx(14,15): error TS2322: Type '{ a: 10; b: "hi Type '{ a: 10; b: "hi"; }' is not assignable to type 'Prop'. Property 'children' is missing in type '{ a: 10; b: "hi"; }'. tests/cases/conformance/jsx/file.tsx(17,11): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. -tests/cases/conformance/jsx/file.tsx(25,11): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. tests/cases/conformance/jsx/file.tsx(31,11): error TS2322: Type '{ a: 10; b: "hi"; children: (Element | ((name: string) => Element))[]; }' is not assignable to type 'IntrinsicAttributes & Prop'. Type '{ a: 10; b: "hi"; children: (Element | ((name: string) => Element))[]; }' is not assignable to type 'Prop'. Types of property 'children' are incompatible. @@ -29,7 +28,7 @@ tests/cases/conformance/jsx/file.tsx(49,11): error TS2322: Type '{ a: 10; b: "hi Property 'type' is missing in type 'Element[]'. -==== tests/cases/conformance/jsx/file.tsx (7 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (6 errors) ==== import React = require('react'); interface Prop { @@ -61,8 +60,6 @@ tests/cases/conformance/jsx/file.tsx(49,11): error TS2322: Type '{ a: 10; b: "hi } let k1 = - ~~~~~~~~~~~~~~~~~~~~ -!!! error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. hi hi hi! ; diff --git a/tests/baselines/reference/classBlockScoping.js b/tests/baselines/reference/classBlockScoping.js new file mode 100644 index 00000000000..76d0dd892de --- /dev/null +++ b/tests/baselines/reference/classBlockScoping.js @@ -0,0 +1,71 @@ +//// [classBlockScoping.ts] +function f(b: boolean) { + let Foo: any; + if (b) { + Foo = class Foo { + static y = new Foo(); + + static x() { + new Foo(); + } + + m() { + new Foo(); + } + }; + + new Foo(); + } + else { + class Foo { + static y = new Foo(); + + static x() { + new Foo(); + } + + m() { + new Foo(); + } + } + + new Foo(); + } +} + +//// [classBlockScoping.js] +function f(b) { + var Foo; + if (b) { + Foo = (_a = (function () { + function Foo() { + } + Foo.x = function () { + new Foo(); + }; + Foo.prototype.m = function () { + new Foo(); + }; + return Foo; + }()), + _a.y = new _a(), + _a); + new Foo(); + } + else { + var Foo_1 = (function () { + function Foo() { + } + Foo.x = function () { + new Foo(); + }; + Foo.prototype.m = function () { + new Foo(); + }; + return Foo; + }()); + Foo_1.y = new Foo_1(); + new Foo_1(); + } + var _a; +} diff --git a/tests/baselines/reference/classBlockScoping.symbols b/tests/baselines/reference/classBlockScoping.symbols new file mode 100644 index 00000000000..571d54f2d8e --- /dev/null +++ b/tests/baselines/reference/classBlockScoping.symbols @@ -0,0 +1,64 @@ +=== tests/cases/compiler/classBlockScoping.ts === +function f(b: boolean) { +>f : Symbol(f, Decl(classBlockScoping.ts, 0, 0)) +>b : Symbol(b, Decl(classBlockScoping.ts, 0, 11)) + + let Foo: any; +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 1, 5)) + + if (b) { +>b : Symbol(b, Decl(classBlockScoping.ts, 0, 11)) + + Foo = class Foo { +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 1, 5)) +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 3, 9)) + + static y = new Foo(); +>y : Symbol(Foo.y, Decl(classBlockScoping.ts, 3, 21)) +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 3, 9)) + + static x() { +>x : Symbol(Foo.x, Decl(classBlockScoping.ts, 4, 27)) + + new Foo(); +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 3, 9)) + } + + m() { +>m : Symbol(Foo.m, Decl(classBlockScoping.ts, 8, 7)) + + new Foo(); +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 3, 9)) + } + }; + + new Foo(); +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 1, 5)) + } + else { + class Foo { +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 17, 8)) + + static y = new Foo(); +>y : Symbol(Foo.y, Decl(classBlockScoping.ts, 18, 15)) +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 17, 8)) + + static x() { +>x : Symbol(Foo.x, Decl(classBlockScoping.ts, 19, 27)) + + new Foo(); +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 17, 8)) + } + + m() { +>m : Symbol(Foo.m, Decl(classBlockScoping.ts, 23, 7)) + + new Foo(); +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 17, 8)) + } + } + + new Foo(); +>Foo : Symbol(Foo, Decl(classBlockScoping.ts, 17, 8)) + } +} diff --git a/tests/baselines/reference/classBlockScoping.types b/tests/baselines/reference/classBlockScoping.types new file mode 100644 index 00000000000..a54499d7400 --- /dev/null +++ b/tests/baselines/reference/classBlockScoping.types @@ -0,0 +1,74 @@ +=== tests/cases/compiler/classBlockScoping.ts === +function f(b: boolean) { +>f : (b: boolean) => void +>b : boolean + + let Foo: any; +>Foo : any + + if (b) { +>b : boolean + + Foo = class Foo { +>Foo = class Foo { static y = new Foo(); static x() { new Foo(); } m() { new Foo(); } } : typeof Foo +>Foo : any +>class Foo { static y = new Foo(); static x() { new Foo(); } m() { new Foo(); } } : typeof Foo +>Foo : typeof Foo + + static y = new Foo(); +>y : Foo +>new Foo() : Foo +>Foo : typeof Foo + + static x() { +>x : () => void + + new Foo(); +>new Foo() : Foo +>Foo : typeof Foo + } + + m() { +>m : () => void + + new Foo(); +>new Foo() : Foo +>Foo : typeof Foo + } + }; + + new Foo(); +>new Foo() : any +>Foo : any + } + else { + class Foo { +>Foo : Foo + + static y = new Foo(); +>y : Foo +>new Foo() : Foo +>Foo : typeof Foo + + static x() { +>x : () => void + + new Foo(); +>new Foo() : Foo +>Foo : typeof Foo + } + + m() { +>m : () => void + + new Foo(); +>new Foo() : Foo +>Foo : typeof Foo + } + } + + new Foo(); +>new Foo() : Foo +>Foo : typeof Foo + } +} diff --git a/tests/baselines/reference/classDeclarationBlockScoping1.js b/tests/baselines/reference/classDeclarationBlockScoping1.js index ac3195af696..03c6254d9ea 100644 --- a/tests/baselines/reference/classDeclarationBlockScoping1.js +++ b/tests/baselines/reference/classDeclarationBlockScoping1.js @@ -15,8 +15,8 @@ var C = (function () { }()); { var C_1 = (function () { - function C_1() { + function C() { } - return C_1; + return C; }()); } diff --git a/tests/baselines/reference/classDeclarationBlockScoping2.js b/tests/baselines/reference/classDeclarationBlockScoping2.js index c3e3a89677a..7cc8a064a0c 100644 --- a/tests/baselines/reference/classDeclarationBlockScoping2.js +++ b/tests/baselines/reference/classDeclarationBlockScoping2.js @@ -19,9 +19,9 @@ function f() { var c1 = C; { var C_1 = (function () { - function C_1() { + function C() { } - return C_1; + return C; }()); var c2 = C_1; } diff --git a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt index 28c550ccda1..ccf56532bc4 100644 --- a/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt +++ b/tests/baselines/reference/contextuallyTypedStringLiteralsInJsxAttributes02.errors.txt @@ -1,15 +1,13 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(27,24): error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'LinkProps'. + Property 'goTo' is missing in type '{ extra: true; onClick: (k: "left" | "right") => void; }'. tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(28,24): error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(29,24): error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(30,24): error TS2322: Type '{ goTo: "home"; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(33,25): error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & ButtonProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. -tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,25): error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. - Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'LinkProps'. + Property 'goTo' is missing in type '{ onClick: (k: "left" | "right") => void; extra: true; }'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(29,43): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(30,36): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(33,65): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. +tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,44): error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. ==== tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx (6 errors) ==== @@ -42,29 +40,27 @@ tests/cases/conformance/types/contextualTypes/jsxAttributes/file.tsx(36,25): err const b0 = {console.log(k)}}} extra />; // k has type "left" | "right" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. +!!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'LinkProps'. +!!! error TS2322: Property 'goTo' is missing in type '{ extra: true; onClick: (k: "left" | "right") => void; }'. const b2 = {console.log(k)}} extra />; // k has type "left" | "right" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'onClick' does not exist on type 'IntrinsicAttributes & LinkProps'. +!!! error TS2322: Type '{ onClick: (k: "left" | "right") => void; extra: true; }' is not assignable to type 'LinkProps'. +!!! error TS2322: Property 'goTo' is missing in type '{ onClick: (k: "left" | "right") => void; extra: true; }'. const b3 = ; // goTo has type"home" | "contact" - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. const b4 = ; // goTo has type "home" | "contact" - ~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ goTo: "home"; extra: true; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. export function NoOverload(buttonProps: ButtonProps): JSX.Element { return undefined } const c1 = {console.log(k)}}} extra />; // k has type any - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ extra: true; onClick: (k: "left" | "right") => void; }' is not assignable to type 'IntrinsicAttributes & ButtonProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & ButtonProps'. export function NoOverload1(linkProps: LinkProps): JSX.Element { return undefined } const d1 = ; // goTo has type "home" | "contact" - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2322: Type '{ extra: true; goTo: "home"; }' is not assignable to type 'IntrinsicAttributes & LinkProps'. -!!! error TS2322: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. + ~~~~~ +!!! error TS2339: Property 'extra' does not exist on type 'IntrinsicAttributes & LinkProps'. \ No newline at end of file diff --git a/tests/baselines/reference/correctlyMarkAliasAsReferences1.js b/tests/baselines/reference/correctlyMarkAliasAsReferences1.js new file mode 100644 index 00000000000..7816881f4a2 --- /dev/null +++ b/tests/baselines/reference/correctlyMarkAliasAsReferences1.js @@ -0,0 +1,23 @@ +//// [tests/cases/conformance/jsx/correctlyMarkAliasAsReferences1.tsx] //// + +//// [declaration.d.ts] +declare module "classnames"; + +//// [0.tsx] +/// +import * as cx from 'classnames'; +import * as React from "react"; + +let buttonProps; // any +let k = ; + + +//// [0.js] +/// +import * as cx from 'classnames'; +import * as React from "react"; +let buttonProps; // any +let k = React.createElement("button", Object.assign({}, buttonProps), + React.createElement("span", { className: cx('class1', { class2: true }) })); diff --git a/tests/baselines/reference/correctlyMarkAliasAsReferences1.symbols b/tests/baselines/reference/correctlyMarkAliasAsReferences1.symbols new file mode 100644 index 00000000000..3267a29050e --- /dev/null +++ b/tests/baselines/reference/correctlyMarkAliasAsReferences1.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/jsx/0.tsx === +/// +import * as cx from 'classnames'; +>cx : Symbol(cx, Decl(0.tsx, 1, 6)) + +import * as React from "react"; +>React : Symbol(React, Decl(0.tsx, 2, 6)) + +let buttonProps; // any +>buttonProps : Symbol(buttonProps, Decl(0.tsx, 4, 3)) + +let k = ; +>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43)) + +=== tests/cases/conformance/jsx/declaration.d.ts === +declare module "classnames"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/correctlyMarkAliasAsReferences1.types b/tests/baselines/reference/correctlyMarkAliasAsReferences1.types new file mode 100644 index 00000000000..dbcad2fdc3c --- /dev/null +++ b/tests/baselines/reference/correctlyMarkAliasAsReferences1.types @@ -0,0 +1,35 @@ +=== tests/cases/conformance/jsx/0.tsx === +/// +import * as cx from 'classnames'; +>cx : any + +import * as React from "react"; +>React : typeof React + +let buttonProps; // any +>buttonProps : any + +let k = : JSX.Element +>button : any +>buttonProps : any + + +> : JSX.Element +>span : any +>className : any +>cx('class1', { class2: true }) : any +>cx : any +>'class1' : "class1" +>{ class2: true } : { class2: boolean; } +>class2 : boolean +>true : true + + ; +>button : any + +=== tests/cases/conformance/jsx/declaration.d.ts === +declare module "classnames"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/correctlyMarkAliasAsReferences2.js b/tests/baselines/reference/correctlyMarkAliasAsReferences2.js new file mode 100644 index 00000000000..7af59b017a8 --- /dev/null +++ b/tests/baselines/reference/correctlyMarkAliasAsReferences2.js @@ -0,0 +1,23 @@ +//// [tests/cases/conformance/jsx/correctlyMarkAliasAsReferences2.tsx] //// + +//// [declaration.d.ts] +declare module "classnames"; + +//// [0.tsx] +/// +import * as cx from 'classnames'; +import * as React from "react"; + +let buttonProps : {[attributeName: string]: ''} +let k = ; + + +//// [0.js] +/// +import * as cx from 'classnames'; +import * as React from "react"; +let buttonProps; +let k = React.createElement("button", Object.assign({}, buttonProps), + React.createElement("span", { className: cx('class1', { class2: true }) })); diff --git a/tests/baselines/reference/correctlyMarkAliasAsReferences2.symbols b/tests/baselines/reference/correctlyMarkAliasAsReferences2.symbols new file mode 100644 index 00000000000..76d9b8cdfe0 --- /dev/null +++ b/tests/baselines/reference/correctlyMarkAliasAsReferences2.symbols @@ -0,0 +1,30 @@ +=== tests/cases/conformance/jsx/0.tsx === +/// +import * as cx from 'classnames'; +>cx : Symbol(cx, Decl(0.tsx, 1, 6)) + +import * as React from "react"; +>React : Symbol(React, Decl(0.tsx, 2, 6)) + +let buttonProps : {[attributeName: string]: ''} +>buttonProps : Symbol(buttonProps, Decl(0.tsx, 4, 3)) +>attributeName : Symbol(attributeName, Decl(0.tsx, 4, 20)) + +let k = ; +>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43)) + +=== tests/cases/conformance/jsx/declaration.d.ts === +declare module "classnames"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/correctlyMarkAliasAsReferences2.types b/tests/baselines/reference/correctlyMarkAliasAsReferences2.types new file mode 100644 index 00000000000..cfaba960da2 --- /dev/null +++ b/tests/baselines/reference/correctlyMarkAliasAsReferences2.types @@ -0,0 +1,36 @@ +=== tests/cases/conformance/jsx/0.tsx === +/// +import * as cx from 'classnames'; +>cx : any + +import * as React from "react"; +>React : typeof React + +let buttonProps : {[attributeName: string]: ''} +>buttonProps : { [attributeName: string]: ""; } +>attributeName : string + +let k = : JSX.Element +>button : any +>buttonProps : { [attributeName: string]: ""; } + + +> : JSX.Element +>span : any +>className : any +>cx('class1', { class2: true }) : any +>cx : any +>'class1' : "class1" +>{ class2: true } : { class2: boolean; } +>class2 : boolean +>true : true + + ; +>button : any + +=== tests/cases/conformance/jsx/declaration.d.ts === +declare module "classnames"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/correctlyMarkAliasAsReferences3.js b/tests/baselines/reference/correctlyMarkAliasAsReferences3.js new file mode 100644 index 00000000000..166e29d56db --- /dev/null +++ b/tests/baselines/reference/correctlyMarkAliasAsReferences3.js @@ -0,0 +1,23 @@ +//// [tests/cases/conformance/jsx/correctlyMarkAliasAsReferences3.tsx] //// + +//// [declaration.d.ts] +declare module "classnames"; + +//// [0.tsx] +/// +import * as cx from 'classnames'; +import * as React from "react"; + +let buttonProps; +let k = ; + + +//// [0.js] +/// +import * as cx from 'classnames'; +import * as React from "react"; +let buttonProps; +let k = React.createElement("button", Object.assign({}, buttonProps), + React.createElement("span", { className: cx('class1', { class2: true }) })); diff --git a/tests/baselines/reference/correctlyMarkAliasAsReferences3.symbols b/tests/baselines/reference/correctlyMarkAliasAsReferences3.symbols new file mode 100644 index 00000000000..088f553baa4 --- /dev/null +++ b/tests/baselines/reference/correctlyMarkAliasAsReferences3.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/jsx/0.tsx === +/// +import * as cx from 'classnames'; +>cx : Symbol(cx, Decl(0.tsx, 1, 6)) + +import * as React from "react"; +>React : Symbol(React, Decl(0.tsx, 2, 6)) + +let buttonProps; +>buttonProps : Symbol(buttonProps, Decl(0.tsx, 4, 3)) + +let k = ; +>button : Symbol(JSX.IntrinsicElements.button, Decl(react.d.ts, 2385, 43)) + +=== tests/cases/conformance/jsx/declaration.d.ts === +declare module "classnames"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/correctlyMarkAliasAsReferences3.types b/tests/baselines/reference/correctlyMarkAliasAsReferences3.types new file mode 100644 index 00000000000..cca59ae2f5e --- /dev/null +++ b/tests/baselines/reference/correctlyMarkAliasAsReferences3.types @@ -0,0 +1,35 @@ +=== tests/cases/conformance/jsx/0.tsx === +/// +import * as cx from 'classnames'; +>cx : any + +import * as React from "react"; +>React : typeof React + +let buttonProps; +>buttonProps : any + +let k = : JSX.Element +>button : any +>buttonProps : undefined + + +> : JSX.Element +>span : any +>className : any +>cx('class1', { class2: true }) : any +>cx : any +>'class1' : "class1" +>{ class2: true } : { class2: boolean; } +>class2 : boolean +>true : true + + ; +>button : any + +=== tests/cases/conformance/jsx/declaration.d.ts === +declare module "classnames"; +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/correctlyMarkAliasAsReferences4.js b/tests/baselines/reference/correctlyMarkAliasAsReferences4.js new file mode 100644 index 00000000000..631d06cc5b3 --- /dev/null +++ b/tests/baselines/reference/correctlyMarkAliasAsReferences4.js @@ -0,0 +1,19 @@ +//// [tests/cases/conformance/jsx/correctlyMarkAliasAsReferences4.tsx] //// + +//// [declaration.d.ts] +declare module "classnames"; + +//// [0.tsx] +/// +import * as cx from 'classnames'; +import * as React from "react"; + +let buttonProps : {[attributeName: string]: ''} +let k = ); + } +} diff --git a/tests/cases/conformance/jsx/checkJsxChildrenProperty13.tsx b/tests/cases/conformance/jsx/checkJsxChildrenProperty13.tsx new file mode 100644 index 00000000000..1584bf43159 --- /dev/null +++ b/tests/cases/conformance/jsx/checkJsxChildrenProperty13.tsx @@ -0,0 +1,31 @@ +// @filename: file.tsx +// @jsx: preserve +// @noLib: true +// @libFiles: react.d.ts,lib.d.ts + +import React = require('react'); + +interface ButtonProp { + a: number, + b: string, + children: Button; +} + +class Button extends React.Component { + render() { + // Error children are specified twice + return ( +
Hello World
+
); + } +} + +interface InnerButtonProp { + a: number +} + +class InnerButton extends React.Component { + render() { + return (); + } +} diff --git a/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences1.tsx b/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences1.tsx new file mode 100644 index 00000000000..a074b3b8086 --- /dev/null +++ b/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences1.tsx @@ -0,0 +1,17 @@ +// @target: es2017 +// @jsx: react +// @moduleResolution: node +// @libFiles: react.d.ts,lib.d.ts + +// @filename: declaration.d.ts +declare module "classnames"; + +// @filename: 0.tsx +/// +import * as cx from 'classnames'; +import * as React from "react"; + +let buttonProps; // any +let k = ; diff --git a/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences2.tsx b/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences2.tsx new file mode 100644 index 00000000000..9755c624fc5 --- /dev/null +++ b/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences2.tsx @@ -0,0 +1,17 @@ +// @target: es2017 +// @jsx: react +// @moduleResolution: node +// @libFiles: react.d.ts,lib.d.ts + +// @filename: declaration.d.ts +declare module "classnames"; + +// @filename: 0.tsx +/// +import * as cx from 'classnames'; +import * as React from "react"; + +let buttonProps : {[attributeName: string]: ''} +let k = ; diff --git a/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences3.tsx b/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences3.tsx new file mode 100644 index 00000000000..c3bfb0c8a47 --- /dev/null +++ b/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences3.tsx @@ -0,0 +1,18 @@ +// @target: es2017 +// @jsx: react +// @moduleResolution: node +// @noImplicitAny: true +// @libFiles: react.d.ts,lib.d.ts + +// @filename: declaration.d.ts +declare module "classnames"; + +// @filename: 0.tsx +/// +import * as cx from 'classnames'; +import * as React from "react"; + +let buttonProps; +let k = ; diff --git a/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences4.tsx b/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences4.tsx new file mode 100644 index 00000000000..edb9f75f87b --- /dev/null +++ b/tests/cases/conformance/jsx/correctlyMarkAliasAsReferences4.tsx @@ -0,0 +1,15 @@ +// @target: es2017 +// @jsx: react +// @moduleResolution: node +// @libFiles: react.d.ts,lib.d.ts + +// @filename: declaration.d.ts +declare module "classnames"; + +// @filename: 0.tsx +/// +import * as cx from 'classnames'; +import * as React from "react"; + +let buttonProps : {[attributeName: string]: ''} +let k =