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
36 changes: 22 additions & 14 deletions src/transformation/visitors/function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,25 @@ import { transformBindingPattern } from "./variable-declaration";
function transformParameterDefaultValueDeclaration(
context: TransformationContext,
parameterName: lua.Identifier,
value?: ts.Expression,
value: ts.Expression,
tsOriginal?: ts.Node
): lua.Statement {
const parameterValue = value ? context.transformExpression(value) : undefined;
const assignment = lua.createAssignmentStatement(parameterName, parameterValue);
): lua.Statement | undefined {
const { precedingStatements: statements, result: parameterValue } = transformInPrecedingStatementScope(
context,
() => context.transformExpression(value)
);
if (!lua.isNilLiteral(parameterValue)) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Couldn't we do that at the top of the function? Check ts.isUndefinedLiteral || ts.isNullLiteral? That way we can avoid a whole bunch of transformations.

Copy link
Copy Markdown
Contributor Author

@GlassBricks GlassBricks Mar 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doing this makes this the most general; it applies to anything that results in a nil literal (casts/parenthesis/etc, language extensions, plugins) and shouldn't have any performance impact.

statements.push(lua.createAssignmentStatement(parameterName, parameterValue));
}
if (statements.length === 0) return undefined;

const nilCondition = lua.createBinaryExpression(
parameterName,
lua.createNilLiteral(),
lua.SyntaxKind.EqualityOperator
);

const ifBlock = lua.createBlock([assignment]);
const ifBlock = lua.createBlock(statements, tsOriginal);

return lua.createIfStatement(nilCondition, ifBlock, undefined, tsOriginal);
}
Expand Down Expand Up @@ -106,7 +112,7 @@ export function transformFunctionBodyHeader(
parameters: ts.NodeArray<ts.ParameterDeclaration>,
spreadIdentifier?: lua.Identifier
): lua.Statement[] {
const headerStatements = [];
const headerStatements: lua.Statement[] = [];

// Add default parameters and object binding patterns
const bindingPatternDeclarations: lua.Statement[] = [];
Expand All @@ -116,9 +122,12 @@ export function transformFunctionBodyHeader(
const identifier = lua.createIdentifier(`____bindingPattern${bindPatternIndex++}`);
if (declaration.initializer !== undefined) {
// Default binding parameter
headerStatements.push(
transformParameterDefaultValueDeclaration(context, identifier, declaration.initializer)
const initializer = transformParameterDefaultValueDeclaration(
context,
identifier,
declaration.initializer
);
if (initializer) headerStatements.push(initializer);
}

// Binding pattern
Expand All @@ -129,13 +138,12 @@ export function transformFunctionBodyHeader(
bindingPatternDeclarations.push(...precedingStatements, ...bindings);
} else if (declaration.initializer !== undefined) {
// Default parameter
headerStatements.push(
transformParameterDefaultValueDeclaration(
context,
transformIdentifier(context, declaration.name),
declaration.initializer
)
const initializer = transformParameterDefaultValueDeclaration(
context,
transformIdentifier(context, declaration.name),
declaration.initializer
);
if (initializer) headerStatements.push(initializer);
}
}

Expand Down
22 changes: 22 additions & 0 deletions test/unit/functions/__snapshots__/functions.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Function default parameter with value "null" 1`] = `
"local ____exports = {}
function ____exports.__main(self)
local function foo(self, x)
return x
end
return foo(nil)
end
return ____exports"
`;

exports[`Function default parameter with value "undefined" 1`] = `
"local ____exports = {}
function ____exports.__main(self)
local function foo(self, x)
return x
end
return foo(nil)
end
return ____exports"
`;

exports[`function.length unsupported ("5.0"): code 1`] = `
"local ____exports = {}
function ____exports.__main(self)
Expand Down
42 changes: 42 additions & 0 deletions test/unit/functions/functions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,48 @@ test("Function default binding parameter maintains order", () => {
`.expectToMatchJsResult();
});

test.each(["undefined", "null"])("Function default parameter with value %p", defaultValue => {
util.testFunction`
function foo(x = ${defaultValue}) {
return x;
}
return foo();
`
.expectToMatchJsResult()
.tap(builder => {
const lua = builder.getMainLuaCodeChunk();
expect(lua).not.toMatch("if x == nil then");
})
.expectLuaToMatchSnapshot();
});

test("Function default parameter with preceding statements", () => {
util.testFunction`
let i = 1
function foo(x = i++) {
return x;
}
return [i, foo(), i];
`.expectToMatchJsResult();
});

test("Function default parameter with nil value and preceding statements", () => {
util.testFunction`
const a = new LuaTable()
a.set("foo", "bar")
function foo(x: any = a.set("foo", "baz")) {
return x ?? "nil";
}
return [a.get("foo"), foo(), a.get("foo")];
`
.withLanguageExtensions()
.tap(builder => {
const lua = builder.getMainLuaCodeChunk();
expect(lua).not.toMatch(" x = nil");
})
.expectToEqual(["bar", "nil", "baz"]);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would prefer if you could just use expectToMatchJsResult here, using default TS (no language extensions) with an object and helper function for example.

Copy link
Copy Markdown
Contributor Author

@GlassBricks GlassBricks Mar 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you give a more detailed example what that could look like?
Besides using language extensions, I can't think of a good method that transpiles to nil (not just returns undefined) that works both in JS and lua.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I see what you are testing now, that seems maybe a bit too specific but okay

});

test("Class method call", () => {
util.testFunction`
class TestClass {
Expand Down