mirror of
https://github.com/microsoft/TypeScript.git
synced 2025-11-18 17:21:48 +00:00
Merge pull request #11150 from Microsoft/object-spread
Object spread/rest
This commit is contained in:
+89
-20
@@ -1139,8 +1139,8 @@ namespace ts {
|
||||
}
|
||||
else if (node.kind === SyntaxKind.ArrayLiteralExpression) {
|
||||
for (const e of (<ArrayLiteralExpression>node).elements) {
|
||||
if (e.kind === SyntaxKind.SpreadElementExpression) {
|
||||
bindAssignmentTargetFlow((<SpreadElementExpression>e).expression);
|
||||
if (e.kind === SyntaxKind.SpreadElement) {
|
||||
bindAssignmentTargetFlow((<SpreadElement>e).expression);
|
||||
}
|
||||
else {
|
||||
bindDestructuringTargetFlow(e);
|
||||
@@ -1155,6 +1155,9 @@ namespace ts {
|
||||
else if (p.kind === SyntaxKind.ShorthandPropertyAssignment) {
|
||||
bindAssignmentTargetFlow((<ShorthandPropertyAssignment>p).name);
|
||||
}
|
||||
else if (p.kind === SyntaxKind.SpreadAssignment) {
|
||||
bindAssignmentTargetFlow((<SpreadAssignment>p).expression);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1916,6 +1919,9 @@ namespace ts {
|
||||
return bindParameter(<ParameterDeclaration>node);
|
||||
case SyntaxKind.VariableDeclaration:
|
||||
case SyntaxKind.BindingElement:
|
||||
if ((node as BindingElement).dotDotDotToken && node.parent.kind === SyntaxKind.ObjectBindingPattern) {
|
||||
emitFlags |= NodeFlags.HasRestAttribute;
|
||||
}
|
||||
return bindVariableDeclarationOrBindingElement(<VariableDeclaration | BindingElement>node);
|
||||
case SyntaxKind.PropertyDeclaration:
|
||||
case SyntaxKind.PropertySignature:
|
||||
@@ -1929,8 +1935,21 @@ namespace ts {
|
||||
case SyntaxKind.EnumMember:
|
||||
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes);
|
||||
|
||||
case SyntaxKind.SpreadAssignment:
|
||||
case SyntaxKind.JsxSpreadAttribute:
|
||||
emitFlags |= NodeFlags.HasJsxSpreadAttributes;
|
||||
let root = container;
|
||||
let hasRest = false;
|
||||
while (root.parent) {
|
||||
if (root.kind === SyntaxKind.ObjectLiteralExpression &&
|
||||
root.parent.kind === SyntaxKind.BinaryExpression &&
|
||||
(root.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken &&
|
||||
(root.parent as BinaryExpression).left === root) {
|
||||
hasRest = true;
|
||||
break;
|
||||
}
|
||||
root = root.parent;
|
||||
}
|
||||
emitFlags |= hasRest ? NodeFlags.HasRestAttribute : NodeFlags.HasSpreadAttribute;
|
||||
return;
|
||||
|
||||
case SyntaxKind.CallSignature:
|
||||
@@ -2495,9 +2514,9 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertTypeScript;
|
||||
}
|
||||
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadExpression
|
||||
|| isSuperOrSuperProperty(expression, expressionKind)) {
|
||||
// If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6
|
||||
// If the this node contains a SpreadExpression, or is a super call, then it is an ES6
|
||||
// node.
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
}
|
||||
@@ -2526,7 +2545,7 @@ namespace ts {
|
||||
if (node.typeArguments) {
|
||||
transformFlags |= TransformFlags.AssertTypeScript;
|
||||
}
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) {
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
|
||||
// If the this node contains a SpreadElementExpression then it is an ES6
|
||||
// node.
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
@@ -2541,10 +2560,13 @@ namespace ts {
|
||||
const operatorTokenKind = node.operatorToken.kind;
|
||||
const leftKind = node.left.kind;
|
||||
|
||||
if (operatorTokenKind === SyntaxKind.EqualsToken
|
||||
&& (leftKind === SyntaxKind.ObjectLiteralExpression
|
||||
|| leftKind === SyntaxKind.ArrayLiteralExpression)) {
|
||||
// Destructuring assignments are ES6 syntax.
|
||||
if (operatorTokenKind === SyntaxKind.EqualsToken && leftKind === SyntaxKind.ObjectLiteralExpression) {
|
||||
// Destructuring object assignments with are ES2015 syntax
|
||||
// and possibly ESNext if they contain rest
|
||||
transformFlags |= TransformFlags.AssertESNext | TransformFlags.AssertES2015 | TransformFlags.AssertDestructuringAssignment;
|
||||
}
|
||||
else if (operatorTokenKind === SyntaxKind.EqualsToken && leftKind === SyntaxKind.ArrayLiteralExpression) {
|
||||
// Destructuring assignments are ES2015 syntax.
|
||||
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.AssertDestructuringAssignment;
|
||||
}
|
||||
else if (operatorTokenKind === SyntaxKind.AsteriskAsteriskToken
|
||||
@@ -2578,6 +2600,11 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsParameterPropertyAssignments;
|
||||
}
|
||||
|
||||
// parameters with object rest destructuring are ES Next syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
}
|
||||
|
||||
// If a parameter has an initializer, a binding pattern or a dotDotDot token, then
|
||||
// it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
|
||||
if (subtreeFlags & TransformFlags.ContainsBindingPattern || initializer || dotDotDotToken) {
|
||||
@@ -2811,6 +2838,11 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertES2017;
|
||||
}
|
||||
|
||||
// function declarations with object rest destructuring are ES Next syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
}
|
||||
|
||||
// If a FunctionDeclaration's subtree has marked the container as needing to capture the
|
||||
// lexical this, or the function contains parameters with initializers, then this node is
|
||||
// ES6 syntax.
|
||||
@@ -2848,6 +2880,12 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertES2017;
|
||||
}
|
||||
|
||||
// function expressions with object rest destructuring are ES Next syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
}
|
||||
|
||||
|
||||
// If a FunctionExpression's subtree has marked the container as needing to capture the
|
||||
// lexical this, or the function contains parameters with initializers, then this node is
|
||||
// ES6 syntax.
|
||||
@@ -2885,6 +2923,11 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertES2017;
|
||||
}
|
||||
|
||||
// arrow functions with object rest destructuring are ES Next syntax
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
}
|
||||
|
||||
// If an ArrowFunction contains a lexical this, its container must capture the lexical this.
|
||||
if (subtreeFlags & TransformFlags.ContainsLexicalThis) {
|
||||
transformFlags |= TransformFlags.ContainsCapturedLexicalThis;
|
||||
@@ -2913,8 +2956,13 @@ namespace ts {
|
||||
let transformFlags = subtreeFlags;
|
||||
const nameKind = node.name.kind;
|
||||
|
||||
// A VariableDeclaration with a binding pattern is ES6 syntax.
|
||||
if (nameKind === SyntaxKind.ObjectBindingPattern || nameKind === SyntaxKind.ArrayBindingPattern) {
|
||||
// A VariableDeclaration with an object binding pattern is ES2015 syntax
|
||||
// and possibly ESNext syntax if it contains an object binding pattern
|
||||
if (nameKind === SyntaxKind.ObjectBindingPattern) {
|
||||
transformFlags |= TransformFlags.AssertESNext | TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
|
||||
}
|
||||
// A VariableDeclaration with an object binding pattern is ES2015 syntax.
|
||||
else if (nameKind === SyntaxKind.ArrayBindingPattern) {
|
||||
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
|
||||
}
|
||||
|
||||
@@ -3055,6 +3103,10 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.AssertJsx;
|
||||
break;
|
||||
|
||||
case SyntaxKind.ForOfStatement:
|
||||
// for-of might be ESNext if it has a rest destructuring
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
// FALLTHROUGH
|
||||
case SyntaxKind.NoSubstitutionTemplateLiteral:
|
||||
case SyntaxKind.TemplateHead:
|
||||
case SyntaxKind.TemplateMiddle:
|
||||
@@ -3062,7 +3114,6 @@ namespace ts {
|
||||
case SyntaxKind.TemplateExpression:
|
||||
case SyntaxKind.TaggedTemplateExpression:
|
||||
case SyntaxKind.ShorthandPropertyAssignment:
|
||||
case SyntaxKind.ForOfStatement:
|
||||
case SyntaxKind.StaticKeyword:
|
||||
// These nodes are ES6 syntax.
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
@@ -3126,11 +3177,18 @@ namespace ts {
|
||||
}
|
||||
break;
|
||||
|
||||
case SyntaxKind.SpreadElementExpression:
|
||||
// This node is ES6 syntax, but is handled by a containing node.
|
||||
transformFlags |= TransformFlags.ContainsSpreadElementExpression;
|
||||
case SyntaxKind.SpreadElement:
|
||||
case SyntaxKind.SpreadAssignment:
|
||||
// This node is ES6 or ES next syntax, but is handled by a containing node.
|
||||
transformFlags |= TransformFlags.ContainsSpreadExpression;
|
||||
break;
|
||||
|
||||
case SyntaxKind.BindingElement:
|
||||
if ((node as BindingElement).dotDotDotToken) {
|
||||
// this node is ES2015 or ES next syntax, but is handled by a containing node.
|
||||
transformFlags |= TransformFlags.ContainsSpreadExpression;
|
||||
}
|
||||
|
||||
case SyntaxKind.SuperKeyword:
|
||||
// This node is ES6 syntax.
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
@@ -3143,8 +3201,13 @@ namespace ts {
|
||||
|
||||
case SyntaxKind.ObjectBindingPattern:
|
||||
case SyntaxKind.ArrayBindingPattern:
|
||||
// These nodes are ES6 syntax.
|
||||
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
|
||||
// These nodes are ES2015 or ES Next syntax.
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
|
||||
transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsBindingPattern;
|
||||
}
|
||||
else {
|
||||
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
|
||||
}
|
||||
break;
|
||||
|
||||
case SyntaxKind.Decorator:
|
||||
@@ -3166,13 +3229,19 @@ namespace ts {
|
||||
transformFlags |= TransformFlags.ContainsLexicalThis;
|
||||
}
|
||||
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
|
||||
// If an ObjectLiteralExpression contains a spread element, then it
|
||||
// is an ES next node.
|
||||
transformFlags |= TransformFlags.AssertESNext;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case SyntaxKind.ArrayLiteralExpression:
|
||||
case SyntaxKind.NewExpression:
|
||||
excludeFlags = TransformFlags.ArrayLiteralOrCallOrNewExcludes;
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) {
|
||||
// If the this node contains a SpreadElementExpression, then it is an ES6
|
||||
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
|
||||
// If the this node contains a SpreadExpression, then it is an ES6
|
||||
// node.
|
||||
transformFlags |= TransformFlags.AssertES2015;
|
||||
}
|
||||
|
||||
+217
-80
@@ -2494,6 +2494,13 @@ namespace ts {
|
||||
writePunctuation(writer, SyntaxKind.OpenBraceToken);
|
||||
writer.writeLine();
|
||||
writer.increaseIndent();
|
||||
writeObjectLiteralType(resolved);
|
||||
writer.decreaseIndent();
|
||||
writePunctuation(writer, SyntaxKind.CloseBraceToken);
|
||||
inObjectTypeLiteral = saveInObjectTypeLiteral;
|
||||
}
|
||||
|
||||
function writeObjectLiteralType(resolved: ResolvedType) {
|
||||
for (const signature of resolved.callSignatures) {
|
||||
buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack);
|
||||
writePunctuation(writer, SyntaxKind.SemicolonToken);
|
||||
@@ -2526,11 +2533,8 @@ namespace ts {
|
||||
writer.writeLine();
|
||||
}
|
||||
}
|
||||
writer.decreaseIndent();
|
||||
writePunctuation(writer, SyntaxKind.CloseBraceToken);
|
||||
inObjectTypeLiteral = saveInObjectTypeLiteral;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags) {
|
||||
const targetSymbol = getTargetSymbol(symbol);
|
||||
@@ -2972,26 +2976,31 @@ namespace ts {
|
||||
return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
|
||||
}
|
||||
|
||||
function getTextOfPropertyName(name: PropertyName): string {
|
||||
switch (name.kind) {
|
||||
case SyntaxKind.Identifier:
|
||||
return (<Identifier>name).text;
|
||||
case SyntaxKind.StringLiteral:
|
||||
case SyntaxKind.NumericLiteral:
|
||||
return (<LiteralExpression>name).text;
|
||||
case SyntaxKind.ComputedPropertyName:
|
||||
if (isStringOrNumericLiteral((<ComputedPropertyName>name).expression.kind)) {
|
||||
return (<LiteralExpression>(<ComputedPropertyName>name).expression).text;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isComputedNonLiteralName(name: PropertyName): boolean {
|
||||
return name.kind === SyntaxKind.ComputedPropertyName && !isStringOrNumericLiteral((<ComputedPropertyName>name).expression.kind);
|
||||
}
|
||||
|
||||
function getRestType(source: Type, properties: PropertyName[], symbol: Symbol): Type {
|
||||
Debug.assert(!!(source.flags & TypeFlags.Object), "Rest types only support object types right now.");
|
||||
const members = createMap<Symbol>();
|
||||
const names = createMap<true>();
|
||||
for (const name of properties) {
|
||||
names[getTextOfPropertyName(name)] = true;
|
||||
}
|
||||
for (const prop of getPropertiesOfType(source)) {
|
||||
const inNamesToRemove = prop.name in names;
|
||||
const isPrivate = getDeclarationModifierFlagsFromSymbol(prop) & (ModifierFlags.Private | ModifierFlags.Protected);
|
||||
const isMethod = prop.flags & SymbolFlags.Method;
|
||||
const isSetOnlyAccessor = prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor);
|
||||
if (!inNamesToRemove && !isPrivate && !isMethod && !isSetOnlyAccessor) {
|
||||
members[prop.name] = prop;
|
||||
}
|
||||
}
|
||||
const stringIndexInfo = getIndexInfoOfType(source, IndexKind.String);
|
||||
const numberIndexInfo = getIndexInfoOfType(source, IndexKind.Number);
|
||||
return createAnonymousType(symbol, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo);
|
||||
}
|
||||
|
||||
/** Return the inferred type for a binding element */
|
||||
function getTypeForBindingElement(declaration: BindingElement): Type {
|
||||
const pattern = <BindingPattern>declaration.parent;
|
||||
@@ -3012,26 +3021,41 @@ namespace ts {
|
||||
|
||||
let type: Type;
|
||||
if (pattern.kind === SyntaxKind.ObjectBindingPattern) {
|
||||
// Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
|
||||
const name = declaration.propertyName || <Identifier>declaration.name;
|
||||
if (isComputedNonLiteralName(name)) {
|
||||
// computed properties with non-literal names are treated as 'any'
|
||||
return anyType;
|
||||
}
|
||||
if (declaration.initializer) {
|
||||
getContextualType(declaration.initializer);
|
||||
if (declaration.dotDotDotToken) {
|
||||
if (!(parentType.flags & TypeFlags.Object)) {
|
||||
error(declaration, Diagnostics.Rest_types_may_only_be_created_from_object_types);
|
||||
return unknownType;
|
||||
}
|
||||
const literalMembers: PropertyName[] = [];
|
||||
for (const element of pattern.elements) {
|
||||
if (element.kind !== SyntaxKind.OmittedExpression && !(element as BindingElement).dotDotDotToken) {
|
||||
literalMembers.push(element.propertyName || element.name as Identifier);
|
||||
}
|
||||
}
|
||||
type = getRestType(parentType, literalMembers, declaration.symbol);
|
||||
}
|
||||
else {
|
||||
// Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
|
||||
const name = declaration.propertyName || <Identifier>declaration.name;
|
||||
if (isComputedNonLiteralName(name)) {
|
||||
// computed properties with non-literal names are treated as 'any'
|
||||
return anyType;
|
||||
}
|
||||
if (declaration.initializer) {
|
||||
getContextualType(declaration.initializer);
|
||||
}
|
||||
|
||||
// Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature,
|
||||
// or otherwise the type of the string index signature.
|
||||
const text = getTextOfPropertyName(name);
|
||||
// Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature,
|
||||
// or otherwise the type of the string index signature.
|
||||
const text = getTextOfPropertyName(name);
|
||||
|
||||
type = getTypeOfPropertyOfType(parentType, text) ||
|
||||
isNumericLiteralName(text) && getIndexTypeOfType(parentType, IndexKind.Number) ||
|
||||
getIndexTypeOfType(parentType, IndexKind.String);
|
||||
if (!type) {
|
||||
error(name, Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), declarationNameToString(name));
|
||||
return unknownType;
|
||||
type = getTypeOfPropertyOfType(parentType, text) ||
|
||||
isNumericLiteralName(text) && getIndexTypeOfType(parentType, IndexKind.Number) ||
|
||||
getIndexTypeOfType(parentType, IndexKind.String);
|
||||
if (!type) {
|
||||
error(name, Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), declarationNameToString(name));
|
||||
return unknownType;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -3039,7 +3063,11 @@ namespace ts {
|
||||
// present (aka the tuple element property). This call also checks that the parentType is in
|
||||
// fact an iterable or array (depending on target language).
|
||||
const elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false);
|
||||
if (!declaration.dotDotDotToken) {
|
||||
if (declaration.dotDotDotToken) {
|
||||
// Rest element has an array type with the same element type as the parent type
|
||||
type = createArrayType(elementType);
|
||||
}
|
||||
else {
|
||||
// Use specific property type when parent is a tuple or numeric index type when parent is an array
|
||||
const propName = "" + indexOf(pattern.elements, declaration);
|
||||
type = isTupleLikeType(parentType)
|
||||
@@ -3055,10 +3083,6 @@ namespace ts {
|
||||
return unknownType;
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Rest element has an array type with the same element type as the parent type
|
||||
type = createArrayType(elementType);
|
||||
}
|
||||
}
|
||||
// In strict null checking mode, if a default value of a non-undefined type is specified, remove
|
||||
// undefined from the final type.
|
||||
@@ -3239,8 +3263,8 @@ namespace ts {
|
||||
let hasComputedProperties = false;
|
||||
forEach(pattern.elements, e => {
|
||||
const name = e.propertyName || <Identifier>e.name;
|
||||
if (isComputedNonLiteralName(name)) {
|
||||
// do not include computed properties in the implied type
|
||||
if (isComputedNonLiteralName(name) || e.dotDotDotToken) {
|
||||
// do not include computed properties or rests in the implied type
|
||||
hasComputedProperties = true;
|
||||
return;
|
||||
}
|
||||
@@ -4337,6 +4361,11 @@ namespace ts {
|
||||
getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
|
||||
}
|
||||
|
||||
function unionSpreadIndexInfos(info1: IndexInfo, info2: IndexInfo): IndexInfo {
|
||||
return info1 && info2 && createIndexInfo(
|
||||
getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
|
||||
}
|
||||
|
||||
function resolveIntersectionTypeMembers(type: IntersectionType) {
|
||||
// The members and properties collections are empty for intersection types. To get all properties of an
|
||||
// intersection type use getPropertiesOfType (only the language service uses this).
|
||||
@@ -4473,7 +4502,9 @@ namespace ts {
|
||||
|
||||
function getPropertiesOfType(type: Type): Symbol[] {
|
||||
type = getApparentType(type);
|
||||
return type.flags & TypeFlags.UnionOrIntersection ? getPropertiesOfUnionOrIntersectionType(<UnionType>type) : getPropertiesOfObjectType(type);
|
||||
return type.flags & TypeFlags.UnionOrIntersection ?
|
||||
getPropertiesOfUnionOrIntersectionType(<UnionType>type) :
|
||||
getPropertiesOfObjectType(type);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4528,6 +4559,7 @@ namespace ts {
|
||||
if (isReadonlySymbol(prop)) {
|
||||
isReadonly = true;
|
||||
}
|
||||
|
||||
}
|
||||
else if (containingType.flags & TypeFlags.Union) {
|
||||
isPartial = true;
|
||||
@@ -5860,6 +5892,68 @@ namespace ts {
|
||||
return links.resolvedType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Since the source of spread types are object literals, which are not binary,
|
||||
* this function should be called in a left folding style, with left = previous result of getSpreadType
|
||||
* and right = the new element to be spread.
|
||||
*/
|
||||
function getSpreadType(left: Type, right: Type, isFromObjectLiteral: boolean): ResolvedType | IntrinsicType {
|
||||
Debug.assert(!!(left.flags & (TypeFlags.Object | TypeFlags.Any)) && !!(right.flags & (TypeFlags.Object | TypeFlags.Any)), "Only object types may be spread.");
|
||||
if (left.flags & TypeFlags.Any || right.flags & TypeFlags.Any) {
|
||||
return anyType;
|
||||
}
|
||||
const members = createMap<Symbol>();
|
||||
const skippedPrivateMembers = createMap<boolean>();
|
||||
let stringIndexInfo: IndexInfo;
|
||||
let numberIndexInfo: IndexInfo;
|
||||
if (left === emptyObjectType) {
|
||||
// for the first spread element, left === emptyObjectType, so take the right's string indexer
|
||||
stringIndexInfo = getIndexInfoOfType(right, IndexKind.String);
|
||||
numberIndexInfo = getIndexInfoOfType(right, IndexKind.Number);
|
||||
}
|
||||
else {
|
||||
stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, IndexKind.String), getIndexInfoOfType(right, IndexKind.String));
|
||||
numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, IndexKind.Number), getIndexInfoOfType(right, IndexKind.Number));
|
||||
}
|
||||
|
||||
for (const rightProp of getPropertiesOfType(right)) {
|
||||
// we approximate own properties as non-methods plus methods that are inside the object literal
|
||||
const isOwnProperty = !(rightProp.flags & SymbolFlags.Method) || isFromObjectLiteral;
|
||||
const isSetterWithoutGetter = rightProp.flags & SymbolFlags.SetAccessor && !(rightProp.flags & SymbolFlags.GetAccessor);
|
||||
if (getDeclarationModifierFlagsFromSymbol(rightProp) & (ModifierFlags.Private | ModifierFlags.Protected)) {
|
||||
skippedPrivateMembers[rightProp.name] = true;
|
||||
}
|
||||
else if (isOwnProperty && !isSetterWithoutGetter) {
|
||||
members[rightProp.name] = rightProp;
|
||||
}
|
||||
}
|
||||
for (const leftProp of getPropertiesOfType(left)) {
|
||||
if (leftProp.flags & SymbolFlags.SetAccessor && !(leftProp.flags & SymbolFlags.GetAccessor)
|
||||
|| leftProp.name in skippedPrivateMembers) {
|
||||
continue;
|
||||
}
|
||||
if (leftProp.name in members) {
|
||||
const rightProp = members[leftProp.name];
|
||||
const rightType = getTypeOfSymbol(rightProp);
|
||||
if (maybeTypeOfKind(rightType, TypeFlags.Undefined) || rightProp.flags & SymbolFlags.Optional) {
|
||||
const declarations: Declaration[] = concatenate(leftProp.declarations, rightProp.declarations);
|
||||
const flags = SymbolFlags.Property | SymbolFlags.Transient | (leftProp.flags & SymbolFlags.Optional);
|
||||
const result = <TransientSymbol>createSymbol(flags, leftProp.name);
|
||||
result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, TypeFacts.NEUndefined)]);
|
||||
result.leftSpread = leftProp;
|
||||
result.rightSpread = rightProp;
|
||||
result.declarations = declarations;
|
||||
result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp);
|
||||
members[leftProp.name] = result;
|
||||
}
|
||||
}
|
||||
else {
|
||||
members[leftProp.name] = leftProp;
|
||||
}
|
||||
}
|
||||
return createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo);
|
||||
}
|
||||
|
||||
function createLiteralType(flags: TypeFlags, text: string) {
|
||||
const type = <LiteralType>createType(flags);
|
||||
type.text = text;
|
||||
@@ -8571,7 +8665,7 @@ namespace ts {
|
||||
unknownType;
|
||||
}
|
||||
|
||||
function getTypeOfDestructuredSpreadElement(type: Type) {
|
||||
function getTypeOfDestructuredSpreadExpression(type: Type) {
|
||||
return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false) || unknownType);
|
||||
}
|
||||
|
||||
@@ -8585,8 +8679,8 @@ namespace ts {
|
||||
return getTypeOfDestructuredArrayElement(getAssignedType(node), indexOf(node.elements, element));
|
||||
}
|
||||
|
||||
function getAssignedTypeOfSpreadElement(node: SpreadElementExpression): Type {
|
||||
return getTypeOfDestructuredSpreadElement(getAssignedType(<ArrayLiteralExpression>node.parent));
|
||||
function getAssignedTypeOfSpreadExpression(node: SpreadElement): Type {
|
||||
return getTypeOfDestructuredSpreadExpression(getAssignedType(<ArrayLiteralExpression>node.parent));
|
||||
}
|
||||
|
||||
function getAssignedTypeOfPropertyAssignment(node: PropertyAssignment | ShorthandPropertyAssignment): Type {
|
||||
@@ -8610,8 +8704,8 @@ namespace ts {
|
||||
return undefinedType;
|
||||
case SyntaxKind.ArrayLiteralExpression:
|
||||
return getAssignedTypeOfArrayLiteralElement(<ArrayLiteralExpression>parent, node);
|
||||
case SyntaxKind.SpreadElementExpression:
|
||||
return getAssignedTypeOfSpreadElement(<SpreadElementExpression>parent);
|
||||
case SyntaxKind.SpreadElement:
|
||||
return getAssignedTypeOfSpreadExpression(<SpreadElement>parent);
|
||||
case SyntaxKind.PropertyAssignment:
|
||||
return getAssignedTypeOfPropertyAssignment(<PropertyAssignment>parent);
|
||||
case SyntaxKind.ShorthandPropertyAssignment:
|
||||
@@ -8627,7 +8721,7 @@ namespace ts {
|
||||
getTypeOfDestructuredProperty(parentType, node.propertyName || <Identifier>node.name) :
|
||||
!node.dotDotDotToken ?
|
||||
getTypeOfDestructuredArrayElement(parentType, indexOf(pattern.elements, node)) :
|
||||
getTypeOfDestructuredSpreadElement(parentType);
|
||||
getTypeOfDestructuredSpreadExpression(parentType);
|
||||
return getTypeWithDefault(type, node.initializer);
|
||||
}
|
||||
|
||||
@@ -10642,7 +10736,7 @@ namespace ts {
|
||||
return mapper && mapper.context;
|
||||
}
|
||||
|
||||
function checkSpreadElementExpression(node: SpreadElementExpression, contextualMapper?: TypeMapper): Type {
|
||||
function checkSpreadExpression(node: SpreadElement, contextualMapper?: TypeMapper): Type {
|
||||
// It is usually not safe to call checkExpressionCached if we can be contextually typing.
|
||||
// You can tell that we are contextually typing because of the contextualMapper parameter.
|
||||
// While it is true that a spread element can have a contextual type, it does not do anything
|
||||
@@ -10664,7 +10758,7 @@ namespace ts {
|
||||
const elementTypes: Type[] = [];
|
||||
const inDestructuringPattern = isAssignmentTarget(node);
|
||||
for (const e of elements) {
|
||||
if (inDestructuringPattern && e.kind === SyntaxKind.SpreadElementExpression) {
|
||||
if (inDestructuringPattern && e.kind === SyntaxKind.SpreadElement) {
|
||||
// Given the following situation:
|
||||
// var c: {};
|
||||
// [...c] = ["", 0];
|
||||
@@ -10677,7 +10771,7 @@ namespace ts {
|
||||
// get the contextual element type from it. So we do something similar to
|
||||
// getContextualTypeForElementExpression, which will crucially not error
|
||||
// if there is no index type / iterated type.
|
||||
const restArrayType = checkExpression((<SpreadElementExpression>e).expression, contextualMapper);
|
||||
const restArrayType = checkExpression((<SpreadElement>e).expression, contextualMapper);
|
||||
const restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) ||
|
||||
(languageVersion >= ScriptTarget.ES2015 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined);
|
||||
if (restElementType) {
|
||||
@@ -10688,7 +10782,7 @@ namespace ts {
|
||||
const type = checkExpressionForMutableLocation(e, contextualMapper);
|
||||
elementTypes.push(type);
|
||||
}
|
||||
hasSpreadElement = hasSpreadElement || e.kind === SyntaxKind.SpreadElementExpression;
|
||||
hasSpreadElement = hasSpreadElement || e.kind === SyntaxKind.SpreadElement;
|
||||
}
|
||||
if (!hasSpreadElement) {
|
||||
// If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
|
||||
@@ -10805,8 +10899,11 @@ namespace ts {
|
||||
// Grammar checking
|
||||
checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
|
||||
|
||||
const propertiesTable = createMap<Symbol>();
|
||||
const propertiesArray: Symbol[] = [];
|
||||
let propertiesTable = createMap<Symbol>();
|
||||
let propertiesArray: Symbol[] = [];
|
||||
let spread: Type = emptyObjectType;
|
||||
let propagatedFlags: TypeFlags = 0;
|
||||
|
||||
const contextualType = getApparentTypeOfContextualType(node);
|
||||
const contextualTypeHasPattern = contextualType && contextualType.pattern &&
|
||||
(contextualType.pattern.kind === SyntaxKind.ObjectBindingPattern || contextualType.pattern.kind === SyntaxKind.ObjectLiteralExpression);
|
||||
@@ -10831,6 +10928,7 @@ namespace ts {
|
||||
Debug.assert(memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment);
|
||||
type = checkExpressionForMutableLocation((<ShorthandPropertyAssignment>memberDecl).name, contextualMapper);
|
||||
}
|
||||
|
||||
typeFlags |= type.flags;
|
||||
const prop = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name);
|
||||
if (inDestructuringPattern) {
|
||||
@@ -10868,6 +10966,23 @@ namespace ts {
|
||||
prop.target = member;
|
||||
member = prop;
|
||||
}
|
||||
else if (memberDecl.kind === SyntaxKind.SpreadAssignment) {
|
||||
if (propertiesArray.length > 0) {
|
||||
spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true);
|
||||
propertiesArray = [];
|
||||
propertiesTable = createMap<Symbol>();
|
||||
hasComputedStringProperty = false;
|
||||
hasComputedNumberProperty = false;
|
||||
typeFlags = 0;
|
||||
}
|
||||
const type = checkExpression((memberDecl as SpreadAssignment).expression);
|
||||
if (!(type.flags & (TypeFlags.Object | TypeFlags.Any))) {
|
||||
error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types);
|
||||
return unknownType;
|
||||
}
|
||||
spread = getSpreadType(spread, type, /*isFromObjectLiteral*/ false);
|
||||
continue;
|
||||
}
|
||||
else {
|
||||
// TypeScript 1.0 spec (April 2014)
|
||||
// A get accessor declaration is processed in the same manner as
|
||||
@@ -10907,20 +11022,36 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
const stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, IndexKind.String) : undefined;
|
||||
const numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, IndexKind.Number) : undefined;
|
||||
const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo);
|
||||
const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral;
|
||||
result.flags |= TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag | (typeFlags & TypeFlags.PropagatingFlags);
|
||||
result.objectFlags |= ObjectFlags.ObjectLiteral;
|
||||
if (patternWithComputedProperties) {
|
||||
result.objectFlags |= ObjectFlags.ObjectLiteralPatternWithComputedProperties;
|
||||
if (spread !== emptyObjectType) {
|
||||
if (propertiesArray.length > 0) {
|
||||
spread = getSpreadType(spread, createObjectLiteralType(), /*isFromObjectLiteral*/ true);
|
||||
}
|
||||
spread.flags |= propagatedFlags;
|
||||
spread.symbol = node.symbol;
|
||||
return spread;
|
||||
}
|
||||
if (inDestructuringPattern) {
|
||||
result.pattern = node;
|
||||
|
||||
return createObjectLiteralType();
|
||||
|
||||
function createObjectLiteralType() {
|
||||
const stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, propertiesArray, IndexKind.String) : undefined;
|
||||
const numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, IndexKind.Number) : undefined;
|
||||
const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo);
|
||||
const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshLiteral;
|
||||
result.flags |= TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag | (typeFlags & TypeFlags.PropagatingFlags);
|
||||
result.objectFlags |= ObjectFlags.ObjectLiteral;
|
||||
if (patternWithComputedProperties) {
|
||||
result.objectFlags |= ObjectFlags.ObjectLiteralPatternWithComputedProperties;
|
||||
}
|
||||
if (inDestructuringPattern) {
|
||||
result.pattern = node;
|
||||
}
|
||||
if (!(result.flags & TypeFlags.Nullable)) {
|
||||
propagatedFlags |= (result.flags & TypeFlags.PropagatingFlags);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function checkJsxSelfClosingElement(node: JsxSelfClosingElement) {
|
||||
checkJsxOpeningLikeElement(node);
|
||||
@@ -11819,7 +11950,7 @@ namespace ts {
|
||||
function getSpreadArgumentIndex(args: Expression[]): number {
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
if (arg && arg.kind === SyntaxKind.SpreadElementExpression) {
|
||||
if (arg && arg.kind === SyntaxKind.SpreadElement) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
@@ -13785,7 +13916,7 @@ namespace ts {
|
||||
error(name, Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), declarationNameToString(name));
|
||||
}
|
||||
}
|
||||
else {
|
||||
else if (property.kind !== SyntaxKind.SpreadAssignment) {
|
||||
error(property, Diagnostics.Property_assignment_expected);
|
||||
}
|
||||
}
|
||||
@@ -13807,7 +13938,7 @@ namespace ts {
|
||||
const elements = node.elements;
|
||||
const element = elements[elementIndex];
|
||||
if (element.kind !== SyntaxKind.OmittedExpression) {
|
||||
if (element.kind !== SyntaxKind.SpreadElementExpression) {
|
||||
if (element.kind !== SyntaxKind.SpreadElement) {
|
||||
const propName = "" + elementIndex;
|
||||
const type = isTypeAny(sourceType)
|
||||
? sourceType
|
||||
@@ -13831,10 +13962,10 @@ namespace ts {
|
||||
}
|
||||
else {
|
||||
if (elementIndex < elements.length - 1) {
|
||||
error(element, Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern);
|
||||
error(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
|
||||
}
|
||||
else {
|
||||
const restExpression = (<SpreadElementExpression>element).expression;
|
||||
const restExpression = (<SpreadElement>element).expression;
|
||||
if (restExpression.kind === SyntaxKind.BinaryExpression && (<BinaryExpression>restExpression).operatorToken.kind === SyntaxKind.EqualsToken) {
|
||||
error((<BinaryExpression>restExpression).operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer);
|
||||
}
|
||||
@@ -14467,8 +14598,8 @@ namespace ts {
|
||||
return checkBinaryExpression(<BinaryExpression>node, contextualMapper);
|
||||
case SyntaxKind.ConditionalExpression:
|
||||
return checkConditionalExpression(<ConditionalExpression>node, contextualMapper);
|
||||
case SyntaxKind.SpreadElementExpression:
|
||||
return checkSpreadElementExpression(<SpreadElementExpression>node, contextualMapper);
|
||||
case SyntaxKind.SpreadElement:
|
||||
return checkSpreadExpression(<SpreadElement>node, contextualMapper);
|
||||
case SyntaxKind.OmittedExpression:
|
||||
return undefinedWideningType;
|
||||
case SyntaxKind.YieldExpression:
|
||||
@@ -19115,6 +19246,10 @@ namespace ts {
|
||||
return symbols;
|
||||
}
|
||||
else if (symbol.flags & SymbolFlags.Transient) {
|
||||
if ((symbol as SymbolLinks).leftSpread) {
|
||||
const links = symbol as SymbolLinks;
|
||||
return [links.leftSpread, links.rightSpread];
|
||||
}
|
||||
let target: Symbol;
|
||||
let next = symbol;
|
||||
while (next = getSymbolLinks(next).target) {
|
||||
@@ -19815,7 +19950,7 @@ namespace ts {
|
||||
if (requestedExternalEmitHelpers & NodeFlags.HasClassExtends && languageVersion < ScriptTarget.ES2015) {
|
||||
verifyHelperSymbol(exports, "__extends", SymbolFlags.Value);
|
||||
}
|
||||
if (requestedExternalEmitHelpers & NodeFlags.HasJsxSpreadAttributes && compilerOptions.jsx !== JsxEmit.Preserve) {
|
||||
if (requestedExternalEmitHelpers & NodeFlags.HasSpreadAttribute && compilerOptions.jsx !== JsxEmit.Preserve) {
|
||||
verifyHelperSymbol(exports, "__assign", SymbolFlags.Value);
|
||||
}
|
||||
if (requestedExternalEmitHelpers & NodeFlags.HasDecorators) {
|
||||
@@ -20378,7 +20513,6 @@ namespace ts {
|
||||
checkGrammarHeritageClause(heritageClause);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -20426,6 +20560,9 @@ namespace ts {
|
||||
const GetOrSetAccessor = GetAccessor | SetAccessor;
|
||||
|
||||
for (const prop of node.properties) {
|
||||
if (prop.kind === SyntaxKind.SpreadAssignment) {
|
||||
continue;
|
||||
}
|
||||
const name = prop.name;
|
||||
if (name.kind === SyntaxKind.ComputedPropertyName) {
|
||||
// If the name is not a ComputedPropertyName, the grammar checking will skip it
|
||||
@@ -20729,7 +20866,7 @@ namespace ts {
|
||||
if (node.dotDotDotToken) {
|
||||
const elements = (<BindingPattern>node.parent).elements;
|
||||
if (node !== lastOrUndefined(elements)) {
|
||||
return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern);
|
||||
return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
|
||||
}
|
||||
|
||||
if (node.name.kind === SyntaxKind.ArrayBindingPattern || node.name.kind === SyntaxKind.ObjectBindingPattern) {
|
||||
@@ -20737,7 +20874,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (node.initializer) {
|
||||
// Error on equals token which immediate precedes the initializer
|
||||
// Error on equals token which immediately precedes the initializer
|
||||
return grammarErrorAtPos(getSourceFileOfNode(node), node.initializer.pos - 1, 1, Diagnostics.A_rest_element_cannot_have_an_initializer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,6 +265,7 @@ namespace ts {
|
||||
"es2015": ScriptTarget.ES2015,
|
||||
"es2016": ScriptTarget.ES2016,
|
||||
"es2017": ScriptTarget.ES2017,
|
||||
"esnext": ScriptTarget.ESNext,
|
||||
}),
|
||||
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015,
|
||||
paramType: Diagnostics.VERSION,
|
||||
|
||||
@@ -1455,7 +1455,7 @@
|
||||
"category": "Error",
|
||||
"code": 2461
|
||||
},
|
||||
"A rest element must be last in an array destructuring pattern": {
|
||||
"A rest element must be last in a destructuring pattern": {
|
||||
"category": "Error",
|
||||
"code": 2462
|
||||
},
|
||||
@@ -1983,6 +1983,14 @@
|
||||
"category": "Error",
|
||||
"code": 2697
|
||||
},
|
||||
"Spread types may only be created from object types.": {
|
||||
"category": "Error",
|
||||
"code": 2698
|
||||
},
|
||||
"Rest types may only be created from object types.": {
|
||||
"category": "Error",
|
||||
"code": 2700
|
||||
},
|
||||
|
||||
"Import declaration '{0}' is using private name '{1}'.": {
|
||||
"category": "Error",
|
||||
|
||||
+30
-4
@@ -42,6 +42,14 @@ var __assign = (this && this.__assign) || Object.assign || function(t) {
|
||||
return t;
|
||||
};`;
|
||||
|
||||
const restHelper = `
|
||||
var __rest = (this && this.__rest) || function (s, e) {
|
||||
var t = {};
|
||||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && !e.indexOf(p))
|
||||
t[p] = s[p];
|
||||
return t;
|
||||
};`;
|
||||
|
||||
// emit output for the __decorate helper function
|
||||
const decorateHelper = `
|
||||
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
||||
@@ -226,6 +234,7 @@ const _super = (function (geti, seti) {
|
||||
let currentFileIdentifiers: Map<string>;
|
||||
let extendsEmitted: boolean;
|
||||
let assignEmitted: boolean;
|
||||
let restEmitted: boolean;
|
||||
let decorateEmitted: boolean;
|
||||
let paramEmitted: boolean;
|
||||
let awaiterEmitted: boolean;
|
||||
@@ -732,6 +741,8 @@ const _super = (function (geti, seti) {
|
||||
return emitPropertyAssignment(<PropertyAssignment>node);
|
||||
case SyntaxKind.ShorthandPropertyAssignment:
|
||||
return emitShorthandPropertyAssignment(<ShorthandPropertyAssignment>node);
|
||||
case SyntaxKind.SpreadAssignment:
|
||||
return emitSpreadAssignment(node as SpreadAssignment);
|
||||
|
||||
// Enum
|
||||
case SyntaxKind.EnumMember:
|
||||
@@ -822,8 +833,8 @@ const _super = (function (geti, seti) {
|
||||
return emitTemplateExpression(<TemplateExpression>node);
|
||||
case SyntaxKind.YieldExpression:
|
||||
return emitYieldExpression(<YieldExpression>node);
|
||||
case SyntaxKind.SpreadElementExpression:
|
||||
return emitSpreadElementExpression(<SpreadElementExpression>node);
|
||||
case SyntaxKind.SpreadElement:
|
||||
return emitSpreadExpression(<SpreadElement>node);
|
||||
case SyntaxKind.ClassExpression:
|
||||
return emitClassExpression(<ClassExpression>node);
|
||||
case SyntaxKind.OmittedExpression:
|
||||
@@ -1374,7 +1385,7 @@ const _super = (function (geti, seti) {
|
||||
emitExpressionWithPrefix(" ", node.expression);
|
||||
}
|
||||
|
||||
function emitSpreadElementExpression(node: SpreadElementExpression) {
|
||||
function emitSpreadExpression(node: SpreadElement) {
|
||||
write("...");
|
||||
emitExpression(node.expression);
|
||||
}
|
||||
@@ -2102,6 +2113,13 @@ const _super = (function (geti, seti) {
|
||||
}
|
||||
}
|
||||
|
||||
function emitSpreadAssignment(node: SpreadAssignment) {
|
||||
if (node.expression) {
|
||||
write("...");
|
||||
emitExpression(node.expression);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Enum
|
||||
//
|
||||
@@ -2205,11 +2223,19 @@ const _super = (function (geti, seti) {
|
||||
helpersEmitted = true;
|
||||
}
|
||||
|
||||
if (compilerOptions.jsx !== JsxEmit.Preserve && !assignEmitted && (node.flags & NodeFlags.HasJsxSpreadAttributes)) {
|
||||
if ((languageVersion < ScriptTarget.ESNext || currentSourceFile.scriptKind === ScriptKind.JSX || currentSourceFile.scriptKind === ScriptKind.TSX) &&
|
||||
compilerOptions.jsx !== JsxEmit.Preserve &&
|
||||
!assignEmitted &&
|
||||
node.flags & NodeFlags.HasSpreadAttribute) {
|
||||
writeLines(assignHelper);
|
||||
assignEmitted = true;
|
||||
}
|
||||
|
||||
if (languageVersion < ScriptTarget.ESNext && !restEmitted && node.flags & NodeFlags.HasRestAttribute) {
|
||||
writeLines(restHelper);
|
||||
restEmitted = true;
|
||||
}
|
||||
|
||||
if (!decorateEmitted && node.flags & NodeFlags.HasDecorators) {
|
||||
writeLines(decorateHelper);
|
||||
if (compilerOptions.emitDecoratorMetadata) {
|
||||
|
||||
+551
-4
@@ -692,12 +692,12 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function createSpread(expression: Expression, location?: TextRange) {
|
||||
const node = <SpreadElementExpression>createNode(SyntaxKind.SpreadElementExpression, location);
|
||||
const node = <SpreadElement>createNode(SyntaxKind.SpreadElement, location);
|
||||
node.expression = parenthesizeExpressionForList(expression);
|
||||
return node;
|
||||
}
|
||||
|
||||
export function updateSpread(node: SpreadElementExpression, expression: Expression) {
|
||||
export function updateSpread(node: SpreadElement, expression: Expression) {
|
||||
if (node.expression !== expression) {
|
||||
return updateNode(createSpread(expression, node), node);
|
||||
}
|
||||
@@ -1399,14 +1399,27 @@ namespace ts {
|
||||
return node;
|
||||
}
|
||||
|
||||
export function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression) {
|
||||
export function createSpreadAssignment(expression: Expression, location?: TextRange) {
|
||||
const node = <SpreadAssignment>createNode(SyntaxKind.SpreadAssignment, location);
|
||||
node.expression = expression !== undefined ? parenthesizeExpressionForList(expression) : undefined;
|
||||
return node;
|
||||
}
|
||||
|
||||
export function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression) {
|
||||
if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) {
|
||||
return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
// Top-level nodes
|
||||
export function updateSpreadAssignment(node: SpreadAssignment, expression: Expression) {
|
||||
if (node.expression !== expression) {
|
||||
return updateNode(createSpreadAssignment(expression, node), node);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
// Top-level nodes
|
||||
|
||||
export function updateSourceFileNode(node: SourceFile, statements: Statement[]) {
|
||||
if (node.statements !== statements) {
|
||||
@@ -3055,4 +3068,538 @@ namespace ts {
|
||||
function tryGetModuleNameFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions) {
|
||||
return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms the body of a function-like node.
|
||||
*
|
||||
* @param node A function-like node.
|
||||
*/
|
||||
export function transformFunctionBody(node: FunctionLikeDeclaration,
|
||||
visitor: (node: Node) => VisitResult<Node>,
|
||||
currentSourceFile: SourceFile,
|
||||
context: TransformationContext,
|
||||
enableSubstitutionsForCapturedThis: () => void,
|
||||
convertObjectRest?: boolean) {
|
||||
let multiLine = false; // indicates whether the block *must* be emitted as multiple lines
|
||||
let singleLine = false; // indicates whether the block *may* be emitted as a single line
|
||||
let statementsLocation: TextRange;
|
||||
let closeBraceLocation: TextRange;
|
||||
|
||||
const statements: Statement[] = [];
|
||||
const body = node.body;
|
||||
let statementOffset: number;
|
||||
|
||||
context.startLexicalEnvironment();
|
||||
if (isBlock(body)) {
|
||||
// ensureUseStrict is false because no new prologue-directive should be added.
|
||||
// addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array
|
||||
statementOffset = addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor);
|
||||
}
|
||||
|
||||
addCaptureThisForNodeIfNeeded(statements, node, enableSubstitutionsForCapturedThis);
|
||||
addDefaultValueAssignmentsIfNeeded(statements, node, visitor, convertObjectRest);
|
||||
addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false);
|
||||
|
||||
// If we added any generated statements, this must be a multi-line block.
|
||||
if (!multiLine && statements.length > 0) {
|
||||
multiLine = true;
|
||||
}
|
||||
|
||||
if (isBlock(body)) {
|
||||
statementsLocation = body.statements;
|
||||
addRange(statements, visitNodes(body.statements, visitor, isStatement, statementOffset));
|
||||
|
||||
// If the original body was a multi-line block, this must be a multi-line block.
|
||||
if (!multiLine && body.multiLine) {
|
||||
multiLine = true;
|
||||
}
|
||||
}
|
||||
else {
|
||||
Debug.assert(node.kind === SyntaxKind.ArrowFunction);
|
||||
|
||||
// To align with the old emitter, we use a synthetic end position on the location
|
||||
// for the statement list we synthesize when we down-level an arrow function with
|
||||
// an expression function body. This prevents both comments and source maps from
|
||||
// being emitted for the end position only.
|
||||
statementsLocation = moveRangeEnd(body, -1);
|
||||
|
||||
const equalsGreaterThanToken = (<ArrowFunction>node).equalsGreaterThanToken;
|
||||
if (!nodeIsSynthesized(equalsGreaterThanToken) && !nodeIsSynthesized(body)) {
|
||||
if (rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
|
||||
singleLine = true;
|
||||
}
|
||||
else {
|
||||
multiLine = true;
|
||||
}
|
||||
}
|
||||
|
||||
const expression = visitNode(body, visitor, isExpression);
|
||||
const returnStatement = createReturn(expression, /*location*/ body);
|
||||
setEmitFlags(returnStatement, EmitFlags.NoTokenSourceMaps | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTrailingComments);
|
||||
statements.push(returnStatement);
|
||||
|
||||
// To align with the source map emit for the old emitter, we set a custom
|
||||
// source map location for the close brace.
|
||||
closeBraceLocation = body;
|
||||
}
|
||||
|
||||
const lexicalEnvironment = context.endLexicalEnvironment();
|
||||
addRange(statements, lexicalEnvironment);
|
||||
|
||||
// If we added any final generated statements, this must be a multi-line block
|
||||
if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) {
|
||||
multiLine = true;
|
||||
}
|
||||
|
||||
const block = createBlock(createNodeArray(statements, statementsLocation), node.body, multiLine);
|
||||
if (!multiLine && singleLine) {
|
||||
setEmitFlags(block, EmitFlags.SingleLine);
|
||||
}
|
||||
|
||||
if (closeBraceLocation) {
|
||||
setTokenSourceMapRange(block, SyntaxKind.CloseBraceToken, closeBraceLocation);
|
||||
}
|
||||
|
||||
setOriginalNode(block, node.body);
|
||||
return block;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a statement to capture the `this` of a function declaration if it is needed.
|
||||
*
|
||||
* @param statements The statements for the new function body.
|
||||
* @param node A node.
|
||||
*/
|
||||
export function addCaptureThisForNodeIfNeeded(statements: Statement[], node: Node, enableSubstitutionsForCapturedThis: () => void): void {
|
||||
if (node.transformFlags & TransformFlags.ContainsCapturedLexicalThis && node.kind !== SyntaxKind.ArrowFunction) {
|
||||
captureThisForNode(statements, node, createThis(), enableSubstitutionsForCapturedThis);
|
||||
}
|
||||
}
|
||||
|
||||
export function captureThisForNode(statements: Statement[], node: Node, initializer: Expression | undefined, enableSubstitutionsForCapturedThis?: () => void, originalStatement?: Statement): void {
|
||||
enableSubstitutionsForCapturedThis();
|
||||
const captureThisStatement = createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(
|
||||
"_this",
|
||||
/*type*/ undefined,
|
||||
initializer
|
||||
)
|
||||
]),
|
||||
originalStatement
|
||||
);
|
||||
|
||||
setEmitFlags(captureThisStatement, EmitFlags.NoComments | EmitFlags.CustomPrologue);
|
||||
setSourceMapRange(captureThisStatement, node);
|
||||
statements.push(captureThisStatement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a value indicating whether we need to add default value assignments for a
|
||||
* function-like node.
|
||||
*
|
||||
* @param node A function-like node.
|
||||
*/
|
||||
function shouldAddDefaultValueAssignments(node: FunctionLikeDeclaration): boolean {
|
||||
return (node.transformFlags & TransformFlags.ContainsDefaultValueAssignments) !== 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds statements to the body of a function-like node if it contains parameters with
|
||||
* binding patterns or initializers.
|
||||
*
|
||||
* @param statements The statements for the new function body.
|
||||
* @param node A function-like node.
|
||||
*/
|
||||
export function addDefaultValueAssignmentsIfNeeded(statements: Statement[],
|
||||
node: FunctionLikeDeclaration,
|
||||
visitor: (node: Node) => VisitResult<Node>,
|
||||
convertObjectRest: boolean): void {
|
||||
if (!shouldAddDefaultValueAssignments(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const parameter of node.parameters) {
|
||||
const { name, initializer, dotDotDotToken } = parameter;
|
||||
|
||||
// A rest parameter cannot have a binding pattern or an initializer,
|
||||
// so let's just ignore it.
|
||||
if (dotDotDotToken) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isBindingPattern(name)) {
|
||||
addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer, visitor, convertObjectRest);
|
||||
}
|
||||
else if (initializer) {
|
||||
addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer, visitor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds statements to the body of a function-like node for parameters with binding patterns
|
||||
*
|
||||
* @param statements The statements for the new function body.
|
||||
* @param parameter The parameter for the function.
|
||||
* @param name The name of the parameter.
|
||||
* @param initializer The initializer for the parameter.
|
||||
*/
|
||||
function addDefaultValueAssignmentForBindingPattern(statements: Statement[],
|
||||
parameter: ParameterDeclaration,
|
||||
name: BindingPattern, initializer: Expression,
|
||||
visitor: (node: Node) => VisitResult<Node>,
|
||||
convertObjectRest: boolean): void {
|
||||
const temp = getGeneratedNameForNode(parameter);
|
||||
|
||||
// In cases where a binding pattern is simply '[]' or '{}',
|
||||
// we usually don't want to emit a var declaration; however, in the presence
|
||||
// of an initializer, we must emit that expression to preserve side effects.
|
||||
if (name.elements.length > 0) {
|
||||
statements.push(
|
||||
setEmitFlags(
|
||||
createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
createVariableDeclarationList(
|
||||
flattenParameterDestructuring(parameter, temp, visitor, convertObjectRest)
|
||||
)
|
||||
),
|
||||
EmitFlags.CustomPrologue
|
||||
)
|
||||
);
|
||||
}
|
||||
else if (initializer) {
|
||||
statements.push(
|
||||
setEmitFlags(
|
||||
createStatement(
|
||||
createAssignment(
|
||||
temp,
|
||||
visitNode(initializer, visitor, isExpression)
|
||||
)
|
||||
),
|
||||
EmitFlags.CustomPrologue
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds statements to the body of a function-like node for parameters with initializers.
|
||||
*
|
||||
* @param statements The statements for the new function body.
|
||||
* @param parameter The parameter for the function.
|
||||
* @param name The name of the parameter.
|
||||
* @param initializer The initializer for the parameter.
|
||||
*/
|
||||
function addDefaultValueAssignmentForInitializer(statements: Statement[],
|
||||
parameter: ParameterDeclaration,
|
||||
name: Identifier,
|
||||
initializer: Expression,
|
||||
visitor: (node: Node) => VisitResult<Node>): void {
|
||||
initializer = visitNode(initializer, visitor, isExpression);
|
||||
const statement = createIf(
|
||||
createStrictEquality(
|
||||
getSynthesizedClone(name),
|
||||
createVoidZero()
|
||||
),
|
||||
setEmitFlags(
|
||||
createBlock([
|
||||
createStatement(
|
||||
createAssignment(
|
||||
setEmitFlags(getMutableClone(name), EmitFlags.NoSourceMap),
|
||||
setEmitFlags(initializer, EmitFlags.NoSourceMap | getEmitFlags(initializer)),
|
||||
/*location*/ parameter
|
||||
)
|
||||
)
|
||||
], /*location*/ parameter),
|
||||
EmitFlags.SingleLine | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTokenSourceMaps
|
||||
),
|
||||
/*elseStatement*/ undefined,
|
||||
/*location*/ parameter
|
||||
);
|
||||
statement.startsOnNewLine = true;
|
||||
setEmitFlags(statement, EmitFlags.NoTokenSourceMaps | EmitFlags.NoTrailingSourceMap | EmitFlags.CustomPrologue);
|
||||
statements.push(statement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a value indicating whether we need to add statements to handle a rest parameter.
|
||||
*
|
||||
* @param node A ParameterDeclaration node.
|
||||
* @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
|
||||
* part of a constructor declaration with a
|
||||
* synthesized call to `super`
|
||||
*/
|
||||
function shouldAddRestParameter(node: ParameterDeclaration, inConstructorWithSynthesizedSuper: boolean) {
|
||||
return node && node.dotDotDotToken && node.name.kind === SyntaxKind.Identifier && !inConstructorWithSynthesizedSuper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds statements to the body of a function-like node if it contains a rest parameter.
|
||||
*
|
||||
* @param statements The statements for the new function body.
|
||||
* @param node A function-like node.
|
||||
* @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
|
||||
* part of a constructor declaration with a
|
||||
* synthesized call to `super`
|
||||
*/
|
||||
export function addRestParameterIfNeeded(statements: Statement[], node: FunctionLikeDeclaration, inConstructorWithSynthesizedSuper: boolean): void {
|
||||
const parameter = lastOrUndefined(node.parameters);
|
||||
if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// `declarationName` is the name of the local declaration for the parameter.
|
||||
const declarationName = getMutableClone(<Identifier>parameter.name);
|
||||
setEmitFlags(declarationName, EmitFlags.NoSourceMap);
|
||||
|
||||
// `expressionName` is the name of the parameter used in expressions.
|
||||
const expressionName = getSynthesizedClone(<Identifier>parameter.name);
|
||||
const restIndex = node.parameters.length - 1;
|
||||
const temp = createLoopVariable();
|
||||
|
||||
// var param = [];
|
||||
statements.push(
|
||||
setEmitFlags(
|
||||
createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(
|
||||
declarationName,
|
||||
/*type*/ undefined,
|
||||
createArrayLiteral([])
|
||||
)
|
||||
]),
|
||||
/*location*/ parameter
|
||||
),
|
||||
EmitFlags.CustomPrologue
|
||||
)
|
||||
);
|
||||
|
||||
// for (var _i = restIndex; _i < arguments.length; _i++) {
|
||||
// param[_i - restIndex] = arguments[_i];
|
||||
// }
|
||||
const forStatement = createFor(
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(temp, /*type*/ undefined, createLiteral(restIndex))
|
||||
], /*location*/ parameter),
|
||||
createLessThan(
|
||||
temp,
|
||||
createPropertyAccess(createIdentifier("arguments"), "length"),
|
||||
/*location*/ parameter
|
||||
),
|
||||
createPostfixIncrement(temp, /*location*/ parameter),
|
||||
createBlock([
|
||||
startOnNewLine(
|
||||
createStatement(
|
||||
createAssignment(
|
||||
createElementAccess(
|
||||
expressionName,
|
||||
createSubtract(temp, createLiteral(restIndex))
|
||||
),
|
||||
createElementAccess(createIdentifier("arguments"), temp)
|
||||
),
|
||||
/*location*/ parameter
|
||||
)
|
||||
)
|
||||
])
|
||||
);
|
||||
|
||||
setEmitFlags(forStatement, EmitFlags.CustomPrologue);
|
||||
startOnNewLine(forStatement);
|
||||
statements.push(forStatement);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
export function convertForOf(node: ForOfStatement, convertedLoopBodyStatements: Statement[],
|
||||
visitor: (node: Node) => VisitResult<Node>,
|
||||
enableSubstitutionsForBlockScopedBindings: () => void,
|
||||
context: TransformationContext,
|
||||
convertObjectRest?: boolean): ForStatement | ForOfStatement {
|
||||
// The following ES6 code:
|
||||
//
|
||||
// for (let v of expr) { }
|
||||
//
|
||||
// should be emitted as
|
||||
//
|
||||
// for (var _i = 0, _a = expr; _i < _a.length; _i++) {
|
||||
// var v = _a[_i];
|
||||
// }
|
||||
//
|
||||
// where _a and _i are temps emitted to capture the RHS and the counter,
|
||||
// respectively.
|
||||
// When the left hand side is an expression instead of a let declaration,
|
||||
// the "let v" is not emitted.
|
||||
// When the left hand side is a let/const, the v is renamed if there is
|
||||
// another v in scope.
|
||||
// Note that all assignments to the LHS are emitted in the body, including
|
||||
// all destructuring.
|
||||
// Note also that because an extra statement is needed to assign to the LHS,
|
||||
// for-of bodies are always emitted as blocks.
|
||||
|
||||
const expression = visitNode(node.expression, visitor, isExpression);
|
||||
const initializer = node.initializer;
|
||||
const statements: Statement[] = [];
|
||||
|
||||
// In the case where the user wrote an identifier as the RHS, like this:
|
||||
//
|
||||
// for (let v of arr) { }
|
||||
//
|
||||
// we don't want to emit a temporary variable for the RHS, just use it directly.
|
||||
const counter = convertObjectRest ? undefined : createLoopVariable();
|
||||
const rhsReference = expression.kind === SyntaxKind.Identifier
|
||||
? createUniqueName((<Identifier>expression).text)
|
||||
: createTempVariable(/*recordTempVariable*/ undefined);
|
||||
const elementAccess = convertObjectRest ? rhsReference : createElementAccess(rhsReference, counter);
|
||||
|
||||
// Initialize LHS
|
||||
// var v = _a[_i];
|
||||
if (isVariableDeclarationList(initializer)) {
|
||||
if (initializer.flags & NodeFlags.BlockScoped) {
|
||||
enableSubstitutionsForBlockScopedBindings();
|
||||
}
|
||||
|
||||
const firstOriginalDeclaration = firstOrUndefined(initializer.declarations);
|
||||
if (firstOriginalDeclaration && isBindingPattern(firstOriginalDeclaration.name)) {
|
||||
// This works whether the declaration is a var, let, or const.
|
||||
// It will use rhsIterationValue _a[_i] as the initializer.
|
||||
const declarations = flattenVariableDestructuring(
|
||||
firstOriginalDeclaration,
|
||||
elementAccess,
|
||||
visitor,
|
||||
/*recordTempVariable*/ undefined,
|
||||
convertObjectRest
|
||||
);
|
||||
|
||||
const declarationList = createVariableDeclarationList(declarations, /*location*/ initializer);
|
||||
setOriginalNode(declarationList, initializer);
|
||||
|
||||
// Adjust the source map range for the first declaration to align with the old
|
||||
// emitter.
|
||||
const firstDeclaration = declarations[0];
|
||||
const lastDeclaration = lastOrUndefined(declarations);
|
||||
setSourceMapRange(declarationList, createRange(firstDeclaration.pos, lastDeclaration.end));
|
||||
|
||||
statements.push(
|
||||
createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
declarationList
|
||||
)
|
||||
);
|
||||
}
|
||||
else {
|
||||
// The following call does not include the initializer, so we have
|
||||
// to emit it separately.
|
||||
statements.push(
|
||||
createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
setOriginalNode(
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(
|
||||
firstOriginalDeclaration ? firstOriginalDeclaration.name : createTempVariable(/*recordTempVariable*/ undefined),
|
||||
/*type*/ undefined,
|
||||
createElementAccess(rhsReference, counter)
|
||||
)
|
||||
], /*location*/ moveRangePos(initializer, -1)),
|
||||
initializer
|
||||
),
|
||||
/*location*/ moveRangeEnd(initializer, -1)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Initializer is an expression. Emit the expression in the body, so that it's
|
||||
// evaluated on every iteration.
|
||||
const assignment = createAssignment(initializer, elementAccess);
|
||||
if (isDestructuringAssignment(assignment)) {
|
||||
// This is a destructuring pattern, so we flatten the destructuring instead.
|
||||
statements.push(
|
||||
createStatement(
|
||||
flattenDestructuringAssignment(
|
||||
context,
|
||||
assignment,
|
||||
/*needsValue*/ false,
|
||||
context.hoistVariableDeclaration,
|
||||
visitor,
|
||||
convertObjectRest
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
else {
|
||||
// Currently there is not way to check that assignment is binary expression of destructing assignment
|
||||
// so we have to cast never type to binaryExpression
|
||||
(<BinaryExpression>assignment).end = initializer.end;
|
||||
statements.push(createStatement(assignment, /*location*/ moveRangeEnd(initializer, -1)));
|
||||
}
|
||||
}
|
||||
|
||||
let bodyLocation: TextRange;
|
||||
let statementsLocation: TextRange;
|
||||
if (convertedLoopBodyStatements) {
|
||||
addRange(statements, convertedLoopBodyStatements);
|
||||
}
|
||||
else {
|
||||
const statement = visitNode(node.statement, visitor, isStatement);
|
||||
if (isBlock(statement)) {
|
||||
addRange(statements, statement.statements);
|
||||
bodyLocation = statement;
|
||||
statementsLocation = statement.statements;
|
||||
}
|
||||
else {
|
||||
statements.push(statement);
|
||||
}
|
||||
}
|
||||
|
||||
// The old emitter does not emit source maps for the expression
|
||||
setEmitFlags(expression, EmitFlags.NoSourceMap | getEmitFlags(expression));
|
||||
|
||||
// The old emitter does not emit source maps for the block.
|
||||
// We add the location to preserve comments.
|
||||
const body = createBlock(
|
||||
createNodeArray(statements, /*location*/ statementsLocation),
|
||||
/*location*/ bodyLocation
|
||||
);
|
||||
|
||||
setEmitFlags(body, EmitFlags.NoSourceMap | EmitFlags.NoTokenSourceMaps);
|
||||
|
||||
let forStatement: ForStatement | ForOfStatement;
|
||||
if (convertObjectRest) {
|
||||
forStatement = createForOf(
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(rhsReference, /*type*/ undefined, /*initializer*/ undefined, /*location*/ node.expression)
|
||||
], /*location*/ node.expression),
|
||||
node.expression,
|
||||
body,
|
||||
/*location*/ node
|
||||
);
|
||||
}
|
||||
else {
|
||||
forStatement = createFor(
|
||||
setEmitFlags(
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(counter, /*type*/ undefined, createLiteral(0), /*location*/ moveRangePos(node.expression, -1)),
|
||||
createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression)
|
||||
], /*location*/ node.expression),
|
||||
EmitFlags.NoHoisting
|
||||
),
|
||||
createLessThan(
|
||||
counter,
|
||||
createPropertyAccess(rhsReference, "length"),
|
||||
/*location*/ node.expression
|
||||
),
|
||||
createPostfixIncrement(counter, /*location*/ node.expression),
|
||||
body,
|
||||
/*location*/ node
|
||||
);
|
||||
}
|
||||
|
||||
// Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
|
||||
setEmitFlags(forStatement, EmitFlags.NoTokenTrailingSourceMaps);
|
||||
return forStatement;
|
||||
}
|
||||
}
|
||||
|
||||
+22
-5
@@ -74,6 +74,8 @@ namespace ts {
|
||||
visitNode(cbNode, (<ShorthandPropertyAssignment>node).questionToken) ||
|
||||
visitNode(cbNode, (<ShorthandPropertyAssignment>node).equalsToken) ||
|
||||
visitNode(cbNode, (<ShorthandPropertyAssignment>node).objectAssignmentInitializer);
|
||||
case SyntaxKind.SpreadAssignment:
|
||||
return visitNode(cbNode, (<SpreadAssignment>node).expression);
|
||||
case SyntaxKind.Parameter:
|
||||
case SyntaxKind.PropertyDeclaration:
|
||||
case SyntaxKind.PropertySignature:
|
||||
@@ -197,8 +199,8 @@ namespace ts {
|
||||
visitNode(cbNode, (<ConditionalExpression>node).whenTrue) ||
|
||||
visitNode(cbNode, (<ConditionalExpression>node).colonToken) ||
|
||||
visitNode(cbNode, (<ConditionalExpression>node).whenFalse);
|
||||
case SyntaxKind.SpreadElementExpression:
|
||||
return visitNode(cbNode, (<SpreadElementExpression>node).expression);
|
||||
case SyntaxKind.SpreadElement:
|
||||
return visitNode(cbNode, (<SpreadElement>node).expression);
|
||||
case SyntaxKind.Block:
|
||||
case SyntaxKind.ModuleBlock:
|
||||
return visitNodes(cbNodes, (<Block>node).statements);
|
||||
@@ -1269,9 +1271,11 @@ namespace ts {
|
||||
// which would be a candidate for improved error reporting.
|
||||
return token() === SyntaxKind.OpenBracketToken || isLiteralPropertyName();
|
||||
case ParsingContext.ObjectLiteralMembers:
|
||||
return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.AsteriskToken || isLiteralPropertyName();
|
||||
return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.AsteriskToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName();
|
||||
case ParsingContext.RestProperties:
|
||||
return isLiteralPropertyName();
|
||||
case ParsingContext.ObjectBindingElements:
|
||||
return token() === SyntaxKind.OpenBracketToken || isLiteralPropertyName();
|
||||
return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName();
|
||||
case ParsingContext.HeritageClauseElement:
|
||||
// If we see { } then only consume it as an expression if it is followed by , or {
|
||||
// That way we won't consume the body of a class in its heritage clause.
|
||||
@@ -1398,6 +1402,7 @@ namespace ts {
|
||||
case ParsingContext.ArrayBindingElements:
|
||||
return token() === SyntaxKind.CloseBracketToken;
|
||||
case ParsingContext.Parameters:
|
||||
case ParsingContext.RestProperties:
|
||||
// Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
|
||||
return token() === SyntaxKind.CloseParenToken || token() === SyntaxKind.CloseBracketToken /*|| token === SyntaxKind.OpenBraceToken*/;
|
||||
case ParsingContext.TypeArguments:
|
||||
@@ -1583,6 +1588,9 @@ namespace ts {
|
||||
case ParsingContext.Parameters:
|
||||
return isReusableParameter(node);
|
||||
|
||||
case ParsingContext.RestProperties:
|
||||
return false;
|
||||
|
||||
// Any other lists we do not care about reusing nodes in. But feel free to add if
|
||||
// you can do so safely. Danger areas involve nodes that may involve speculative
|
||||
// parsing. If speculative parsing is involved with the node, then the range the
|
||||
@@ -1780,6 +1788,7 @@ namespace ts {
|
||||
case ParsingContext.BlockStatements: return Diagnostics.Declaration_or_statement_expected;
|
||||
case ParsingContext.SwitchClauses: return Diagnostics.case_or_default_expected;
|
||||
case ParsingContext.SwitchClauseStatements: return Diagnostics.Statement_expected;
|
||||
case ParsingContext.RestProperties: // fallthrough
|
||||
case ParsingContext.TypeMembers: return Diagnostics.Property_or_signature_expected;
|
||||
case ParsingContext.ClassMembers: return Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
|
||||
case ParsingContext.EnumMembers: return Diagnostics.Enum_member_expected;
|
||||
@@ -4122,7 +4131,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function parseSpreadElement(): Expression {
|
||||
const node = <SpreadElementExpression>createNode(SyntaxKind.SpreadElementExpression);
|
||||
const node = <SpreadElement>createNode(SyntaxKind.SpreadElement);
|
||||
parseExpected(SyntaxKind.DotDotDotToken);
|
||||
node.expression = parseAssignmentExpressionOrHigher();
|
||||
return finishNode(node);
|
||||
@@ -4162,6 +4171,12 @@ namespace ts {
|
||||
|
||||
function parseObjectLiteralElement(): ObjectLiteralElementLike {
|
||||
const fullStart = scanner.getStartPos();
|
||||
const dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);
|
||||
if (dotDotDotToken) {
|
||||
const spreadElement = <SpreadAssignment>createNode(SyntaxKind.SpreadAssignment, fullStart);
|
||||
spreadElement.expression = parseAssignmentExpressionOrHigher();
|
||||
return addJSDocComment(finishNode(spreadElement));
|
||||
}
|
||||
const decorators = parseDecorators();
|
||||
const modifiers = parseModifiers();
|
||||
|
||||
@@ -4865,6 +4880,7 @@ namespace ts {
|
||||
|
||||
function parseObjectBindingElement(): BindingElement {
|
||||
const node = <BindingElement>createNode(SyntaxKind.BindingElement);
|
||||
node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);
|
||||
const tokenIsIdentifier = isIdentifier();
|
||||
const propertyName = parsePropertyName();
|
||||
if (tokenIsIdentifier && token() !== SyntaxKind.ColonToken) {
|
||||
@@ -5809,6 +5825,7 @@ namespace ts {
|
||||
JsxChildren, // Things between opening and closing JSX tags
|
||||
ArrayLiteralMembers, // Members in array literal
|
||||
Parameters, // Parameters in parameter list
|
||||
RestProperties, // Property names in a rest type list
|
||||
TypeParameters, // Type parameters in type parameter list
|
||||
TypeArguments, // Type arguments in type argument list
|
||||
TupleElementTypes, // Element types in tuple element type list
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/// <reference path="visitor.ts" />
|
||||
/// <reference path="transformers/ts.ts" />
|
||||
/// <reference path="transformers/jsx.ts" />
|
||||
/// <reference path="transformers/esnext.ts" />
|
||||
/// <reference path="transformers/es2017.ts" />
|
||||
/// <reference path="transformers/es2016.ts" />
|
||||
/// <reference path="transformers/es2015.ts" />
|
||||
@@ -116,6 +117,10 @@ namespace ts {
|
||||
transformers.push(transformJsx);
|
||||
}
|
||||
|
||||
if (languageVersion < ScriptTarget.ESNext) {
|
||||
transformers.push(transformESNext);
|
||||
}
|
||||
|
||||
if (languageVersion < ScriptTarget.ES2017) {
|
||||
transformers.push(transformES2017);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,8 @@ namespace ts {
|
||||
node: BinaryExpression,
|
||||
needsValue: boolean,
|
||||
recordTempVariable: (node: Identifier) => void,
|
||||
visitor?: (node: Node) => VisitResult<Node>): Expression {
|
||||
visitor?: (node: Node) => VisitResult<Node>,
|
||||
transformRest?: boolean): Expression {
|
||||
|
||||
if (isEmptyObjectLiteralOrArrayLiteral(node.left)) {
|
||||
const right = node.right;
|
||||
@@ -51,7 +52,7 @@ namespace ts {
|
||||
location = value;
|
||||
}
|
||||
|
||||
flattenDestructuring(node, value, location, emitAssignment, emitTempVariableAssignment, visitor);
|
||||
flattenDestructuring(node, value, location, emitAssignment, emitTempVariableAssignment, recordTempVariable, emitRestAssignment, transformRest, visitor);
|
||||
|
||||
if (needsValue) {
|
||||
expressions.push(value);
|
||||
@@ -61,7 +62,7 @@ namespace ts {
|
||||
aggregateTransformFlags(expression);
|
||||
return expression;
|
||||
|
||||
function emitAssignment(name: Identifier, value: Expression, location: TextRange) {
|
||||
function emitAssignment(name: Identifier | ObjectLiteralExpression, value: Expression, location: TextRange) {
|
||||
const expression = createAssignment(name, value, location);
|
||||
|
||||
// NOTE: this completely disables source maps, but aligns with the behavior of
|
||||
@@ -77,6 +78,10 @@ namespace ts {
|
||||
emitAssignment(name, value, location);
|
||||
return name;
|
||||
}
|
||||
|
||||
function emitRestAssignment(elements: ObjectLiteralElementLike[], value: Expression, location: TextRange) {
|
||||
emitAssignment(createObjectLiteral(elements), value, location);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -89,14 +94,15 @@ namespace ts {
|
||||
export function flattenParameterDestructuring(
|
||||
node: ParameterDeclaration,
|
||||
value: Expression,
|
||||
visitor?: (node: Node) => VisitResult<Node>) {
|
||||
visitor?: (node: Node) => VisitResult<Node>,
|
||||
transformRest?: boolean) {
|
||||
const declarations: VariableDeclaration[] = [];
|
||||
|
||||
flattenDestructuring(node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
|
||||
flattenDestructuring(node, value, node, emitAssignment, emitTempVariableAssignment, noop, emitRestAssignment, transformRest, visitor);
|
||||
|
||||
return declarations;
|
||||
|
||||
function emitAssignment(name: Identifier, value: Expression, location: TextRange) {
|
||||
function emitAssignment(name: Identifier | BindingPattern, value: Expression, location: TextRange) {
|
||||
const declaration = createVariableDeclaration(name, /*type*/ undefined, value, location);
|
||||
|
||||
// NOTE: this completely disables source maps, but aligns with the behavior of
|
||||
@@ -112,6 +118,10 @@ namespace ts {
|
||||
emitAssignment(name, value, location);
|
||||
return name;
|
||||
}
|
||||
|
||||
function emitRestAssignment(elements: BindingElement[], value: Expression, location: TextRange) {
|
||||
emitAssignment(createObjectBindingPattern(elements), value, location);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,15 +135,16 @@ namespace ts {
|
||||
node: VariableDeclaration,
|
||||
value?: Expression,
|
||||
visitor?: (node: Node) => VisitResult<Node>,
|
||||
recordTempVariable?: (node: Identifier) => void) {
|
||||
recordTempVariable?: (node: Identifier) => void,
|
||||
transformRest?: boolean) {
|
||||
const declarations: VariableDeclaration[] = [];
|
||||
|
||||
let pendingAssignments: Expression[];
|
||||
flattenDestructuring(node, value, node, emitAssignment, emitTempVariableAssignment, visitor);
|
||||
flattenDestructuring(node, value, node, emitAssignment, emitTempVariableAssignment, recordTempVariable, emitRestAssignment, transformRest, visitor);
|
||||
|
||||
return declarations;
|
||||
|
||||
function emitAssignment(name: Identifier, value: Expression, location: TextRange, original: Node) {
|
||||
function emitAssignment(name: Identifier | BindingPattern, value: Expression, location: TextRange, original: Node) {
|
||||
if (pendingAssignments) {
|
||||
pendingAssignments.push(value);
|
||||
value = inlineExpressions(pendingAssignments);
|
||||
@@ -167,6 +178,10 @@ namespace ts {
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
function emitRestAssignment(elements: BindingElement[], value: Expression, location: TextRange, original: Node) {
|
||||
emitAssignment(createObjectBindingPattern(elements), value, location, original);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -186,15 +201,17 @@ namespace ts {
|
||||
|
||||
const pendingAssignments: Expression[] = [];
|
||||
|
||||
flattenDestructuring(node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment, visitor);
|
||||
flattenDestructuring(node, /*value*/ undefined, node, emitAssignment, emitTempVariableAssignment, noop, emitRestAssignment, /*transformRest*/ false, visitor);
|
||||
|
||||
const expression = inlineExpressions(pendingAssignments);
|
||||
aggregateTransformFlags(expression);
|
||||
return expression;
|
||||
|
||||
function emitAssignment(name: Identifier, value: Expression, location: TextRange, original: Node) {
|
||||
function emitAssignment(name: Identifier | ObjectLiteralExpression, value: Expression, location: TextRange, original: Node) {
|
||||
const expression = createAssignmentCallback
|
||||
? createAssignmentCallback(name, value, location)
|
||||
? createAssignmentCallback(name.kind === SyntaxKind.Identifier ? name : emitTempVariableAssignment(name, location),
|
||||
value,
|
||||
location)
|
||||
: createAssignment(name, value, location);
|
||||
|
||||
emitPendingAssignment(expression, original);
|
||||
@@ -206,6 +223,10 @@ namespace ts {
|
||||
return name;
|
||||
}
|
||||
|
||||
function emitRestAssignment(elements: ObjectLiteralElementLike[], value: Expression, location: TextRange, original: Node) {
|
||||
emitAssignment(createObjectLiteral(elements), value, location, original);
|
||||
}
|
||||
|
||||
function emitPendingAssignment(expression: Expression, original: Node) {
|
||||
expression.original = original;
|
||||
|
||||
@@ -223,6 +244,9 @@ namespace ts {
|
||||
location: TextRange,
|
||||
emitAssignment: (name: Identifier, value: Expression, location: TextRange, original: Node) => void,
|
||||
emitTempVariableAssignment: (value: Expression, location: TextRange) => Identifier,
|
||||
recordTempVariable: (node: Identifier) => void,
|
||||
emitRestAssignment: (elements: (ObjectLiteralElementLike[] | BindingElement[]), value: Expression, location: TextRange, original: Node) => void,
|
||||
transformRest: boolean,
|
||||
visitor?: (node: Node) => VisitResult<Node>) {
|
||||
if (value && visitor) {
|
||||
value = visitNode(value, visitor, isExpression);
|
||||
@@ -284,23 +308,91 @@ namespace ts {
|
||||
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
|
||||
}
|
||||
|
||||
for (const p of properties) {
|
||||
let bindingElements: ObjectLiteralElementLike[] = [];
|
||||
for (let i = 0; i < properties.length; i++) {
|
||||
const p = properties[i];
|
||||
if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) {
|
||||
const propName = <Identifier | LiteralExpression>(<PropertyAssignment>p).name;
|
||||
const target = p.kind === SyntaxKind.ShorthandPropertyAssignment ? <ShorthandPropertyAssignment>p : (<PropertyAssignment>p).initializer || propName;
|
||||
// Assignment for target = value.propName should highligh whole property, hence use p as source map node
|
||||
emitDestructuringAssignment(target, createDestructuringPropertyAccess(value, propName), p);
|
||||
if (!transformRest ||
|
||||
p.transformFlags & TransformFlags.ContainsSpreadExpression ||
|
||||
(p.kind === SyntaxKind.PropertyAssignment && p.initializer.transformFlags & TransformFlags.ContainsSpreadExpression)) {
|
||||
if (bindingElements.length) {
|
||||
emitRestAssignment(bindingElements, value, location, target);
|
||||
bindingElements = [];
|
||||
}
|
||||
const propName = <Identifier | LiteralExpression>(<PropertyAssignment>p).name;
|
||||
const bindingTarget = p.kind === SyntaxKind.ShorthandPropertyAssignment ? <ShorthandPropertyAssignment>p : (<PropertyAssignment>p).initializer || propName;
|
||||
// Assignment for bindingTarget = value.propName should highlight whole property, hence use p as source map node
|
||||
emitDestructuringAssignment(bindingTarget, createDestructuringPropertyAccess(value, propName), p);
|
||||
}
|
||||
else {
|
||||
bindingElements.push(p);
|
||||
}
|
||||
}
|
||||
else if (i === properties.length - 1 && p.kind === SyntaxKind.SpreadAssignment) {
|
||||
Debug.assert((p as SpreadAssignment).expression.kind === SyntaxKind.Identifier);
|
||||
if (bindingElements.length) {
|
||||
emitRestAssignment(bindingElements, value, location, target);
|
||||
bindingElements = [];
|
||||
}
|
||||
const propName = (p as SpreadAssignment).expression as Identifier;
|
||||
const restCall = createRestCall(value, target.properties, p => p.name, target);
|
||||
emitDestructuringAssignment(propName, restCall, p);
|
||||
}
|
||||
}
|
||||
if (bindingElements.length) {
|
||||
emitRestAssignment(bindingElements, value, location, target);
|
||||
bindingElements = [];
|
||||
}
|
||||
}
|
||||
|
||||
function emitArrayLiteralAssignment(target: ArrayLiteralExpression, value: Expression, location: TextRange) {
|
||||
if (transformRest) {
|
||||
emitESNextArrayLiteralAssignment(target, value, location);
|
||||
}
|
||||
else {
|
||||
emitES2015ArrayLiteralAssignment(target, value, location);
|
||||
}
|
||||
}
|
||||
|
||||
function emitESNextArrayLiteralAssignment(target: ArrayLiteralExpression, value: Expression, location: TextRange) {
|
||||
const elements = target.elements;
|
||||
const numElements = elements.length;
|
||||
if (numElements !== 1) {
|
||||
// For anything but a single element destructuring we need to generate a temporary
|
||||
// to ensure value is evaluated exactly once.
|
||||
// When doing so we want to hightlight the passed in source map node since thats the one needing this temp assignment
|
||||
// When doing so we want to highlight the passed-in source map node since thats the one needing this temp assignment
|
||||
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
|
||||
}
|
||||
|
||||
const expressions: Expression[] = [];
|
||||
const spreadContainingExpressions: [Expression, Identifier][] = [];
|
||||
for (let i = 0; i < numElements; i++) {
|
||||
const e = elements[i];
|
||||
if (e.kind === SyntaxKind.OmittedExpression) {
|
||||
continue;
|
||||
}
|
||||
if (e.transformFlags & TransformFlags.ContainsSpreadExpression && i < numElements - 1) {
|
||||
const tmp = createTempVariable(recordTempVariable);
|
||||
spreadContainingExpressions.push([e, tmp]);
|
||||
expressions.push(tmp);
|
||||
}
|
||||
else {
|
||||
expressions.push(e);
|
||||
}
|
||||
}
|
||||
emitAssignment(updateArrayLiteral(target, expressions) as any as Identifier, value, undefined, undefined);
|
||||
for (const [e, tmp] of spreadContainingExpressions) {
|
||||
emitDestructuringAssignment(e, tmp, e);
|
||||
}
|
||||
}
|
||||
|
||||
function emitES2015ArrayLiteralAssignment(target: ArrayLiteralExpression, value: Expression, location: TextRange) {
|
||||
const elements = target.elements;
|
||||
const numElements = elements.length;
|
||||
if (numElements !== 1) {
|
||||
// For anything but a single element destructuring we need to generate a temporary
|
||||
// to ensure value is evaluated exactly once.
|
||||
// When doing so we want to highlight the passed-in source map node since thats the one needing this temp assignment
|
||||
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true, location, emitTempVariableAssignment);
|
||||
}
|
||||
|
||||
@@ -308,20 +400,41 @@ namespace ts {
|
||||
const e = elements[i];
|
||||
if (e.kind !== SyntaxKind.OmittedExpression) {
|
||||
// Assignment for target = value.propName should highligh whole property, hence use e as source map node
|
||||
if (e.kind !== SyntaxKind.SpreadElementExpression) {
|
||||
if (e.kind !== SyntaxKind.SpreadElement) {
|
||||
emitDestructuringAssignment(e, createElementAccess(value, createLiteral(i)), e);
|
||||
}
|
||||
else if (i === numElements - 1) {
|
||||
emitDestructuringAssignment((<SpreadElementExpression>e).expression, createArraySlice(value, i), e);
|
||||
emitDestructuringAssignment((<SpreadElement>e).expression, createArraySlice(value, i), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
|
||||
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`*/
|
||||
function createRestCall<T extends Node>(value: Expression, elements: T[], getPropertyName: (element: T) => PropertyName, location: TextRange): Expression {
|
||||
const propertyNames: LiteralExpression[] = [];
|
||||
for (let i = 0; i < elements.length - 1; i++) {
|
||||
if (isOmittedExpression(elements[i])) {
|
||||
continue;
|
||||
}
|
||||
const str = <StringLiteral>createSynthesizedNode(SyntaxKind.StringLiteral);
|
||||
str.pos = location.pos;
|
||||
str.end = location.end;
|
||||
str.text = getTextOfPropertyName(getPropertyName(elements[i]));
|
||||
propertyNames.push(str);
|
||||
}
|
||||
const args = createSynthesizedNodeArray([value, createArrayLiteral(propertyNames, location)]);
|
||||
return createCall(createIdentifier("__rest"), undefined, args);
|
||||
}
|
||||
|
||||
function emitBindingElement(target: VariableDeclaration | ParameterDeclaration | BindingElement, value: Expression) {
|
||||
// Any temporary assignments needed to emit target = value should point to target
|
||||
const initializer = visitor ? visitNode(target.initializer, visitor, isExpression) : target.initializer;
|
||||
if (initializer) {
|
||||
if (transformRest) {
|
||||
value = value || initializer;
|
||||
}
|
||||
else if (initializer) {
|
||||
// Combine value and initializer
|
||||
value = value ? createDefaultValueCheck(value, initializer, target) : initializer;
|
||||
}
|
||||
@@ -331,9 +444,11 @@ namespace ts {
|
||||
}
|
||||
|
||||
const name = target.name;
|
||||
if (isBindingPattern(name)) {
|
||||
const elements = name.elements;
|
||||
const numElements = elements.length;
|
||||
if (!isBindingPattern(name)) {
|
||||
emitAssignment(name, value, target, target);
|
||||
}
|
||||
else {
|
||||
const numElements = name.elements.length;
|
||||
if (numElements !== 1) {
|
||||
// For anything other than a single-element destructuring we need to generate a temporary
|
||||
// to ensure value is evaluated exactly once. Additionally, if we have zero elements
|
||||
@@ -341,29 +456,104 @@ namespace ts {
|
||||
// so in that case, we'll intentionally create that temporary.
|
||||
value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ numElements !== 0, target, emitTempVariableAssignment);
|
||||
}
|
||||
for (let i = 0; i < numElements; i++) {
|
||||
const element = elements[i];
|
||||
if (isOmittedExpression(element)) {
|
||||
continue;
|
||||
}
|
||||
else if (name.kind === SyntaxKind.ObjectBindingPattern) {
|
||||
// Rewrite element to a declaration with an initializer that fetches property
|
||||
const propName = element.propertyName || <Identifier>element.name;
|
||||
emitBindingElement(element, createDestructuringPropertyAccess(value, propName));
|
||||
}
|
||||
else {
|
||||
if (!element.dotDotDotToken) {
|
||||
// Rewrite element to a declaration that accesses array element at index i
|
||||
emitBindingElement(element, createElementAccess(value, i));
|
||||
}
|
||||
else if (i === numElements - 1) {
|
||||
emitBindingElement(element, createArraySlice(value, i));
|
||||
}
|
||||
}
|
||||
if (name.kind === SyntaxKind.ArrayBindingPattern) {
|
||||
emitArrayBindingElement(name as ArrayBindingPattern, value);
|
||||
}
|
||||
else {
|
||||
emitObjectBindingElement(target, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function emitArrayBindingElement(name: ArrayBindingPattern, value: Expression) {
|
||||
if (transformRest) {
|
||||
emitESNextArrayBindingElement(name, value);
|
||||
}
|
||||
else {
|
||||
emitAssignment(name, value, target, target);
|
||||
emitES2015ArrayBindingElement(name, value);
|
||||
}
|
||||
}
|
||||
|
||||
function emitES2015ArrayBindingElement(name: ArrayBindingPattern, value: Expression) {
|
||||
const elements = name.elements;
|
||||
const numElements = elements.length;
|
||||
for (let i = 0; i < numElements; i++) {
|
||||
const element = elements[i];
|
||||
if (isOmittedExpression(element)) {
|
||||
continue;
|
||||
}
|
||||
if (!element.dotDotDotToken) {
|
||||
// Rewrite element to a declaration that accesses array element at index i
|
||||
emitBindingElement(element, createElementAccess(value, i));
|
||||
}
|
||||
else if (i === numElements - 1) {
|
||||
emitBindingElement(element, createArraySlice(value, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function emitESNextArrayBindingElement(name: ArrayBindingPattern, value: Expression) {
|
||||
const elements = name.elements;
|
||||
const numElements = elements.length;
|
||||
const bindingElements: BindingElement[] = [];
|
||||
const spreadContainingElements: BindingElement[] = [];
|
||||
for (let i = 0; i < numElements; i++) {
|
||||
const element = elements[i];
|
||||
if (isOmittedExpression(element)) {
|
||||
continue;
|
||||
}
|
||||
if (element.transformFlags & TransformFlags.ContainsSpreadExpression && i < numElements - 1) {
|
||||
spreadContainingElements.push(element);
|
||||
bindingElements.push(createBindingElement(undefined, undefined, getGeneratedNameForNode(element), undefined, value));
|
||||
}
|
||||
else {
|
||||
bindingElements.push(element);
|
||||
}
|
||||
}
|
||||
emitAssignment(updateArrayBindingPattern(name, bindingElements) as any as Identifier, value, undefined, undefined);
|
||||
for (const element of spreadContainingElements) {
|
||||
emitBindingElement(element, getGeneratedNameForNode(element));
|
||||
}
|
||||
}
|
||||
|
||||
function emitObjectBindingElement(target: VariableDeclaration | ParameterDeclaration | BindingElement, value: Expression) {
|
||||
const name = target.name as BindingPattern;
|
||||
const elements = name.elements;
|
||||
const numElements = elements.length;
|
||||
let bindingElements: BindingElement[] = [];
|
||||
for (let i = 0; i < numElements; i++) {
|
||||
const element = elements[i];
|
||||
if (isOmittedExpression(element)) {
|
||||
continue;
|
||||
}
|
||||
if (i === numElements - 1 && element.dotDotDotToken) {
|
||||
if (bindingElements.length) {
|
||||
emitRestAssignment(bindingElements, value, target, target);
|
||||
bindingElements = [];
|
||||
}
|
||||
const restCall = createRestCall(value,
|
||||
name.elements,
|
||||
element => (element as BindingElement).propertyName || <Identifier>(element as BindingElement).name,
|
||||
name);
|
||||
emitBindingElement(element, restCall);
|
||||
}
|
||||
else if (transformRest && !(element.transformFlags & TransformFlags.ContainsSpreadExpression)) {
|
||||
// do not emit until we have a complete bundle of ES2015 syntax
|
||||
bindingElements.push(element);
|
||||
}
|
||||
else {
|
||||
if (bindingElements.length) {
|
||||
emitRestAssignment(bindingElements, value, target, target);
|
||||
bindingElements = [];
|
||||
}
|
||||
// Rewrite element to a declaration with an initializer that fetches property
|
||||
const propName = element.propertyName || <Identifier>element.name;
|
||||
emitBindingElement(element, createDestructuringPropertyAccess(value, propName));
|
||||
}
|
||||
}
|
||||
if (bindingElements.length) {
|
||||
emitRestAssignment(bindingElements, value, target, target);
|
||||
bindingElements = [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -861,7 +861,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (constructor) {
|
||||
addDefaultValueAssignmentsIfNeeded(statements, constructor);
|
||||
addDefaultValueAssignmentsIfNeeded(statements, constructor, visitor, /*convertObjectRest*/ false);
|
||||
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
|
||||
Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
|
||||
|
||||
@@ -954,7 +954,7 @@ namespace ts {
|
||||
// If this isn't a derived class, just capture 'this' for arrow functions if necessary.
|
||||
if (!hasExtendsClause) {
|
||||
if (ctor) {
|
||||
addCaptureThisForNodeIfNeeded(statements, ctor);
|
||||
addCaptureThisForNodeIfNeeded(statements, ctor, enableSubstitutionsForCapturedThis);
|
||||
}
|
||||
return SuperCaptureResult.NoReplacement;
|
||||
}
|
||||
@@ -1016,7 +1016,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
// Perform the capture.
|
||||
captureThisForNode(statements, ctor, superCallExpression, firstStatement);
|
||||
captureThisForNode(statements, ctor, superCallExpression, enableSubstitutionsForCapturedThis, firstStatement);
|
||||
|
||||
// If we're actually replacing the original statement, we need to signal this to the caller.
|
||||
if (superCallExpression) {
|
||||
@@ -1085,242 +1085,6 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a value indicating whether we need to add default value assignments for a
|
||||
* function-like node.
|
||||
*
|
||||
* @param node A function-like node.
|
||||
*/
|
||||
function shouldAddDefaultValueAssignments(node: FunctionLikeDeclaration): boolean {
|
||||
return (node.transformFlags & TransformFlags.ContainsDefaultValueAssignments) !== 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds statements to the body of a function-like node if it contains parameters with
|
||||
* binding patterns or initializers.
|
||||
*
|
||||
* @param statements The statements for the new function body.
|
||||
* @param node A function-like node.
|
||||
*/
|
||||
function addDefaultValueAssignmentsIfNeeded(statements: Statement[], node: FunctionLikeDeclaration): void {
|
||||
if (!shouldAddDefaultValueAssignments(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const parameter of node.parameters) {
|
||||
const { name, initializer, dotDotDotToken } = parameter;
|
||||
|
||||
// A rest parameter cannot have a binding pattern or an initializer,
|
||||
// so let's just ignore it.
|
||||
if (dotDotDotToken) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isBindingPattern(name)) {
|
||||
addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer);
|
||||
}
|
||||
else if (initializer) {
|
||||
addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds statements to the body of a function-like node for parameters with binding patterns
|
||||
*
|
||||
* @param statements The statements for the new function body.
|
||||
* @param parameter The parameter for the function.
|
||||
* @param name The name of the parameter.
|
||||
* @param initializer The initializer for the parameter.
|
||||
*/
|
||||
function addDefaultValueAssignmentForBindingPattern(statements: Statement[], parameter: ParameterDeclaration, name: BindingPattern, initializer: Expression): void {
|
||||
const temp = getGeneratedNameForNode(parameter);
|
||||
|
||||
// In cases where a binding pattern is simply '[]' or '{}',
|
||||
// we usually don't want to emit a var declaration; however, in the presence
|
||||
// of an initializer, we must emit that expression to preserve side effects.
|
||||
if (name.elements.length > 0) {
|
||||
statements.push(
|
||||
setEmitFlags(
|
||||
createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
createVariableDeclarationList(
|
||||
flattenParameterDestructuring(parameter, temp, visitor)
|
||||
)
|
||||
),
|
||||
EmitFlags.CustomPrologue
|
||||
)
|
||||
);
|
||||
}
|
||||
else if (initializer) {
|
||||
statements.push(
|
||||
setEmitFlags(
|
||||
createStatement(
|
||||
createAssignment(
|
||||
temp,
|
||||
visitNode(initializer, visitor, isExpression)
|
||||
)
|
||||
),
|
||||
EmitFlags.CustomPrologue
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds statements to the body of a function-like node for parameters with initializers.
|
||||
*
|
||||
* @param statements The statements for the new function body.
|
||||
* @param parameter The parameter for the function.
|
||||
* @param name The name of the parameter.
|
||||
* @param initializer The initializer for the parameter.
|
||||
*/
|
||||
function addDefaultValueAssignmentForInitializer(statements: Statement[], parameter: ParameterDeclaration, name: Identifier, initializer: Expression): void {
|
||||
initializer = visitNode(initializer, visitor, isExpression);
|
||||
const statement = createIf(
|
||||
createStrictEquality(
|
||||
getSynthesizedClone(name),
|
||||
createVoidZero()
|
||||
),
|
||||
setEmitFlags(
|
||||
createBlock([
|
||||
createStatement(
|
||||
createAssignment(
|
||||
setEmitFlags(getMutableClone(name), EmitFlags.NoSourceMap),
|
||||
setEmitFlags(initializer, EmitFlags.NoSourceMap | getEmitFlags(initializer)),
|
||||
/*location*/ parameter
|
||||
)
|
||||
)
|
||||
], /*location*/ parameter),
|
||||
EmitFlags.SingleLine | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTokenSourceMaps
|
||||
),
|
||||
/*elseStatement*/ undefined,
|
||||
/*location*/ parameter
|
||||
);
|
||||
statement.startsOnNewLine = true;
|
||||
setEmitFlags(statement, EmitFlags.NoTokenSourceMaps | EmitFlags.NoTrailingSourceMap | EmitFlags.CustomPrologue);
|
||||
statements.push(statement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a value indicating whether we need to add statements to handle a rest parameter.
|
||||
*
|
||||
* @param node A ParameterDeclaration node.
|
||||
* @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
|
||||
* part of a constructor declaration with a
|
||||
* synthesized call to `super`
|
||||
*/
|
||||
function shouldAddRestParameter(node: ParameterDeclaration, inConstructorWithSynthesizedSuper: boolean) {
|
||||
return node && node.dotDotDotToken && node.name.kind === SyntaxKind.Identifier && !inConstructorWithSynthesizedSuper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds statements to the body of a function-like node if it contains a rest parameter.
|
||||
*
|
||||
* @param statements The statements for the new function body.
|
||||
* @param node A function-like node.
|
||||
* @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
|
||||
* part of a constructor declaration with a
|
||||
* synthesized call to `super`
|
||||
*/
|
||||
function addRestParameterIfNeeded(statements: Statement[], node: FunctionLikeDeclaration, inConstructorWithSynthesizedSuper: boolean): void {
|
||||
const parameter = lastOrUndefined(node.parameters);
|
||||
if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// `declarationName` is the name of the local declaration for the parameter.
|
||||
const declarationName = getMutableClone(<Identifier>parameter.name);
|
||||
setEmitFlags(declarationName, EmitFlags.NoSourceMap);
|
||||
|
||||
// `expressionName` is the name of the parameter used in expressions.
|
||||
const expressionName = getSynthesizedClone(<Identifier>parameter.name);
|
||||
const restIndex = node.parameters.length - 1;
|
||||
const temp = createLoopVariable();
|
||||
|
||||
// var param = [];
|
||||
statements.push(
|
||||
setEmitFlags(
|
||||
createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(
|
||||
declarationName,
|
||||
/*type*/ undefined,
|
||||
createArrayLiteral([])
|
||||
)
|
||||
]),
|
||||
/*location*/ parameter
|
||||
),
|
||||
EmitFlags.CustomPrologue
|
||||
)
|
||||
);
|
||||
|
||||
// for (var _i = restIndex; _i < arguments.length; _i++) {
|
||||
// param[_i - restIndex] = arguments[_i];
|
||||
// }
|
||||
const forStatement = createFor(
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(temp, /*type*/ undefined, createLiteral(restIndex))
|
||||
], /*location*/ parameter),
|
||||
createLessThan(
|
||||
temp,
|
||||
createPropertyAccess(createIdentifier("arguments"), "length"),
|
||||
/*location*/ parameter
|
||||
),
|
||||
createPostfixIncrement(temp, /*location*/ parameter),
|
||||
createBlock([
|
||||
startOnNewLine(
|
||||
createStatement(
|
||||
createAssignment(
|
||||
createElementAccess(
|
||||
expressionName,
|
||||
createSubtract(temp, createLiteral(restIndex))
|
||||
),
|
||||
createElementAccess(createIdentifier("arguments"), temp)
|
||||
),
|
||||
/*location*/ parameter
|
||||
)
|
||||
)
|
||||
])
|
||||
);
|
||||
|
||||
setEmitFlags(forStatement, EmitFlags.CustomPrologue);
|
||||
startOnNewLine(forStatement);
|
||||
statements.push(forStatement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a statement to capture the `this` of a function declaration if it is needed.
|
||||
*
|
||||
* @param statements The statements for the new function body.
|
||||
* @param node A node.
|
||||
*/
|
||||
function addCaptureThisForNodeIfNeeded(statements: Statement[], node: Node): void {
|
||||
if (node.transformFlags & TransformFlags.ContainsCapturedLexicalThis && node.kind !== SyntaxKind.ArrowFunction) {
|
||||
captureThisForNode(statements, node, createThis());
|
||||
}
|
||||
}
|
||||
|
||||
function captureThisForNode(statements: Statement[], node: Node, initializer: Expression | undefined, originalStatement?: Statement): void {
|
||||
enableSubstitutionsForCapturedThis();
|
||||
const captureThisStatement = createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(
|
||||
"_this",
|
||||
/*type*/ undefined,
|
||||
initializer
|
||||
)
|
||||
]),
|
||||
originalStatement
|
||||
);
|
||||
|
||||
setEmitFlags(captureThisStatement, EmitFlags.NoComments | EmitFlags.CustomPrologue);
|
||||
setSourceMapRange(captureThisStatement, node);
|
||||
statements.push(captureThisStatement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds statements to the class body function for a class to define the members of the
|
||||
* class.
|
||||
@@ -1518,7 +1282,7 @@ namespace ts {
|
||||
/*typeParameters*/ undefined,
|
||||
visitNodes(node.parameters, visitor, isParameter),
|
||||
/*type*/ undefined,
|
||||
transformFunctionBody(node),
|
||||
transformFunctionBody(node, visitor, currentSourceFile, context, enableSubstitutionsForCapturedThis),
|
||||
/*location*/ node
|
||||
),
|
||||
/*original*/ node);
|
||||
@@ -1545,7 +1309,7 @@ namespace ts {
|
||||
/*typeParameters*/ undefined,
|
||||
visitNodes(node.parameters, visitor, isParameter),
|
||||
/*type*/ undefined,
|
||||
saveStateAndInvoke(node, transformFunctionBody),
|
||||
saveStateAndInvoke(node, node => transformFunctionBody(node, visitor, currentSourceFile, context, enableSubstitutionsForCapturedThis)),
|
||||
location
|
||||
),
|
||||
/*original*/ node
|
||||
@@ -1555,96 +1319,6 @@ namespace ts {
|
||||
return expression;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms the body of a function-like node.
|
||||
*
|
||||
* @param node A function-like node.
|
||||
*/
|
||||
function transformFunctionBody(node: FunctionLikeDeclaration) {
|
||||
let multiLine = false; // indicates whether the block *must* be emitted as multiple lines
|
||||
let singleLine = false; // indicates whether the block *may* be emitted as a single line
|
||||
let statementsLocation: TextRange;
|
||||
let closeBraceLocation: TextRange;
|
||||
|
||||
const statements: Statement[] = [];
|
||||
const body = node.body;
|
||||
let statementOffset: number;
|
||||
|
||||
startLexicalEnvironment();
|
||||
if (isBlock(body)) {
|
||||
// ensureUseStrict is false because no new prologue-directive should be added.
|
||||
// addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array
|
||||
statementOffset = addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor);
|
||||
}
|
||||
|
||||
addCaptureThisForNodeIfNeeded(statements, node);
|
||||
addDefaultValueAssignmentsIfNeeded(statements, node);
|
||||
addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false);
|
||||
|
||||
// If we added any generated statements, this must be a multi-line block.
|
||||
if (!multiLine && statements.length > 0) {
|
||||
multiLine = true;
|
||||
}
|
||||
|
||||
if (isBlock(body)) {
|
||||
statementsLocation = body.statements;
|
||||
addRange(statements, visitNodes(body.statements, visitor, isStatement, statementOffset));
|
||||
|
||||
// If the original body was a multi-line block, this must be a multi-line block.
|
||||
if (!multiLine && body.multiLine) {
|
||||
multiLine = true;
|
||||
}
|
||||
}
|
||||
else {
|
||||
Debug.assert(node.kind === SyntaxKind.ArrowFunction);
|
||||
|
||||
// To align with the old emitter, we use a synthetic end position on the location
|
||||
// for the statement list we synthesize when we down-level an arrow function with
|
||||
// an expression function body. This prevents both comments and source maps from
|
||||
// being emitted for the end position only.
|
||||
statementsLocation = moveRangeEnd(body, -1);
|
||||
|
||||
const equalsGreaterThanToken = (<ArrowFunction>node).equalsGreaterThanToken;
|
||||
if (!nodeIsSynthesized(equalsGreaterThanToken) && !nodeIsSynthesized(body)) {
|
||||
if (rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
|
||||
singleLine = true;
|
||||
}
|
||||
else {
|
||||
multiLine = true;
|
||||
}
|
||||
}
|
||||
|
||||
const expression = visitNode(body, visitor, isExpression);
|
||||
const returnStatement = createReturn(expression, /*location*/ body);
|
||||
setEmitFlags(returnStatement, EmitFlags.NoTokenSourceMaps | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTrailingComments);
|
||||
statements.push(returnStatement);
|
||||
|
||||
// To align with the source map emit for the old emitter, we set a custom
|
||||
// source map location for the close brace.
|
||||
closeBraceLocation = body;
|
||||
}
|
||||
|
||||
const lexicalEnvironment = endLexicalEnvironment();
|
||||
addRange(statements, lexicalEnvironment);
|
||||
|
||||
// If we added any final generated statements, this must be a multi-line block
|
||||
if (!multiLine && lexicalEnvironment && lexicalEnvironment.length) {
|
||||
multiLine = true;
|
||||
}
|
||||
|
||||
const block = createBlock(createNodeArray(statements, statementsLocation), node.body, multiLine);
|
||||
if (!multiLine && singleLine) {
|
||||
setEmitFlags(block, EmitFlags.SingleLine);
|
||||
}
|
||||
|
||||
if (closeBraceLocation) {
|
||||
setTokenSourceMapRange(block, SyntaxKind.CloseBraceToken, closeBraceLocation);
|
||||
}
|
||||
|
||||
setOriginalNode(block, node.body);
|
||||
return block;
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits an ExpressionStatement that contains a destructuring assignment.
|
||||
*
|
||||
@@ -1926,171 +1600,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function convertForOfToFor(node: ForOfStatement, convertedLoopBodyStatements: Statement[]): ForStatement {
|
||||
// The following ES6 code:
|
||||
//
|
||||
// for (let v of expr) { }
|
||||
//
|
||||
// should be emitted as
|
||||
//
|
||||
// for (var _i = 0, _a = expr; _i < _a.length; _i++) {
|
||||
// var v = _a[_i];
|
||||
// }
|
||||
//
|
||||
// where _a and _i are temps emitted to capture the RHS and the counter,
|
||||
// respectively.
|
||||
// When the left hand side is an expression instead of a let declaration,
|
||||
// the "let v" is not emitted.
|
||||
// When the left hand side is a let/const, the v is renamed if there is
|
||||
// another v in scope.
|
||||
// Note that all assignments to the LHS are emitted in the body, including
|
||||
// all destructuring.
|
||||
// Note also that because an extra statement is needed to assign to the LHS,
|
||||
// for-of bodies are always emitted as blocks.
|
||||
|
||||
const expression = visitNode(node.expression, visitor, isExpression);
|
||||
const initializer = node.initializer;
|
||||
const statements: Statement[] = [];
|
||||
|
||||
// In the case where the user wrote an identifier as the RHS, like this:
|
||||
//
|
||||
// for (let v of arr) { }
|
||||
//
|
||||
// we don't want to emit a temporary variable for the RHS, just use it directly.
|
||||
const counter = createLoopVariable();
|
||||
const rhsReference = expression.kind === SyntaxKind.Identifier
|
||||
? createUniqueName((<Identifier>expression).text)
|
||||
: createTempVariable(/*recordTempVariable*/ undefined);
|
||||
|
||||
// Initialize LHS
|
||||
// var v = _a[_i];
|
||||
if (isVariableDeclarationList(initializer)) {
|
||||
if (initializer.flags & NodeFlags.BlockScoped) {
|
||||
enableSubstitutionsForBlockScopedBindings();
|
||||
}
|
||||
|
||||
const firstOriginalDeclaration = firstOrUndefined(initializer.declarations);
|
||||
if (firstOriginalDeclaration && isBindingPattern(firstOriginalDeclaration.name)) {
|
||||
// This works whether the declaration is a var, let, or const.
|
||||
// It will use rhsIterationValue _a[_i] as the initializer.
|
||||
const declarations = flattenVariableDestructuring(
|
||||
firstOriginalDeclaration,
|
||||
createElementAccess(rhsReference, counter),
|
||||
visitor
|
||||
);
|
||||
|
||||
const declarationList = createVariableDeclarationList(declarations, /*location*/ initializer);
|
||||
setOriginalNode(declarationList, initializer);
|
||||
|
||||
// Adjust the source map range for the first declaration to align with the old
|
||||
// emitter.
|
||||
const firstDeclaration = declarations[0];
|
||||
const lastDeclaration = lastOrUndefined(declarations);
|
||||
setSourceMapRange(declarationList, createRange(firstDeclaration.pos, lastDeclaration.end));
|
||||
|
||||
statements.push(
|
||||
createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
declarationList
|
||||
)
|
||||
);
|
||||
}
|
||||
else {
|
||||
// The following call does not include the initializer, so we have
|
||||
// to emit it separately.
|
||||
statements.push(
|
||||
createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
setOriginalNode(
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(
|
||||
firstOriginalDeclaration ? firstOriginalDeclaration.name : createTempVariable(/*recordTempVariable*/ undefined),
|
||||
/*type*/ undefined,
|
||||
createElementAccess(rhsReference, counter)
|
||||
)
|
||||
], /*location*/ moveRangePos(initializer, -1)),
|
||||
initializer
|
||||
),
|
||||
/*location*/ moveRangeEnd(initializer, -1)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Initializer is an expression. Emit the expression in the body, so that it's
|
||||
// evaluated on every iteration.
|
||||
const assignment = createAssignment(initializer, createElementAccess(rhsReference, counter));
|
||||
if (isDestructuringAssignment(assignment)) {
|
||||
// This is a destructuring pattern, so we flatten the destructuring instead.
|
||||
statements.push(
|
||||
createStatement(
|
||||
flattenDestructuringAssignment(
|
||||
context,
|
||||
assignment,
|
||||
/*needsValue*/ false,
|
||||
hoistVariableDeclaration,
|
||||
visitor
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
else {
|
||||
// Currently there is not way to check that assignment is binary expression of destructing assignment
|
||||
// so we have to cast never type to binaryExpression
|
||||
(<BinaryExpression>assignment).end = initializer.end;
|
||||
statements.push(createStatement(assignment, /*location*/ moveRangeEnd(initializer, -1)));
|
||||
}
|
||||
}
|
||||
|
||||
let bodyLocation: TextRange;
|
||||
let statementsLocation: TextRange;
|
||||
if (convertedLoopBodyStatements) {
|
||||
addRange(statements, convertedLoopBodyStatements);
|
||||
}
|
||||
else {
|
||||
const statement = visitNode(node.statement, visitor, isStatement);
|
||||
if (isBlock(statement)) {
|
||||
addRange(statements, statement.statements);
|
||||
bodyLocation = statement;
|
||||
statementsLocation = statement.statements;
|
||||
}
|
||||
else {
|
||||
statements.push(statement);
|
||||
}
|
||||
}
|
||||
|
||||
// The old emitter does not emit source maps for the expression
|
||||
setEmitFlags(expression, EmitFlags.NoSourceMap | getEmitFlags(expression));
|
||||
|
||||
// The old emitter does not emit source maps for the block.
|
||||
// We add the location to preserve comments.
|
||||
const body = createBlock(
|
||||
createNodeArray(statements, /*location*/ statementsLocation),
|
||||
/*location*/ bodyLocation
|
||||
);
|
||||
|
||||
setEmitFlags(body, EmitFlags.NoSourceMap | EmitFlags.NoTokenSourceMaps);
|
||||
|
||||
const forStatement = createFor(
|
||||
setEmitFlags(
|
||||
createVariableDeclarationList([
|
||||
createVariableDeclaration(counter, /*type*/ undefined, createLiteral(0), /*location*/ moveRangePos(node.expression, -1)),
|
||||
createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression)
|
||||
], /*location*/ node.expression),
|
||||
EmitFlags.NoHoisting
|
||||
),
|
||||
createLessThan(
|
||||
counter,
|
||||
createPropertyAccess(rhsReference, "length"),
|
||||
/*location*/ node.expression
|
||||
),
|
||||
createPostfixIncrement(counter, /*location*/ node.expression),
|
||||
body,
|
||||
/*location*/ node
|
||||
);
|
||||
|
||||
// Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
|
||||
setEmitFlags(forStatement, EmitFlags.NoTokenTrailingSourceMaps);
|
||||
return forStatement;
|
||||
return <ForStatement>convertForOf(node, convertedLoopBodyStatements, visitor, enableSubstitutionsForBlockScopedBindings, context, /*transformRest*/ false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2751,7 +2261,7 @@ namespace ts {
|
||||
setEmitFlags(thisArg, EmitFlags.NoSubstitution);
|
||||
}
|
||||
let resultingCall: CallExpression | BinaryExpression;
|
||||
if (node.transformFlags & TransformFlags.ContainsSpreadElementExpression) {
|
||||
if (node.transformFlags & TransformFlags.ContainsSpreadExpression) {
|
||||
// [source]
|
||||
// f(...a, b)
|
||||
// x.m(...a, b)
|
||||
@@ -2813,7 +2323,7 @@ namespace ts {
|
||||
*/
|
||||
function visitNewExpression(node: NewExpression): LeftHandSideExpression {
|
||||
// We are here because we contain a SpreadElementExpression.
|
||||
Debug.assert((node.transformFlags & TransformFlags.ContainsSpreadElementExpression) !== 0);
|
||||
Debug.assert((node.transformFlags & TransformFlags.ContainsSpreadExpression) !== 0);
|
||||
|
||||
// [source]
|
||||
// new C(...a)
|
||||
@@ -2834,7 +2344,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms an array of Expression nodes that contains a SpreadElementExpression.
|
||||
* Transforms an array of Expression nodes that contains a SpreadExpression.
|
||||
*
|
||||
* @param elements The array of Expression nodes.
|
||||
* @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
|
||||
@@ -2851,14 +2361,14 @@ namespace ts {
|
||||
// expressions into an array literal.
|
||||
const numElements = elements.length;
|
||||
const segments = flatten(
|
||||
spanMap(elements, partitionSpreadElement, (partition, visitPartition, _start, end) =>
|
||||
spanMap(elements, partitionSpread, (partition, visitPartition, _start, end) =>
|
||||
visitPartition(partition, multiLine, hasTrailingComma && end === numElements)
|
||||
)
|
||||
);
|
||||
|
||||
if (segments.length === 1) {
|
||||
const firstElement = elements[0];
|
||||
return needsUniqueCopy && isSpreadElementExpression(firstElement) && firstElement.expression.kind !== SyntaxKind.ArrayLiteralExpression
|
||||
return needsUniqueCopy && isSpreadExpression(firstElement) && firstElement.expression.kind !== SyntaxKind.ArrayLiteralExpression
|
||||
? createArraySlice(segments[0])
|
||||
: segments[0];
|
||||
}
|
||||
@@ -2867,17 +2377,17 @@ namespace ts {
|
||||
return createArrayConcat(segments.shift(), segments);
|
||||
}
|
||||
|
||||
function partitionSpreadElement(node: Expression) {
|
||||
return isSpreadElementExpression(node)
|
||||
? visitSpanOfSpreadElements
|
||||
: visitSpanOfNonSpreadElements;
|
||||
function partitionSpread(node: Expression) {
|
||||
return isSpreadExpression(node)
|
||||
? visitSpanOfSpreads
|
||||
: visitSpanOfNonSpreads;
|
||||
}
|
||||
|
||||
function visitSpanOfSpreadElements(chunk: Expression[]): VisitResult<Expression> {
|
||||
return map(chunk, visitExpressionOfSpreadElement);
|
||||
function visitSpanOfSpreads(chunk: Expression[]): VisitResult<Expression> {
|
||||
return map(chunk, visitExpressionOfSpread);
|
||||
}
|
||||
|
||||
function visitSpanOfNonSpreadElements(chunk: Expression[], multiLine: boolean, hasTrailingComma: boolean): VisitResult<Expression> {
|
||||
function visitSpanOfNonSpreads(chunk: Expression[], multiLine: boolean, hasTrailingComma: boolean): VisitResult<Expression> {
|
||||
return createArrayLiteral(
|
||||
visitNodes(createNodeArray(chunk, /*location*/ undefined, hasTrailingComma), visitor, isExpression),
|
||||
/*location*/ undefined,
|
||||
@@ -2886,11 +2396,11 @@ namespace ts {
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms the expression of a SpreadElementExpression node.
|
||||
* Transforms the expression of a SpreadExpression node.
|
||||
*
|
||||
* @param node A SpreadElementExpression node.
|
||||
* @param node A SpreadExpression node.
|
||||
*/
|
||||
function visitExpressionOfSpreadElement(node: SpreadElementExpression) {
|
||||
function visitExpressionOfSpread(node: SpreadElement) {
|
||||
return visitNode(node.expression, visitor, isExpression);
|
||||
}
|
||||
|
||||
@@ -3076,7 +2586,7 @@ namespace ts {
|
||||
const statements: Statement[] = [];
|
||||
startLexicalEnvironment();
|
||||
addRange(statements, prologue);
|
||||
addCaptureThisForNodeIfNeeded(statements, node);
|
||||
addCaptureThisForNodeIfNeeded(statements, node, enableSubstitutionsForCapturedThis);
|
||||
addRange(statements, visitNodes(createNodeArray(remaining), visitor, isStatement));
|
||||
addRange(statements, endLexicalEnvironment());
|
||||
const clone = getMutableClone(node);
|
||||
@@ -3266,11 +2776,11 @@ namespace ts {
|
||||
}
|
||||
|
||||
const callArgument = singleOrUndefined((<CallExpression>statementExpression).arguments);
|
||||
if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== SyntaxKind.SpreadElementExpression) {
|
||||
if (!callArgument || !nodeIsSynthesized(callArgument) || callArgument.kind !== SyntaxKind.SpreadElement) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const expression = (<SpreadElementExpression>callArgument).expression;
|
||||
const expression = (<SpreadElement>callArgument).expression;
|
||||
return isIdentifier(expression) && expression === parameter.name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,6 @@ namespace ts {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.BinaryExpression:
|
||||
return visitBinaryExpression(<BinaryExpression>node);
|
||||
|
||||
default:
|
||||
Debug.failBadSyntaxKind(node);
|
||||
return visitEachChild(node, visitor, context);
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
/// <reference path="../factory.ts" />
|
||||
/// <reference path="../visitor.ts" />
|
||||
|
||||
/*@internal*/
|
||||
namespace ts {
|
||||
export function transformESNext(context: TransformationContext) {
|
||||
const {
|
||||
hoistVariableDeclaration,
|
||||
} = context;
|
||||
let currentSourceFile: SourceFile;
|
||||
return transformSourceFile;
|
||||
|
||||
function transformSourceFile(node: SourceFile) {
|
||||
currentSourceFile = node;
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
function visitor(node: Node): VisitResult<Node> {
|
||||
if (node.transformFlags & TransformFlags.ESNext) {
|
||||
return visitorWorker(node);
|
||||
}
|
||||
else if (node.transformFlags & TransformFlags.ContainsESNext) {
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
else {
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
function visitorWorker(node: Node): VisitResult<Node> {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.ObjectLiteralExpression:
|
||||
return visitObjectLiteralExpression(node as ObjectLiteralExpression);
|
||||
case SyntaxKind.BinaryExpression:
|
||||
return visitBinaryExpression(node as BinaryExpression);
|
||||
case SyntaxKind.VariableDeclaration:
|
||||
return visitVariableDeclaration(node as VariableDeclaration);
|
||||
case SyntaxKind.ForOfStatement:
|
||||
return visitForOfStatement(node as ForOfStatement);
|
||||
case SyntaxKind.ObjectBindingPattern:
|
||||
case SyntaxKind.ArrayBindingPattern:
|
||||
return node;
|
||||
case SyntaxKind.FunctionDeclaration:
|
||||
return visitFunctionDeclaration(node as FunctionDeclaration);
|
||||
case SyntaxKind.FunctionExpression:
|
||||
return visitFunctionExpression(node as FunctionExpression);
|
||||
case SyntaxKind.ArrowFunction:
|
||||
return visitArrowFunction(node as ArrowFunction);
|
||||
case SyntaxKind.Parameter:
|
||||
return visitParameter(node as ParameterDeclaration);
|
||||
default:
|
||||
Debug.failBadSyntaxKind(node);
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
}
|
||||
|
||||
function chunkObjectLiteralElements(elements: ObjectLiteralElement[]): Expression[] {
|
||||
let chunkObject: (ShorthandPropertyAssignment | PropertyAssignment)[];
|
||||
const objects: Expression[] = [];
|
||||
for (const e of elements) {
|
||||
if (e.kind === SyntaxKind.SpreadAssignment) {
|
||||
if (chunkObject) {
|
||||
objects.push(createObjectLiteral(chunkObject));
|
||||
chunkObject = undefined;
|
||||
}
|
||||
const target = (e as SpreadAssignment).expression;
|
||||
objects.push(visitNode(target, visitor, isExpression));
|
||||
}
|
||||
else {
|
||||
if (!chunkObject) {
|
||||
chunkObject = [];
|
||||
}
|
||||
if (e.kind === SyntaxKind.PropertyAssignment) {
|
||||
const p = e as PropertyAssignment;
|
||||
chunkObject.push(createPropertyAssignment(p.name, visitNode(p.initializer, visitor, isExpression)));
|
||||
}
|
||||
else {
|
||||
chunkObject.push(e as ShorthandPropertyAssignment);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (chunkObject) {
|
||||
objects.push(createObjectLiteral(chunkObject));
|
||||
}
|
||||
|
||||
return objects;
|
||||
}
|
||||
|
||||
function visitObjectLiteralExpression(node: ObjectLiteralExpression): Expression {
|
||||
// spread elements emit like so:
|
||||
// non-spread elements are chunked together into object literals, and then all are passed to __assign:
|
||||
// { a, ...o, b } => __assign({a}, o, {b});
|
||||
// If the first element is a spread element, then the first argument to __assign is {}:
|
||||
// { ...o, a, b, ...o2 } => __assign({}, o, {a, b}, o2)
|
||||
const objects = chunkObjectLiteralElements(node.properties);
|
||||
if (objects.length && objects[0].kind !== SyntaxKind.ObjectLiteralExpression) {
|
||||
objects.unshift(createObjectLiteral());
|
||||
}
|
||||
return createCall(createIdentifier("__assign"), undefined, objects);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a BinaryExpression that contains a destructuring assignment.
|
||||
*
|
||||
* @param node A BinaryExpression node.
|
||||
*/
|
||||
function visitBinaryExpression(node: BinaryExpression): Expression {
|
||||
if (isDestructuringAssignment(node) && node.left.transformFlags & TransformFlags.AssertESNext) {
|
||||
return flattenDestructuringAssignment(context, node, /*needsDestructuringValue*/ true, hoistVariableDeclaration, visitor, /*transformRest*/ true);
|
||||
}
|
||||
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a VariableDeclaration node with a binding pattern.
|
||||
*
|
||||
* @param node A VariableDeclaration node.
|
||||
*/
|
||||
function visitVariableDeclaration(node: VariableDeclaration): VisitResult<VariableDeclaration> {
|
||||
// If we are here it is because the name contains a binding pattern with a rest somewhere in it.
|
||||
if (isBindingPattern(node.name) && node.name.transformFlags & TransformFlags.AssertESNext) {
|
||||
const result = flattenVariableDestructuring(node, /*value*/ undefined, visitor, /*recordTempVariable*/ undefined, /*transformRest*/ true);
|
||||
return result;
|
||||
}
|
||||
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
|
||||
*
|
||||
* @param node A ForOfStatement.
|
||||
*/
|
||||
function visitForOfStatement(node: ForOfStatement): VisitResult<Statement> {
|
||||
// The following ESNext code:
|
||||
//
|
||||
// for (let { x, y, ...rest } of expr) { }
|
||||
//
|
||||
// should be emitted as
|
||||
//
|
||||
// for (var _a of expr) {
|
||||
// let { x, y } = _a, rest = __rest(_a, ["x", "y"]);
|
||||
// }
|
||||
//
|
||||
// where _a is a temp emitted to capture the RHS.
|
||||
// When the left hand side is an expression instead of a let declaration,
|
||||
// the `let` before the `{ x, y }` is not emitted.
|
||||
// When the left hand side is a let/const, the v is renamed if there is
|
||||
// another v in scope.
|
||||
// Note that all assignments to the LHS are emitted in the body, including
|
||||
// all destructuring.
|
||||
// Note also that because an extra statement is needed to assign to the LHS,
|
||||
// for-of bodies are always emitted as blocks.
|
||||
|
||||
// for (<init> of <expression>) <statement>
|
||||
// where <init> is [let] variabledeclarationlist | expression
|
||||
const initializer = node.initializer;
|
||||
if (!isRestBindingPattern(initializer) && !isRestAssignment(initializer)) {
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
return convertForOf(node, undefined, visitor, noop, context, /*transformRest*/ true);
|
||||
}
|
||||
|
||||
function isRestBindingPattern(initializer: ForInitializer) {
|
||||
if (isVariableDeclarationList(initializer)) {
|
||||
const declaration = firstOrUndefined(initializer.declarations);
|
||||
return declaration && declaration.name &&
|
||||
declaration.name.kind === SyntaxKind.ObjectBindingPattern &&
|
||||
!!(declaration.name.transformFlags & TransformFlags.ContainsSpreadExpression);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isRestAssignment(initializer: ForInitializer) {
|
||||
return initializer.kind === SyntaxKind.ObjectLiteralExpression &&
|
||||
initializer.transformFlags & TransformFlags.ContainsSpreadExpression;
|
||||
}
|
||||
|
||||
function visitParameter(node: ParameterDeclaration): ParameterDeclaration {
|
||||
if (isObjectRestParameter(node)) {
|
||||
// Binding patterns are converted into a generated name and are
|
||||
// evaluated inside the function body.
|
||||
return setOriginalNode(
|
||||
createParameter(
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
/*dotDotDotToken*/ undefined,
|
||||
getGeneratedNameForNode(node),
|
||||
/*questionToken*/ undefined,
|
||||
/*type*/ undefined,
|
||||
node.initializer,
|
||||
/*location*/ node
|
||||
),
|
||||
/*original*/ node
|
||||
);
|
||||
}
|
||||
else {
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
function isObjectRestParameter(node: ParameterDeclaration) {
|
||||
return node.name &&
|
||||
node.name.kind === SyntaxKind.ObjectBindingPattern &&
|
||||
!!(node.name.transformFlags & TransformFlags.ContainsSpreadExpression);
|
||||
}
|
||||
|
||||
function visitFunctionDeclaration(node: FunctionDeclaration): FunctionDeclaration {
|
||||
const hasRest = forEach(node.parameters, isObjectRestParameter);
|
||||
const body = hasRest ?
|
||||
transformFunctionBody(node, visitor, currentSourceFile, context, noop, /*convertObjectRest*/ true) as Block :
|
||||
visitEachChild(node.body, visitor, context);
|
||||
|
||||
return setOriginalNode(
|
||||
createFunctionDeclaration(
|
||||
/*decorators*/ undefined,
|
||||
node.modifiers,
|
||||
node.asteriskToken,
|
||||
node.name,
|
||||
/*typeParameters*/ undefined,
|
||||
visitNodes(node.parameters, visitor, isParameter),
|
||||
/*type*/ undefined,
|
||||
body,
|
||||
/*location*/ node
|
||||
),
|
||||
/*original*/ node);
|
||||
}
|
||||
|
||||
function visitArrowFunction(node: ArrowFunction) {
|
||||
const hasRest = forEach(node.parameters, isObjectRestParameter);
|
||||
const body = hasRest ?
|
||||
transformFunctionBody(node, visitor, currentSourceFile, context, noop, /*convertObjectRest*/ true) as Block :
|
||||
visitEachChild(node.body, visitor, context);
|
||||
const func = setOriginalNode(
|
||||
createArrowFunction(
|
||||
/*modifiers*/ undefined,
|
||||
/*typeParameters*/ undefined,
|
||||
visitNodes(node.parameters, visitor, isParameter),
|
||||
/*type*/ undefined,
|
||||
node.equalsGreaterThanToken,
|
||||
body,
|
||||
/*location*/ node
|
||||
),
|
||||
/*original*/ node
|
||||
);
|
||||
setEmitFlags(func, EmitFlags.CapturesThis);
|
||||
return func;
|
||||
}
|
||||
|
||||
function visitFunctionExpression(node: FunctionExpression): Expression {
|
||||
const hasRest = forEach(node.parameters, isObjectRestParameter);
|
||||
const body = hasRest ?
|
||||
transformFunctionBody(node, visitor, currentSourceFile, context, noop, /*convertObjectRest*/ true) as Block :
|
||||
visitEachChild(node.body, visitor, context);
|
||||
return setOriginalNode(
|
||||
createFunctionExpression(
|
||||
/*modifiers*/ undefined,
|
||||
node.asteriskToken,
|
||||
name,
|
||||
/*typeParameters*/ undefined,
|
||||
visitNodes(node.parameters, visitor, isParameter),
|
||||
/*type*/ undefined,
|
||||
body,
|
||||
/*location*/ node
|
||||
),
|
||||
/*original*/ node
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1474,7 +1474,7 @@ namespace ts {
|
||||
if (isAssignmentExpression(node)) {
|
||||
return hasExportedReferenceInDestructuringTarget(node.left);
|
||||
}
|
||||
else if (isSpreadElementExpression(node)) {
|
||||
else if (isSpreadExpression(node)) {
|
||||
return hasExportedReferenceInDestructuringTarget(node.expression);
|
||||
}
|
||||
else if (isObjectLiteralExpression(node)) {
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"visitor.ts",
|
||||
"transformers/ts.ts",
|
||||
"transformers/jsx.ts",
|
||||
"transformers/esnext.ts",
|
||||
"transformers/es2017.ts",
|
||||
"transformers/es2016.ts",
|
||||
"transformers/es2015.ts",
|
||||
|
||||
+61
-43
@@ -246,7 +246,7 @@ namespace ts {
|
||||
ConditionalExpression,
|
||||
TemplateExpression,
|
||||
YieldExpression,
|
||||
SpreadElementExpression,
|
||||
SpreadElement,
|
||||
ClassExpression,
|
||||
OmittedExpression,
|
||||
ExpressionWithTypeArguments,
|
||||
@@ -320,6 +320,7 @@ namespace ts {
|
||||
// Property assignments
|
||||
PropertyAssignment,
|
||||
ShorthandPropertyAssignment,
|
||||
SpreadAssignment,
|
||||
|
||||
// Enum
|
||||
EnumMember,
|
||||
@@ -418,20 +419,21 @@ namespace ts {
|
||||
HasDecorators = 1 << 11, // If the file has decorators (initialized by binding)
|
||||
HasParamDecorators = 1 << 12, // If the file has parameter decorators (initialized by binding)
|
||||
HasAsyncFunctions = 1 << 13, // If the file has async functions (initialized by binding)
|
||||
HasJsxSpreadAttributes = 1 << 14, // If the file as JSX spread attributes (initialized by binding)
|
||||
DisallowInContext = 1 << 15, // If node was parsed in a context where 'in-expressions' are not allowed
|
||||
YieldContext = 1 << 16, // If node was parsed in the 'yield' context created when parsing a generator
|
||||
DecoratorContext = 1 << 17, // If node was parsed as part of a decorator
|
||||
AwaitContext = 1 << 18, // If node was parsed in the 'await' context created when parsing an async function
|
||||
ThisNodeHasError = 1 << 19, // If the parser encountered an error when parsing the code that created this node
|
||||
JavaScriptFile = 1 << 20, // If node was parsed in a JavaScript
|
||||
ThisNodeOrAnySubNodesHasError = 1 << 21, // If this node or any of its children had an error
|
||||
HasAggregatedChildData = 1 << 22, // If we've computed data from children and cached it in this node
|
||||
HasSpreadAttribute = 1 << 14, // If the file as JSX spread attributes (initialized by binding)
|
||||
HasRestAttribute = 1 << 15, // If the file has object destructure elements
|
||||
DisallowInContext = 1 << 16, // If node was parsed in a context where 'in-expressions' are not allowed
|
||||
YieldContext = 1 << 17, // If node was parsed in the 'yield' context created when parsing a generator
|
||||
DecoratorContext = 1 << 18, // If node was parsed as part of a decorator
|
||||
AwaitContext = 1 << 19, // If node was parsed in the 'await' context created when parsing an async function
|
||||
ThisNodeHasError = 1 << 20, // If the parser encountered an error when parsing the code that created this node
|
||||
JavaScriptFile = 1 << 21, // If node was parsed in a JavaScript
|
||||
ThisNodeOrAnySubNodesHasError = 1 << 22, // If this node or any of its children had an error
|
||||
HasAggregatedChildData = 1 << 23, // If we've computed data from children and cached it in this node
|
||||
|
||||
BlockScoped = Let | Const,
|
||||
|
||||
ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn,
|
||||
EmitHelperFlags = HasClassExtends | HasDecorators | HasParamDecorators | HasAsyncFunctions | HasJsxSpreadAttributes,
|
||||
EmitHelperFlags = HasClassExtends | HasDecorators | HasParamDecorators | HasAsyncFunctions | HasSpreadAttribute,
|
||||
ReachabilityAndEmitFlags = ReachabilityCheckFlags | EmitHelperFlags,
|
||||
|
||||
// Parsing context flags
|
||||
@@ -454,7 +456,6 @@ namespace ts {
|
||||
Async = 1 << 8, // Property/Method/Function
|
||||
Default = 1 << 9, // Function/Class (export default declaration)
|
||||
Const = 1 << 11, // Variable declaration
|
||||
|
||||
HasComputedFlags = 1 << 29, // Modifier flags have been computed
|
||||
|
||||
AccessibilityModifier = Public | Private | Protected,
|
||||
@@ -649,7 +650,7 @@ namespace ts {
|
||||
export interface BindingElement extends Declaration {
|
||||
kind: SyntaxKind.BindingElement;
|
||||
propertyName?: PropertyName; // Binding property name (in object binding pattern)
|
||||
dotDotDotToken?: DotDotDotToken; // Present on rest binding element
|
||||
dotDotDotToken?: DotDotDotToken; // Present on rest element (in object binding pattern)
|
||||
name: BindingName; // Declared binding element name
|
||||
initializer?: Expression; // Optional initializer
|
||||
}
|
||||
@@ -675,7 +676,7 @@ namespace ts {
|
||||
name?: PropertyName;
|
||||
}
|
||||
|
||||
export type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration;
|
||||
export type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration | SpreadAssignment;
|
||||
|
||||
export interface PropertyAssignment extends ObjectLiteralElement {
|
||||
kind: SyntaxKind.PropertyAssignment;
|
||||
@@ -694,6 +695,11 @@ namespace ts {
|
||||
objectAssignmentInitializer?: Expression;
|
||||
}
|
||||
|
||||
export interface SpreadAssignment extends ObjectLiteralElement {
|
||||
kind: SyntaxKind.SpreadAssignment;
|
||||
expression: Expression;
|
||||
}
|
||||
|
||||
// SyntaxKind.VariableDeclaration
|
||||
// SyntaxKind.Parameter
|
||||
// SyntaxKind.BindingElement
|
||||
@@ -1279,8 +1285,8 @@ namespace ts {
|
||||
multiLine?: boolean;
|
||||
}
|
||||
|
||||
export interface SpreadElementExpression extends Expression {
|
||||
kind: SyntaxKind.SpreadElementExpression;
|
||||
export interface SpreadElement extends Expression {
|
||||
kind: SyntaxKind.SpreadElement;
|
||||
expression: Expression;
|
||||
}
|
||||
|
||||
@@ -2381,6 +2387,12 @@ namespace ts {
|
||||
CannotBeNamed
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export const enum SyntheticSymbolKind {
|
||||
UnionOrIntersection,
|
||||
Spread
|
||||
}
|
||||
|
||||
export const enum TypePredicateKind {
|
||||
This,
|
||||
Identifier
|
||||
@@ -2592,7 +2604,9 @@ namespace ts {
|
||||
instantiations?: Map<Type>; // Instantiations of generic type alias (undefined if non-generic)
|
||||
mapper?: TypeMapper; // Type mapper for instantiation alias
|
||||
referenced?: boolean; // True if alias symbol has been referenced as a value
|
||||
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
|
||||
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
|
||||
leftSpread?: Symbol; // Left source for synthetic spread property
|
||||
rightSpread?: Symbol; // Right source for synthetic spread property
|
||||
hasNonUniformType?: boolean; // True if constituents have non-uniform types
|
||||
isPartial?: boolean; // True if syntheric property of union type occurs in some but not all constituents
|
||||
isDiscriminantProperty?: boolean; // True if discriminant synthetic property
|
||||
@@ -3163,7 +3177,8 @@ namespace ts {
|
||||
ES2015 = 2,
|
||||
ES2016 = 3,
|
||||
ES2017 = 4,
|
||||
Latest = ES2017,
|
||||
ESNext = 5,
|
||||
Latest = ESNext,
|
||||
}
|
||||
|
||||
export const enum LanguageVariant {
|
||||
@@ -3478,32 +3493,34 @@ namespace ts {
|
||||
ContainsTypeScript = 1 << 1,
|
||||
Jsx = 1 << 2,
|
||||
ContainsJsx = 1 << 3,
|
||||
ES2017 = 1 << 4,
|
||||
ContainsES2017 = 1 << 5,
|
||||
ES2016 = 1 << 6,
|
||||
ContainsES2016 = 1 << 7,
|
||||
ES2015 = 1 << 8,
|
||||
ContainsES2015 = 1 << 9,
|
||||
Generator = 1 << 10,
|
||||
ContainsGenerator = 1 << 11,
|
||||
DestructuringAssignment = 1 << 12,
|
||||
ContainsDestructuringAssignment = 1 << 13,
|
||||
ESNext = 1 << 4,
|
||||
ContainsESNext = 1 << 5,
|
||||
ES2017 = 1 << 6,
|
||||
ContainsES2017 = 1 << 7,
|
||||
ES2016 = 1 << 8,
|
||||
ContainsES2016 = 1 << 9,
|
||||
ES2015 = 1 << 10,
|
||||
ContainsES2015 = 1 << 11,
|
||||
Generator = 1 << 12,
|
||||
ContainsGenerator = 1 << 13,
|
||||
DestructuringAssignment = 1 << 14,
|
||||
ContainsDestructuringAssignment = 1 << 15,
|
||||
|
||||
// Markers
|
||||
// - Flags used to indicate that a subtree contains a specific transformation.
|
||||
ContainsDecorators = 1 << 14,
|
||||
ContainsPropertyInitializer = 1 << 15,
|
||||
ContainsLexicalThis = 1 << 16,
|
||||
ContainsCapturedLexicalThis = 1 << 17,
|
||||
ContainsLexicalThisInComputedPropertyName = 1 << 18,
|
||||
ContainsDefaultValueAssignments = 1 << 19,
|
||||
ContainsParameterPropertyAssignments = 1 << 20,
|
||||
ContainsSpreadElementExpression = 1 << 21,
|
||||
ContainsComputedPropertyName = 1 << 22,
|
||||
ContainsBlockScopedBinding = 1 << 23,
|
||||
ContainsBindingPattern = 1 << 24,
|
||||
ContainsYield = 1 << 25,
|
||||
ContainsHoistedDeclarationOrCompletion = 1 << 26,
|
||||
ContainsDecorators = 1 << 16,
|
||||
ContainsPropertyInitializer = 1 << 17,
|
||||
ContainsLexicalThis = 1 << 18,
|
||||
ContainsCapturedLexicalThis = 1 << 19,
|
||||
ContainsLexicalThisInComputedPropertyName = 1 << 20,
|
||||
ContainsDefaultValueAssignments = 1 << 21,
|
||||
ContainsParameterPropertyAssignments = 1 << 22,
|
||||
ContainsSpreadExpression = 1 << 23,
|
||||
ContainsComputedPropertyName = 1 << 24,
|
||||
ContainsBlockScopedBinding = 1 << 25,
|
||||
ContainsBindingPattern = 1 << 26,
|
||||
ContainsYield = 1 << 27,
|
||||
ContainsHoistedDeclarationOrCompletion = 1 << 28,
|
||||
|
||||
HasComputedFlags = 1 << 29, // Transform flags have been computed.
|
||||
|
||||
@@ -3511,6 +3528,7 @@ namespace ts {
|
||||
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
|
||||
AssertTypeScript = TypeScript | ContainsTypeScript,
|
||||
AssertJsx = Jsx | ContainsJsx,
|
||||
AssertESNext = ESNext | ContainsESNext,
|
||||
AssertES2017 = ES2017 | ContainsES2017,
|
||||
AssertES2016 = ES2016 | ContainsES2016,
|
||||
AssertES2015 = ES2015 | ContainsES2015,
|
||||
@@ -3520,7 +3538,7 @@ namespace ts {
|
||||
// Scope Exclusions
|
||||
// - Bitmasks that exclude flags from propagating out of a specific context
|
||||
// into the subtree flags of their container.
|
||||
NodeExcludes = TypeScript | Jsx | ES2017 | ES2016 | ES2015 | DestructuringAssignment | Generator | HasComputedFlags,
|
||||
NodeExcludes = TypeScript | Jsx | ESNext | ES2017 | ES2016 | ES2015 | DestructuringAssignment | Generator | HasComputedFlags,
|
||||
ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
|
||||
FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
|
||||
ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
|
||||
@@ -3529,7 +3547,7 @@ namespace ts {
|
||||
ModuleExcludes = NodeExcludes | ContainsDecorators | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion,
|
||||
TypeExcludes = ~ContainsTypeScript,
|
||||
ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName,
|
||||
ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpreadElementExpression,
|
||||
ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpreadExpression,
|
||||
VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern,
|
||||
ParameterExcludes = NodeExcludes | ContainsBindingPattern,
|
||||
|
||||
|
||||
@@ -485,6 +485,22 @@ namespace ts {
|
||||
return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
|
||||
}
|
||||
|
||||
export function getTextOfPropertyName(name: PropertyName): string {
|
||||
switch (name.kind) {
|
||||
case SyntaxKind.Identifier:
|
||||
return (<Identifier>name).text;
|
||||
case SyntaxKind.StringLiteral:
|
||||
case SyntaxKind.NumericLiteral:
|
||||
return (<LiteralExpression>name).text;
|
||||
case SyntaxKind.ComputedPropertyName:
|
||||
if (isStringOrNumericLiteral((<ComputedPropertyName>name).expression.kind)) {
|
||||
return (<LiteralExpression>(<ComputedPropertyName>name).expression).text;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function entityNameToString(name: EntityNameOrEntityNameExpression): string {
|
||||
switch (name.kind) {
|
||||
case SyntaxKind.Identifier:
|
||||
@@ -1179,7 +1195,7 @@ namespace ts {
|
||||
case SyntaxKind.PostfixUnaryExpression:
|
||||
case SyntaxKind.BinaryExpression:
|
||||
case SyntaxKind.ConditionalExpression:
|
||||
case SyntaxKind.SpreadElementExpression:
|
||||
case SyntaxKind.SpreadElement:
|
||||
case SyntaxKind.TemplateExpression:
|
||||
case SyntaxKind.NoSubstitutionTemplateLiteral:
|
||||
case SyntaxKind.OmittedExpression:
|
||||
@@ -1641,7 +1657,7 @@ namespace ts {
|
||||
return (<ForInStatement | ForOfStatement>parent).initializer === node ? AssignmentKind.Definite : AssignmentKind.None;
|
||||
case SyntaxKind.ParenthesizedExpression:
|
||||
case SyntaxKind.ArrayLiteralExpression:
|
||||
case SyntaxKind.SpreadElementExpression:
|
||||
case SyntaxKind.SpreadElement:
|
||||
node = parent;
|
||||
break;
|
||||
case SyntaxKind.ShorthandPropertyAssignment:
|
||||
@@ -2226,7 +2242,7 @@ namespace ts {
|
||||
case SyntaxKind.YieldExpression:
|
||||
return 2;
|
||||
|
||||
case SyntaxKind.SpreadElementExpression:
|
||||
case SyntaxKind.SpreadElement:
|
||||
return 1;
|
||||
|
||||
default:
|
||||
@@ -3862,6 +3878,7 @@ namespace ts {
|
||||
const kind = node.kind;
|
||||
return kind === SyntaxKind.PropertyAssignment
|
||||
|| kind === SyntaxKind.ShorthandPropertyAssignment
|
||||
|| kind === SyntaxKind.SpreadAssignment
|
||||
|| kind === SyntaxKind.MethodDeclaration
|
||||
|| kind === SyntaxKind.GetAccessor
|
||||
|| kind === SyntaxKind.SetAccessor
|
||||
@@ -3949,8 +3966,8 @@ namespace ts {
|
||||
|| kind === SyntaxKind.NoSubstitutionTemplateLiteral;
|
||||
}
|
||||
|
||||
export function isSpreadElementExpression(node: Node): node is SpreadElementExpression {
|
||||
return node.kind === SyntaxKind.SpreadElementExpression;
|
||||
export function isSpreadExpression(node: Node): node is SpreadElement {
|
||||
return node.kind === SyntaxKind.SpreadElement;
|
||||
}
|
||||
|
||||
export function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments {
|
||||
@@ -4008,7 +4025,7 @@ namespace ts {
|
||||
|| kind === SyntaxKind.YieldExpression
|
||||
|| kind === SyntaxKind.ArrowFunction
|
||||
|| kind === SyntaxKind.BinaryExpression
|
||||
|| kind === SyntaxKind.SpreadElementExpression
|
||||
|| kind === SyntaxKind.SpreadElement
|
||||
|| kind === SyntaxKind.AsExpression
|
||||
|| kind === SyntaxKind.OmittedExpression
|
||||
|| isUnaryExpressionKind(kind);
|
||||
@@ -4310,6 +4327,7 @@ namespace ts {
|
||||
namespace ts {
|
||||
export function getDefaultLibFileName(options: CompilerOptions): string {
|
||||
switch (options.target) {
|
||||
case ScriptTarget.ESNext:
|
||||
case ScriptTarget.ES2017:
|
||||
return "lib.es2017.d.ts";
|
||||
case ScriptTarget.ES2016:
|
||||
|
||||
+14
-6
@@ -267,9 +267,9 @@ namespace ts {
|
||||
case SyntaxKind.VoidExpression:
|
||||
case SyntaxKind.AwaitExpression:
|
||||
case SyntaxKind.YieldExpression:
|
||||
case SyntaxKind.SpreadElementExpression:
|
||||
case SyntaxKind.SpreadElement:
|
||||
case SyntaxKind.NonNullExpression:
|
||||
result = reduceNode((<ParenthesizedExpression | DeleteExpression | TypeOfExpression | VoidExpression | AwaitExpression | YieldExpression | SpreadElementExpression | NonNullExpression>node).expression, f, result);
|
||||
result = reduceNode((<ParenthesizedExpression | DeleteExpression | TypeOfExpression | VoidExpression | AwaitExpression | YieldExpression | SpreadElement | NonNullExpression>node).expression, f, result);
|
||||
break;
|
||||
|
||||
case SyntaxKind.PrefixUnaryExpression:
|
||||
@@ -510,6 +510,10 @@ namespace ts {
|
||||
result = reduceNode((<ShorthandPropertyAssignment>node).objectAssignmentInitializer, f, result);
|
||||
break;
|
||||
|
||||
case SyntaxKind.SpreadAssignment:
|
||||
result = reduceNode((node as SpreadAssignment).expression, f, result);
|
||||
break;
|
||||
|
||||
// Top-level nodes
|
||||
case SyntaxKind.SourceFile:
|
||||
result = reduceLeft((<SourceFile>node).statements, f, result);
|
||||
@@ -872,9 +876,9 @@ namespace ts {
|
||||
return updateYield(<YieldExpression>node,
|
||||
visitNode((<YieldExpression>node).expression, visitor, isExpression));
|
||||
|
||||
case SyntaxKind.SpreadElementExpression:
|
||||
return updateSpread(<SpreadElementExpression>node,
|
||||
visitNode((<SpreadElementExpression>node).expression, visitor, isExpression));
|
||||
case SyntaxKind.SpreadElement:
|
||||
return updateSpread(<SpreadElement>node,
|
||||
visitNode((<SpreadElement>node).expression, visitor, isExpression));
|
||||
|
||||
case SyntaxKind.ClassExpression:
|
||||
return updateClassExpression(<ClassExpression>node,
|
||||
@@ -1127,7 +1131,11 @@ namespace ts {
|
||||
visitNode((<ShorthandPropertyAssignment>node).name, visitor, isIdentifier),
|
||||
visitNode((<ShorthandPropertyAssignment>node).objectAssignmentInitializer, visitor, isExpression));
|
||||
|
||||
// Top-level nodes
|
||||
case SyntaxKind.SpreadAssignment:
|
||||
return updateSpreadAssignment(node as SpreadAssignment,
|
||||
visitNode((node as SpreadAssignment).expression, visitor, isExpression));
|
||||
|
||||
// Top-level nodes
|
||||
case SyntaxKind.SourceFile:
|
||||
context.startLexicalEnvironment();
|
||||
return updateSourceFileNode(<SourceFile>node,
|
||||
|
||||
Reference in New Issue
Block a user