Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Destructuring support for parameter properties #1671

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 28 additions & 13 deletions src/compiler/binder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ module ts {

var name = getDeclarationName(node);
if (name !== undefined) {
var symbol = hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name));
var symbol = hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(SymbolFlags.None, name));
if (symbol.flags & excludes) {
if (node.name) {
node.name.parent = node;
Expand All @@ -143,11 +143,11 @@ module ts {
});
file.semanticDiagnostics.push(createDiagnosticForNode(node.name, message, getDisplayName(node)));

symbol = createSymbol(0, name);
symbol = createSymbol(SymbolFlags.None, name);
}
}
else {
symbol = createSymbol(0, "__missing");
symbol = createSymbol(SymbolFlags.None, "__missing");
}
addDeclarationToSymbol(symbol, node, includes);
symbol.parent = parent;
Expand Down Expand Up @@ -192,7 +192,7 @@ module ts {
// 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
// but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
// when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
var exportKind = 0;
var exportKind = SymbolFlags.None;
if (symbolKind & SymbolFlags.Value) {
exportKind |= SymbolFlags.ExportValue;
}
Expand Down Expand Up @@ -384,7 +384,7 @@ module ts {
case SyntaxKind.VariableDeclaration:
case SyntaxKind.BindingElement:
if (isBindingPattern((<Declaration>node).name)) {
bindChildren(node, 0, /*isBlockScopeContainer*/ false);
bindChildren(node, SymbolFlags.None, /*isBlockScopeContainer*/ false);
}
else if (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) {
bindBlockScopedVariableDeclaration(<Declaration>node);
Expand All @@ -395,7 +395,7 @@ module ts {
break;
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
bindDeclaration(<Declaration>node, SymbolFlags.Property | ((<PropertyDeclaration>node).questionToken ? SymbolFlags.Optional : 0), SymbolFlags.PropertyExcludes, /*isBlockScopeContainer*/ false);
bindDeclaration(<Declaration>node, SymbolFlags.Property | ((<PropertyDeclaration>node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes, /*isBlockScopeContainer*/ false);
break;
case SyntaxKind.PropertyAssignment:
case SyntaxKind.ShorthandPropertyAssignment:
Expand All @@ -407,22 +407,22 @@ module ts {
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
bindDeclaration(<Declaration>node, SymbolFlags.Signature, 0, /*isBlockScopeContainer*/ false);
bindDeclaration(<Declaration>node, SymbolFlags.Signature, /*excludes*/ SymbolFlags.None, /*isBlockScopeContainer*/ false);
break;
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
// If this is an ObjectLiteralExpression method, then it sits in the same space
// as other properties in the object literal. So we use SymbolFlags.PropertyExcludes
// so that it will conflict with any other object literal members with the same
// name.
bindDeclaration(<Declaration>node, SymbolFlags.Method | ((<MethodDeclaration>node).questionToken ? SymbolFlags.Optional : 0),
bindDeclaration(<Declaration>node, SymbolFlags.Method | ((<MethodDeclaration>node).questionToken ? SymbolFlags.Optional : SymbolFlags.None),
isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes, /*isBlockScopeContainer*/ true);
break;
case SyntaxKind.FunctionDeclaration:
bindDeclaration(<Declaration>node, SymbolFlags.Function, SymbolFlags.FunctionExcludes, /*isBlockScopeContainer*/ true);
break;
case SyntaxKind.Constructor:
bindDeclaration(<Declaration>node, SymbolFlags.Constructor, /*symbolExcludes:*/ 0, /*isBlockScopeContainer:*/ true);
bindDeclaration(<Declaration>node, SymbolFlags.Constructor, /*symbolExcludes:*/ SymbolFlags.None, /*isBlockScopeContainer:*/ true);
break;
case SyntaxKind.GetAccessor:
bindDeclaration(<Declaration>node, SymbolFlags.GetAccessor, SymbolFlags.GetAccessorExcludes, /*isBlockScopeContainer*/ true);
Expand Down Expand Up @@ -482,7 +482,7 @@ module ts {
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.SwitchStatement:
bindChildren(node, 0, /*isBlockScopeContainer*/ true);
bindChildren(node, SymbolFlags.None, /*isBlockScopeContainer*/ true);
break;
default:
var saveParent = parent;
Expand All @@ -493,7 +493,9 @@ module ts {
}

function bindParameter(node: ParameterDeclaration) {
if (isBindingPattern(node.name)) {
var isBinding = isBindingPattern(node.name);

if (isBinding) {
bindAnonymousDeclaration(node, SymbolFlags.FunctionScopedVariable, getDestructuringParameterName(node), /*isBlockScopeContainer*/ false);
}
else {
Expand All @@ -502,12 +504,25 @@ module ts {

// If this is a property-parameter, then also declare the property symbol into the
// containing class.
if (node.flags & NodeFlags.AccessibilityModifier &&
if ((node.flags & NodeFlags.AccessibilityModifier) &&
node.parent.kind === SyntaxKind.Constructor &&
node.parent.parent.kind === SyntaxKind.ClassDeclaration) {

var classDeclaration = <ClassDeclaration>node.parent.parent;
declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);

if (isBinding) {
forEach((<BindingPattern>node.name).elements, function declareBindingParameterProperties(curr: BindingElement) {
if (isBindingPattern(curr.name)) {
forEach((<BindingPattern>curr.name).elements, declareBindingParameterProperties)
}
else if (curr.name.kind === SyntaxKind.Identifier) {
declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, curr, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
}
});
}
else {
declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
}
}
}
}
Expand Down
25 changes: 14 additions & 11 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ module ts {
}

function getExcludedSymbolFlags(flags: SymbolFlags): SymbolFlags {
var result: SymbolFlags = 0;
var result = SymbolFlags.None;
if (flags & SymbolFlags.BlockScopedVariable) result |= SymbolFlags.BlockScopedVariableExcludes;
if (flags & SymbolFlags.FunctionScopedVariable) result |= SymbolFlags.FunctionScopedVariableExcludes;
if (flags & SymbolFlags.Property) result |= SymbolFlags.PropertyExcludes;
Expand Down Expand Up @@ -1745,7 +1745,7 @@ module ts {
function getTypeFromObjectBindingPattern(pattern: BindingPattern): Type {
var members: SymbolTable = {};
forEach(pattern.elements, e => {
var flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0);
var flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : SymbolFlags.None);
var name = e.propertyName || <Identifier>e.name;
var symbol = <TransientSymbol>createSymbol(flags, name.text);
symbol.type = getTypeFromBindingElement(e);
Expand Down Expand Up @@ -5481,7 +5481,7 @@ module ts {
}

function getDeclarationFlagsFromSymbol(s: Symbol) {
return s.valueDeclaration ? getCombinedNodeFlags(s.valueDeclaration) : s.flags & SymbolFlags.Prototype ? NodeFlags.Public | NodeFlags.Static : 0;
return s.valueDeclaration ? getCombinedNodeFlags(s.valueDeclaration) : s.flags & SymbolFlags.Prototype ? (NodeFlags.Public | NodeFlags.Static) : SymbolFlags.None;
}

function checkClassPropertyAccess(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, type: Type, prop: Symbol) {
Expand Down Expand Up @@ -7189,7 +7189,7 @@ module ts {

checkVariableLikeDeclaration(node);
var func = getContainingFunction(node);
if (node.flags & (NodeFlags.Public | NodeFlags.Private | NodeFlags.Protected)) {
if (node.flags & NodeFlags.AccessibilityModifier) {
func = getContainingFunction(node);
if (!(func.kind === SyntaxKind.Constructor && nodeIsPresent(func.body))) {
error(node, Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
Expand All @@ -7208,17 +7208,20 @@ module ts {
checkGrammarIndexSignature(<SignatureDeclaration>node);
}
// TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
else if (node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.ConstructorType ||
else if (node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.ConstructorType ||
node.kind === SyntaxKind.CallSignature || node.kind === SyntaxKind.Constructor ||
node.kind === SyntaxKind.ConstructSignature){
checkGrammarFunctionLikeDeclaration(<FunctionLikeDeclaration>node);
}

checkTypeParameters(node.typeParameters);

forEach(node.parameters, checkParameter);

if (node.type) {
checkSourceElement(node.type);
}

if (produceDiagnostics) {
checkCollisionWithArgumentsInGeneratedCode(node);
if (compilerOptions.noImplicitAny && !node.type) {
Expand Down Expand Up @@ -7769,8 +7772,8 @@ module ts {

// we use SymbolFlags.ExportValue, SymbolFlags.ExportType and SymbolFlags.ExportNamespace
// to denote disjoint declarationSpaces (without making new enum type).
var exportedDeclarationSpaces: SymbolFlags = 0;
var nonExportedDeclarationSpaces: SymbolFlags = 0;
var exportedDeclarationSpaces = SymbolFlags.None;
var nonExportedDeclarationSpaces = SymbolFlags.None;
forEach(symbol.declarations, d => {
var declarationSpaces = getDeclarationSpaces(d);
if (getEffectiveDeclarationFlags(d, NodeFlags.Export)) {
Expand Down Expand Up @@ -7804,7 +7807,7 @@ module ts {
case SyntaxKind.EnumDeclaration:
return SymbolFlags.ExportType | SymbolFlags.ExportValue;
case SyntaxKind.ImportDeclaration:
var result: SymbolFlags = 0;
var result = SymbolFlags.None;
var target = resolveImport(getSymbolOfNode(d));
forEach(target.declarations, d => { result |= getDeclarationSpaces(d); });
return result;
Expand Down Expand Up @@ -9105,9 +9108,9 @@ module ts {
}
if (target !== unknownSymbol) {
var excludedMeanings =
(symbol.flags & SymbolFlags.Value ? SymbolFlags.Value : 0) |
(symbol.flags & SymbolFlags.Type ? SymbolFlags.Type : 0) |
(symbol.flags & SymbolFlags.Namespace ? SymbolFlags.Namespace : 0);
(symbol.flags & SymbolFlags.Value ? SymbolFlags.Value : SymbolFlags.None) |
(symbol.flags & SymbolFlags.Type ? SymbolFlags.Type : SymbolFlags.None) |
(symbol.flags & SymbolFlags.Namespace ? SymbolFlags.Namespace : SymbolFlags.None);
if (target.flags & excludedMeanings) {
error(node, Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0, symbolToString(symbol));
}
Expand Down
34 changes: 21 additions & 13 deletions src/compiler/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3053,7 +3053,7 @@ module ts {
}
}

function emitBindingElement(target: BindingElement, value: Expression) {
function emitBindingElement(target: BindingElement, value?: Expression) {
if (target.initializer) {
// Combine value and initializer
value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer;
Expand Down Expand Up @@ -3369,18 +3369,26 @@ module ts {
}

function emitParameterPropertyAssignments(node: ConstructorDeclaration) {
forEach(node.parameters, param => {
if (param.flags & NodeFlags.AccessibilityModifier) {
writeLine();
emitStart(param);
emitStart(param.name);
write("this.");
emitNode(param.name);
emitEnd(param.name);
write(" = ");
emit(param.name);
write(";");
emitEnd(param);
forEach(node.parameters, function emitBoundProperty(binding: ParameterDeclaration | BindingElement) {
if (binding.flags & NodeFlags.AccessibilityModifier) {
if (isBindingPattern(binding.name)) {
emitStart(binding);
forEach((<BindingPattern>binding.name).elements, emitBoundProperty);
emitEnd(binding.name);
}
else {
writeLine();
emitStart(binding);
emitStart(binding.name);
write("this.");
emitNode(binding.name);
emitEnd(binding.name);
write(" = ");
emit(binding.name);
write(";");
emitEnd(binding);
}

}
});
}
Expand Down
24 changes: 22 additions & 2 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1395,7 +1395,10 @@ module ts {
}

function canFollowModifier(): boolean {
return token === SyntaxKind.OpenBracketToken || token === SyntaxKind.AsteriskToken || isLiteralPropertyName();
return token === SyntaxKind.OpenBracketToken
|| token === SyntaxKind.OpenBraceToken
|| token === SyntaxKind.AsteriskToken
|| isLiteralPropertyName();
}

// True if positioned at the start of a list element
Expand Down Expand Up @@ -2152,7 +2155,8 @@ module ts {

function parseParameter(): ParameterDeclaration {
var node = <ParameterDeclaration>createNode(SyntaxKind.Parameter);
setModifiers(node, parseModifiers());
var modifiers = parseModifiers();
setModifiers(node, modifiers);
node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);

// SingleNameBinding[Yield,GeneratorParameter] : See 13.2.3
Expand All @@ -2161,6 +2165,10 @@ module ts {

node.name = inGeneratorParameterContext() ? doInYieldContext(parseIdentifierOrPattern) : parseIdentifierOrPattern();

if (isBindingPattern(node.name)) {
propagateModifiersToBindingElements(<BindingPattern>node.name, modifiers);
}

if (getFullWidth(node.name) === 0 && node.flags === 0 && isModifier(token)) {
// in cases like
// 'use strict'
Expand Down Expand Up @@ -2188,6 +2196,18 @@ module ts {
return finishNode(node);
}

function propagateModifiersToBindingElements(bindingPattern: BindingPattern, modifiers: ModifiersArray): void {
forEach(bindingPattern.elements, propagate);

function propagate(node: BindingElement): void {
setModifiers(node, modifiers);

if (isBindingPattern(node.name)) {
forEach((<BindingPattern>node.name).elements, propagate);
}
}
}

function parseParameterInitializer() {
return parseInitializer(/*inParameter*/ true);
}
Expand Down
1 change: 1 addition & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1129,6 +1129,7 @@ module ts {
}

export const enum SymbolFlags {
None = 0x00000000, // None
FunctionScopedVariable = 0x00000001, // Variable (var) or parameter
BlockScopedVariable = 0x00000002, // A block-scoped variable (let or const)
Property = 0x00000004, // Property or enum member
Expand Down
67 changes: 67 additions & 0 deletions tests/baselines/reference/destructuringParameterProperties1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//// [destructuringParameterProperties1.ts]
class C1 {
constructor(public [x, y, z]: string[]) {
}
}

type TupleType1 = [string, number, boolean];

class C2 {
constructor(public [x, y, z]: TupleType1) {
}
}

type ObjType1 = { x: number; y: string; z: boolean }

class C3 {
constructor(public { x, y, z }: ObjType1) {
}
}

var c1 = new C1([]);
c1 = new C1(["larry", "{curly}", "moe"]);
var useC1Properties = c1.x === c1.y && c1.y === c1.z;

var c2 = new C2(["10", 10, !!10]);
var [c2_x, c2_y, c2_z] = [c2.x, c2.y, c2.z];

var c3 = new C3({x: 0, y: "", z: false});
c3 = new C3({x: 0, "y": "y", z: true});
var [c3_x, c3_y, c3_z] = [c3.x, c3.y, c3.z];

//// [destructuringParameterProperties1.js]
var C1 = (function () {
function C1(_a) {
var x = _a[0], y = _a[1], z = _a[2];
this.x = x;
this.y = y;
this.z = z;
}
return C1;
})();
var C2 = (function () {
function C2(_a) {
var x = _a[0], y = _a[1], z = _a[2];
this.x = x;
this.y = y;
this.z = z;
}
return C2;
})();
var C3 = (function () {
function C3(_a) {
var x = _a.x, y = _a.y, z = _a.z;
this.x = x;
this.y = y;
this.z = z;
}
return C3;
})();
var c1 = new C1([]);
c1 = new C1(["larry", "{curly}", "moe"]);
var useC1Properties = c1.x === c1.y && c1.y === c1.z;
var c2 = new C2(["10", 10, !!10]);
var _a = [c2.x, c2.y, c2.z], c2_x = _a[0], c2_y = _a[1], c2_z = _a[2];
var c3 = new C3({ x: 0, y: "", z: false });
c3 = new C3({ x: 0, "y": "y", z: true });
var _b = [c3.x, c3.y, c3.z], c3_x = _b[0], c3_y = _b[1], c3_z = _b[2];
Loading