Skip to content
Merged
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
3 changes: 0 additions & 3 deletions src/transformation/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,6 @@ export const UnsupportedNonDestructuringLuaIterator = (node: ts.Node) =>
export const UnresolvableRequirePath = (node: ts.Node, reason: string, path?: string) =>
new TranspileError(`${reason}. TypeScript path: ${path}.`, node);

export const UnsupportedObjectDestructuringInForOf = (node: ts.Node) =>
new TranspileError(`Unsupported object destructuring in for...of statement.`, node);

export const InvalidAmbientIdentifierName = (node: ts.Identifier) =>
new TranspileError(
`Invalid ambient identifier name "${node.text}". Ambient identifiers must be valid lua identifiers.`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,20 @@ export function transformDestructuringAssignment(
node: ts.DestructuringAssignment,
root: lua.Expression
): lua.Statement[] {
switch (node.left.kind) {
case ts.SyntaxKind.ObjectLiteralExpression:
return transformObjectDestructuringAssignment(context, node as ts.ObjectDestructuringAssignment, root);
case ts.SyntaxKind.ArrayLiteralExpression:
return transformArrayDestructuringAssignment(context, node as ts.ArrayDestructuringAssignment, root);
}
return transformAssignmentPattern(context, node.left, root);
}

function transformArrayDestructuringAssignment(
export function transformAssignmentPattern(
context: TransformationContext,
node: ts.ArrayDestructuringAssignment,
node: ts.AssignmentPattern,
root: lua.Expression
): lua.Statement[] {
return transformArrayLiteralAssignmentPattern(context, node.left, root);
switch (node.kind) {
case ts.SyntaxKind.ObjectLiteralExpression:
return transformObjectLiteralAssignmentPattern(context, node, root);
case ts.SyntaxKind.ArrayLiteralExpression:
return transformArrayLiteralAssignmentPattern(context, node, root);
}
}

function transformArrayLiteralAssignmentPattern(
Expand Down Expand Up @@ -132,14 +132,6 @@ function transformArrayLiteralAssignmentPattern(
});
}

function transformObjectDestructuringAssignment(
context: TransformationContext,
node: ts.ObjectDestructuringAssignment,
root: lua.Expression
): lua.Statement[] {
return transformObjectLiteralAssignmentPattern(context, node.left, root);
}

function transformObjectLiteralAssignmentPattern(
context: TransformationContext,
node: ts.ObjectLiteralExpression,
Expand Down
47 changes: 11 additions & 36 deletions src/transformation/visitors/loops/for-of.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
import * as ts from "typescript";
import * as lua from "../../../LuaAST";
import { cast, castEach } from "../../../utils";
import { castEach } from "../../../utils";
import { FunctionVisitor, TransformationContext } from "../../context";
import { AnnotationKind, getTypeAnnotations, isForRangeType, isLuaIteratorType } from "../../utils/annotations";
import {
InvalidForRangeCall,
MissingForOfVariables,
UnsupportedNonDestructuringLuaIterator,
UnsupportedObjectDestructuringInForOf,
} from "../../utils/errors";
import { createUnpackCall } from "../../utils/lua-ast";
import { InvalidForRangeCall, MissingForOfVariables, UnsupportedNonDestructuringLuaIterator } from "../../utils/errors";
import { LuaLibFeature, transformLuaLibFunction } from "../../utils/lualib";
import { isArrayType, isNumberType } from "../../utils/typescript";
import { isArrayType, isNumberType, isAssignmentPattern } from "../../utils/typescript";
import { transformArguments } from "../call";
import { transformIdentifier } from "../identifier";
import {
Expand All @@ -20,6 +14,8 @@ import {
transformVariableDeclaration,
} from "../variable-declaration";
import { getVariableDeclarationBinding, transformLoopBody } from "./utils";
import { transformAssignment } from "../binary-expression/assignments";
import { transformAssignmentPattern } from "../binary-expression/destructuring-assignments";

function transformForOfInitializer(
context: TransformationContext,
Expand All @@ -29,15 +25,8 @@ function transformForOfInitializer(
if (ts.isVariableDeclarationList(initializer)) {
const binding = getVariableDeclarationBinding(initializer);
// Declaration of new variable
if (ts.isArrayBindingPattern(binding)) {
if (binding.elements.length === 0) {
// Ignore empty destructuring assignment
return [];
}

if (ts.isArrayBindingPattern(binding) || ts.isObjectBindingPattern(binding)) {
return transformBindingPattern(context, binding, expression);
} else if (ts.isObjectBindingPattern(binding)) {
throw UnsupportedObjectDestructuringInForOf(initializer);
}

const variableStatements = transformVariableDeclaration(context, initializer.declarations[0]);
Expand All @@ -53,27 +42,13 @@ function transformForOfInitializer(
throw MissingForOfVariables(initializer);
}
} else {
// Assignment to existing variable
let variables: lua.AssignmentLeftHandSideExpression | lua.AssignmentLeftHandSideExpression[];
let valueExpression: lua.Expression = expression;
if (ts.isArrayLiteralExpression(initializer)) {
if (initializer.elements.length > 0) {
valueExpression = createUnpackCall(context, expression, initializer);
variables = castEach(
initializer.elements.map(e => context.transformExpression(e)),
lua.isAssignmentLeftHandSideExpression
);
} else {
// Ignore empty destructring assignment
return [];
}
} else if (ts.isObjectLiteralExpression(initializer)) {
throw UnsupportedObjectDestructuringInForOf(initializer);
} else {
variables = cast(context.transformExpression(initializer), lua.isAssignmentLeftHandSideExpression);
// Assignment to existing variable(s)

if (isAssignmentPattern(initializer)) {
return transformAssignmentPattern(context, initializer, expression);
}

return [lua.createAssignmentStatement(variables, valueExpression)];
return transformAssignment(context, initializer, expression);
}
}

Expand Down
28 changes: 28 additions & 0 deletions test/unit/destructuring.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,34 @@ test.each(["[]", "{}"])("empty binding pattern", bindingPattern => {
`.expectToMatchJsResult();
});

// TODO: https://github.com/microsoft/TypeScript/pull/35906
// Adjust this test to use expectToMatchJsResult() and testCases when this issue is fixed.
test.each([
["foo", "['bar']"],
["[foo]", "[['bar']]"],
["[foo = 'bar']", "[[]]"],
["{ foo }", "[{ foo: 'bar' }]"],
["{ x: foo }", "[{ x: 'bar' }]"],
["{ foo = 'bar' }", "[{}] as { foo?: string }[]"],
])("forof assignment updates dependencies", (initializer, expression) => {
util.testModule`
let foo = '';
export { foo };
for (${initializer} of ${expression}) {}
`
.setReturnExport("foo")
.expectToEqual("bar");
});

test.each(testCases)("forof variable declaration binding patterns (%p)", ({ binding, value }) => {
util.testFunction`
let ${allBindings};
for (const ${binding} of [${value} as any]) {
return { ${allBindings} };
}
`.expectToMatchJsResult();
});

describe("array destructuring optimization", () => {
// TODO: Try to generalize optimization logic between declaration and assignment and make more generic tests

Expand Down
22 changes: 1 addition & 21 deletions test/unit/loops.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import * as ts from "typescript";
import * as tstl from "../../src";
import {
ForbiddenForIn,
UnsupportedForTarget,
UnsupportedObjectDestructuringInForOf,
} from "../../src/transformation/utils/errors";
import { ForbiddenForIn, UnsupportedForTarget } from "../../src/transformation/utils/errors";
import * as util from "../util";

test("while", () => {
Expand Down Expand Up @@ -428,22 +424,6 @@ test("forof array which modifies length", () => {
`.expectToMatchJsResult();
});

test.each([
{ initializer: "const {a, b}", vars: "" },
{ initializer: "const {a: x, b: y}", vars: "" },
{ initializer: "{a, b}", vars: "let a: string, b: string;" },
{ initializer: "{a: c, b: d}", vars: "let c: string, d: string;" },
])("forof object destructuring (%p)", ({ initializer, vars }) => {
const code = `
declare const arr: {a: string, b: string}[];
${vars}
for (${initializer} of arr) {}`;

expect(() => util.transpileString(code)).toThrow(
UnsupportedObjectDestructuringInForOf(ts.createEmptyStatement()).message
);
});

test("forof nested destructuring", () => {
util.testFunction`
let result = 0;
Expand Down