release: v0.2.2 fix optional chaining, static self, destructuring, mixed imports and add UnLua.Delegate/Input types

This commit is contained in:
szy73711 committed 2026-11-29 03:34:45 +08:00
1 parent 70630f689f
commit cb1539d738
9 files changed
+754 -36

No files matched your search

+290 -1
View File
@@ -5,8 +5,13 @@ import * as path from "node:path";
import * as ts from "typescript";
import * as tstl from "typescript-to-lua";
import { createRequire } from "node:module";
import { spawnSync } from "node:child_process";
const require = createRequire(import.meta.url);
const luaBin = ["lua5.4", "lua"].find((cmd) => {
const probe = spawnSync(cmd, ["-v"], { encoding: "utf8" });
return probe.status === 0 && /Lua 5\.4/.test((probe.stdout || "") + (probe.stderr || ""));
});
const projectRoot = path.resolve(import.meta.dirname, "..");
const unluaTypesPath = path.join(projectRoot, "types", "unlua.d.ts");
const unluaTypesContent = fs.readFileSync(unluaTypesPath, "utf8");
@@ -98,6 +103,15 @@ test("@unlua class extending UE native class compiles to UnLua.Class() + self.Ov
static Helper(a: number, b = 10): number {
return a + b;
}
static HelperNoSelf(this: void, a: number, b = 10): number {
return a + b;
}
/** @noSelf */
static HelperDocNoSelf(a: number): number {
return a * 2;
}
}
`,
});
@@ -109,7 +123,9 @@ test("@unlua class extending UE native class compiles to UnLua.Class() + self.Ov
assert.match(lua, /function MyActor\.ReceiveBeginPlay\(self\)/);
assert.match(lua, /self\.Overridden\.ReceiveBeginPlay\(self\)/);
assert.match(lua, /MyActor\.MAX_HP = 100/);
assert.match(lua, /function MyActor\.Helper\(a, b\)/);
assert.match(lua, /function MyActor\.Helper\(self, a, b\)/);
assert.match(lua, /function MyActor\.HelperNoSelf\(a, b\)/);
assert.match(lua, /function MyActor\.HelperDocNoSelf\(a\)/);
assert.match(lua, /if b == nil then/);
assert.match(lua, /return MyActor\s*$/);
assert.doesNotMatch(lua, /____exports/);
@@ -458,3 +474,276 @@ test("forbids multiple @unlua classes in one file, invalid @unlua args, and dire
assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaMultipleClassesInFile));
assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaForbiddenSuperUsage));
});
// ============================================================
// 4. 进阶边界与回归测试(v0.2.2+)
// ============================================================
test("@unlua static methods preserve self matching TSTL colon calls, while @noSelf / this:void use dot calls", () => {
const result = transpileWithUnLua({
"Game/CalcActor.ts": `
@unlua
export default class CalcActor extends UE.AActor {
static readonly BASE = 100;
static Add(a: number, b = 5): number {
return this.BASE + a + b;
}
static PureMul(this: void, a: number, b: number): number {
return a * b;
}
Compute(): number {
return CalcActor.Add(10, 20) + CalcActor.Add(1) + CalcActor.PureMul(3, 4);
}
}
`,
});
assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2));
const lua = getLuaCode(result, "Game/CalcActor.lua");
assert.match(lua, /function CalcActor\.Add\(self, a, b\)/);
assert.match(lua, /function CalcActor\.PureMul\(a, b\)/);
assert.match(lua, /CalcActor:Add\(10, 20\)/);
assert.match(lua, /CalcActor\.PureMul\(3, 4\)/);
if (luaBin) {
const script = `
_G.UnLua = { Class = function() return {} end }
local CalcActor = (function()\n${lua}\nend)()
local inst = setmetatable({}, { __index = CalcActor })
-- (100+10+20) + (100+1+5) + (3*4) = 130 + 106 + 12 = 248
assert(inst:Compute() == 248, "Expected 248, got " .. tostring(inst:Compute()))
`;
const run = spawnSync(luaBin, ["-e", script], { encoding: "utf8" });
assert.equal(run.status, 0, run.stderr || run.stdout);
}
});
test("@unlua methods properly unpack destructured object & array parameters with defaults and rest", () => {
const result = transpileWithUnLua({
"Game/DestructActor.ts": `
export interface Opts {
x: number;
y?: number;
nested?: { z: number };
}
@unlua
export default class DestructActor extends UE.AActor {
SumObj({ x, y = 10, nested: { z } = { z: 3 } }: Opts = { x: 1 }): number {
return x + y + z;
}
SumArr([a, b = 2, ...rest]: number[]): number {
let total = a + b;
for (let i = 0; i < rest.length; i++) {
total += rest[i];
}
return total;
}
}
`,
});
assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2));
const lua = getLuaCode(result, "Game/DestructActor.lua");
if (luaBin) {
const script = `
_G.UnLua = { Class = function() return {} end }
local DestructActor = (function()\n${lua}\nend)()
local inst = setmetatable({}, { __index = DestructActor })
assert(inst:SumObj() == 14, "default obj failed: " .. tostring(inst:SumObj()))
assert(inst:SumObj({ x = 5, y = 6, nested = { z = 7 } }) == 18)
assert(inst:SumArr({ 1, 2, 3, 4 }) == 10)
assert(inst:SumArr({ 5 }) == 7)
`;
const run = spawnSync(luaBin, ["-e", script], { encoding: "utf8" });
assert.equal(run.status, 0, run.stderr || run.stdout);
}
});
test("mixed default + type-only named imports from @unlua module emit direct require without .default", () => {
const result = transpileWithUnLua({
"Game/BaseItem.ts": `
export interface ItemConfig { id: number; }
export type ItemTag = "Weapon" | "Potion";
@unlua
export default class BaseItem extends UE.AActor {
GetScore(cfg: ItemConfig): number {
return cfg.id * 2;
}
}
`,
"Game/SpecialItem.ts": `
import BaseItem, { ItemConfig, type ItemTag } from "./BaseItem";
@unlua
export default class SpecialItem extends BaseItem {
GetTagScore(cfg: ItemConfig, tag: ItemTag): number {
const bonus = tag === "Weapon" ? 10 : 5;
return super.GetScore(cfg) + bonus;
}
}
`,
});
assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2));
const lua = getLuaCode(result, "Game/SpecialItem.lua");
assert.match(lua, /local BaseItem = require\("Game\.BaseItem"\)/);
assert.doesNotMatch(lua, /\.default\b/);
assert.match(lua, /BaseItem\.GetScore\(self, cfg\)/);
});
test("UnLua.Delegate compiles to inline { target, callback } table and rejects inline arrow functions", () => {
const good = transpileWithUnLua({
"Game/TimerActor.ts": `
declare namespace UE {
class UKismetSystemLibrary {
static K2_SetTimerDelegate(this: void, Delegate: FScriptDelegate<() => void>, Time: number, bLooping: boolean): void;
}
}
@unlua
export default class TimerActor extends UE.AActor {
ReceiveBeginPlay(): void {
UE.UKismetSystemLibrary.K2_SetTimerDelegate(UnLua.Delegate(this, this.OnTickTimer), 1.0, true);
}
OnTickTimer(): void {}
}
`,
});
assert.equal(getUnLuaErrors(good).length, 0, JSON.stringify(getUnLuaErrors(good), null, 2));
const lua = getLuaCode(good, "Game/TimerActor.lua");
assert.match(lua, /K2_SetTimerDelegate\(\{self, self\.OnTickTimer\}, 1, true\)/);
assert.doesNotMatch(lua, /UnLua\.Delegate/);
const bad = transpileWithUnLua({
"Game/BadTimerActor.ts": `
@unlua
export default class BadTimerActor extends UE.AActor {
ReceiveBeginPlay(): void {
const d = UnLua.Delegate(this, () => {});
void d;
}
}
`,
});
const codes = getUnLuaErrors(bad).map((d) => d.code);
assert.ok(codes.includes(UnLuaDiagnosticCode.UnLuaDelegateForbiddenInlineFunction));
});
test("UnLua.Input.BindKey references @unlua class variable directly without ____exports", () => {
const result = transpileWithUnLua({
"Game/InputActor.ts": `
@unlua
export default class InputActor extends UE.AActor {
OnSpacePressed(key: unknown): void {
void key;
}
}
UnLua.Input.BindKey(InputActor, "SpaceBar", "Pressed", function (this: InputActor, key: unknown) {
this.OnSpacePressed(key);
}, { Ctrl: true });
`,
});
assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2));
const lua = getLuaCode(result, "Game/InputActor.lua");
assert.match(lua, /UnLua\.Input\.BindKey\(\s*InputActor,/);
assert.doesNotMatch(lua, /____exports/);
});
test("forbids BigInt literals, new UE.AActor(), WeakMap/WeakSet/Function/Object.freeze, dynamic import, and missing @unlua on standalone @unlua subclass", () => {
const result = transpileWithUnLua({
"UI/BasePanel.ts": `
@unlua("UI.NativePanel")
export default class BasePanel {
Show(): void {}
}
`,
"UI/SubPanelForgot.ts": `
import BasePanel from "./BasePanel";
export default class SubPanelForgot extends BasePanel {}
`,
"Game/MoreBad.ts": `
export function badThings(obj: Record<string, unknown>) {
const big = 123n;
const big2 = BigInt(456);
const wm = new WeakMap();
const ws = new WeakSet();
const fn = new Function("return 1");
const frozen = Object.freeze(obj);
const created = Object.create(null);
const actor = new UE.AActor();
const dyn = import("./BasePanel" as string);
return [big, big2, wm, ws, fn, frozen, created, actor, dyn];
}
`,
});
const codes = new Set(getUnLuaErrors(result).map((d) => d.code));
assert.ok(codes.has(UnLuaDiagnosticCode.MissingUnLuaDecorator));
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenBuiltinType));
assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaClassForbiddenNew));
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenDynamicImport));
});
test("forbids inline callback on FScriptDelegate.Bind and FMulticastSparseDelegate.Add", () => {
const result = transpileWithUnLua({
"Game/BadDelegates.ts": `
@unlua
export default class BadDelegates extends UE.AActor {
Single!: UE.FScriptDelegate<() => void>;
Sparse!: UE.FMulticastSparseDelegate<() => void>;
ReceiveBeginPlay(): void {
this.Single.Bind(this, function () {});
this.Sparse.Add(this, () => {});
}
}
`,
});
const errs = getUnLuaErrors(result).filter(
(d) => d.code === UnLuaDiagnosticCode.UnLuaDelegateForbiddenInlineFunction
);
assert.equal(errs.length, 2);
});
test("optional chaining (a?.b?.c) with synthetic identifiers does not crash plugin", () => {
const result = transpileWithUnLua({
"Game/OptChainActor.ts": `
export interface NestedData {
inner?: { value?: number };
}
@unlua
export default class OptChainActor extends UE.AActor {
ReadNested(data?: NestedData): number {
return data?.inner?.value ?? -1;
}
}
`,
});
assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2));
const lua = getLuaCode(result, "Game/OptChainActor.lua");
if (luaBin) {
const script = `
_G.UnLua = { Class = function() return {} end }
local OptChainActor = (function()\n${lua}\nend)()
local inst = setmetatable({}, { __index = OptChainActor })
assert(inst:ReadNested(nil) == -1)
assert(inst:ReadNested({}) == -1)
assert(inst:ReadNested({ inner = { value = 42 } }) == 42)
`;
const run = spawnSync(luaBin, ["-e", script], { encoding: "utf8" });
assert.equal(run.status, 0, run.stderr || run.stdout);
}
});