Merge branch 'streamlineDestructuring' into emitHelper

This commit is contained in:
Ron Buckton
2016-11-15 18:13:52 -08:00
46 changed files with 3070 additions and 2622 deletions
+99 -51
View File
@@ -234,8 +234,8 @@ namespace ts {
if (node.name.kind === SyntaxKind.ComputedPropertyName) {
const nameExpression = (<ComputedPropertyName>node.name).expression;
// treat computed property names where expression is string/numeric literal as just string/numeric literal
if (isStringOrNumericLiteral(nameExpression.kind)) {
return (<LiteralExpression>nameExpression).text;
if (isStringOrNumericLiteral(nameExpression)) {
return nameExpression.text;
}
Debug.assert(isWellKnownSymbolSyntactically(nameExpression));
@@ -570,6 +570,31 @@ namespace ts {
}
}
function bindEach(nodes: NodeArray<Node>) {
if (nodes === undefined) {
return;
}
if (skipTransformFlagAggregation) {
forEach(nodes, bind);
}
else {
const savedSubtreeTransformFlags = subtreeTransformFlags;
subtreeTransformFlags = TransformFlags.None;
let nodeArrayFlags = TransformFlags.None;
for (const node of nodes) {
bind(node);
nodeArrayFlags |= node.transformFlags & ~TransformFlags.HasComputedFlags;
}
nodes.transformFlags = nodeArrayFlags | TransformFlags.HasComputedFlags;
subtreeTransformFlags |= savedSubtreeTransformFlags;
}
}
function bindEachChild(node: Node) {
forEachChild(node, bind, bindEach);
}
function bindChildrenWorker(node: Node): void {
// Binding of JsDocComment should be done before the current block scope container changes.
// because the scope of JsDocComment should not be affected by whether the current node is a
@@ -578,7 +603,7 @@ namespace ts {
forEach(node.jsDocComments, bind);
}
if (checkUnreachable(node)) {
forEachChild(node, bind);
bindEachChild(node);
return;
}
switch (node.kind) {
@@ -643,7 +668,7 @@ namespace ts {
bindCallExpressionFlow(<CallExpression>node);
break;
default:
forEachChild(node, bind);
bindEachChild(node);
break;
}
}
@@ -976,7 +1001,7 @@ namespace ts {
return undefined;
}
function bindbreakOrContinueFlow(node: BreakOrContinueStatement, breakTarget: FlowLabel, continueTarget: FlowLabel) {
function bindBreakOrContinueFlow(node: BreakOrContinueStatement, breakTarget: FlowLabel, continueTarget: FlowLabel) {
const flowLabel = node.kind === SyntaxKind.BreakStatement ? breakTarget : continueTarget;
if (flowLabel) {
addAntecedent(flowLabel, currentFlow);
@@ -990,11 +1015,11 @@ namespace ts {
const activeLabel = findActiveLabel(node.label.text);
if (activeLabel) {
activeLabel.referenced = true;
bindbreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
}
}
else {
bindbreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
}
}
@@ -1062,6 +1087,8 @@ namespace ts {
}
function bindCaseBlock(node: CaseBlock): void {
const savedSubtreeTransformFlags = subtreeTransformFlags;
subtreeTransformFlags = 0;
const clauses = node.clauses;
let fallthroughFlow = unreachableFlow;
for (let i = 0; i < clauses.length; i++) {
@@ -1081,6 +1108,8 @@ namespace ts {
errorOnFirstToken(clause, Diagnostics.Fallthrough_case_in_switch);
}
}
clauses.transformFlags = subtreeTransformFlags | TransformFlags.HasComputedFlags;
subtreeTransformFlags |= savedSubtreeTransformFlags;
}
function bindCaseClause(node: CaseClause): void {
@@ -1088,7 +1117,7 @@ namespace ts {
currentFlow = preSwitchCaseFlow;
bind(node.expression);
currentFlow = saveCurrentFlow;
forEach(node.statements, bind);
bindEach(node.statements);
}
function pushActiveLabel(name: string, breakTarget: FlowLabel, continueTarget: FlowLabel): ActiveLabel {
@@ -1180,12 +1209,12 @@ namespace ts {
const saveTrueTarget = currentTrueTarget;
currentTrueTarget = currentFalseTarget;
currentFalseTarget = saveTrueTarget;
forEachChild(node, bind);
bindEachChild(node);
currentFalseTarget = currentTrueTarget;
currentTrueTarget = saveTrueTarget;
}
else {
forEachChild(node, bind);
bindEachChild(node);
if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) {
bindAssignmentTargetFlow(node.operand);
}
@@ -1193,7 +1222,7 @@ namespace ts {
}
function bindPostfixUnaryExpressionFlow(node: PostfixUnaryExpression) {
forEachChild(node, bind);
bindEachChild(node);
if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) {
bindAssignmentTargetFlow(node.operand);
}
@@ -1212,7 +1241,7 @@ namespace ts {
}
}
else {
forEachChild(node, bind);
bindEachChild(node);
if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) {
bindAssignmentTargetFlow(node.left);
if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) {
@@ -1226,7 +1255,7 @@ namespace ts {
}
function bindDeleteExpressionFlow(node: DeleteExpression) {
forEachChild(node, bind);
bindEachChild(node);
if (node.expression.kind === SyntaxKind.PropertyAccessExpression) {
bindAssignmentTargetFlow(node.expression);
}
@@ -1251,7 +1280,7 @@ namespace ts {
function bindInitializedVariableFlow(node: VariableDeclaration | ArrayBindingElement) {
const name = !isOmittedExpression(node) ? node.name : undefined;
if (isBindingPattern(name)) {
for (const child of name.elements) {
for (const child of <ArrayBindingElement[]>name.elements) {
bindInitializedVariableFlow(child);
}
}
@@ -1261,7 +1290,7 @@ namespace ts {
}
function bindVariableDeclarationFlow(node: VariableDeclaration) {
forEachChild(node, bind);
bindEachChild(node);
if (node.initializer || node.parent.parent.kind === SyntaxKind.ForInStatement || node.parent.parent.kind === SyntaxKind.ForOfStatement) {
bindInitializedVariableFlow(node);
}
@@ -1276,12 +1305,12 @@ namespace ts {
expr = (<ParenthesizedExpression>expr).expression;
}
if (expr.kind === SyntaxKind.FunctionExpression || expr.kind === SyntaxKind.ArrowFunction) {
forEach(node.typeArguments, bind);
forEach(node.arguments, bind);
bindEach(node.typeArguments);
bindEach(node.arguments);
bind(node.expression);
}
else {
forEachChild(node, bind);
bindEachChild(node);
}
if (node.expression.kind === SyntaxKind.PropertyAccessExpression) {
const propertyAccess = <PropertyAccessExpression>node.expression;
@@ -2517,7 +2546,7 @@ namespace ts {
transformFlags |= TransformFlags.AssertTypeScript;
}
if (subtreeFlags & TransformFlags.ContainsSpreadExpression
if (subtreeFlags & TransformFlags.ContainsSpread
|| isSuperOrSuperProperty(expression, expressionKind)) {
// If the this node contains a SpreadExpression, or is a super call, then it is an ES6
// node.
@@ -2548,7 +2577,7 @@ namespace ts {
if (node.typeArguments) {
transformFlags |= TransformFlags.AssertTypeScript;
}
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
if (subtreeFlags & TransformFlags.ContainsSpread) {
// If the this node contains a SpreadElementExpression then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES2015;
@@ -2557,7 +2586,6 @@ namespace ts {
return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes;
}
function computeBinaryExpression(node: BinaryExpression, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const operatorTokenKind = node.operatorToken.kind;
@@ -2604,7 +2632,7 @@ namespace ts {
}
// parameters with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
@@ -2726,7 +2754,7 @@ namespace ts {
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
return transformFlags & ~TransformFlags.CatchClauseExcludes;
}
function computeExpressionWithTypeArguments(node: ExpressionWithTypeArguments, subtreeFlags: TransformFlags) {
@@ -2753,6 +2781,11 @@ namespace ts {
transformFlags |= TransformFlags.AssertTypeScript;
}
// function declarations with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.ConstructorExcludes;
}
@@ -2771,6 +2804,11 @@ namespace ts {
transformFlags |= TransformFlags.AssertTypeScript;
}
// function declarations with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
// An async method declaration is ES2017 syntax.
if (hasModifier(node, ModifierFlags.Async)) {
transformFlags |= TransformFlags.AssertES2017;
@@ -2797,6 +2835,11 @@ namespace ts {
transformFlags |= TransformFlags.AssertTypeScript;
}
// function declarations with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.MethodOrAccessorExcludes;
}
@@ -2842,7 +2885,7 @@ namespace ts {
}
// function declarations with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
@@ -2884,7 +2927,7 @@ namespace ts {
}
// function expressions with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
@@ -2927,7 +2970,7 @@ namespace ts {
}
// arrow functions with object rest destructuring are ES Next syntax
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
@@ -2957,16 +3000,11 @@ namespace ts {
function computeVariableDeclaration(node: VariableDeclaration, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
const nameKind = node.name.kind;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
// 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;
// A VariableDeclaration containing ObjectRest is ESNext syntax
if (subtreeFlags & TransformFlags.ContainsObjectRest) {
transformFlags |= TransformFlags.AssertESNext;
}
// Type annotations are TypeScript syntax.
@@ -3182,16 +3220,12 @@ namespace ts {
break;
case SyntaxKind.SpreadElement:
case SyntaxKind.SpreadAssignment:
// This node is ES6 or ES next syntax, but is handled by a containing node.
transformFlags |= TransformFlags.ContainsSpreadExpression;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsSpread;
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.SpreadAssignment:
transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectSpread;
break;
case SyntaxKind.SuperKeyword:
// This node is ES6 syntax.
@@ -3204,13 +3238,22 @@ namespace ts {
break;
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
// These nodes are ES2015 or ES Next syntax.
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsBindingPattern;
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
if (subtreeFlags & TransformFlags.ContainsRest) {
transformFlags |= TransformFlags.AssertESNext | TransformFlags.ContainsObjectRest;
}
else {
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
excludeFlags = TransformFlags.BindingPatternExcludes;
break;
case SyntaxKind.ArrayBindingPattern:
transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern;
excludeFlags = TransformFlags.BindingPatternExcludes;
break;
case SyntaxKind.BindingElement:
transformFlags |= TransformFlags.AssertES2015;
if ((<BindingElement>node).dotDotDotToken) {
transformFlags |= TransformFlags.ContainsRest;
}
break;
@@ -3233,7 +3276,7 @@ namespace ts {
transformFlags |= TransformFlags.ContainsLexicalThis;
}
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
if (subtreeFlags & TransformFlags.ContainsObjectSpread) {
// If an ObjectLiteralExpression contains a spread element, then it
// is an ES next node.
transformFlags |= TransformFlags.AssertESNext;
@@ -3244,7 +3287,7 @@ namespace ts {
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.NewExpression:
excludeFlags = TransformFlags.ArrayLiteralOrCallOrNewExcludes;
if (subtreeFlags & TransformFlags.ContainsSpreadExpression) {
if (subtreeFlags & TransformFlags.ContainsSpread) {
// If the this node contains a SpreadExpression, then it is an ES6
// node.
transformFlags |= TransformFlags.AssertES2015;
@@ -3337,6 +3380,11 @@ namespace ts {
return TransformFlags.TypeExcludes;
case SyntaxKind.ObjectLiteralExpression:
return TransformFlags.ObjectLiteralExcludes;
case SyntaxKind.CatchClause:
return TransformFlags.CatchClauseExcludes;
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
return TransformFlags.BindingPatternExcludes;
default:
return TransformFlags.NodeExcludes;
}
+4 -6
View File
@@ -3030,7 +3030,7 @@ namespace ts {
}
function isComputedNonLiteralName(name: PropertyName): boolean {
return name.kind === SyntaxKind.ComputedPropertyName && !isStringOrNumericLiteral((<ComputedPropertyName>name).expression.kind);
return name.kind === SyntaxKind.ComputedPropertyName && !isStringOrNumericLiteral((<ComputedPropertyName>name).expression);
}
function getRestType(source: Type, properties: PropertyName[], symbol: Symbol): Type {
@@ -3081,7 +3081,7 @@ namespace ts {
}
const literalMembers: PropertyName[] = [];
for (const element of pattern.elements) {
if (element.kind !== SyntaxKind.OmittedExpression && !(element as BindingElement).dotDotDotToken) {
if (!(element as BindingElement).dotDotDotToken) {
literalMembers.push(element.propertyName || element.name as Identifier);
}
}
@@ -8927,7 +8927,7 @@ namespace ts {
return type;
}
function getTypeOfDestructuredProperty(type: Type, name: Identifier | LiteralExpression | ComputedPropertyName) {
function getTypeOfDestructuredProperty(type: Type, name: PropertyName) {
const text = getTextOfPropertyName(name);
return getTypeOfPropertyOfType(type, text) ||
isNumericLiteralName(text) && getIndexTypeOfType(type, IndexKind.Number) ||
@@ -14221,9 +14221,7 @@ namespace ts {
}
}
else if (property.kind === SyntaxKind.SpreadAssignment) {
if (property.expression.kind !== SyntaxKind.Identifier) {
error(property.expression, Diagnostics.An_object_rest_element_must_be_an_identifier);
}
checkReferenceExpression(property.expression, Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access);
}
else {
error(property, Diagnostics.Property_assignment_expected);
+7
View File
@@ -826,6 +826,13 @@ namespace ts {
}
}
export function appendProperty<T>(map: Map<T>, key: string | number, value: T): Map<T> {
if (key === undefined || value === undefined) return map;
if (map === undefined) map = createMap<T>();
map[key] = value;
return map;
}
export function assign<T1 extends MapLike<{}>, T2, T3>(t: T1, arg1: T2, arg2: T3): T1 & T2 & T3;
export function assign<T1 extends MapLike<{}>, T2>(t: T1, arg1: T2): T1 & T2;
export function assign<T1 extends MapLike<{}>>(t: T1, ...args: any[]): any;
+1 -1
View File
@@ -1991,7 +1991,7 @@
"category": "Error",
"code": 2700
},
"An object rest element must be an identifier.": {
"The target of an object rest assignment must be a variable or a property access.": {
"category": "Error",
"code": 2701
},
+278 -516
View File
@@ -102,12 +102,12 @@ namespace ts {
// Literals
export function createLiteral(textSource: StringLiteral | Identifier, location?: TextRange): StringLiteral;
export function createLiteral(textSource: StringLiteral | NumericLiteral | Identifier, location?: TextRange): StringLiteral;
export function createLiteral(value: string, location?: TextRange): StringLiteral;
export function createLiteral(value: number, location?: TextRange): NumericLiteral;
export function createLiteral(value: boolean, location?: TextRange): BooleanLiteral;
export function createLiteral(value: string | number | boolean, location?: TextRange): PrimaryExpression;
export function createLiteral(value: string | number | boolean | StringLiteral | Identifier, location?: TextRange): PrimaryExpression {
export function createLiteral(value: string | number | boolean | StringLiteral | NumericLiteral | Identifier, location?: TextRange): PrimaryExpression {
if (typeof value === "number") {
const node = <NumericLiteral>createNode(SyntaxKind.NumericLiteral, location, /*flags*/ undefined);
node.text = value.toString();
@@ -238,9 +238,9 @@ namespace ts {
return node;
}
export function updateParameter(node: ParameterDeclaration, decorators: Decorator[], modifiers: Modifier[], name: BindingName, type: TypeNode, initializer: Expression) {
if (node.decorators !== decorators || node.modifiers !== modifiers || node.name !== name || node.type !== type || node.initializer !== initializer) {
return updateNode(createParameter(decorators, modifiers, node.dotDotDotToken, name, node.questionToken, type, initializer, /*location*/ node, /*flags*/ node.flags), node);
export function updateParameter(node: ParameterDeclaration, decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: DotDotDotToken, name: BindingName, type: TypeNode, initializer: Expression) {
if (node.decorators !== decorators || node.modifiers !== modifiers || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.type !== type || node.initializer !== initializer) {
return updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, node.questionToken, type, initializer, /*location*/ node, /*flags*/ node.flags), node);
}
return node;
@@ -378,9 +378,9 @@ namespace ts {
return node;
}
export function updateBindingElement(node: BindingElement, propertyName: PropertyName, name: BindingName, initializer: Expression) {
if (node.propertyName !== propertyName || node.name !== name || node.initializer !== initializer) {
return updateNode(createBindingElement(propertyName, node.dotDotDotToken, name, initializer, node), node);
export function updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken, propertyName: PropertyName, name: BindingName, initializer: Expression) {
if (node.propertyName !== propertyName || node.dotDotDotToken !== dotDotDotToken || node.name !== name || node.initializer !== initializer) {
return updateNode(createBindingElement(propertyName, dotDotDotToken, name, initializer, node), node);
}
return node;
}
@@ -646,13 +646,25 @@ namespace ts {
return node;
}
export function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression, location?: TextRange) {
const node = <ConditionalExpression>createNode(SyntaxKind.ConditionalExpression, location);
node.condition = condition;
node.questionToken = questionToken;
node.whenTrue = whenTrue;
node.colonToken = colonToken;
node.whenFalse = whenFalse;
export function createConditional(condition: Expression, whenTrue: Expression, whenFalse: Expression, location?: TextRange): ConditionalExpression;
export function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression, location?: TextRange): ConditionalExpression;
export function createConditional(condition: Expression, questionTokenOrWhenTrue: QuestionToken | Expression, whenTrueOrWhenFalse: Expression, colonTokenOrLocation?: ColonToken | TextRange, whenFalse?: Expression, location?: TextRange) {
const node = <ConditionalExpression>createNode(SyntaxKind.ConditionalExpression, whenFalse ? location : colonTokenOrLocation);
node.condition = parenthesizeForConditionalHead(condition);
if (whenFalse) {
// second overload
node.questionToken = <QuestionToken>questionTokenOrWhenTrue;
node.whenTrue = whenTrueOrWhenFalse;
node.colonToken = <ColonToken>colonTokenOrLocation;
node.whenFalse = whenFalse;
}
else {
// first overload
node.questionToken = createToken(SyntaxKind.QuestionToken);
node.whenTrue = <Expression>questionTokenOrWhenTrue;
node.colonToken = createToken(SyntaxKind.ColonToken);
node.whenFalse = whenTrueOrWhenFalse;
}
return node;
}
@@ -1405,7 +1417,7 @@ namespace ts {
return node;
}
export function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression) {
export function updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression) {
if (node.name !== name || node.objectAssignmentInitializer !== objectAssignmentInitializer) {
return updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer, node), node);
}
@@ -1419,7 +1431,7 @@ namespace ts {
return node;
}
// Top-level nodes
// Top-level nodes
export function updateSourceFileNode(node: SourceFile, statements: Statement[]) {
if (node.statements !== statements) {
@@ -1540,6 +1552,8 @@ namespace ts {
return <Expression>createBinary(left, SyntaxKind.LessThanToken, right, location);
}
export function createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression, location?: TextRange): DestructuringAssignment;
export function createAssignment(left: Expression, right: Expression, location?: TextRange): BinaryExpression;
export function createAssignment(left: Expression, right: Expression, location?: TextRange) {
return createBinary(left, SyntaxKind.EqualsToken, right, location);
}
@@ -1580,6 +1594,14 @@ namespace ts {
return createVoid(createLiteral(0));
}
export type TypeOfTag = "undefined" | "number" | "boolean" | "string" | "symbol" | "object" | "function";
export function createTypeCheck(value: Expression, tag: TypeOfTag) {
return tag === "undefined"
? createStrictEquality(value, createVoidZero())
: createStrictEquality(createTypeOf(value), createLiteral(tag));
}
export function createMemberAccessForPropertyName(target: Expression, memberName: PropertyName, location?: TextRange): MemberExpression {
if (isComputedPropertyName(memberName)) {
return createElementAccess(target, memberName.expression, location);
@@ -1736,6 +1758,8 @@ namespace ts {
return setEmitFlags(createIdentifier(name), EmitFlags.HelperName | EmitFlags.AdviseOnEmitNode);
}
// Utilities
export interface CallBinding {
target: LeftHandSideExpression;
thisArg: Expression;
@@ -2081,10 +2105,8 @@ namespace ts {
return qualifiedName;
}
// Utilities
export function convertToFunctionBody(node: ConciseBody) {
return isBlock(node) ? node : createBlock([createReturn(node, /*location*/ node)], /*location*/ node);
export function convertToFunctionBody(node: ConciseBody, multiLine?: boolean) {
return isBlock(node) ? node : createBlock([createReturn(node, /*location*/ node)], /*location*/ node, multiLine);
}
function isUseStrictPrologue(node: ExpressionStatement): boolean {
@@ -2349,6 +2371,16 @@ namespace ts {
return SyntaxKind.Unknown;
}
export function parenthesizeForConditionalHead(condition: Expression) {
const conditionalPrecedence = getOperatorPrecedence(SyntaxKind.ConditionalExpression, SyntaxKind.QuestionToken);
const emittedCondition = skipPartiallyEmittedExpressions(condition);
const conditionPrecedence = getExpressionPrecedence(emittedCondition);
if (compareValues(conditionPrecedence, conditionalPrecedence) === Comparison.LessThan) {
return createParen(condition);
}
return condition;
}
/**
* Wraps an expression in parentheses if it is needed in order to use the expression
* as the expression of a NewExpression node.
@@ -2965,542 +2997,272 @@ namespace ts {
}
/**
* Transforms the body of a function-like node.
*
* @param node A function-like node.
* Gets the initializer of an BindingOrAssignmentElement.
*/
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.resumeLexicalEnvironment();
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);
export function getInitializerOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): Expression | undefined {
if (isDeclarationBindingElement(bindingElement)) {
// `1` in `let { a = 1 } = ...`
// `1` in `let { a: b = 1 } = ...`
// `1` in `let { a: {b} = 1 } = ...`
// `1` in `let { a: [b] = 1 } = ...`
// `1` in `let [a = 1] = ...`
// `1` in `let [{a} = 1] = ...`
// `1` in `let [[a] = 1] = ...`
return bindingElement.initializer;
}
addCaptureThisForNodeIfNeeded(statements, node, enableSubstitutionsForCapturedThis);
addDefaultValueAssignmentsIfNeeded(context, 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 (isPropertyAssignment(bindingElement)) {
// `1` in `({ a: b = 1 } = ...)`
// `1` in `({ a: {b} = 1 } = ...)`
// `1` in `({ a: [b] = 1 } = ...)`
return isAssignmentExpression(bindingElement.initializer, /*excludeCompoundAssignment*/ true)
? bindingElement.initializer.right
: undefined;
}
if (isBlock(body)) {
statementsLocation = body.statements;
addRange(statements, visitNodes(body.statements, visitor, isStatement, statementOffset));
if (isShorthandPropertyAssignment(bindingElement)) {
// `1` in `({ a = 1 } = ...)`
return bindingElement.objectAssignmentInitializer;
}
// If the original body was a multi-line block, this must be a multi-line block.
if (!multiLine && body.multiLine) {
multiLine = true;
if (isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
// `1` in `[a = 1] = ...`
// `1` in `[{a} = 1] = ...`
// `1` in `[[a] = 1] = ...`
return bindingElement.right;
}
if (isSpreadExpression(bindingElement)) {
// Recovery consistent with existing emit.
return getInitializerOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.expression);
}
}
/**
* Gets the name of an BindingOrAssignmentElement.
*/
export function getTargetOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementTarget {
if (isDeclarationBindingElement(bindingElement)) {
// `a` in `let { a } = ...`
// `a` in `let { a = 1 } = ...`
// `b` in `let { a: b } = ...`
// `b` in `let { a: b = 1 } = ...`
// `a` in `let { ...a } = ...`
// `{b}` in `let { a: {b} } = ...`
// `{b}` in `let { a: {b} = 1 } = ...`
// `[b]` in `let { a: [b] } = ...`
// `[b]` in `let { a: [b] = 1 } = ...`
// `a` in `let [a] = ...`
// `a` in `let [a = 1] = ...`
// `a` in `let [...a] = ...`
// `{a}` in `let [{a}] = ...`
// `{a}` in `let [{a} = 1] = ...`
// `[a]` in `let [[a]] = ...`
// `[a]` in `let [[a] = 1] = ...`
return <ObjectBindingPattern | ArrayBindingPattern | Identifier>bindingElement.name;
}
if (isObjectLiteralElementLike(bindingElement)) {
switch (bindingElement.kind) {
case SyntaxKind.PropertyAssignment:
// `b` in `({ a: b } = ...)`
// `b` in `({ a: b = 1 } = ...)`
// `{b}` in `({ a: {b} } = ...)`
// `{b}` in `({ a: {b} = 1 } = ...)`
// `[b]` in `({ a: [b] } = ...)`
// `[b]` in `({ a: [b] = 1 } = ...)`
// `b.c` in `({ a: b.c } = ...)`
// `b.c` in `({ a: b.c = 1 } = ...)`
// `b[0]` in `({ a: b[0] } = ...)`
// `b[0]` in `({ a: b[0] = 1 } = ...)`
return getTargetOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.initializer);
case SyntaxKind.ShorthandPropertyAssignment:
// `a` in `({ a } = ...)`
// `a` in `({ a = 1 } = ...)`
return bindingElement.name;
case SyntaxKind.SpreadAssignment:
// `a` in `({ ...a } = ...)`
return getTargetOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.expression);
}
// no target
return undefined;
}
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);
if (isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
// `a` in `[a = 1] = ...`
// `{a}` in `[{a} = 1] = ...`
// `[a]` in `[[a] = 1] = ...`
// `a.b` in `[a.b = 1] = ...`
// `a[0]` in `[a[0] = 1] = ...`
return getTargetOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.left);
}
const equalsGreaterThanToken = (<ArrowFunction>node).equalsGreaterThanToken;
if (!nodeIsSynthesized(equalsGreaterThanToken) && !nodeIsSynthesized(body)) {
if (rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
singleLine = true;
if (isSpreadExpression(bindingElement)) {
// `a` in `[...a] = ...`
return getTargetOfBindingOrAssignmentElement(<BindingOrAssignmentElement>bindingElement.expression);
}
// `a` in `[a] = ...`
// `{a}` in `[{a}] = ...`
// `[a]` in `[[a]] = ...`
// `a.b` in `[a.b] = ...`
// `a[0]` in `[a[0]] = ...`
return bindingElement;
}
/**
* Determines whether an BindingOrAssignmentElement is a rest element.
*/
export function getRestIndicatorOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement): BindingOrAssignmentElementRestIndicator {
switch (bindingElement.kind) {
case SyntaxKind.Parameter:
case SyntaxKind.BindingElement:
// `...` in `let [...a] = ...`
return (<ParameterDeclaration | BindingElement>bindingElement).dotDotDotToken;
case SyntaxKind.SpreadElement:
case SyntaxKind.SpreadAssignment:
// `...` in `[...a] = ...`
return <SpreadElement | SpreadAssignment>bindingElement;
}
return undefined;
}
/**
* Gets the property name of a BindingOrAssignmentElement
*/
export function getPropertyNameOfBindingOrAssignmentElement(bindingElement: BindingOrAssignmentElement) {
switch (bindingElement.kind) {
case SyntaxKind.BindingElement:
// `a` in `let { a: b } = ...`
// `[a]` in `let { [a]: b } = ...`
// `"a"` in `let { "a": b } = ...`
// `1` in `let { 1: b } = ...`
if ((<BindingElement>bindingElement).propertyName) {
const propertyName = (<BindingElement>bindingElement).propertyName;
return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
? propertyName.expression
: propertyName;
}
else {
multiLine = true;
break;
case SyntaxKind.PropertyAssignment:
// `a` in `({ a: b } = ...)`
// `[a]` in `({ [a]: b } = ...)`
// `"a"` in `({ "a": b } = ...)`
// `1` in `({ 1: b } = ...)`
if ((<PropertyAssignment>bindingElement).name) {
const propertyName = (<PropertyAssignment>bindingElement).name;
return isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
? propertyName.expression
: propertyName;
}
}
const expression = visitNode(body, visitor, isExpression);
const returnStatement = createReturn(expression, /*location*/ body);
setEmitFlags(returnStatement, EmitFlags.NoTokenSourceMaps | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTrailingComments);
statements.push(returnStatement);
break;
// To align with the source map emit for the old emitter, we set a custom
// source map location for the close brace.
closeBraceLocation = body;
case SyntaxKind.SpreadAssignment:
// `a` in `({ ...a } = ...)`
return (<SpreadAssignment>bindingElement).name;
}
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 target = getTargetOfBindingOrAssignmentElement(bindingElement);
if (target && isPropertyName(target)) {
return isComputedPropertyName(target) && isStringOrNumericLiteral(target.expression)
? target.expression
: target;
}
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;
Debug.fail("Invalid property name for binding element.");
}
/**
* 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.
* Gets the elements of a BindingOrAssignmentPattern
*/
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 getElementsOfBindingOrAssignmentPattern(name: BindingOrAssignmentPattern): BindingOrAssignmentElement[] {
switch (name.kind) {
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
case SyntaxKind.ArrayLiteralExpression:
// `a` in `{a}`
// `a` in `[a]`
return <BindingOrAssignmentElement[]>name.elements;
case SyntaxKind.ObjectLiteralExpression:
// `a` in `{a}`
return <BindingOrAssignmentElement[]>name.properties;
}
}
export function captureThisForNode(statements: Statement[], node: Node, initializer: Expression | undefined, enableSubstitutionsForCapturedThis?: () => void, originalStatement?: Statement): void {
if (enableSubstitutionsForCapturedThis) {
enableSubstitutionsForCapturedThis();
export function convertToArrayAssignmentElement(element: BindingOrAssignmentElement) {
if (isBindingElement(element)) {
if (element.dotDotDotToken) {
Debug.assertNode(element.name, isIdentifier);
return setOriginalNode(createSpread(<Identifier>element.name, element), element);
}
const expression = convertToAssignmentElementTarget(<ObjectBindingPattern | ArrayBindingPattern | Identifier>element.name);
return element.initializer ? setOriginalNode(createAssignment(expression, element.initializer, element), element) : expression;
}
const captureThisStatement = createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
"_this",
/*type*/ undefined,
initializer
)
]),
originalStatement
);
setEmitFlags(captureThisStatement, EmitFlags.NoComments | EmitFlags.CustomPrologue);
setSourceMapRange(captureThisStatement, node);
statements.push(captureThisStatement);
Debug.assertNode(element, isExpression);
return <Expression>element;
}
/**
* 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;
export function convertToObjectAssignmentElement(element: BindingOrAssignmentElement) {
if (isBindingElement(element)) {
if (element.dotDotDotToken) {
Debug.assertNode(element.name, isIdentifier);
return setOriginalNode(createSpreadAssignment(<Identifier>element.name, element), element);
}
if (element.propertyName) {
const expression = convertToAssignmentElementTarget(<ObjectBindingPattern | ArrayBindingPattern | Identifier>element.name);
return setOriginalNode(createPropertyAssignment(element.propertyName, element.initializer ? createAssignment(expression, element.initializer) : expression, element), element);
}
Debug.assertNode(element.name, isIdentifier);
return setOriginalNode(createShorthandPropertyAssignment(<Identifier>element.name, element.initializer, element), element);
}
Debug.assertNode(element, isObjectLiteralElementLike);
return <ObjectLiteralElementLike>element;
}
/**
* 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(context: TransformationContext,
statements: Statement[],
node: FunctionLikeDeclaration,
visitor: (node: Node) => VisitResult<Node>,
convertObjectRest: boolean): void {
if (!shouldAddDefaultValueAssignments(node)) {
return;
}
export function convertToAssignmentPattern(node: BindingOrAssignmentPattern): AssignmentPattern {
switch (node.kind) {
case SyntaxKind.ArrayBindingPattern:
case SyntaxKind.ArrayLiteralExpression:
return convertToArrayAssignmentPattern(node);
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(context, statements, parameter, name, initializer, visitor, convertObjectRest);
}
else if (initializer) {
addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer, visitor);
}
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ObjectLiteralExpression:
return convertToObjectAssignmentPattern(node);
}
}
/**
* 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(context: TransformationContext,
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(context, parameter, temp, visitor, convertObjectRest)
)
),
EmitFlags.CustomPrologue
)
);
}
else if (initializer) {
statements.push(
setEmitFlags(
createStatement(
createAssignment(
temp,
visitNode(initializer, visitor, isExpression)
)
),
EmitFlags.CustomPrologue
)
);
export function convertToObjectAssignmentPattern(node: ObjectBindingOrAssignmentPattern) {
if (isObjectBindingPattern(node)) {
return setOriginalNode(createObjectLiteral(map(node.elements, convertToObjectAssignmentElement), node), node);
}
Debug.assertNode(node, isObjectLiteralExpression);
return <ObjectLiteralExpression>node;
}
/**
* 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);
export function convertToArrayAssignmentPattern(node: ArrayBindingOrAssignmentPattern) {
if (isArrayBindingPattern(node)) {
return setOriginalNode(createArrayLiteral(map(node.elements, convertToArrayAssignmentElement), node), node);
}
Debug.assertNode(node, isArrayLiteralExpression);
return <ArrayLiteralExpression>node;
}
/**
* 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;
export function convertToAssignmentElementTarget(node: BindingOrAssignmentElementTarget): Expression {
if (isBindingPattern(node)) {
return convertToAssignmentPattern(node);
}
// `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(
context,
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;
Debug.assertNode(node, isExpression);
return <Expression>node;
}
export interface ExternalModuleInfo {
+2 -2
View File
@@ -1168,7 +1168,7 @@ namespace ts {
function parsePropertyNameWorker(allowComputedPropertyNames: boolean): PropertyName {
if (token() === SyntaxKind.StringLiteral || token() === SyntaxKind.NumericLiteral) {
return parseLiteralNode(/*internName*/ true);
return <StringLiteral | NumericLiteral>parseLiteralNode(/*internName*/ true);
}
if (allowComputedPropertyNames && token() === SyntaxKind.OpenBracketToken) {
return parseComputedPropertyName();
@@ -5514,7 +5514,7 @@ namespace ts {
node.flags |= NodeFlags.GlobalAugmentation;
}
else {
node.name = parseLiteralNode(/*internName*/ true);
node.name = <StringLiteral>parseLiteralNode(/*internName*/ true);
}
if (token() === SyntaxKind.OpenBraceToken) {
+14 -15
View File
@@ -236,20 +236,6 @@ namespace ts {
}
}
/** Suspends the current lexical environment, usually after visiting a parameter list. */
function suspendLexicalEnvironment(): void {
Debug.assert(!scopeModificationDisabled, "Cannot suspend a lexical environment during the print phase.");
Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
lexicalEnvironmentSuspended = true;
}
/** Resumes a suspended lexical environment, usually before visiting a function body. */
function resumeLexicalEnvironment(): void {
Debug.assert(!scopeModificationDisabled, "Cannot resume a lexical environment during the print phase.");
Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended suspended.");
lexicalEnvironmentSuspended = false;
}
/**
* Starts a new lexical environment. Any existing hoisted variable or function declarations
* are pushed onto a stack, and the related storage variables are reset.
@@ -269,6 +255,20 @@ namespace ts {
lexicalEnvironmentFunctionDeclarations = undefined;
}
/** Suspends the current lexical environment, usually after visiting a parameter list. */
function suspendLexicalEnvironment(): void {
Debug.assert(!scopeModificationDisabled, "Cannot suspend a lexical environment during the print phase.");
Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
lexicalEnvironmentSuspended = true;
}
/** Resumes a suspended lexical environment, usually before visiting a function body. */
function resumeLexicalEnvironment(): void {
Debug.assert(!scopeModificationDisabled, "Cannot resume a lexical environment during the print phase.");
Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended suspended.");
lexicalEnvironmentSuspended = false;
}
/**
* Ends a lexical environment. The previous set of hoisted declarations are restored and
* any hoisted declarations added in this environment are returned.
@@ -306,7 +306,6 @@ namespace ts {
lexicalEnvironmentVariableDeclarationsStack = [];
lexicalEnvironmentFunctionDeclarationsStack = [];
}
return statements;
}
File diff suppressed because it is too large Load Diff
+541 -40
View File
@@ -490,7 +490,7 @@ namespace ts {
const statements: Statement[] = [];
startLexicalEnvironment();
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor);
addCaptureThisForNodeIfNeeded(statements, node, enableSubstitutionsForCapturedThis);
addCaptureThisForNodeIfNeeded(statements, node);
addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset));
addRange(statements, endLexicalEnvironment());
return updateSourceFileNode(
@@ -876,7 +876,7 @@ namespace ts {
}
if (constructor) {
addDefaultValueAssignmentsIfNeeded(context, statements, constructor, visitor, /*convertObjectRest*/ false);
addDefaultValueAssignmentsIfNeeded(statements, constructor);
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
@@ -969,7 +969,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, enableSubstitutionsForCapturedThis);
addCaptureThisForNodeIfNeeded(statements, ctor);
}
return SuperCaptureResult.NoReplacement;
}
@@ -986,7 +986,7 @@ namespace ts {
// for something like property initializers.
// Create a captured '_this' variable and assume it will subsequently be used.
if (hasSynthesizedSuper) {
captureThisForNode(statements, ctor, createDefaultSuperCallOrThis(), enableSubstitutionsForCapturedThis);
captureThisForNode(statements, ctor, createDefaultSuperCallOrThis());
enableSubstitutionsForCapturedThis();
return SuperCaptureResult.ReplaceSuperCapture;
}
@@ -1044,7 +1044,7 @@ namespace ts {
}
// Perform the capture.
captureThisForNode(statements, ctor, superCallExpression, enableSubstitutionsForCapturedThis, firstStatement);
captureThisForNode(statements, ctor, superCallExpression, firstStatement);
// If we're actually replacing the original statement, we need to signal this to the caller.
if (superCallExpression) {
@@ -1113,6 +1113,245 @@ 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(
flattenDestructuringBinding(
parameter,
visitor,
context,
FlattenLevel.All,
temp
)
)
),
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(
createTypeCheck(getSynthesizedClone(name), "undefined"),
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.
@@ -1280,7 +1519,7 @@ namespace ts {
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node, visitor, currentSourceFile, context, enableSubstitutionsForCapturedThis),
transformFunctionBody(node),
node
);
setOriginalNode(func, node);
@@ -1302,7 +1541,7 @@ namespace ts {
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
node.transformFlags & TransformFlags.ES2015
? transformFunctionBody(node, visitor, currentSourceFile, context, enableSubstitutionsForCapturedThis)
? transformFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
}
@@ -1322,7 +1561,7 @@ namespace ts {
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
node.transformFlags & TransformFlags.ES2015
? transformFunctionBody(node, visitor, currentSourceFile, context, enableSubstitutionsForCapturedThis)
? transformFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
}
@@ -1348,7 +1587,7 @@ namespace ts {
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
saveStateAndInvoke(node, node => transformFunctionBody(node, visitor, currentSourceFile, context, enableSubstitutionsForCapturedThis)),
saveStateAndInvoke(node, transformFunctionBody),
location
),
/*original*/ node
@@ -1358,6 +1597,96 @@ 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;
resumeLexicalEnvironment();
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 = 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;
}
/**
* Visits an ExpressionStatement that contains a destructuring assignment.
*
@@ -1367,16 +1696,10 @@ namespace ts {
// If we are here it is most likely because our expression is a destructuring assignment.
switch (node.expression.kind) {
case SyntaxKind.ParenthesizedExpression:
return updateStatement(node,
visitParenthesizedExpression(<ParenthesizedExpression>node.expression, /*needsDestructuringValue*/ false)
);
return updateStatement(node, visitParenthesizedExpression(<ParenthesizedExpression>node.expression, /*needsDestructuringValue*/ false));
case SyntaxKind.BinaryExpression:
return updateStatement(node,
visitBinaryExpression(<BinaryExpression>node.expression, /*needsDestructuringValue*/ false)
);
return updateStatement(node, visitBinaryExpression(<BinaryExpression>node.expression, /*needsDestructuringValue*/ false));
}
return visitEachChild(node, visitor, context);
}
@@ -1389,22 +1712,14 @@ namespace ts {
*/
function visitParenthesizedExpression(node: ParenthesizedExpression, needsDestructuringValue: boolean): ParenthesizedExpression {
// If we are here it is most likely because our expression is a destructuring assignment.
if (needsDestructuringValue) {
if (!needsDestructuringValue) {
switch (node.expression.kind) {
case SyntaxKind.ParenthesizedExpression:
return createParen(
visitParenthesizedExpression(<ParenthesizedExpression>node.expression, /*needsDestructuringValue*/ true),
/*location*/ node
);
return updateParen(node, visitParenthesizedExpression(<ParenthesizedExpression>node.expression, /*needsDestructuringValue*/ false));
case SyntaxKind.BinaryExpression:
return createParen(
visitBinaryExpression(<BinaryExpression>node.expression, /*needsDestructuringValue*/ true),
/*location*/ node
);
return updateParen(node, visitBinaryExpression(<BinaryExpression>node.expression, /*needsDestructuringValue*/ false));
}
}
return visitEachChild(node, visitor, context);
}
@@ -1418,10 +1733,13 @@ namespace ts {
function visitBinaryExpression(node: BinaryExpression, needsDestructuringValue: boolean): Expression {
// If we are here it is because this is a destructuring assignment.
if (isDestructuringAssignment(node)) {
return flattenDestructuringAssignment(context, node, needsDestructuringValue, hoistVariableDeclaration, visitor);
return flattenDestructuringAssignment(
<DestructuringAssignment>node,
visitor,
context,
FlattenLevel.All,
needsDestructuringValue);
}
return visitEachChild(node, visitor, context);
}
function visitVariableStatement(node: VariableStatement): Statement {
@@ -1433,7 +1751,12 @@ namespace ts {
if (decl.initializer) {
let assignment: Expression;
if (isBindingPattern(decl.name)) {
assignment = flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, /*createAssignmentCallback*/ undefined, visitor);
assignment = flattenDestructuringAssignment(
decl,
visitor,
context,
FlattenLevel.All
);
}
else {
assignment = createBinary(<Identifier>decl.name, SyntaxKind.EqualsToken, visitNode(decl.initializer, visitor, isExpression));
@@ -1584,10 +1907,16 @@ namespace ts {
function visitVariableDeclaration(node: VariableDeclaration): VisitResult<VariableDeclaration> {
// If we are here it is because the name contains a binding pattern.
if (isBindingPattern(node.name)) {
const recordTempVariablesInLine = !enclosingVariableStatement
|| !hasModifier(enclosingVariableStatement, ModifierFlags.Export);
return flattenVariableDestructuring(context, node, /*value*/ undefined, visitor,
recordTempVariablesInLine ? undefined : hoistVariableDeclaration);
const doNotRecordTempVariablesInLine = enclosingVariableStatement
&& hasModifier(enclosingVariableStatement, ModifierFlags.Export);
return flattenDestructuringBinding(
node,
visitor,
context,
FlattenLevel.All,
/*value*/ undefined,
doNotRecordTempVariablesInLine
);
}
return visitEachChild(node, visitor, context);
@@ -1642,7 +1971,173 @@ namespace ts {
}
function convertForOfToFor(node: ForOfStatement, convertedLoopBodyStatements: Statement[]): ForStatement {
return <ForStatement>convertForOf(node, convertedLoopBodyStatements, visitor, enableSubstitutionsForBlockScopedBindings, context, /*transformRest*/ false);
// 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);
const elementAccess = 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 = flattenDestructuringBinding(
firstOriginalDeclaration,
visitor,
context,
FlattenLevel.All,
elementAccess
);
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(
assignment,
visitor,
context,
FlattenLevel.All
)
)
);
}
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;
}
/**
@@ -2216,7 +2711,13 @@ namespace ts {
const temp = createTempVariable(undefined);
const newVariableDeclaration = createVariableDeclaration(temp, undefined, undefined, node.variableDeclaration);
const vars = flattenVariableDestructuring(context, node.variableDeclaration, temp, visitor);
const vars = flattenDestructuringBinding(
node.variableDeclaration,
visitor,
context,
FlattenLevel.All,
temp
);
const list = createVariableDeclarationList(vars, /*location*/node.variableDeclaration, /*flags*/node.variableDeclaration.flags);
const destructure = createVariableStatement(undefined, list);
@@ -2303,7 +2804,7 @@ namespace ts {
setEmitFlags(thisArg, EmitFlags.NoSubstitution);
}
let resultingCall: CallExpression | BinaryExpression;
if (node.transformFlags & TransformFlags.ContainsSpreadExpression) {
if (node.transformFlags & TransformFlags.ContainsSpread) {
// [source]
// f(...a, b)
// x.m(...a, b)
@@ -2365,7 +2866,7 @@ namespace ts {
*/
function visitNewExpression(node: NewExpression): LeftHandSideExpression {
// We are here because we contain a SpreadElementExpression.
Debug.assert((node.transformFlags & TransformFlags.ContainsSpreadExpression) !== 0);
Debug.assert((node.transformFlags & TransformFlags.ContainsSpread) !== 0);
// [source]
// new C(...a)
+52 -61
View File
@@ -17,84 +17,75 @@ namespace ts {
}
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.ES2016) {
return visitorWorker(node);
}
else if (node.transformFlags & TransformFlags.ContainsES2016) {
return visitEachChild(node, visitor, context);
}
else {
if ((node.transformFlags & TransformFlags.ContainsES2016) === 0) {
return node;
}
}
function visitorWorker(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(<BinaryExpression>node);
default:
Debug.failBadSyntaxKind(node);
return visitEachChild(node, visitor, context);
}
}
function visitBinaryExpression(node: BinaryExpression): Expression {
// We are here because ES2016 adds support for the exponentiation operator.
switch (node.operatorToken.kind) {
case SyntaxKind.AsteriskAsteriskEqualsToken:
return visitExponentiationAssignmentExpression(node);
case SyntaxKind.AsteriskAsteriskToken:
return visitExponentiationExpression(node);
default:
return visitEachChild(node, visitor, context);
}
}
function visitExponentiationAssignmentExpression(node: BinaryExpression) {
let target: Expression;
let value: Expression;
const left = visitNode(node.left, visitor, isExpression);
const right = visitNode(node.right, visitor, isExpression);
if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskEqualsToken) {
let target: Expression;
let value: Expression;
if (isElementAccessExpression(left)) {
// Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
const expressionTemp = createTempVariable(hoistVariableDeclaration);
const argumentExpressionTemp = createTempVariable(hoistVariableDeclaration);
target = createElementAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression),
/*location*/ left
);
value = createElementAccess(
expressionTemp,
argumentExpressionTemp,
/*location*/ left
);
}
else if (isPropertyAccessExpression(left)) {
// Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
const expressionTemp = createTempVariable(hoistVariableDeclaration);
target = createPropertyAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
left.name,
/*location*/ left
);
value = createPropertyAccess(
expressionTemp,
left.name,
/*location*/ left
);
}
else {
// Transforms `a **= b` into `a = Math.pow(a, b)`
target = left;
value = left;
}
return createAssignment(target, createMathPow(value, right, /*location*/ node), /*location*/ node);
if (isElementAccessExpression(left)) {
// Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
const expressionTemp = createTempVariable(hoistVariableDeclaration);
const argumentExpressionTemp = createTempVariable(hoistVariableDeclaration);
target = createElementAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression),
/*location*/ left
);
value = createElementAccess(
expressionTemp,
argumentExpressionTemp,
/*location*/ left
);
}
else if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskToken) {
// Transforms `a ** b` into `Math.pow(a, b)`
return createMathPow(left, right, /*location*/ node);
else if (isPropertyAccessExpression(left)) {
// Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
const expressionTemp = createTempVariable(hoistVariableDeclaration);
target = createPropertyAccess(
createAssignment(expressionTemp, left.expression, /*location*/ left.expression),
left.name,
/*location*/ left
);
value = createPropertyAccess(
expressionTemp,
left.name,
/*location*/ left
);
}
else {
Debug.failBadSyntaxKind(node);
return visitEachChild(node, visitor, context);
// Transforms `a **= b` into `a = Math.pow(a, b)`
target = left;
value = left;
}
return createAssignment(target, createMathPow(value, right, /*location*/ node), /*location*/ node);
}
function visitExponentiationExpression(node: BinaryExpression) {
// Transforms `a ** b` into `Math.pow(a, b)`
const left = visitNode(node.left, visitor, isExpression);
const right = visitNode(node.right, visitor, isExpression);
return createMathPow(left, right, /*location*/ node);
}
}
}
+32 -52
View File
@@ -30,12 +30,6 @@ namespace ts {
*/
let enabledSubstitutions: ES2017SubstitutionFlags;
/**
* Keeps track of whether we are within any containing namespaces when performing
* just-in-time substitution while printing an expression identifier.
*/
let applicableSubstitutions: ES2017SubstitutionFlags;
/**
* This keeps track of containers where `super` is valid, for use with
* just-in-time substitution for `super` expressions inside of async methods.
@@ -67,13 +61,9 @@ namespace ts {
}
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.ES2017) {
if (node.transformFlags & TransformFlags.ContainsES2017) {
return visitorWorker(node);
}
else if (node.transformFlags & TransformFlags.ContainsES2017) {
return visitEachChild(node, visitor, context);
}
return node;
}
@@ -104,8 +94,7 @@ namespace ts {
return visitArrowFunction(<ArrowFunction>node);
default:
Debug.failBadSyntaxKind(node);
return node;
return visitEachChild(node, visitor, context);
}
}
@@ -136,8 +125,7 @@ namespace ts {
* @param node The node to visit.
*/
function visitMethodDeclaration(node: MethodDeclaration) {
Debug.assert(hasModifier(node, ModifierFlags.Async));
const updated = updateMethod(
return updateMethod(
node,
/*decorators*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
@@ -145,9 +133,10 @@ namespace ts {
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
isAsyncFunctionLike(node)
? transformAsyncFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
return updated;
}
/**
@@ -159,8 +148,7 @@ namespace ts {
* @param node The node to visit.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
Debug.assert(hasModifier(node, ModifierFlags.Async));
const updated = updateFunctionDeclaration(
return updateFunctionDeclaration(
node,
/*decorators*/ undefined,
visitNodes(node.modifiers, visitor, isModifier),
@@ -168,9 +156,10 @@ namespace ts {
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
isAsyncFunctionLike(node)
? transformAsyncFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
return updated;
}
/**
@@ -182,22 +171,20 @@ namespace ts {
* @param node The node to visit.
*/
function visitFunctionExpression(node: FunctionExpression): Expression {
Debug.assert(hasModifier(node, ModifierFlags.Async));
if (nodeIsMissing(node.body)) {
return createOmittedExpression();
}
const updated = updateFunctionExpression(
return updateFunctionExpression(
node,
visitNodes(node.modifiers, visitor, isModifier),
/*modifiers*/ undefined,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
isAsyncFunctionLike(node)
? transformAsyncFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
setOriginalNode(updated, node);
return updated;
}
/**
@@ -209,23 +196,21 @@ namespace ts {
* @param node The node to visit.
*/
function visitArrowFunction(node: ArrowFunction) {
Debug.assert(hasModifier(node, ModifierFlags.Async));
const updated = updateArrowFunction(
return updateArrowFunction(
node,
visitNodes(node.modifiers, visitor, isModifier),
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
isAsyncFunctionLike(node)
? transformAsyncFunctionBody(node)
: visitFunctionBody(node.body, visitor, context)
);
setOriginalNode(updated, node);
return updated;
}
function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody;
function transformFunctionBody(node: ArrowFunction): ConciseBody;
function transformFunctionBody(node: FunctionLikeDeclaration): ConciseBody {
function transformAsyncFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody;
function transformAsyncFunctionBody(node: ArrowFunction): ConciseBody;
function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody {
const original = getOriginalNode(node, isFunctionLike);
const nodeType = original.type;
const promiseConstructor = languageVersion < ScriptTarget.ES2015 ? getPromiseConstructor(nodeType) : undefined;
@@ -237,7 +222,6 @@ namespace ts {
// `this` and `arguments` objects to `__awaiter`. The generator function
// passed to `__awaiter` is executed inside of the callback to the
// promise constructor.
resumeLexicalEnvironment();
if (!isArrowFunction) {
@@ -284,8 +268,7 @@ namespace ts {
const declarations = endLexicalEnvironment();
if (some(declarations)) {
const block = convertToFunctionBody(expression);
const statements = mergeLexicalEnvironment(block.statements, declarations);
return updateBlock(block, statements);
return updateBlock(block, createNodeArray(concatenate(block.statements, declarations), block.statements));
}
return expression;
@@ -294,15 +277,13 @@ namespace ts {
function transformFunctionBodyWorker(body: ConciseBody, start?: number) {
if (isBlock(body)) {
return updateBlock(
body,
visitLexicalEnvironment(body.statements, visitor, context, start));
return updateBlock(body, visitLexicalEnvironment(body.statements, visitor, context, start));
}
else {
startLexicalEnvironment();
const visited = convertToFunctionBody(visitNode(body, visitor, isConciseBody));
const statements = mergeLexicalEnvironment(visited.statements, endLexicalEnvironment());
return updateBlock(visited, statements);
const declarations = endLexicalEnvironment();
return updateBlock(visited, createNodeArray(concatenate(visited.statements, declarations), visited.statements));
}
}
@@ -421,18 +402,17 @@ namespace ts {
* @param emit A callback used to emit the node in the printer.
*/
function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void {
const savedApplicableSubstitutions = applicableSubstitutions;
const savedCurrentSuperContainer = currentSuperContainer;
// If we need to support substitutions for `super` in an async method,
// we should track it here.
if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) {
const savedCurrentSuperContainer = currentSuperContainer;
currentSuperContainer = node;
previousOnEmitNode(emitContext, node, emitCallback);
currentSuperContainer = savedCurrentSuperContainer;
}
else {
previousOnEmitNode(emitContext, node, emitCallback);
}
previousOnEmitNode(emitContext, node, emitCallback);
applicableSubstitutions = savedApplicableSubstitutions;
currentSuperContainer = savedCurrentSuperContainer;
}
/**
+251 -142
View File
@@ -5,13 +5,11 @@
namespace ts {
export function transformESNext(context: TransformationContext) {
const {
hoistVariableDeclaration,
endLexicalEnvironment
} = context;
let currentSourceFile: SourceFile;
return transformSourceFile;
function transformSourceFile(node: SourceFile) {
currentSourceFile = node;
const visited = visitEachChild(node, visitor, context);
addEmitHelpers(visited, context.readEmitHelpers());
@@ -19,30 +17,39 @@ namespace ts {
}
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;
}
return visitorWorker(node, /*noDestructuringValue*/ false);
}
function visitorWorker(node: Node): VisitResult<Node> {
function visitorNoDestructuringValue(node: Node): VisitResult<Node> {
return visitorWorker(node, /*noDestructuringValue*/ true);
}
function visitorWorker(node: Node, noDestructuringValue: boolean): VisitResult<Node> {
if ((node.transformFlags & TransformFlags.ContainsESNext) === 0) {
return node;
}
switch (node.kind) {
case SyntaxKind.ObjectLiteralExpression:
return visitObjectLiteralExpression(node as ObjectLiteralExpression);
case SyntaxKind.BinaryExpression:
return visitBinaryExpression(node as BinaryExpression);
return visitBinaryExpression(node as BinaryExpression, noDestructuringValue);
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.ForStatement:
return visitForStatement(node as ForStatement);
case SyntaxKind.VoidExpression:
return visitVoidExpression(node as VoidExpression);
case SyntaxKind.Constructor:
return visitConstructorDeclaration(node as ConstructorDeclaration);
case SyntaxKind.MethodDeclaration:
return visitMethodDeclaration(node as MethodDeclaration);
case SyntaxKind.GetAccessor:
return visitGetAccessorDeclaration(node as GetAccessorDeclaration);
case SyntaxKind.SetAccessor:
return visitSetAccessorDeclaration(node as SetAccessorDeclaration);
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(node as FunctionDeclaration);
case SyntaxKind.FunctionExpression:
@@ -51,8 +58,11 @@ namespace ts {
return visitArrowFunction(node as ArrowFunction);
case SyntaxKind.Parameter:
return visitParameter(node as ParameterDeclaration);
case SyntaxKind.ExpressionStatement:
return visitExpressionStatement(node as ExpressionStatement);
case SyntaxKind.ParenthesizedExpression:
return visitParenthesizedExpression(node as ParenthesizedExpression, noDestructuringValue);
default:
Debug.failBadSyntaxKind(node);
return visitEachChild(node, visitor, context);
}
}
@@ -90,12 +100,12 @@ namespace ts {
}
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)
if (forEach(node.properties, p => p.kind === SyntaxKind.SpreadAssignment)) {
if (node.transformFlags & TransformFlags.ContainsObjectSpread) {
// 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());
@@ -105,16 +115,36 @@ namespace ts {
return visitEachChild(node, visitor, context);
}
function visitExpressionStatement(node: ExpressionStatement): ExpressionStatement {
return visitEachChild(node, visitorNoDestructuringValue, context);
}
function visitParenthesizedExpression(node: ParenthesizedExpression, noDestructuringValue: boolean): ParenthesizedExpression {
return visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
}
/**
* 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);
function visitBinaryExpression(node: BinaryExpression, noDestructuringValue: boolean): Expression {
if (isDestructuringAssignment(node) && node.left.transformFlags & TransformFlags.ContainsObjectRest) {
return flattenDestructuringAssignment(
node,
visitor,
context,
FlattenLevel.ObjectRest,
!noDestructuringValue
);
}
else if (node.operatorToken.kind === SyntaxKind.CommaToken) {
return updateBinary(
node,
visitNode(node.left, visitorNoDestructuringValue, isExpression),
visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, isExpression)
);
}
return visitEachChild(node, visitor, context);
}
@@ -125,151 +155,230 @@ namespace ts {
*/
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(context, node, /*value*/ undefined, visitor, /*recordTempVariable*/ undefined, /*transformRest*/ true);
return result;
if (isBindingPattern(node.name) && node.name.transformFlags & TransformFlags.ContainsObjectRest) {
return flattenDestructuringBinding(
node,
visitor,
context,
FlattenLevel.ObjectRest
);
}
return visitEachChild(node, visitor, context);
}
function visitForStatement(node: ForStatement): VisitResult<Statement> {
return updateFor(
node,
visitNode(node.initializer, visitorNoDestructuringValue, isForInitializer),
visitNode(node.condition, visitor, isExpression),
visitNode(node.incrementor, visitor, isExpression),
visitNode(node.statement, visitor, isStatement)
);
}
function visitVoidExpression(node: VoidExpression) {
return visitEachChild(node, visitorNoDestructuringValue, 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);
let leadingStatements: Statement[];
let temp: Identifier;
const initializer = skipParentheses(node.initializer);
if (initializer.transformFlags & TransformFlags.ContainsObjectRest) {
if (isVariableDeclarationList(initializer)) {
temp = createTempVariable(/*recordTempVariable*/ undefined);
const firstDeclaration = firstOrUndefined(initializer.declarations);
const declarations = flattenDestructuringBinding(
firstDeclaration,
visitor,
context,
FlattenLevel.ObjectRest,
temp,
/*doNotRecordTempVariablesInLine*/ false,
/*skipInitializer*/ true,
);
if (some(declarations)) {
const statement = createVariableStatement(
/*modifiers*/ undefined,
updateVariableDeclarationList(initializer, declarations),
/*location*/ initializer
);
leadingStatements = append(leadingStatements, statement);
}
}
else if (isAssignmentPattern(initializer)) {
temp = createTempVariable(/*recordTempVariable*/ undefined);
const expression = flattenDestructuringAssignment(
aggregateTransformFlags(createAssignment(initializer, temp, /*location*/ node.initializer)),
visitor,
context,
FlattenLevel.ObjectRest
);
leadingStatements = append(leadingStatements, createStatement(expression, /*location*/ node.initializer));
}
}
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);
if (temp) {
const expression = visitNode(node.expression, visitor, isExpression);
const statement = visitNode(node.statement, visitor, isStatement);
const block = isBlock(statement)
? updateBlock(statement, createNodeArray(concatenate(leadingStatements, statement.statements), statement.statements))
: createBlock(append(leadingStatements, statement), statement, /*multiLine*/ true);
return updateForOf(
node,
createVariableDeclarationList(
[
createVariableDeclaration(temp, /*type*/ undefined, /*initializer*/ undefined, node.initializer)
],
node.initializer,
NodeFlags.Let
),
expression,
block
);
}
return false;
}
function isRestAssignment(initializer: ForInitializer) {
return initializer.kind === SyntaxKind.ObjectLiteralExpression &&
initializer.transformFlags & TransformFlags.ContainsSpreadExpression;
return visitEachChild(node, visitor, context);
}
function visitParameter(node: ParameterDeclaration): ParameterDeclaration {
if (isObjectRestParameter(node)) {
if (node.transformFlags & TransformFlags.ContainsObjectRest) {
// 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
return updateParameter(
node,
/*decorators*/ undefined,
/*modifiers*/ undefined,
node.dotDotDotToken,
getGeneratedNameForNode(node),
/*type*/ undefined,
visitNode(node.initializer, visitor, isExpression)
);
}
else {
return node;
}
return visitEachChild(node, visitor, context);
}
function isObjectRestParameter(node: ParameterDeclaration) {
return node.name &&
node.name.kind === SyntaxKind.ObjectBindingPattern &&
!!(node.name.transformFlags & TransformFlags.ContainsSpreadExpression);
function visitConstructorDeclaration(node: ConstructorDeclaration) {
return updateConstructor(
node,
/*decorators*/ undefined,
node.modifiers,
visitParameterList(node.parameters, visitor, context),
transformFunctionBody(node)
);
}
function visitFunctionDeclaration(node: FunctionDeclaration): FunctionDeclaration {
const hasRest = forEach(node.parameters, isObjectRestParameter);
return setOriginalNode(
createFunctionDeclaration(
/*decorators*/ undefined,
node.modifiers,
node.asteriskToken,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
hasRest ?
transformFunctionBody(node, visitor, currentSourceFile, context, noop, /*convertObjectRest*/ true) as Block :
visitFunctionBody(node.body, visitor, context),
/*location*/ node
),
/*original*/ node);
function visitGetAccessorDeclaration(node: GetAccessorDeclaration) {
return updateGetAccessor(
node,
/*decorators*/ undefined,
node.modifiers,
visitNode(node.name, visitor, isPropertyName),
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
}
function visitSetAccessorDeclaration(node: SetAccessorDeclaration) {
return updateSetAccessor(
node,
/*decorators*/ undefined,
node.modifiers,
visitNode(node.name, visitor, isPropertyName),
visitParameterList(node.parameters, visitor, context),
transformFunctionBody(node)
);
}
function visitMethodDeclaration(node: MethodDeclaration) {
return updateMethod(
node,
/*decorators*/ undefined,
node.modifiers,
visitNode(node.name, visitor, isPropertyName),
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
}
function visitFunctionDeclaration(node: FunctionDeclaration) {
return updateFunctionDeclaration(
node,
/*decorators*/ undefined,
node.modifiers,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
}
function visitArrowFunction(node: ArrowFunction) {
const hasRest = forEach(node.parameters, isObjectRestParameter);
const func = setOriginalNode(
createArrowFunction(
node.modifiers,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
node.equalsGreaterThanToken,
hasRest ?
transformFunctionBody(node, visitor, currentSourceFile, context, noop, /*convertObjectRest*/ true) as Block :
visitFunctionBody(node.body, visitor, context),
/*location*/ node
),
/*original*/ node
return updateArrowFunction(
node,
node.modifiers,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
setEmitFlags(func, EmitFlags.CapturesThis);
return func;
}
function visitFunctionExpression(node: FunctionExpression): Expression {
const hasRest = forEach(node.parameters, isObjectRestParameter);
return setOriginalNode(
createFunctionExpression(
node.modifiers,
node.asteriskToken,
name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
hasRest ?
transformFunctionBody(node, visitor, currentSourceFile, context, noop, /*convertObjectRest*/ true) as Block :
visitFunctionBody(node.body, visitor, context),
/*location*/ node
),
/*original*/ node
function visitFunctionExpression(node: FunctionExpression) {
return updateFunctionExpression(
node,
node.modifiers,
node.name,
/*typeParameters*/ undefined,
visitParameterList(node.parameters, visitor, context),
/*type*/ undefined,
transformFunctionBody(node)
);
}
function transformFunctionBody(node: FunctionDeclaration | FunctionExpression | ConstructorDeclaration | MethodDeclaration | AccessorDeclaration): FunctionBody;
function transformFunctionBody(node: ArrowFunction): ConciseBody;
function transformFunctionBody(node: FunctionLikeDeclaration): ConciseBody {
let leadingStatements: Statement[];
for (const parameter of node.parameters) {
if (parameter.transformFlags & TransformFlags.ContainsObjectRest) {
const temp = getGeneratedNameForNode(parameter);
const declarations = flattenDestructuringBinding(
parameter,
visitor,
context,
FlattenLevel.ObjectRest,
temp,
/*doNotRecordTempVariablesInLine*/ false,
/*skipInitializer*/ true,
);
if (some(declarations)) {
const statement = createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList(
declarations
)
);
setEmitFlags(statement, EmitFlags.CustomPrologue);
leadingStatements = append(leadingStatements, statement);
}
}
}
const body = visitNode(node.body, visitor, isConciseBody);
const trailingStatements = endLexicalEnvironment();
if (some(leadingStatements) || some(trailingStatements)) {
const block = convertToFunctionBody(body, /*multiLine*/ true);
return updateBlock(block, createNodeArray(concatenate(concatenate(leadingStatements, block.statements), trailingStatements), block.statements));
}
return body;
}
}
const assignHelper: EmitHelper = {
+2 -6
View File
@@ -30,12 +30,9 @@ namespace ts {
}
function visitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.Jsx) {
if (node.transformFlags & TransformFlags.ContainsJsx) {
return visitorWorker(node);
}
else if (node.transformFlags & TransformFlags.ContainsJsx) {
return visitEachChild(node, visitor, context);
}
else {
return node;
}
@@ -53,8 +50,7 @@ namespace ts {
return visitJsxExpression(<JsxExpression>node);
default:
Debug.failBadSyntaxKind(node);
return undefined;
return visitEachChild(node, visitor, context);
}
}
+6 -5
View File
@@ -19,8 +19,7 @@ namespace ts {
const {
startLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration,
endLexicalEnvironment
} = context;
const compilerOptions = context.getCompilerOptions();
@@ -758,10 +757,12 @@ namespace ts {
*/
function transformInitializedVariable(node: VariableDeclaration): Expression {
if (isBindingPattern(node.name)) {
return flattenVariableDestructuringToExpression(
context,
return flattenDestructuringAssignment(
node,
hoistVariableDeclaration,
/*visitor*/ undefined,
context,
FlattenLevel.All,
/*needsValue*/ false,
createExportExpression
);
}
+15 -2
View File
@@ -818,7 +818,14 @@ namespace ts {
function transformInitializedVariable(node: VariableDeclaration, isExportedDeclaration: boolean): Expression {
const createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
return isBindingPattern(node.name)
? flattenVariableDestructuringToExpression(context, node, hoistVariableDeclaration, createAssignment, destructuringVisitor)
? flattenDestructuringAssignment(
node,
destructuringVisitor,
context,
FlattenLevel.All,
/*needsValue*/ false,
createAssignment
)
: createAssignment(node.name, visitNode(node.initializer, destructuringVisitor, isExpression));
}
@@ -1469,7 +1476,13 @@ namespace ts {
*/
function visitDestructuringAssignment(node: DestructuringAssignment): VisitResult<Expression> {
if (hasExportedReferenceInDestructuringTarget(node.left)) {
return flattenDestructuringAssignment(context, node, /*needsValue*/ true, hoistVariableDeclaration, destructuringVisitor);
return flattenDestructuringAssignment(
node,
destructuringVisitor,
context,
FlattenLevel.All,
/*needsValue*/ true
);
}
return visitEachChild(node, destructuringVisitor, context);
+8 -17
View File
@@ -1777,12 +1777,7 @@ namespace ts {
const temp = createTempVariable(hoistVariableDeclaration);
return createLogicalOr(
createLogicalAnd(
createStrictEquality(
createTypeOf(
createAssignment(temp, serialized)
),
createLiteral("function")
),
createTypeCheck(createAssignment(temp, serialized), "function"),
temp
),
createIdentifier("Object")
@@ -1891,13 +1886,8 @@ namespace ts {
*/
function getGlobalSymbolNameWithFallback(): Expression {
return createConditional(
createStrictEquality(
createTypeOf(createIdentifier("Symbol")),
createLiteral("function")
),
createToken(SyntaxKind.QuestionToken),
createTypeCheck(createIdentifier("Symbol"), "function"),
createIdentifier("Symbol"),
createToken(SyntaxKind.ColonToken),
createIdentifier("Object")
);
}
@@ -2249,12 +2239,13 @@ namespace ts {
function transformInitializedVariable(node: VariableDeclaration): Expression {
const name = node.name;
if (isBindingPattern(name)) {
return flattenVariableDestructuringToExpression(
context,
return flattenDestructuringAssignment(
node,
hoistVariableDeclaration,
createNamespaceExportExpression,
visitor
visitor,
context,
FlattenLevel.All,
/*needsValue*/ false,
createNamespaceExportExpression
);
}
else {
+104 -60
View File
@@ -508,6 +508,7 @@ namespace ts {
export interface NodeArray<T extends Node> extends Array<T>, TextRange {
hasTrailingComma?: boolean;
/* @internal */ transformFlags?: TransformFlags;
}
export interface Token<TKind extends SyntaxKind> extends Node {
@@ -579,9 +580,9 @@ namespace ts {
export type EntityName = Identifier | QualifiedName;
export type PropertyName = Identifier | LiteralExpression | ComputedPropertyName;
export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName;
export type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern;
export type DeclarationName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | BindingPattern;
export interface Declaration extends Node {
_declarationBrand: any;
@@ -589,7 +590,7 @@ namespace ts {
}
export interface DeclarationStatement extends Declaration, Statement {
name?: Identifier | LiteralExpression;
name?: Identifier | StringLiteral | NumericLiteral;
}
export interface ComputedPropertyName extends Node {
@@ -724,22 +725,20 @@ namespace ts {
name: PropertyName;
}
export interface BindingPattern extends Node {
elements: NodeArray<BindingElement | ArrayBindingElement>;
}
export interface ObjectBindingPattern extends BindingPattern {
export interface ObjectBindingPattern extends Node {
kind: SyntaxKind.ObjectBindingPattern;
elements: NodeArray<BindingElement>;
}
export type ArrayBindingElement = BindingElement | OmittedExpression;
export interface ArrayBindingPattern extends BindingPattern {
export interface ArrayBindingPattern extends Node {
kind: SyntaxKind.ArrayBindingPattern;
elements: NodeArray<ArrayBindingElement>;
}
export type BindingPattern = ObjectBindingPattern | ArrayBindingPattern;
export type ArrayBindingElement = BindingElement | OmittedExpression;
/**
* Several node kinds share function-like features such as a signature,
* a name, and a body. These nodes should extend FunctionLikeDeclaration.
@@ -921,7 +920,7 @@ namespace ts {
export interface StringLiteral extends LiteralExpression {
kind: SyntaxKind.StringLiteral;
/* @internal */ textSourceNode?: Identifier | StringLiteral; // Allows a StringLiteral to get its text from another node (used by transforms).
/* @internal */ textSourceNode?: Identifier | StringLiteral | NumericLiteral; // Allows a StringLiteral to get its text from another node (used by transforms).
}
// Note: 'brands' in our syntax nodes serve to give us a small amount of nominal typing.
@@ -1186,20 +1185,64 @@ namespace ts {
right: Expression;
}
export interface AssignmentExpression extends BinaryExpression {
export type AssignmentOperatorToken = Token<AssignmentOperator>;
export interface AssignmentExpression<TOperator extends AssignmentOperatorToken> extends BinaryExpression {
left: LeftHandSideExpression;
operatorToken: Token<SyntaxKind.EqualsToken>;
operatorToken: TOperator;
}
export interface ObjectDestructuringAssignment extends AssignmentExpression {
export interface ObjectDestructuringAssignment extends AssignmentExpression<EqualsToken> {
left: ObjectLiteralExpression;
}
export interface ArrayDestructuringAssignment extends AssignmentExpression {
export interface ArrayDestructuringAssignment extends AssignmentExpression<EqualsToken> {
left: ArrayLiteralExpression;
}
export type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment;
export type DestructuringAssignment
= ObjectDestructuringAssignment
| ArrayDestructuringAssignment
;
export type BindingOrAssignmentElement
= VariableDeclaration
| ParameterDeclaration
| BindingElement
| PropertyAssignment // AssignmentProperty
| ShorthandPropertyAssignment // AssignmentProperty
| SpreadAssignment // AssignmentRestProperty
| OmittedExpression // Elision
| SpreadElement // AssignmentRestElement
| ArrayLiteralExpression // ArrayAssignmentPattern
| ObjectLiteralExpression // ObjectAssignmentPattern
| AssignmentExpression<EqualsToken> // AssignmentElement
| Identifier // DestructuringAssignmentTarget
| PropertyAccessExpression // DestructuringAssignmentTarget
| ElementAccessExpression // DestructuringAssignmentTarget
;
export type BindingOrAssignmentElementRestIndicator
= DotDotDotToken // from BindingElement
| SpreadElement // AssignmentRestElement
| SpreadAssignment // AssignmentRestProperty
;
export type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression;
export type ObjectBindingOrAssignmentPattern
= ObjectBindingPattern
| ObjectLiteralExpression // ObjectAssignmentPattern
;
export type ArrayBindingOrAssignmentPattern
= ArrayBindingPattern
| ArrayLiteralExpression // ArrayAssignmentPattern
;
export type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression;
export type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern;
export interface ConditionalExpression extends Expression {
kind: SyntaxKind.ConditionalExpression;
@@ -1719,7 +1762,7 @@ namespace ts {
export interface ModuleDeclaration extends DeclarationStatement {
kind: SyntaxKind.ModuleDeclaration;
name: Identifier | LiteralExpression;
name: Identifier | StringLiteral;
body?: ModuleBlock | NamespaceDeclaration | JSDocNamespaceDeclaration | Identifier;
}
@@ -1925,7 +1968,7 @@ namespace ts {
export interface JSDocRecordMember extends PropertySignature {
kind: SyntaxKind.JSDocRecordMember;
name: Identifier | LiteralExpression;
name: Identifier | StringLiteral | NumericLiteral;
type?: JSDocType;
}
@@ -2692,7 +2735,7 @@ namespace ts {
resolvedSignature?: Signature; // Cached signature of signature node or call expression
resolvedSymbol?: Symbol; // Cached name resolution result
resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result
maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate
maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate
enumMemberValue?: number; // Constant value of enum member
isVisible?: boolean; // Is this node visible
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
@@ -3528,46 +3571,45 @@ namespace ts {
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
TypeScript = 1 << 0,
ContainsTypeScript = 1 << 1,
Jsx = 1 << 2,
ContainsJsx = 1 << 3,
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,
ContainsJsx = 1 << 2,
ContainsESNext = 1 << 3,
ContainsES2017 = 1 << 4,
ContainsES2016 = 1 << 5,
ES2015 = 1 << 6,
ContainsES2015 = 1 << 7,
Generator = 1 << 8,
ContainsGenerator = 1 << 9,
DestructuringAssignment = 1 << 10,
ContainsDestructuringAssignment = 1 << 11,
// Markers
// - Flags used to indicate that a subtree contains a specific transformation.
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,
ContainsDecorators = 1 << 12,
ContainsPropertyInitializer = 1 << 13,
ContainsLexicalThis = 1 << 14,
ContainsCapturedLexicalThis = 1 << 15,
ContainsLexicalThisInComputedPropertyName = 1 << 16,
ContainsDefaultValueAssignments = 1 << 17,
ContainsParameterPropertyAssignments = 1 << 18,
ContainsSpread = 1 << 19,
ContainsObjectSpread = 1 << 20,
ContainsRest = ContainsSpread,
ContainsObjectRest = ContainsObjectSpread,
ContainsComputedPropertyName = 1 << 21,
ContainsBlockScopedBinding = 1 << 22,
ContainsBindingPattern = 1 << 23,
ContainsYield = 1 << 24,
ContainsHoistedDeclarationOrCompletion = 1 << 25,
HasComputedFlags = 1 << 29, // Transform flags have been computed.
// Assertions
// - 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,
AssertJsx = ContainsJsx,
AssertESNext = ContainsESNext,
AssertES2017 = ContainsES2017,
AssertES2016 = ContainsES2016,
AssertES2015 = ES2015 | ContainsES2015,
AssertGenerator = Generator | ContainsGenerator,
AssertDestructuringAssignment = DestructuringAssignment | ContainsDestructuringAssignment,
@@ -3575,18 +3617,20 @@ 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 | 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,
MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion,
NodeExcludes = TypeScript | ES2015 | DestructuringAssignment | Generator | HasComputedFlags,
ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest,
FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest,
ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest,
MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest,
ClassExcludes = NodeExcludes | ContainsDecorators | ContainsPropertyInitializer | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsParameterPropertyAssignments | ContainsLexicalThisInComputedPropertyName,
ModuleExcludes = NodeExcludes | ContainsDecorators | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion,
TypeExcludes = ~ContainsTypeScript,
ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName,
ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpreadExpression,
VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern,
ParameterExcludes = NodeExcludes | ContainsBindingPattern,
ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName | ContainsObjectSpread,
ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpread,
VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRest,
ParameterExcludes = NodeExcludes,
CatchClauseExcludes = NodeExcludes | ContainsObjectRest,
BindingPatternExcludes = NodeExcludes | ContainsRest,
// Masks
// - Additional bitmasks
+80 -13
View File
@@ -478,7 +478,7 @@ namespace ts {
case SyntaxKind.NumericLiteral:
return (<LiteralExpression>name).text;
case SyntaxKind.ComputedPropertyName:
if (isStringOrNumericLiteral((<ComputedPropertyName>name).expression.kind)) {
if (isStringOrNumericLiteral((<ComputedPropertyName>name).expression)) {
return (<LiteralExpression>(<ComputedPropertyName>name).expression).text;
}
}
@@ -1866,8 +1866,10 @@ namespace ts {
return isFunctionLike(node) && hasModifier(node, ModifierFlags.Async) && !isAccessor(node);
}
export function isStringOrNumericLiteral(kind: SyntaxKind): boolean {
return kind === SyntaxKind.StringLiteral || kind === SyntaxKind.NumericLiteral;
export function isStringOrNumericLiteral(node: Node): node is StringLiteral | NumericLiteral {
const kind = node.kind;
return kind === SyntaxKind.StringLiteral
|| kind === SyntaxKind.NumericLiteral;
}
/**
@@ -1883,7 +1885,7 @@ namespace ts {
export function isDynamicName(name: DeclarationName): boolean {
return name.kind === SyntaxKind.ComputedPropertyName &&
!isStringOrNumericLiteral((<ComputedPropertyName>name).expression.kind) &&
!isStringOrNumericLiteral((<ComputedPropertyName>name).expression) &&
!isWellKnownSymbolSyntactically((<ComputedPropertyName>name).expression);
}
@@ -1896,7 +1898,7 @@ namespace ts {
return isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
}
export function getPropertyNameForPropertyNameNode(name: DeclarationName): string {
export function getPropertyNameForPropertyNameNode(name: DeclarationName | ParameterDeclaration): string {
if (name.kind === SyntaxKind.Identifier || name.kind === SyntaxKind.StringLiteral || name.kind === SyntaxKind.NumericLiteral || name.kind === SyntaxKind.Parameter) {
return (<Identifier | LiteralExpression>name).text;
}
@@ -3125,19 +3127,21 @@ namespace ts {
}
}
export function isAssignmentExpression(node: Node): node is AssignmentExpression {
export function isAssignmentExpression(node: Node, excludeCompoundAssignment: true): node is AssignmentExpression<EqualsToken>;
export function isAssignmentExpression(node: Node, excludeCompoundAssignment?: false): node is AssignmentExpression<AssignmentOperatorToken>;
export function isAssignmentExpression(node: Node, excludeCompoundAssignment?: boolean): node is AssignmentExpression<AssignmentOperatorToken> {
return isBinaryExpression(node)
&& isAssignmentOperator(node.operatorToken.kind)
&& (excludeCompoundAssignment
? node.operatorToken.kind === SyntaxKind.EqualsToken
: isAssignmentOperator(node.operatorToken.kind))
&& isLeftHandSideExpression(node.left);
}
export function isDestructuringAssignment(node: Node): node is DestructuringAssignment {
if (isBinaryExpression(node)) {
if (node.operatorToken.kind === SyntaxKind.EqualsToken) {
const kind = node.left.kind;
return kind === SyntaxKind.ObjectLiteralExpression
|| kind === SyntaxKind.ArrayLiteralExpression;
}
if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
const kind = node.left.kind;
return kind === SyntaxKind.ObjectLiteralExpression
|| kind === SyntaxKind.ArrayLiteralExpression;
}
return false;
@@ -3771,6 +3775,14 @@ namespace ts {
// Binding patterns
export function isArrayBindingPattern(node: Node): node is ArrayBindingPattern {
return node.kind === SyntaxKind.ArrayBindingPattern;
}
export function isObjectBindingPattern(node: Node): node is ObjectBindingPattern {
return node.kind === SyntaxKind.ObjectBindingPattern;
}
export function isBindingPattern(node: Node): node is BindingPattern {
if (node) {
const kind = node.kind;
@@ -3781,6 +3793,12 @@ namespace ts {
return false;
}
export function isAssignmentPattern(node: Node): node is AssignmentPattern {
const kind = node.kind;
return kind === SyntaxKind.ArrayLiteralExpression
|| kind === SyntaxKind.ObjectLiteralExpression;
}
export function isBindingElement(node: Node): node is BindingElement {
return node.kind === SyntaxKind.BindingElement;
}
@@ -3791,6 +3809,55 @@ namespace ts {
|| kind === SyntaxKind.OmittedExpression;
}
/**
* Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
*/
export function isDeclarationBindingElement(bindingElement: BindingOrAssignmentElement): bindingElement is VariableDeclaration | ParameterDeclaration | BindingElement {
switch (bindingElement.kind) {
case SyntaxKind.VariableDeclaration:
case SyntaxKind.Parameter:
case SyntaxKind.BindingElement:
return true;
}
return false;
}
/**
* Determines whether a node is a BindingOrAssignmentPattern
*/
export function isBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is BindingOrAssignmentPattern {
return isObjectBindingOrAssignmentPattern(node)
|| isArrayBindingOrAssignmentPattern(node);
}
/**
* Determines whether a node is an ObjectBindingOrAssignmentPattern
*/
export function isObjectBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is ObjectBindingOrAssignmentPattern {
switch (node.kind) {
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ObjectLiteralExpression:
return true;
}
return false;
}
/**
* Determines whether a node is an ArrayBindingOrAssignmentPattern
*/
export function isArrayBindingOrAssignmentPattern(node: BindingOrAssignmentElementTarget): node is ArrayBindingOrAssignmentPattern {
switch (node.kind) {
case SyntaxKind.ArrayBindingPattern:
case SyntaxKind.ArrayLiteralExpression:
return true;
}
return false;
}
// Expression
export function isArrayLiteralExpression(node: Node): node is ArrayLiteralExpression {
+239 -188
View File
@@ -99,20 +99,26 @@ namespace ts {
return node ? f(initial, node) : initial;
}
function reduceNodeArray<T>(nodes: Node[], f: (memo: T, nodes: Node[]) => T, initial: T) {
return nodes ? f(initial, nodes) : initial;
}
/**
* Similar to `reduceLeft`, performs a reduction against each child of a node.
* NOTE: Unlike `forEachChild`, this does *not* visit every node. Only nodes added to the
* `nodeEdgeTraversalMap` above will be visited.
*
* @param node The node containing the children to reduce.
* @param f The callback function
* @param initial The initial value to supply to the reduction.
* @param f The callback function
*/
export function reduceEachChild<T>(node: Node, f: (memo: T, node: Node) => T, initial: T): T {
export function reduceEachChild<T>(node: Node, initial: T, cbNode: (memo: T, node: Node) => T, cbNodeArray?: (memo: T, nodes: Node[]) => T): T {
if (node === undefined) {
return initial;
}
const reduceNodes: (nodes: Node[], f: (memo: T, node: Node | Node[]) => T, initial: T) => T = cbNodeArray ? reduceNodeArray : reduceLeft;
const cbNodes = cbNodeArray || cbNode;
const kind = node.kind;
// No need to visit nodes with no children.
@@ -138,127 +144,127 @@ namespace ts {
// Names
case SyntaxKind.ComputedPropertyName:
result = reduceNode((<ComputedPropertyName>node).expression, f, result);
result = reduceNode((<ComputedPropertyName>node).expression, cbNode, result);
break;
// Signature elements
case SyntaxKind.Parameter:
result = reduceLeft((<ParameterDeclaration>node).decorators, f, result);
result = reduceLeft((<ParameterDeclaration>node).modifiers, f, result);
result = reduceNode((<ParameterDeclaration>node).name, f, result);
result = reduceNode((<ParameterDeclaration>node).type, f, result);
result = reduceNode((<ParameterDeclaration>node).initializer, f, result);
result = reduceNodes((<ParameterDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<ParameterDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<ParameterDeclaration>node).name, cbNode, result);
result = reduceNode((<ParameterDeclaration>node).type, cbNode, result);
result = reduceNode((<ParameterDeclaration>node).initializer, cbNode, result);
break;
case SyntaxKind.Decorator:
result = reduceNode((<Decorator>node).expression, f, result);
result = reduceNode((<Decorator>node).expression, cbNode, result);
break;
// Type member
case SyntaxKind.PropertyDeclaration:
result = reduceLeft((<PropertyDeclaration>node).decorators, f, result);
result = reduceLeft((<PropertyDeclaration>node).modifiers, f, result);
result = reduceNode((<PropertyDeclaration>node).name, f, result);
result = reduceNode((<PropertyDeclaration>node).type, f, result);
result = reduceNode((<PropertyDeclaration>node).initializer, f, result);
result = reduceNodes((<PropertyDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<PropertyDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<PropertyDeclaration>node).name, cbNode, result);
result = reduceNode((<PropertyDeclaration>node).type, cbNode, result);
result = reduceNode((<PropertyDeclaration>node).initializer, cbNode, result);
break;
case SyntaxKind.MethodDeclaration:
result = reduceLeft((<MethodDeclaration>node).decorators, f, result);
result = reduceLeft((<MethodDeclaration>node).modifiers, f, result);
result = reduceNode((<MethodDeclaration>node).name, f, result);
result = reduceLeft((<MethodDeclaration>node).typeParameters, f, result);
result = reduceLeft((<MethodDeclaration>node).parameters, f, result);
result = reduceNode((<MethodDeclaration>node).type, f, result);
result = reduceNode((<MethodDeclaration>node).body, f, result);
result = reduceNodes((<MethodDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<MethodDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<MethodDeclaration>node).name, cbNode, result);
result = reduceNodes((<MethodDeclaration>node).typeParameters, cbNodes, result);
result = reduceNodes((<MethodDeclaration>node).parameters, cbNodes, result);
result = reduceNode((<MethodDeclaration>node).type, cbNode, result);
result = reduceNode((<MethodDeclaration>node).body, cbNode, result);
break;
case SyntaxKind.Constructor:
result = reduceLeft((<ConstructorDeclaration>node).modifiers, f, result);
result = reduceLeft((<ConstructorDeclaration>node).parameters, f, result);
result = reduceNode((<ConstructorDeclaration>node).body, f, result);
result = reduceNodes((<ConstructorDeclaration>node).modifiers, cbNodes, result);
result = reduceNodes((<ConstructorDeclaration>node).parameters, cbNodes, result);
result = reduceNode((<ConstructorDeclaration>node).body, cbNode, result);
break;
case SyntaxKind.GetAccessor:
result = reduceLeft((<GetAccessorDeclaration>node).decorators, f, result);
result = reduceLeft((<GetAccessorDeclaration>node).modifiers, f, result);
result = reduceNode((<GetAccessorDeclaration>node).name, f, result);
result = reduceLeft((<GetAccessorDeclaration>node).parameters, f, result);
result = reduceNode((<GetAccessorDeclaration>node).type, f, result);
result = reduceNode((<GetAccessorDeclaration>node).body, f, result);
result = reduceNodes((<GetAccessorDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<GetAccessorDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<GetAccessorDeclaration>node).name, cbNode, result);
result = reduceNodes((<GetAccessorDeclaration>node).parameters, cbNodes, result);
result = reduceNode((<GetAccessorDeclaration>node).type, cbNode, result);
result = reduceNode((<GetAccessorDeclaration>node).body, cbNode, result);
break;
case SyntaxKind.SetAccessor:
result = reduceLeft((<GetAccessorDeclaration>node).decorators, f, result);
result = reduceLeft((<GetAccessorDeclaration>node).modifiers, f, result);
result = reduceNode((<GetAccessorDeclaration>node).name, f, result);
result = reduceLeft((<GetAccessorDeclaration>node).parameters, f, result);
result = reduceNode((<GetAccessorDeclaration>node).body, f, result);
result = reduceNodes((<GetAccessorDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<GetAccessorDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<GetAccessorDeclaration>node).name, cbNode, result);
result = reduceNodes((<GetAccessorDeclaration>node).parameters, cbNodes, result);
result = reduceNode((<GetAccessorDeclaration>node).body, cbNode, result);
break;
// Binding patterns
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
result = reduceLeft((<BindingPattern>node).elements, f, result);
result = reduceNodes((<BindingPattern>node).elements, cbNodes, result);
break;
case SyntaxKind.BindingElement:
result = reduceNode((<BindingElement>node).propertyName, f, result);
result = reduceNode((<BindingElement>node).name, f, result);
result = reduceNode((<BindingElement>node).initializer, f, result);
result = reduceNode((<BindingElement>node).propertyName, cbNode, result);
result = reduceNode((<BindingElement>node).name, cbNode, result);
result = reduceNode((<BindingElement>node).initializer, cbNode, result);
break;
// Expression
case SyntaxKind.ArrayLiteralExpression:
result = reduceLeft((<ArrayLiteralExpression>node).elements, f, result);
result = reduceNodes((<ArrayLiteralExpression>node).elements, cbNodes, result);
break;
case SyntaxKind.ObjectLiteralExpression:
result = reduceLeft((<ObjectLiteralExpression>node).properties, f, result);
result = reduceNodes((<ObjectLiteralExpression>node).properties, cbNodes, result);
break;
case SyntaxKind.PropertyAccessExpression:
result = reduceNode((<PropertyAccessExpression>node).expression, f, result);
result = reduceNode((<PropertyAccessExpression>node).name, f, result);
result = reduceNode((<PropertyAccessExpression>node).expression, cbNode, result);
result = reduceNode((<PropertyAccessExpression>node).name, cbNode, result);
break;
case SyntaxKind.ElementAccessExpression:
result = reduceNode((<ElementAccessExpression>node).expression, f, result);
result = reduceNode((<ElementAccessExpression>node).argumentExpression, f, result);
result = reduceNode((<ElementAccessExpression>node).expression, cbNode, result);
result = reduceNode((<ElementAccessExpression>node).argumentExpression, cbNode, result);
break;
case SyntaxKind.CallExpression:
result = reduceNode((<CallExpression>node).expression, f, result);
result = reduceLeft((<CallExpression>node).typeArguments, f, result);
result = reduceLeft((<CallExpression>node).arguments, f, result);
result = reduceNode((<CallExpression>node).expression, cbNode, result);
result = reduceNodes((<CallExpression>node).typeArguments, cbNodes, result);
result = reduceNodes((<CallExpression>node).arguments, cbNodes, result);
break;
case SyntaxKind.NewExpression:
result = reduceNode((<NewExpression>node).expression, f, result);
result = reduceLeft((<NewExpression>node).typeArguments, f, result);
result = reduceLeft((<NewExpression>node).arguments, f, result);
result = reduceNode((<NewExpression>node).expression, cbNode, result);
result = reduceNodes((<NewExpression>node).typeArguments, cbNodes, result);
result = reduceNodes((<NewExpression>node).arguments, cbNodes, result);
break;
case SyntaxKind.TaggedTemplateExpression:
result = reduceNode((<TaggedTemplateExpression>node).tag, f, result);
result = reduceNode((<TaggedTemplateExpression>node).template, f, result);
result = reduceNode((<TaggedTemplateExpression>node).tag, cbNode, result);
result = reduceNode((<TaggedTemplateExpression>node).template, cbNode, result);
break;
case SyntaxKind.FunctionExpression:
result = reduceLeft((<FunctionExpression>node).modifiers, f, result);
result = reduceNode((<FunctionExpression>node).name, f, result);
result = reduceLeft((<FunctionExpression>node).typeParameters, f, result);
result = reduceLeft((<FunctionExpression>node).parameters, f, result);
result = reduceNode((<FunctionExpression>node).type, f, result);
result = reduceNode((<FunctionExpression>node).body, f, result);
result = reduceNodes((<FunctionExpression>node).modifiers, cbNodes, result);
result = reduceNode((<FunctionExpression>node).name, cbNode, result);
result = reduceNodes((<FunctionExpression>node).typeParameters, cbNodes, result);
result = reduceNodes((<FunctionExpression>node).parameters, cbNodes, result);
result = reduceNode((<FunctionExpression>node).type, cbNode, result);
result = reduceNode((<FunctionExpression>node).body, cbNode, result);
break;
case SyntaxKind.ArrowFunction:
result = reduceLeft((<ArrowFunction>node).modifiers, f, result);
result = reduceLeft((<ArrowFunction>node).typeParameters, f, result);
result = reduceLeft((<ArrowFunction>node).parameters, f, result);
result = reduceNode((<ArrowFunction>node).type, f, result);
result = reduceNode((<ArrowFunction>node).body, f, result);
result = reduceNodes((<ArrowFunction>node).modifiers, cbNodes, result);
result = reduceNodes((<ArrowFunction>node).typeParameters, cbNodes, result);
result = reduceNodes((<ArrowFunction>node).parameters, cbNodes, result);
result = reduceNode((<ArrowFunction>node).type, cbNode, result);
result = reduceNode((<ArrowFunction>node).body, cbNode, result);
break;
case SyntaxKind.ParenthesizedExpression:
@@ -269,258 +275,258 @@ namespace ts {
case SyntaxKind.YieldExpression:
case SyntaxKind.SpreadElement:
case SyntaxKind.NonNullExpression:
result = reduceNode((<ParenthesizedExpression | DeleteExpression | TypeOfExpression | VoidExpression | AwaitExpression | YieldExpression | SpreadElement | NonNullExpression>node).expression, f, result);
result = reduceNode((<ParenthesizedExpression | DeleteExpression | TypeOfExpression | VoidExpression | AwaitExpression | YieldExpression | SpreadElement | NonNullExpression>node).expression, cbNode, result);
break;
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
result = reduceNode((<PrefixUnaryExpression | PostfixUnaryExpression>node).operand, f, result);
result = reduceNode((<PrefixUnaryExpression | PostfixUnaryExpression>node).operand, cbNode, result);
break;
case SyntaxKind.BinaryExpression:
result = reduceNode((<BinaryExpression>node).left, f, result);
result = reduceNode((<BinaryExpression>node).right, f, result);
result = reduceNode((<BinaryExpression>node).left, cbNode, result);
result = reduceNode((<BinaryExpression>node).right, cbNode, result);
break;
case SyntaxKind.ConditionalExpression:
result = reduceNode((<ConditionalExpression>node).condition, f, result);
result = reduceNode((<ConditionalExpression>node).whenTrue, f, result);
result = reduceNode((<ConditionalExpression>node).whenFalse, f, result);
result = reduceNode((<ConditionalExpression>node).condition, cbNode, result);
result = reduceNode((<ConditionalExpression>node).whenTrue, cbNode, result);
result = reduceNode((<ConditionalExpression>node).whenFalse, cbNode, result);
break;
case SyntaxKind.TemplateExpression:
result = reduceNode((<TemplateExpression>node).head, f, result);
result = reduceLeft((<TemplateExpression>node).templateSpans, f, result);
result = reduceNode((<TemplateExpression>node).head, cbNode, result);
result = reduceNodes((<TemplateExpression>node).templateSpans, cbNodes, result);
break;
case SyntaxKind.ClassExpression:
result = reduceLeft((<ClassExpression>node).modifiers, f, result);
result = reduceNode((<ClassExpression>node).name, f, result);
result = reduceLeft((<ClassExpression>node).typeParameters, f, result);
result = reduceLeft((<ClassExpression>node).heritageClauses, f, result);
result = reduceLeft((<ClassExpression>node).members, f, result);
result = reduceNodes((<ClassExpression>node).modifiers, cbNodes, result);
result = reduceNode((<ClassExpression>node).name, cbNode, result);
result = reduceNodes((<ClassExpression>node).typeParameters, cbNodes, result);
result = reduceNodes((<ClassExpression>node).heritageClauses, cbNodes, result);
result = reduceNodes((<ClassExpression>node).members, cbNodes, result);
break;
case SyntaxKind.ExpressionWithTypeArguments:
result = reduceNode((<ExpressionWithTypeArguments>node).expression, f, result);
result = reduceLeft((<ExpressionWithTypeArguments>node).typeArguments, f, result);
result = reduceNode((<ExpressionWithTypeArguments>node).expression, cbNode, result);
result = reduceNodes((<ExpressionWithTypeArguments>node).typeArguments, cbNodes, result);
break;
// Misc
case SyntaxKind.TemplateSpan:
result = reduceNode((<TemplateSpan>node).expression, f, result);
result = reduceNode((<TemplateSpan>node).literal, f, result);
result = reduceNode((<TemplateSpan>node).expression, cbNode, result);
result = reduceNode((<TemplateSpan>node).literal, cbNode, result);
break;
// Element
case SyntaxKind.Block:
result = reduceLeft((<Block>node).statements, f, result);
result = reduceNodes((<Block>node).statements, cbNodes, result);
break;
case SyntaxKind.VariableStatement:
result = reduceLeft((<VariableStatement>node).modifiers, f, result);
result = reduceNode((<VariableStatement>node).declarationList, f, result);
result = reduceNodes((<VariableStatement>node).modifiers, cbNodes, result);
result = reduceNode((<VariableStatement>node).declarationList, cbNode, result);
break;
case SyntaxKind.ExpressionStatement:
result = reduceNode((<ExpressionStatement>node).expression, f, result);
result = reduceNode((<ExpressionStatement>node).expression, cbNode, result);
break;
case SyntaxKind.IfStatement:
result = reduceNode((<IfStatement>node).expression, f, result);
result = reduceNode((<IfStatement>node).thenStatement, f, result);
result = reduceNode((<IfStatement>node).elseStatement, f, result);
result = reduceNode((<IfStatement>node).expression, cbNode, result);
result = reduceNode((<IfStatement>node).thenStatement, cbNode, result);
result = reduceNode((<IfStatement>node).elseStatement, cbNode, result);
break;
case SyntaxKind.DoStatement:
result = reduceNode((<DoStatement>node).statement, f, result);
result = reduceNode((<DoStatement>node).expression, f, result);
result = reduceNode((<DoStatement>node).statement, cbNode, result);
result = reduceNode((<DoStatement>node).expression, cbNode, result);
break;
case SyntaxKind.WhileStatement:
case SyntaxKind.WithStatement:
result = reduceNode((<WhileStatement | WithStatement>node).expression, f, result);
result = reduceNode((<WhileStatement | WithStatement>node).statement, f, result);
result = reduceNode((<WhileStatement | WithStatement>node).expression, cbNode, result);
result = reduceNode((<WhileStatement | WithStatement>node).statement, cbNode, result);
break;
case SyntaxKind.ForStatement:
result = reduceNode((<ForStatement>node).initializer, f, result);
result = reduceNode((<ForStatement>node).condition, f, result);
result = reduceNode((<ForStatement>node).incrementor, f, result);
result = reduceNode((<ForStatement>node).statement, f, result);
result = reduceNode((<ForStatement>node).initializer, cbNode, result);
result = reduceNode((<ForStatement>node).condition, cbNode, result);
result = reduceNode((<ForStatement>node).incrementor, cbNode, result);
result = reduceNode((<ForStatement>node).statement, cbNode, result);
break;
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
result = reduceNode((<ForInStatement | ForOfStatement>node).initializer, f, result);
result = reduceNode((<ForInStatement | ForOfStatement>node).expression, f, result);
result = reduceNode((<ForInStatement | ForOfStatement>node).statement, f, result);
result = reduceNode((<ForInStatement | ForOfStatement>node).initializer, cbNode, result);
result = reduceNode((<ForInStatement | ForOfStatement>node).expression, cbNode, result);
result = reduceNode((<ForInStatement | ForOfStatement>node).statement, cbNode, result);
break;
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
result = reduceNode((<ReturnStatement>node).expression, f, result);
result = reduceNode((<ReturnStatement>node).expression, cbNode, result);
break;
case SyntaxKind.SwitchStatement:
result = reduceNode((<SwitchStatement>node).expression, f, result);
result = reduceNode((<SwitchStatement>node).caseBlock, f, result);
result = reduceNode((<SwitchStatement>node).expression, cbNode, result);
result = reduceNode((<SwitchStatement>node).caseBlock, cbNode, result);
break;
case SyntaxKind.LabeledStatement:
result = reduceNode((<LabeledStatement>node).label, f, result);
result = reduceNode((<LabeledStatement>node).statement, f, result);
result = reduceNode((<LabeledStatement>node).label, cbNode, result);
result = reduceNode((<LabeledStatement>node).statement, cbNode, result);
break;
case SyntaxKind.TryStatement:
result = reduceNode((<TryStatement>node).tryBlock, f, result);
result = reduceNode((<TryStatement>node).catchClause, f, result);
result = reduceNode((<TryStatement>node).finallyBlock, f, result);
result = reduceNode((<TryStatement>node).tryBlock, cbNode, result);
result = reduceNode((<TryStatement>node).catchClause, cbNode, result);
result = reduceNode((<TryStatement>node).finallyBlock, cbNode, result);
break;
case SyntaxKind.VariableDeclaration:
result = reduceNode((<VariableDeclaration>node).name, f, result);
result = reduceNode((<VariableDeclaration>node).type, f, result);
result = reduceNode((<VariableDeclaration>node).initializer, f, result);
result = reduceNode((<VariableDeclaration>node).name, cbNode, result);
result = reduceNode((<VariableDeclaration>node).type, cbNode, result);
result = reduceNode((<VariableDeclaration>node).initializer, cbNode, result);
break;
case SyntaxKind.VariableDeclarationList:
result = reduceLeft((<VariableDeclarationList>node).declarations, f, result);
result = reduceNodes((<VariableDeclarationList>node).declarations, cbNodes, result);
break;
case SyntaxKind.FunctionDeclaration:
result = reduceLeft((<FunctionDeclaration>node).decorators, f, result);
result = reduceLeft((<FunctionDeclaration>node).modifiers, f, result);
result = reduceNode((<FunctionDeclaration>node).name, f, result);
result = reduceLeft((<FunctionDeclaration>node).typeParameters, f, result);
result = reduceLeft((<FunctionDeclaration>node).parameters, f, result);
result = reduceNode((<FunctionDeclaration>node).type, f, result);
result = reduceNode((<FunctionDeclaration>node).body, f, result);
result = reduceNodes((<FunctionDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<FunctionDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<FunctionDeclaration>node).name, cbNode, result);
result = reduceNodes((<FunctionDeclaration>node).typeParameters, cbNodes, result);
result = reduceNodes((<FunctionDeclaration>node).parameters, cbNodes, result);
result = reduceNode((<FunctionDeclaration>node).type, cbNode, result);
result = reduceNode((<FunctionDeclaration>node).body, cbNode, result);
break;
case SyntaxKind.ClassDeclaration:
result = reduceLeft((<ClassDeclaration>node).decorators, f, result);
result = reduceLeft((<ClassDeclaration>node).modifiers, f, result);
result = reduceNode((<ClassDeclaration>node).name, f, result);
result = reduceLeft((<ClassDeclaration>node).typeParameters, f, result);
result = reduceLeft((<ClassDeclaration>node).heritageClauses, f, result);
result = reduceLeft((<ClassDeclaration>node).members, f, result);
result = reduceNodes((<ClassDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<ClassDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<ClassDeclaration>node).name, cbNode, result);
result = reduceNodes((<ClassDeclaration>node).typeParameters, cbNodes, result);
result = reduceNodes((<ClassDeclaration>node).heritageClauses, cbNodes, result);
result = reduceNodes((<ClassDeclaration>node).members, cbNodes, result);
break;
case SyntaxKind.CaseBlock:
result = reduceLeft((<CaseBlock>node).clauses, f, result);
result = reduceNodes((<CaseBlock>node).clauses, cbNodes, result);
break;
case SyntaxKind.ImportDeclaration:
result = reduceLeft((<ImportDeclaration>node).decorators, f, result);
result = reduceLeft((<ImportDeclaration>node).modifiers, f, result);
result = reduceNode((<ImportDeclaration>node).importClause, f, result);
result = reduceNode((<ImportDeclaration>node).moduleSpecifier, f, result);
result = reduceNodes((<ImportDeclaration>node).decorators, cbNodes, result);
result = reduceNodes((<ImportDeclaration>node).modifiers, cbNodes, result);
result = reduceNode((<ImportDeclaration>node).importClause, cbNode, result);
result = reduceNode((<ImportDeclaration>node).moduleSpecifier, cbNode, result);
break;
case SyntaxKind.ImportClause:
result = reduceNode((<ImportClause>node).name, f, result);
result = reduceNode((<ImportClause>node).namedBindings, f, result);
result = reduceNode((<ImportClause>node).name, cbNode, result);
result = reduceNode((<ImportClause>node).namedBindings, cbNode, result);
break;
case SyntaxKind.NamespaceImport:
result = reduceNode((<NamespaceImport>node).name, f, result);
result = reduceNode((<NamespaceImport>node).name, cbNode, result);
break;
case SyntaxKind.NamedImports:
case SyntaxKind.NamedExports:
result = reduceLeft((<NamedImports | NamedExports>node).elements, f, result);
result = reduceNodes((<NamedImports | NamedExports>node).elements, cbNodes, result);
break;
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
result = reduceNode((<ImportSpecifier | ExportSpecifier>node).propertyName, f, result);
result = reduceNode((<ImportSpecifier | ExportSpecifier>node).name, f, result);
result = reduceNode((<ImportSpecifier | ExportSpecifier>node).propertyName, cbNode, result);
result = reduceNode((<ImportSpecifier | ExportSpecifier>node).name, cbNode, result);
break;
case SyntaxKind.ExportAssignment:
result = reduceLeft((<ExportAssignment>node).decorators, f, result);
result = reduceLeft((<ExportAssignment>node).modifiers, f, result);
result = reduceNode((<ExportAssignment>node).expression, f, result);
result = reduceLeft((<ExportAssignment>node).decorators, cbNode, result);
result = reduceLeft((<ExportAssignment>node).modifiers, cbNode, result);
result = reduceNode((<ExportAssignment>node).expression, cbNode, result);
break;
case SyntaxKind.ExportDeclaration:
result = reduceLeft((<ExportDeclaration>node).decorators, f, result);
result = reduceLeft((<ExportDeclaration>node).modifiers, f, result);
result = reduceNode((<ExportDeclaration>node).exportClause, f, result);
result = reduceNode((<ExportDeclaration>node).moduleSpecifier, f, result);
result = reduceLeft((<ExportDeclaration>node).decorators, cbNode, result);
result = reduceLeft((<ExportDeclaration>node).modifiers, cbNode, result);
result = reduceNode((<ExportDeclaration>node).exportClause, cbNode, result);
result = reduceNode((<ExportDeclaration>node).moduleSpecifier, cbNode, result);
break;
// JSX
case SyntaxKind.JsxElement:
result = reduceNode((<JsxElement>node).openingElement, f, result);
result = reduceLeft((<JsxElement>node).children, f, result);
result = reduceNode((<JsxElement>node).closingElement, f, result);
result = reduceNode((<JsxElement>node).openingElement, cbNode, result);
result = reduceLeft((<JsxElement>node).children, cbNode, result);
result = reduceNode((<JsxElement>node).closingElement, cbNode, result);
break;
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxOpeningElement:
result = reduceNode((<JsxSelfClosingElement | JsxOpeningElement>node).tagName, f, result);
result = reduceLeft((<JsxSelfClosingElement | JsxOpeningElement>node).attributes, f, result);
result = reduceNode((<JsxSelfClosingElement | JsxOpeningElement>node).tagName, cbNode, result);
result = reduceNodes((<JsxSelfClosingElement | JsxOpeningElement>node).attributes, cbNodes, result);
break;
case SyntaxKind.JsxClosingElement:
result = reduceNode((<JsxClosingElement>node).tagName, f, result);
result = reduceNode((<JsxClosingElement>node).tagName, cbNode, result);
break;
case SyntaxKind.JsxAttribute:
result = reduceNode((<JsxAttribute>node).name, f, result);
result = reduceNode((<JsxAttribute>node).initializer, f, result);
result = reduceNode((<JsxAttribute>node).name, cbNode, result);
result = reduceNode((<JsxAttribute>node).initializer, cbNode, result);
break;
case SyntaxKind.JsxSpreadAttribute:
result = reduceNode((<JsxSpreadAttribute>node).expression, f, result);
result = reduceNode((<JsxSpreadAttribute>node).expression, cbNode, result);
break;
case SyntaxKind.JsxExpression:
result = reduceNode((<JsxExpression>node).expression, f, result);
result = reduceNode((<JsxExpression>node).expression, cbNode, result);
break;
// Clauses
case SyntaxKind.CaseClause:
result = reduceNode((<CaseClause>node).expression, f, result);
result = reduceNode((<CaseClause>node).expression, cbNode, result);
// fall-through
case SyntaxKind.DefaultClause:
result = reduceLeft((<CaseClause | DefaultClause>node).statements, f, result);
result = reduceNodes((<CaseClause | DefaultClause>node).statements, cbNodes, result);
break;
case SyntaxKind.HeritageClause:
result = reduceLeft((<HeritageClause>node).types, f, result);
result = reduceNodes((<HeritageClause>node).types, cbNodes, result);
break;
case SyntaxKind.CatchClause:
result = reduceNode((<CatchClause>node).variableDeclaration, f, result);
result = reduceNode((<CatchClause>node).block, f, result);
result = reduceNode((<CatchClause>node).variableDeclaration, cbNode, result);
result = reduceNode((<CatchClause>node).block, cbNode, result);
break;
// Property assignments
case SyntaxKind.PropertyAssignment:
result = reduceNode((<PropertyAssignment>node).name, f, result);
result = reduceNode((<PropertyAssignment>node).initializer, f, result);
result = reduceNode((<PropertyAssignment>node).name, cbNode, result);
result = reduceNode((<PropertyAssignment>node).initializer, cbNode, result);
break;
case SyntaxKind.ShorthandPropertyAssignment:
result = reduceNode((<ShorthandPropertyAssignment>node).name, f, result);
result = reduceNode((<ShorthandPropertyAssignment>node).objectAssignmentInitializer, f, result);
result = reduceNode((<ShorthandPropertyAssignment>node).name, cbNode, result);
result = reduceNode((<ShorthandPropertyAssignment>node).objectAssignmentInitializer, cbNode, result);
break;
case SyntaxKind.SpreadAssignment:
result = reduceNode((node as SpreadAssignment).expression, f, result);
result = reduceNode((node as SpreadAssignment).expression, cbNode, result);
break;
// Top-level nodes
case SyntaxKind.SourceFile:
result = reduceLeft((<SourceFile>node).statements, f, result);
result = reduceNodes((<SourceFile>node).statements, cbNodes, result);
break;
case SyntaxKind.PartiallyEmittedExpression:
result = reduceNode((<PartiallyEmittedExpression>node).expression, f, result);
result = reduceNode((<PartiallyEmittedExpression>node).expression, cbNode, result);
break;
default:
@@ -530,8 +536,8 @@ namespace ts {
const value = (<MapLike<any>>node)[edge.name];
if (value !== undefined) {
result = isArray(value)
? reduceLeft(<NodeArray<Node>>value, f, result)
: f(result, <Node>value);
? reduceNodes(<NodeArray<Node>>value, cbNodes, result)
: cbNode(result, <Node>value);
}
}
}
@@ -553,8 +559,8 @@ namespace ts {
export function visitNode<T extends Node>(node: T, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, optional?: boolean, lift?: (node: NodeArray<Node>) => T): T;
export function visitNode<T extends Node>(node: T, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, optional: boolean, lift: (node: NodeArray<Node>) => T, parenthesize: (node: Node, parentNode: Node) => Node, parentNode: Node): T;
export function visitNode(node: Node, visitor: (node: Node) => VisitResult<Node>, test: (node: Node) => boolean, optional?: boolean, lift?: (node: Node[]) => Node, parenthesize?: (node: Node, parentNode: Node) => Node, parentNode?: Node): Node {
if (node === undefined) {
return undefined;
if (node === undefined || visitor === undefined) {
return node;
}
aggregateTransformFlags(node);
@@ -669,8 +675,8 @@ namespace ts {
if (ensureUseStrict && !startsWithUseStrict(statements)) {
statements = createNodeArray([createStatement(createLiteral("use strict")), ...statements], statements);
}
statements = mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
return statements;
const declarations = context.endLexicalEnvironment();
return createNodeArray(concatenate(statements, declarations), statements);
}
/**
@@ -688,15 +694,15 @@ namespace ts {
* Resumes a suspended lexical environment and visits a function body, ending the lexical
* environment and merging hoisted declarations upon completion.
*/
export function visitFunctionBody(node: FunctionBody, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext, optional?: boolean): FunctionBody;
export function visitFunctionBody(node: FunctionBody, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext): FunctionBody;
/**
* Resumes a suspended lexical environment and visits a concise body, ending the lexical
* environment and merging hoisted declarations upon completion.
*/
export function visitFunctionBody(node: ConciseBody, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext): ConciseBody;
export function visitFunctionBody(node: ConciseBody, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext, optional?: boolean): ConciseBody {
export function visitFunctionBody(node: ConciseBody, visitor: (node: Node) => VisitResult<Node>, context: TransformationContext): ConciseBody {
context.resumeLexicalEnvironment();
const updated = visitNode(node, visitor, isConciseBody, optional);
const updated = visitNode(node, visitor, isConciseBody);
const declarations = context.endLexicalEnvironment();
if (some(declarations)) {
const block = convertToFunctionBody(updated);
@@ -748,6 +754,7 @@ namespace ts {
return updateParameter(<ParameterDeclaration>node,
visitNodes((<ParameterDeclaration>node).decorators, visitor, isDecorator),
visitNodes((<ParameterDeclaration>node).modifiers, visitor, isModifier),
(<ParameterDeclaration>node).dotDotDotToken,
visitNode((<ParameterDeclaration>node).name, visitor, isBindingName),
visitNode((<ParameterDeclaration>node).type, visitor, isTypeNode, /*optional*/ true),
visitNode((<ParameterDeclaration>node).initializer, visitor, isExpression, /*optional*/ true));
@@ -769,14 +776,14 @@ namespace ts {
visitNodes((<MethodDeclaration>node).typeParameters, visitor, isTypeParameter),
visitParameterList((<MethodDeclaration>node).parameters, visitor, context),
visitNode((<MethodDeclaration>node).type, visitor, isTypeNode, /*optional*/ true),
visitFunctionBody((<MethodDeclaration>node).body, visitor, context, /*optional*/ true));
visitFunctionBody((<MethodDeclaration>node).body, visitor, context));
case SyntaxKind.Constructor:
return updateConstructor(<ConstructorDeclaration>node,
visitNodes((<ConstructorDeclaration>node).decorators, visitor, isDecorator),
visitNodes((<ConstructorDeclaration>node).modifiers, visitor, isModifier),
visitParameterList((<ConstructorDeclaration>node).parameters, visitor, context),
visitFunctionBody((<ConstructorDeclaration>node).body, visitor, context, /*optional*/ true));
visitFunctionBody((<ConstructorDeclaration>node).body, visitor, context));
case SyntaxKind.GetAccessor:
return updateGetAccessor(<GetAccessorDeclaration>node,
@@ -785,7 +792,7 @@ namespace ts {
visitNode((<GetAccessorDeclaration>node).name, visitor, isPropertyName),
visitParameterList((<GetAccessorDeclaration>node).parameters, visitor, context),
visitNode((<GetAccessorDeclaration>node).type, visitor, isTypeNode, /*optional*/ true),
visitFunctionBody((<GetAccessorDeclaration>node).body, visitor, context, /*optional*/ true));
visitFunctionBody((<GetAccessorDeclaration>node).body, visitor, context));
case SyntaxKind.SetAccessor:
return updateSetAccessor(<SetAccessorDeclaration>node,
@@ -793,7 +800,7 @@ namespace ts {
visitNodes((<SetAccessorDeclaration>node).modifiers, visitor, isModifier),
visitNode((<SetAccessorDeclaration>node).name, visitor, isPropertyName),
visitParameterList((<SetAccessorDeclaration>node).parameters, visitor, context),
visitFunctionBody((<SetAccessorDeclaration>node).body, visitor, context, /*optional*/ true));
visitFunctionBody((<SetAccessorDeclaration>node).body, visitor, context));
// Binding patterns
case SyntaxKind.ObjectBindingPattern:
@@ -806,6 +813,7 @@ namespace ts {
case SyntaxKind.BindingElement:
return updateBindingElement(<BindingElement>node,
(<BindingElement>node).dotDotDotToken,
visitNode((<BindingElement>node).propertyName, visitor, isPropertyName, /*optional*/ true),
visitNode((<BindingElement>node).name, visitor, isBindingName),
visitNode((<BindingElement>node).initializer, visitor, isExpression, /*optional*/ true));
@@ -857,7 +865,7 @@ namespace ts {
visitNodes((<FunctionExpression>node).typeParameters, visitor, isTypeParameter),
visitParameterList((<FunctionExpression>node).parameters, visitor, context),
visitNode((<FunctionExpression>node).type, visitor, isTypeNode, /*optional*/ true),
visitFunctionBody((<FunctionExpression>node).body, visitor, context, /*optional*/ true));
visitFunctionBody((<FunctionExpression>node).body, visitor, context));
case SyntaxKind.ArrowFunction:
return updateArrowFunction(<ArrowFunction>node,
@@ -1038,7 +1046,7 @@ namespace ts {
visitNodes((<FunctionDeclaration>node).typeParameters, visitor, isTypeParameter),
visitParameterList((<FunctionDeclaration>node).parameters, visitor, context),
visitNode((<FunctionDeclaration>node).type, visitor, isTypeNode, /*optional*/ true),
visitFunctionBody((<FunctionExpression>node).body, visitor, context, /*optional*/ true));
visitFunctionBody((<FunctionExpression>node).body, visitor, context));
case SyntaxKind.ClassDeclaration:
return updateClassDeclaration(<ClassDeclaration>node,
@@ -1170,7 +1178,6 @@ namespace ts {
// Top-level nodes
case SyntaxKind.SourceFile:
context.startLexicalEnvironment();
return updateSourceFileNode(<SourceFile>node,
visitLexicalEnvironment((<SourceFile>node).statements, visitor, context));
@@ -1294,13 +1301,25 @@ namespace ts {
if (node === undefined) {
return TransformFlags.None;
}
else if (node.transformFlags & TransformFlags.HasComputedFlags) {
if (node.transformFlags & TransformFlags.HasComputedFlags) {
return node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
}
else {
const subtreeFlags = aggregateTransformFlagsForSubtree(node);
return computeTransformFlagsForNode(node, subtreeFlags);
const subtreeFlags = aggregateTransformFlagsForSubtree(node);
return computeTransformFlagsForNode(node, subtreeFlags);
}
function aggregateTransformFlagsForNodeArray(nodes: NodeArray<Node>): TransformFlags {
if (nodes === undefined) {
return TransformFlags.None;
}
let subtreeFlags = TransformFlags.None;
let nodeArrayFlags = TransformFlags.None;
for (const node of nodes) {
subtreeFlags |= aggregateTransformFlagsForNode(node);
nodeArrayFlags |= node.transformFlags & ~TransformFlags.HasComputedFlags;
}
nodes.transformFlags = nodeArrayFlags | TransformFlags.HasComputedFlags;
return subtreeFlags;
}
/**
@@ -1314,15 +1333,19 @@ namespace ts {
}
// Aggregate the transform flags of each child.
return reduceEachChild(node, aggregateTransformFlagsForChildNode, TransformFlags.None);
return reduceEachChild(node, TransformFlags.None, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes);
}
/**
* Aggregates the TransformFlags of a child node with the TransformFlags of its
* siblings.
*/
function aggregateTransformFlagsForChildNode(transformFlags: TransformFlags, child: Node): TransformFlags {
return transformFlags | aggregateTransformFlagsForNode(child);
function aggregateTransformFlagsForChildNode(transformFlags: TransformFlags, node: Node): TransformFlags {
return transformFlags | aggregateTransformFlagsForNode(node);
}
function aggregateTransformFlagsForChildNodes(transformFlags: TransformFlags, nodes: NodeArray<Node>): TransformFlags {
return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
}
export namespace Debug {
@@ -1334,6 +1357,13 @@ namespace ts {
? (node: Node, message?: string) => assert(false, message || "Unexpected node.", () => `Node ${formatSyntaxKind(node.kind)} was unexpected.`)
: noop;
export const assertEachNode = shouldAssert(AssertionLevel.Normal)
? (nodes: Node[], test: (node: Node) => boolean, message?: string) => assert(
test === undefined || every(nodes, test),
message || "Unexpected node.",
() => `Node array did not pass test '${getFunctionName(test)}'.`)
: noop;
export const assertNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, test: (node: Node) => boolean, message?: string) => assert(
test === undefined || test(node),
@@ -1341,6 +1371,27 @@ namespace ts {
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`)
: noop;
export const assertOptionalNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, test: (node: Node) => boolean, message?: string) => assert(
test === undefined || node === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`)
: noop;
export const assertOptionalToken = shouldAssert(AssertionLevel.Normal)
? (node: Node, kind: SyntaxKind, message?: string) => assert(
kind === undefined || node === undefined || node.kind === kind,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} was not a '${formatSyntaxKind(kind)}' token.`)
: noop;
export const assertMissingNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, message?: string) => assert(
node === undefined,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} was unexpected'.`)
: noop;
function getFunctionName(func: Function) {
if (typeof func !== "function") {
return "";
+4
View File
@@ -61,6 +61,10 @@ function createRunner(kind: TestRunnerKind): RunnerBase {
}
}
if (Harness.IO.tryEnableSourceMapsForHost && /^development$/i.test(Harness.IO.getEnvironmentVariable("NODE_ENV"))) {
Harness.IO.tryEnableSourceMapsForHost();
}
// users can define tests to run in mytest.config that will override cmd line args, otherwise use cmd line args (test.config), otherwise no options
const mytestconfigFileName = "mytest.config";
+1 -1
View File
@@ -1188,7 +1188,7 @@ namespace ts.FindAllReferences {
if (node.name.kind === SyntaxKind.ComputedPropertyName) {
const nameExpression = (<ComputedPropertyName>node.name).expression;
// treat computed property names where expression is string/numeric literal as just string/numeric literal
if (isStringOrNumericLiteral(nameExpression.kind)) {
if (isStringOrNumericLiteral(nameExpression)) {
return (<LiteralExpression>nameExpression).text;
}
return undefined;
+1 -1
View File
@@ -1282,7 +1282,7 @@ namespace ts {
if (isImportOrExportSpecifierName(location)) {
return location.getText();
}
else if (isStringOrNumericLiteral(location.kind) &&
else if (isStringOrNumericLiteral(location) &&
location.parent.kind === SyntaxKind.ComputedPropertyName) {
return (<LiteralExpression>location).text;
}
@@ -37,17 +37,17 @@ x = [true][0];
x; // boolean
_a = [1][0], x = _a === void 0 ? "" : _a;
x; // string | number
(_b = { x: true }, x = _b.x, _b);
(x = { x: true }.x);
x; // boolean
(_c = { y: 1 }, x = _c.y, _c);
(x = { y: 1 }.y);
x; // number
(_d = { x: true }, _e = _d.x, x = _e === void 0 ? "" : _e, _d);
(_b = { x: true }.x, x = _b === void 0 ? "" : _b);
x; // string | boolean
(_f = { y: 1 }, _g = _f.y, x = _g === void 0 ? /a/ : _g, _f);
(_c = { y: 1 }.y, x = _c === void 0 ? /a/ : _c);
x; // number | RegExp
var a;
for (var _i = 0, a_1 = a; _i < a_1.length; _i++) {
x = a_1[_i];
x; // string
}
var _a, _b, _c, _d, _e, _f, _g;
var _a, _b, _c;
@@ -81,8 +81,8 @@ var B = (function (_super) {
// async method with assignment/destructuring on 'super' requires a binding
B.prototype.advanced = function () {
return __awaiter(this, void 0, void 0, function () {
var f, a, b, _a, _b;
return __generator(this, function (_c) {
var f, a, b;
return __generator(this, function (_a) {
f = function () { };
// call with property access
_super.prototype.x.call(this);
@@ -95,9 +95,9 @@ var B = (function (_super) {
// element access (assign)
_super.prototype["x"] = f;
// destructuring assign with property access
(_a = { f: f }, super.x = _a.f, _a);
(_super.prototype.x = { f: f }.f);
// destructuring assign with element access
(_b = { f: f }, super["x"] = _b.f, _b);
(_super.prototype["x"] = { f: f }.f);
return [2 /*return*/];
});
});
@@ -41,13 +41,13 @@ let [{[foo.toExponential()]: bar7}] = [{bar: "bar"}];
// destructuring in variable declarations
var foo = "bar";
var _a = foo, bar = { bar: "bar" }[_a];
var _b = "bar", bar2 = { bar: "bar" }[_b];
var bar2 = { bar: "bar" }["bar"];
var foo2 = function () { return "bar"; };
var _c = foo2(), bar3 = { bar: "bar" }[_c];
var _d = foo, bar4 = [{ bar: "bar" }][0][_d];
var _e = foo2(), bar5 = [{ bar: "bar" }][0][_e];
var _b = foo2(), bar3 = { bar: "bar" }[_b];
var _c = foo, bar4 = [{ bar: "bar" }][0][_c];
var _d = foo2(), bar5 = [{ bar: "bar" }][0][_d];
function f1(_a) {
var _b = "bar", x = _a[_b];
var x = _a["bar"];
}
function f2(_a) {
var _b = foo, x = _a[_b];
@@ -62,14 +62,14 @@ function f5(_a) {
var _b = foo2(), x = _a[0][_b];
}
// report errors on type errors in computed properties used in destructuring
var _f = foo(), bar6 = [{ bar: "bar" }][0][_f];
var _g = foo.toExponential(), bar7 = [{ bar: "bar" }][0][_g];
var _e = foo(), bar6 = [{ bar: "bar" }][0][_e];
var _f = foo.toExponential(), bar7 = [{ bar: "bar" }][0][_f];
// destructuring assignment
(_h = { bar: "bar" }, _j = foo, bar = _h[_j], _h);
(_k = { bar: "bar" }, _l = "bar", bar2 = _k[_l], _k);
(_m = { bar: "bar" }, _o = foo2(), bar3 = _m[_o], _m);
_p = foo, bar4 = [{ bar: "bar" }][0][_p];
_q = foo2(), bar5 = [{ bar: "bar" }][0][_q];
_r = foo(), bar4 = [{ bar: "bar" }][0][_r];
_s = (1 + {}), bar4 = [{ bar: "bar" }][0][_s];
var _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
(_g = foo, bar = { bar: "bar" }[_g]);
(bar2 = { bar: "bar" }["bar"]);
(_h = foo2(), bar3 = { bar: "bar" }[_h]);
_j = foo, bar4 = [{ bar: "bar" }][0][_j];
_k = foo2(), bar5 = [{ bar: "bar" }][0][_k];
_l = foo(), bar4 = [{ bar: "bar" }][0][_l];
_m = (1 + {}), bar4 = [{ bar: "bar" }][0][_m];
var _g, _h, _j, _k, _l, _m;
@@ -37,7 +37,7 @@ function f2(_a) {
var _b = _a["show"], showRename = _b === void 0 ? function (v) { return v.toString(); } : _b;
}
function f3(_a) {
var _b = "show", _c = _a[_b], showRename = _c === void 0 ? function (v) { return v.toString(); } : _c;
var _b = _a["show"], showRename = _b === void 0 ? function (v) { return v.toString(); } : _b;
}
function ff(_a) {
var _b = _a.nested, nested = _b === void 0 ? { show: function (v) { return v.toString(); } } : _b;
@@ -35,7 +35,7 @@ function f2(_a) {
var _b = _a["show"], showRename = _b === void 0 ? function (v) { return v; } : _b;
}
function f3(_a) {
var _b = "show", _c = _a[_b], showRename = _c === void 0 ? function (v) { return v; } : _c;
var _b = _a["show"], showRename = _b === void 0 ? function (v) { return v; } : _b;
}
function ff(_a) {
var _b = _a.nested, nestedRename = _b === void 0 ? { show: function (v) { return v; } } : _b;
@@ -300,8 +300,8 @@ function f18() {
var a;
var b;
var aa;
(_a = { a: a, b: b }, a = _a.a, b = _a.b, _a);
(_b = { b: b, a: a }, a = _b.a, b = _b.b, _b);
(_a = { a: a, b: b }, a = _a.a, b = _a.b);
(_b = { b: b, a: a }, a = _b.a, b = _b.b);
_c = [a, b], aa[0] = _c[0], b = _c[1];
_d = [b, a], a = _d[0], b = _d[1]; // Error
_e = [2, "def"], _f = _e[0], a = _f === void 0 ? 1 : _f, _g = _e[1], b = _g === void 0 ? "abc" : _g;
@@ -311,7 +311,7 @@ function f19() {
var a, b;
_a = [1, 2], a = _a[0], b = _a[1];
_b = [b, a], a = _b[0], b = _b[1];
(_c = { b: b, a: a }, a = _c.a, b = _c.b, _c);
(_c = { b: b, a: a }, a = _c.a, b = _c.b);
_d = [[2, 3]][0], _e = _d === void 0 ? [1, 2] : _d, a = _e[0], b = _e[1];
var x = (_f = [1, 2], a = _f[0], b = _f[1], _f);
var _a, _b, _c, _d, _e, _f;
@@ -7,5 +7,5 @@ let x = 0;
//// [destructuringAssignmentWithDefault.js]
var a = {};
var x = 0;
(_a = a.x, x = _a === void 0 ? 1 : _a, a);
(_a = a.x, x = _a === void 0 ? 1 : _a);
var _a;
@@ -9,8 +9,8 @@ let x, y, z, a1, a2, a3;
//// [emptyAssignmentPatterns02_ES5.js]
var a;
var x, y, z, a1, a2, a3;
(x = a.x, y = a.y, z = a.z, a);
(a1 = a[0], a2 = a[1], a3 = a[2], a);
(x = a.x, y = a.y, z = a.z);
(a1 = a[0], a2 = a[1], a3 = a[2]);
//// [emptyAssignmentPatterns02_ES5.d.ts]
@@ -9,9 +9,8 @@ let x, y, z, a1, a2, a3;
//// [emptyAssignmentPatterns04_ES5.js]
var a;
var x, y, z, a1, a2, a3;
(_a = a, x = _a.x, y = _a.y, z = _a.z, _a);
(_b = a, a1 = _b[0], a2 = _b[1], a3 = _b[2], _b);
var _a, _b;
(x = a.x, y = a.y, z = a.z);
(a1 = a[0], a2 = a[1], a3 = a[2]);
//// [emptyAssignmentPatterns04_ES5.d.ts]
@@ -28,7 +28,6 @@ if (true) {
var x_1 = { x: 0 }.x;
var y_1 = { y: 0 }.y;
var z_1;
(_a = { z: 0 }, z_1 = _a.z, _a);
(_b = { z: 0 }, z_1 = _b.z, _b);
(z_1 = { z: 0 }.z);
(z_1 = { z: 0 }.z);
}
var _a, _b;
@@ -45,10 +45,10 @@ function f1() {
// Missing properties
function f2() {
var x, y;
(_a = {}, x = _a.x, y = _a.y, _a);
(_b = {}, _c = _b.x, x = _c === void 0 ? 1 : _c, y = _b.y, _b);
(_d = {}, x = _d.x, _e = _d.y, y = _e === void 0 ? 1 : _e, _d);
(_f = {}, _g = _f.x, x = _g === void 0 ? 1 : _g, _h = _f.y, y = _h === void 0 ? 1 : _h, _f);
(_a = {}, x = _a.x, y = _a.y);
(_b = {}, _c = _b.x, x = _c === void 0 ? 1 : _c, y = _b.y);
(_d = {}, x = _d.x, _e = _d.y, y = _e === void 0 ? 1 : _e);
(_f = {}, _g = _f.x, x = _g === void 0 ? 1 : _g, _h = _f.y, y = _h === void 0 ? 1 : _h);
var _a, _b, _c, _d, _e, _f, _g, _h;
}
// Excess properties
@@ -62,8 +62,8 @@ function f3() {
function f4() {
var x, y;
({ x: 0, y: 0 });
(_a = { x: 0, y: 0 }, x = _a.x, _a);
(_b = { x: 0, y: 0 }, y = _b.y, _b);
(_c = { x: 0, y: 0 }, x = _c.x, y = _c.y, _c);
var _a, _b, _c;
(x = { x: 0, y: 0 }.x);
(y = { x: 0, y: 0 }.y);
(_a = { x: 0, y: 0 }, x = _a.x, y = _a.y);
var _a;
}
+10 -10
View File
@@ -52,18 +52,18 @@ var o = { a: 1, b: 'no' };
var clone = __rest(o, []);
var { a } = o, justB = __rest(o, ["a"]);
var { a, b: renamed } = o, empty = __rest(o, ["a", "b"]);
var _a = 'b', renamed = o[_a], justA = __rest(o, [typeof _a === "symbol" ? _a : _a + ""]);
var { 'b': renamed } = o, justA = __rest(o, ["b"]);
var { ['b']: renamed } = o, justA = __rest(o, ['b']);
var { 'b': renamed } = o, justA = __rest(o, ['b']);
var { b: { '0': n, '1': oooo } } = o, justA = __rest(o, ["b"]);
let o2 = { c: 'terrible idea?', d: 'yes' };
var { d: renamed } = o2, d = __rest(o2, ["d"]);
let nestedrest;
var { x } = nestedrest, _b = nestedrest.n1, { y } = _b, _c = _b.n2, { z } = _c, nr = __rest(_c.n3, []), restrest = __rest(nestedrest, ["x", "n1"]);
var { x } = nestedrest, _a = nestedrest.n1, { y } = _a, _b = _a.n2, { z } = _b, nr = __rest(_b.n3, []), restrest = __rest(nestedrest, ["x", "n1"]);
let complex;
var _d = complex.x, { ka } = _d, nested = __rest(_d, ["ka"]), { y: other } = complex, rest = __rest(complex, ["x", "y"]);
(_e = complex.x, { ka } = _e, nested = __rest(_e, ["ka"]), { y: other } = complex, rest = __rest(complex, ["x", "y"]), complex);
var _f = { x: 1, y: 2 }, { x } = _f, fresh = __rest(_f, ["x"]);
(_g = { x: 1, y: 2 }, { x } = _g, fresh = __rest(_g, ["x"]), _g);
var _c = complex.x, { ka } = _c, nested = __rest(_c, ["ka"]), { y: other } = complex, rest = __rest(complex, ["x", "y"]);
(_d = complex.x, { ka } = _d, nested = __rest(_d, ["ka"]), { y: other } = complex, rest = __rest(complex, ["x", "y"]));
var _e = { x: 1, y: 2 }, { x } = _e, fresh = __rest(_e, ["x"]);
(_f = { x: 1, y: 2 }, { x } = _f, fresh = __rest(_f, ["x"]));
class Removable {
set z(value) { }
get both() { return 12; }
@@ -74,6 +74,6 @@ var removable = new Removable();
var { removed } = removable, removableRest = __rest(removable, ["removed"]);
let computed = 'b';
let computed2 = 'a';
var _h = computed, stillNotGreat = o[_h], _j = computed2, soSo = o[_j], o = __rest(o, [typeof _h === "symbol" ? _h : _h + "", typeof _j === "symbol" ? _j : _j + ""]);
(_k = computed, stillNotGreat = o[_k], _l = computed2, soSo = o[_l], o = __rest(o, [typeof _k === "symbol" ? _k : _k + "", typeof _l === "symbol" ? _l : _l + ""]), o);
var _e, _g, _k, _l;
var _g = computed, stillNotGreat = o[_g], _h = computed2, soSo = o[_h], o = __rest(o, [typeof _g === "symbol" ? _g : _g + "", typeof _h === "symbol" ? _h : _h + ""]);
(_j = computed, stillNotGreat = o[_j], _k = computed2, soSo = o[_k], o = __rest(o, [typeof _j === "symbol" ? _j : _j + "", typeof _k === "symbol" ? _k : _k + ""]));
var _d, _f, _j, _k;
@@ -29,10 +29,10 @@ let nested;
let other;
let rest;
let complex;
(_a = complex.x, { ka } = _a, nested = __rest(_a, ["ka"]), { y: other } = complex, rest = __rest(complex, ["x", "y"]), complex);
(_a = complex.x, { ka } = _a, nested = __rest(_a, ["ka"]), { y: other } = complex, rest = __rest(complex, ["x", "y"]));
// should be:
let overEmit;
// var _g = overEmit.a, [_h, ...y] = _g, nested2 = __rest(_h, []), _j = overEmit.b, { z } = _j, c = __rest(_j, ["z"]), rest2 = __rest(overEmit, ["a", "b"]);
var _b = overEmit.a, [_c, ...y] = _b, nested2 = __rest(_c, []), _d = overEmit.b, { z } = _d, c = __rest(_d, ["z"]), rest2 = __rest(overEmit, ["a", "b"]);
(_e = overEmit.a, [_f, ...y] = _e, nested2 = __rest(_f, []), _g = overEmit.b, { z } = _g, c = __rest(_g, ["z"]), rest2 = __rest(overEmit, ["a", "b"]), overEmit);
var _a, _e, _f, _g;
var [_b, ...y] = overEmit.a, nested2 = __rest(_b, []), _c = overEmit.b, { z } = _c, c = __rest(_c, ["z"]), rest2 = __rest(overEmit, ["a", "b"]);
([_d, ...y] = overEmit.a, nested2 = __rest(_d, []), _e = overEmit.b, { z } = _e, c = __rest(_e, ["z"]), rest2 = __rest(overEmit, ["a", "b"]));
var _a, _d, _e;
+4 -4
View File
@@ -36,14 +36,14 @@ var __rest = (this && this.__rest) || function (s, e) {
return t;
};
let array;
for (var array_1 of array) {
var { x } = array_1, restOf = __rest(array_1, ["x"]);
for (let _a of array) {
let { x } = _a, restOf = __rest(_a, ["x"]);
[x, restOf];
}
let xx;
let rrestOff;
for (var array_2 of array) {
({ x: xx } = array_2, rrestOff = __rest(array_2, ["x"]));
for (let _b of array) {
({ x: xx } = _b, rrestOff = __rest(_b, ["x"]));
[xx, rrestOff];
}
for (const norest of array.map(a => (__assign({}, a, { x: 'a string' })))) {
@@ -1,7 +1,7 @@
tests/cases/conformance/types/rest/objectRestNegative.ts(2,10): error TS2462: A rest element must be last in a destructuring pattern
tests/cases/conformance/types/rest/objectRestNegative.ts(3,31): error TS2462: A rest element must be last in a destructuring pattern
tests/cases/conformance/types/rest/objectRestNegative.ts(6,17): error TS2700: Rest types may only be created from object types.
tests/cases/conformance/types/rest/objectRestNegative.ts(11,9): error TS2701: An object rest element must be an identifier.
tests/cases/conformance/types/rest/objectRestNegative.ts(11,9): error TS2701: The target of an object rest assignment must be a variable or a property access.
==== tests/cases/conformance/types/rest/objectRestNegative.ts (4 errors) ====
@@ -23,5 +23,5 @@ tests/cases/conformance/types/rest/objectRestNegative.ts(11,9): error TS2701: An
let rest: { b: string }
({a, ...rest.b + rest.b} = o);
~~~~~~~~~~~~~~~
!!! error TS2701: An object rest element must be an identifier.
!!! error TS2701: The target of an object rest assignment must be a variable or a property access.
@@ -23,13 +23,13 @@ var __rest = (this && this.__rest) || function (s, e) {
return t;
};
var o = { a: 1, b: 'no' };
var mustBeLast = o.mustBeLast, a = o.a;
var a = o.a;
function stillMustBeLast(_a) {
var mustBeLast = _a.mustBeLast, a = _a.a;
var a = _a.a;
}
function generic(t) {
var x = t.x, rest = __rest(t, ["x"]);
return rest;
}
var rest;
(a = o.a, o, o);
(a = o.a, o, rest.b + rest.b = __rest(o, ["a"]));
@@ -6,6 +6,15 @@ declare function suddenly(f: (a: { x: { z, ka }, y: string }) => void);
suddenly(({ x: a, ...rest }) => rest.y);
suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka);
class C {
m({ a, ...clone }: { a: number, b: string}): void {
// actually, never mind, don't clone
}
set p({ a, ...clone }: { a: number, b: string}) {
// actually, never mind, don't clone
}
}
//// [objectRestParameter.js]
@@ -29,3 +38,13 @@ suddenly((_a = { x: { z: 1, ka: 1 }, y: 'noo' }) => {
var _b = _a.x, { z = 12 } = _b, nested = __rest(_b, ["z"]), rest = __rest(_a, ["x"]);
return rest.y + nested.ka;
});
class C {
m(_a) {
var { a } = _a, clone = __rest(_a, ["a"]);
// actually, never mind, don't clone
}
set p(_a) {
var { a } = _a, clone = __rest(_a, ["a"]);
// actually, never mind, don't clone
}
}
@@ -42,4 +42,27 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo'
>nested : Symbol(nested, Decl(objectRestParameter.ts, 5, 24))
>ka : Symbol(ka, Decl(objectRestParameter.ts, 3, 42))
class C {
>C : Symbol(C, Decl(objectRestParameter.ts, 5, 107))
m({ a, ...clone }: { a: number, b: string}): void {
>m : Symbol(C.m, Decl(objectRestParameter.ts, 7, 9))
>a : Symbol(a, Decl(objectRestParameter.ts, 8, 7))
>clone : Symbol(clone, Decl(objectRestParameter.ts, 8, 10))
>a : Symbol(a, Decl(objectRestParameter.ts, 8, 24))
>b : Symbol(b, Decl(objectRestParameter.ts, 8, 35))
// actually, never mind, don't clone
}
set p({ a, ...clone }: { a: number, b: string}) {
>p : Symbol(C.p, Decl(objectRestParameter.ts, 10, 5))
>a : Symbol(a, Decl(objectRestParameter.ts, 11, 11))
>clone : Symbol(clone, Decl(objectRestParameter.ts, 11, 14))
>a : Symbol(a, Decl(objectRestParameter.ts, 11, 28))
>b : Symbol(b, Decl(objectRestParameter.ts, 11, 39))
// actually, never mind, don't clone
}
}
@@ -53,4 +53,27 @@ suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo'
>nested : { ka: any; }
>ka : any
class C {
>C : C
m({ a, ...clone }: { a: number, b: string}): void {
>m : ({a, ...clone}: { a: number; b: string; }) => void
>a : number
>clone : { b: string; }
>a : number
>b : string
// actually, never mind, don't clone
}
set p({ a, ...clone }: { a: number, b: string}) {
>p : { a: number; b: string; }
>a : number
>clone : { b: string; }
>a : number
>b : string
// actually, never mind, don't clone
}
}
@@ -176,63 +176,63 @@ function foo({a = 4, b = { x: 5 }}) {
});
(function () {
var y;
(_a = { y: 1 }, _b = _a.y, y = _b === void 0 ? 5 : _b, _a);
var _a, _b;
(_a = { y: 1 }.y, y = _a === void 0 ? 5 : _a);
var _a;
});
(function () {
var y;
(_a = { y: 1 }, _b = _a.y, y = _b === void 0 ? 5 : _b, _a);
var _a, _b;
(_a = { y: 1 }.y, y = _a === void 0 ? 5 : _a);
var _a;
});
(function () {
var y0;
(_a = { y0: 1 }, _b = _a.y0, y0 = _b === void 0 ? 5 : _b, _a);
var _a, _b;
(_a = { y0: 1 }.y0, y0 = _a === void 0 ? 5 : _a);
var _a;
});
(function () {
var y0;
(_a = { y0: 1 }, _b = _a.y0, y0 = _b === void 0 ? 5 : _b, _a);
var _a, _b;
(_a = { y0: 1 }.y0, y0 = _a === void 0 ? 5 : _a);
var _a;
});
(function () {
var y1;
(_a = {}, _b = _a.y1, y1 = _b === void 0 ? 5 : _b, _a);
var _a, _b;
(_a = {}.y1, y1 = _a === void 0 ? 5 : _a);
var _a;
});
(function () {
var y1;
(_a = {}, _b = _a.y1, y1 = _b === void 0 ? 5 : _b, _a);
var _a, _b;
(_a = {}.y1, y1 = _a === void 0 ? 5 : _a);
var _a;
});
(function () {
var y2, y3;
(_a = {}, _b = _a.y2, y2 = _b === void 0 ? 5 : _b, _c = _a.y3, y3 = _c === void 0 ? { x: 1 } : _c, _a);
(_a = {}, _b = _a.y2, y2 = _b === void 0 ? 5 : _b, _c = _a.y3, y3 = _c === void 0 ? { x: 1 } : _c);
var _a, _b, _c;
});
(function () {
var y2, y3;
(_a = {}, _b = _a.y2, y2 = _b === void 0 ? 5 : _b, _c = _a.y3, y3 = _c === void 0 ? { x: 1 } : _c, _a);
(_a = {}, _b = _a.y2, y2 = _b === void 0 ? 5 : _b, _c = _a.y3, y3 = _c === void 0 ? { x: 1 } : _c);
var _a, _b, _c;
});
(function () {
var y4, y5;
(_a = {}, _b = _a.y4, y4 = _b === void 0 ? 5 : _b, _c = _a.y5, y5 = _c === void 0 ? { x: 1 } : _c, _a);
(_a = {}, _b = _a.y4, y4 = _b === void 0 ? 5 : _b, _c = _a.y5, y5 = _c === void 0 ? { x: 1 } : _c);
var _a, _b, _c;
});
(function () {
var y4, y5;
(_a = {}, _b = _a.y4, y4 = _b === void 0 ? 5 : _b, _c = _a.y5, y5 = _c === void 0 ? { x: 1 } : _c, _a);
(_a = {}, _b = _a.y4, y4 = _b === void 0 ? 5 : _b, _c = _a.y5, y5 = _c === void 0 ? { x: 1 } : _c);
var _a, _b, _c;
});
(function () {
var z;
(_a = { z: { x: 1 } }, _b = _a.z, z = _b === void 0 ? { x: 5 } : _b, _a);
var _a, _b;
(_a = { z: { x: 1 } }.z, z = _a === void 0 ? { x: 5 } : _a);
var _a;
});
(function () {
var z;
(_a = { z: { x: 1 } }, _b = _a.z, z = _b === void 0 ? { x: 5 } : _b, _a);
var _a, _b;
(_a = { z: { x: 1 } }.z, z = _a === void 0 ? { x: 5 } : _a);
var _a;
});
(function () {
var a = { s: s };
@@ -194,13 +194,13 @@ for (_b = getRobot(), _c = _b.name, nameA = _c === void 0 ? "noName" : _c, _b, i
for (_d = { name: "trimmer", skill: "trimming" }, _e = _d.name, nameA = _e === void 0 ? "noName" : _e, _d, i = 0; i < 1; i++) {
console.log(nameA);
}
for (_f = multiRobot.skills, _g = _f === void 0 ? { primary: "none", secondary: "none" } : _f, _h = _g.primary, primaryA = _h === void 0 ? "primary" : _h, _j = _g.secondary, secondaryA = _j === void 0 ? "secondary" : _j, multiRobot, multiRobot, i = 0; i < 1; i++) {
for (_f = multiRobot.skills, _g = _f === void 0 ? { primary: "none", secondary: "none" } : _f, _h = _g.primary, primaryA = _h === void 0 ? "primary" : _h, _j = _g.secondary, secondaryA = _j === void 0 ? "secondary" : _j, multiRobot, i = 0; i < 1; i++) {
console.log(primaryA);
}
for (_k = getMultiRobot(), (_l = _k.skills, _m = _l === void 0 ? { primary: "none", secondary: "none" } : _l, _o = _m.primary, primaryA = _o === void 0 ? "primary" : _o, _p = _m.secondary, secondaryA = _p === void 0 ? "secondary" : _p, _k), _k, i = 0; i < 1; i++) {
for (_k = getMultiRobot(), _l = _k.skills, _m = _l === void 0 ? { primary: "none", secondary: "none" } : _l, _o = _m.primary, primaryA = _o === void 0 ? "primary" : _o, _p = _m.secondary, secondaryA = _p === void 0 ? "secondary" : _p, _k, i = 0; i < 1; i++) {
console.log(primaryA);
}
for (_q = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, (_r = _q.skills, _s = _r === void 0 ? { primary: "none", secondary: "none" } : _r, _t = _s.primary, primaryA = _t === void 0 ? "primary" : _t, _u = _s.secondary, secondaryA = _u === void 0 ? "secondary" : _u, _q), _q,
for (_q = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, _r = _q.skills, _s = _r === void 0 ? { primary: "none", secondary: "none" } : _r, _t = _s.primary, primaryA = _t === void 0 ? "primary" : _t, _u = _s.secondary, secondaryA = _u === void 0 ? "secondary" : _u, _q,
i = 0; i < 1; i++) {
console.log(primaryA);
}
@@ -213,13 +213,13 @@ for (_w = getRobot(), _x = _w.name, name = _x === void 0 ? "noName" : _x, _w, i
for (_y = { name: "trimmer", skill: "trimming" }, _z = _y.name, name = _z === void 0 ? "noName" : _z, _y, i = 0; i < 1; i++) {
console.log(nameA);
}
for (_0 = multiRobot.skills, _1 = _0 === void 0 ? { primary: "none", secondary: "none" } : _0, _2 = _1.primary, primary = _2 === void 0 ? "primary" : _2, _3 = _1.secondary, secondary = _3 === void 0 ? "secondary" : _3, multiRobot, multiRobot, i = 0; i < 1; i++) {
for (_0 = multiRobot.skills, _1 = _0 === void 0 ? { primary: "none", secondary: "none" } : _0, _2 = _1.primary, primary = _2 === void 0 ? "primary" : _2, _3 = _1.secondary, secondary = _3 === void 0 ? "secondary" : _3, multiRobot, i = 0; i < 1; i++) {
console.log(primaryA);
}
for (_4 = getMultiRobot(), (_5 = _4.skills, _6 = _5 === void 0 ? { primary: "none", secondary: "none" } : _5, _7 = _6.primary, primary = _7 === void 0 ? "primary" : _7, _8 = _6.secondary, secondary = _8 === void 0 ? "secondary" : _8, _4), _4, i = 0; i < 1; i++) {
for (_4 = getMultiRobot(), _5 = _4.skills, _6 = _5 === void 0 ? { primary: "none", secondary: "none" } : _5, _7 = _6.primary, primary = _7 === void 0 ? "primary" : _7, _8 = _6.secondary, secondary = _8 === void 0 ? "secondary" : _8, _4, i = 0; i < 1; i++) {
console.log(primaryA);
}
for (_9 = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, (_10 = _9.skills, _11 = _10 === void 0 ? { primary: "none", secondary: "none" } : _10, _12 = _11.primary, primary = _12 === void 0 ? "primary" : _12, _13 = _11.secondary, secondary = _13 === void 0 ? "secondary" : _13, _9), _9,
for (_9 = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, _10 = _9.skills, _11 = _10 === void 0 ? { primary: "none", secondary: "none" } : _10, _12 = _11.primary, primary = _12 === void 0 ? "primary" : _12, _13 = _11.secondary, secondary = _13 === void 0 ? "secondary" : _13, _9,
i = 0; i < 1; i++) {
console.log(primaryA);
}
@@ -232,13 +232,13 @@ for (_16 = getRobot(), _17 = _16.name, nameA = _17 === void 0 ? "noName" : _17,
for (_19 = { name: "trimmer", skill: "trimming" }, _20 = _19.name, nameA = _20 === void 0 ? "noName" : _20, _21 = _19.skill, skillA = _21 === void 0 ? "skill" : _21, _19, i = 0; i < 1; i++) {
console.log(nameA);
}
for (_22 = multiRobot.name, nameA = _22 === void 0 ? "noName" : _22, _23 = multiRobot.skills, _24 = _23 === void 0 ? { primary: "none", secondary: "none" } : _23, _25 = _24.primary, primaryA = _25 === void 0 ? "primary" : _25, _26 = _24.secondary, secondaryA = _26 === void 0 ? "secondary" : _26, multiRobot, multiRobot, i = 0; i < 1; i++) {
for (_22 = multiRobot.name, nameA = _22 === void 0 ? "noName" : _22, _23 = multiRobot.skills, _24 = _23 === void 0 ? { primary: "none", secondary: "none" } : _23, _25 = _24.primary, primaryA = _25 === void 0 ? "primary" : _25, _26 = _24.secondary, secondaryA = _26 === void 0 ? "secondary" : _26, multiRobot, i = 0; i < 1; i++) {
console.log(primaryA);
}
for (_27 = getMultiRobot(), (_28 = _27.name, nameA = _28 === void 0 ? "noName" : _28, _29 = _27.skills, _30 = _29 === void 0 ? { primary: "none", secondary: "none" } : _29, _31 = _30.primary, primaryA = _31 === void 0 ? "primary" : _31, _32 = _30.secondary, secondaryA = _32 === void 0 ? "secondary" : _32, _27), _27, i = 0; i < 1; i++) {
for (_27 = getMultiRobot(), _28 = _27.name, nameA = _28 === void 0 ? "noName" : _28, _29 = _27.skills, _30 = _29 === void 0 ? { primary: "none", secondary: "none" } : _29, _31 = _30.primary, primaryA = _31 === void 0 ? "primary" : _31, _32 = _30.secondary, secondaryA = _32 === void 0 ? "secondary" : _32, _27, i = 0; i < 1; i++) {
console.log(primaryA);
}
for (_33 = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, (_34 = _33.name, nameA = _34 === void 0 ? "noName" : _34, _35 = _33.skills, _36 = _35 === void 0 ? { primary: "none", secondary: "none" } : _35, _37 = _36.primary, primaryA = _37 === void 0 ? "primary" : _37, _38 = _36.secondary, secondaryA = _38 === void 0 ? "secondary" : _38, _33), _33,
for (_33 = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, _34 = _33.name, nameA = _34 === void 0 ? "noName" : _34, _35 = _33.skills, _36 = _35 === void 0 ? { primary: "none", secondary: "none" } : _35, _37 = _36.primary, primaryA = _37 === void 0 ? "primary" : _37, _38 = _36.secondary, secondaryA = _38 === void 0 ? "secondary" : _38, _33,
i = 0; i < 1; i++) {
console.log(primaryA);
}
@@ -251,16 +251,15 @@ for (_41 = getRobot(), _42 = _41.name, name = _42 === void 0 ? "noName" : _42, _
for (_44 = { name: "trimmer", skill: "trimming" }, _45 = _44.name, name = _45 === void 0 ? "noName" : _45, _46 = _44.skill, skill = _46 === void 0 ? "skill" : _46, _44, i = 0; i < 1; i++) {
console.log(nameA);
}
for (_47 = multiRobot.name, name = _47 === void 0 ? "noName" : _47, _48 = multiRobot.skills, _49 = _48 === void 0 ? { primary: "none", secondary: "none" } : _48, _50 = _49.primary, primary = _50 === void 0 ? "primary" : _50, _51 = _49.secondary, secondary = _51 === void 0 ? "secondary" : _51, multiRobot, multiRobot, i = 0; i < 1; i++) {
for (_47 = multiRobot.name, name = _47 === void 0 ? "noName" : _47, _48 = multiRobot.skills, _49 = _48 === void 0 ? { primary: "none", secondary: "none" } : _48, _50 = _49.primary, primary = _50 === void 0 ? "primary" : _50, _51 = _49.secondary, secondary = _51 === void 0 ? "secondary" : _51, multiRobot, i = 0; i < 1; i++) {
console.log(primaryA);
}
for (_52 = getMultiRobot(), (_53 = _52.name, name = _53 === void 0 ? "noName" : _53, _54 = _52.skills, _55 = _54 === void 0 ? { primary: "none", secondary: "none" } : _54, _56 = _55.primary, primary = _56 === void 0 ? "primary" : _56, _57 = _55.secondary, secondary = _57 === void 0 ? "secondary" : _57, _52), _52, i = 0; i < 1; i++) {
for (_52 = getMultiRobot(), _53 = _52.name, name = _53 === void 0 ? "noName" : _53, _54 = _52.skills, _55 = _54 === void 0 ? { primary: "none", secondary: "none" } : _54, _56 = _55.primary, primary = _56 === void 0 ? "primary" : _56, _57 = _55.secondary, secondary = _57 === void 0 ? "secondary" : _57, _52, i = 0; i < 1; i++) {
console.log(primaryA);
}
for (_58 = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, (_59 = _58.name, name = _59 === void 0 ? "noName" : _59, _60 = _58.skills, _61 = _60 === void 0 ? { primary: "none", secondary: "none" } : _60, _62 = _61.primary, primary = _62 === void 0 ? "primary" : _62, _63 = _61.secondary, secondary = _63 === void 0 ? "secondary" : _63, _58), _58,
for (_58 = { name: "trimmer", skills: { primary: "trimming", secondary: "edging" } }, _59 = _58.name, name = _59 === void 0 ? "noName" : _59, _60 = _58.skills, _61 = _60 === void 0 ? { primary: "none", secondary: "none" } : _60, _62 = _61.primary, primary = _62 === void 0 ? "primary" : _62, _63 = _61.secondary, secondary = _63 === void 0 ? "secondary" : _63, _58,
i = 0; i < 1; i++) {
console.log(primaryA);
}
var _k, _q, _4, _9, _27, _33, _52, _58;
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _l, _m, _o, _p, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _5, _6, _7, _8, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _28, _29, _30, _31, _32, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _53, _54, _55, _56, _57, _59, _60, _61, _62, _63;
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63;
//# sourceMappingURL=sourceMapValidationDestructuringForObjectBindingPatternDefaultValues2.js.map
File diff suppressed because one or more lines are too long
@@ -6,3 +6,12 @@ declare function suddenly(f: (a: { x: { z, ka }, y: string }) => void);
suddenly(({ x: a, ...rest }) => rest.y);
suddenly(({ x: { z = 12, ...nested }, ...rest } = { x: { z: 1, ka: 1 }, y: 'noo' }) => rest.y + nested.ka);
class C {
m({ a, ...clone }: { a: number, b: string}): void {
// actually, never mind, don't clone
}
set p({ a, ...clone }: { a: number, b: string}) {
// actually, never mind, don't clone
}
}