Skip to content

Commit ce0b8a7

Browse files
authored
Fixes handling of statements before super call in subclass constructors (TypeScriptToLua#1592)
* Fixes handling of statements before super call in subclass constructors * Adds test for previous addition
1 parent d7a0674 commit ce0b8a7

File tree

2 files changed

+32
-12
lines changed

2 files changed

+32
-12
lines changed

src/transformation/visitors/class/members/constructor.ts

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -45,23 +45,22 @@ export function transformConstructorDeclaration(
4545

4646
const classInstanceFields = transformClassInstanceFields(context, instanceFields);
4747

48-
// If there are field initializers and the first statement is a super call,
49-
// move super call between default assignments and initializers
48+
// If there are field initializers and there is a super call somewhere,
49+
// move super call and everything before it to between default assignments and initializers
5050
if (
5151
(constructorFieldsDeclarations.length > 0 || classInstanceFields.length > 0) &&
5252
statement.body &&
5353
statement.body.statements.length > 0
5454
) {
55-
const firstStatement = statement.body.statements[0];
56-
if (
57-
ts.isExpressionStatement(firstStatement) &&
58-
ts.isCallExpression(firstStatement.expression) &&
59-
firstStatement.expression.expression.kind === ts.SyntaxKind.SuperKeyword
60-
) {
61-
const superCall = body.shift();
62-
if (superCall) {
63-
bodyWithFieldInitializers.push(superCall);
64-
}
55+
const superIndex = statement.body.statements.findIndex(
56+
s =>
57+
ts.isExpressionStatement(s) &&
58+
ts.isCallExpression(s.expression) &&
59+
s.expression.expression.kind === ts.SyntaxKind.SuperKeyword
60+
);
61+
62+
if (superIndex !== -1) {
63+
bodyWithFieldInitializers.push(...body.splice(0, superIndex + 1));
6564
}
6665
}
6766

test/unit/classes/classes.spec.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,27 @@ test("SubclassConstructor", () => {
181181
`.expectToMatchJsResult();
182182
});
183183

184+
test("SubclassConstructorPropertyInitiailizationSuperOrder", () => {
185+
util.testFunction`
186+
class a {
187+
field: number;
188+
constructor(field: number) {
189+
this.field = field;
190+
}
191+
}
192+
class b extends a {
193+
fieldDouble = this.field * 2;
194+
constructor(field: number) {
195+
const newField = field + 1;
196+
super(newField);
197+
}
198+
}
199+
200+
const result = new b(10);
201+
return [result.field, result.fieldDouble];
202+
`.expectToMatchJsResult();
203+
});
204+
184205
test("Subclass constructor across merged namespace", () => {
185206
util.testModule`
186207
namespace NS {

0 commit comments

Comments
 (0)