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
4 changes: 4 additions & 0 deletions src/transformation/utils/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,7 @@ export const annotationDeprecated = createWarningDiagnosticFactory(
`'@${kind}' is deprecated and will be removed in a future update. Please update your code before upgrading to the next release, otherwise your project will no longer compile. ` +
`See https://typescripttolua.github.io/docs/advanced/compiler-annotations#${kind.toLowerCase()} for more information.`
);

export const notAllowedOptionalAssignment = createErrorDiagnosticFactory(
"The left-hand side of an assignment expression may not be an optional property access."
);
6 changes: 6 additions & 0 deletions src/transformation/visitors/binary-expression/assignments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
ImmediatelyInvokedFunctionParameters,
transformToImmediatelyInvokedFunctionExpression,
} from "../../utils/transform";
import { notAllowedOptionalAssignment } from "../../utils/diagnostics";

export function transformAssignmentLeftHandSideExpression(
context: TransformationContext,
Expand All @@ -36,6 +37,11 @@ export function transformAssignment(
right: lua.Expression,
parent?: ts.Expression
): lua.Statement[] {
if (ts.isOptionalChain(lhs)) {
context.diagnostics.push(notAllowedOptionalAssignment(lhs));
return [];
}

if (isArrayLength(context, lhs)) {
const arrayLengthAssignment = lua.createExpressionStatement(
transformLuaLibFunction(
Expand Down
10 changes: 10 additions & 0 deletions test/unit/optionalChaining.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { notAllowedOptionalAssignment } from "../../src/transformation/utils/diagnostics";
import * as util from "../util";

test.each(["null", "undefined", '{ foo: "foo" }'])("optional chaining (%p)", value => {
Expand Down Expand Up @@ -97,6 +98,15 @@ test("no side effects", () => {
`.expectToMatchJsResult();
});

// Test for https://github.com/TypeScriptToLua/TypeScriptToLua/issues/1044
test("does not crash when incorrectly used in assignment (#1044)", () => {
const { diagnostics } = util.testFunction`
foo?.bar = "foo";
`.getLuaResult();

expect(diagnostics.find(d => d.code === notAllowedOptionalAssignment.code)).toBeDefined();
});

describe("optional chaining function calls", () => {
test.each(["() => 4", "undefined"])("stand-alone optional function (%p)", value => {
util.testFunction`
Expand Down