750 lines
27 KiB
JavaScript
750 lines
27 KiB
JavaScript
import test from "node:test";
|
||
import assert from "node:assert/strict";
|
||
import * as fs from "node:fs";
|
||
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");
|
||
const pluginPath = path.join(projectRoot, "dist", "plugin", "index.js");
|
||
const { UnLuaDiagnosticCode } = require(pluginPath);
|
||
|
||
const VIRTUAL_UE_REFLECTION_DTS = `
|
||
declare namespace UE {
|
||
class UObject {
|
||
GetName(): string;
|
||
GetClass(): UClass;
|
||
IsValid(): boolean;
|
||
IsA(someBase: UClass): boolean;
|
||
static StaticClass(this: void): UClass;
|
||
}
|
||
class UClass extends UObject {}
|
||
class AActor extends UObject {
|
||
ReceiveBeginPlay(): void;
|
||
ReceiveTick(DeltaSeconds: number): void;
|
||
ReceiveEndPlay(EndPlayReason: number): void;
|
||
static StaticClass(this: void): UClass;
|
||
}
|
||
class UUserWidget extends UObject {
|
||
Construct(): void;
|
||
Destruct(): void;
|
||
static StaticClass(this: void): UClass;
|
||
}
|
||
}
|
||
`;
|
||
|
||
/**
|
||
* 在内存中编译一组虚拟 TS 文件并启用 UnLua 插件。
|
||
*/
|
||
function transpileWithUnLua(files) {
|
||
const virtualFiles = {
|
||
"unlua.d.ts": unluaTypesContent,
|
||
"ue.generated.d.ts": VIRTUAL_UE_REFLECTION_DTS,
|
||
...files,
|
||
};
|
||
|
||
return tstl.transpileVirtualProject(virtualFiles, {
|
||
target: ts.ScriptTarget.ESNext,
|
||
module: ts.ModuleKind.ESNext,
|
||
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
||
lib: ["lib.esnext.d.ts"],
|
||
strict: true,
|
||
skipLibCheck: true,
|
||
experimentalDecorators: true,
|
||
rootDir: ".",
|
||
luaTarget: tstl.LuaTarget.Lua54,
|
||
luaLibImport: tstl.LuaLibImportKind.RequireMinimal,
|
||
noImplicitSelf: false,
|
||
noHeader: true,
|
||
luaPlugins: [{ name: pluginPath }],
|
||
});
|
||
}
|
||
|
||
function getUnLuaErrors(result) {
|
||
return result.diagnostics.filter((d) => d.source === "ts2lua-unlua");
|
||
}
|
||
|
||
function getLuaCode(result, luaPath) {
|
||
const normalized = luaPath.replace(/\\/g, "/");
|
||
const found = result.transpiledFiles.find((f) => {
|
||
const out = (f.outPath || "").replace(/\\/g, "/");
|
||
return out === normalized || out.endsWith("/" + normalized);
|
||
});
|
||
assert.ok(found, `Expected emitted file '${luaPath}', got: ${result.transpiledFiles.map((f) => f.outPath).join(", ")}`);
|
||
return found.lua;
|
||
}
|
||
|
||
// ============================================================
|
||
// 1. 正常转译(Positive Cases)
|
||
// ============================================================
|
||
|
||
test("@unlua class extending UE native class compiles to UnLua.Class() + self.Overridden + return ClassName", () => {
|
||
const result = transpileWithUnLua({
|
||
"Game/MyActor.ts": `
|
||
@unlua
|
||
export default class MyActor extends UE.AActor {
|
||
private hp!: number;
|
||
static readonly MAX_HP = 100;
|
||
|
||
ReceiveBeginPlay(): void {
|
||
super.ReceiveBeginPlay();
|
||
this.hp = MyActor.MAX_HP;
|
||
}
|
||
|
||
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;
|
||
}
|
||
}
|
||
`,
|
||
});
|
||
|
||
assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2));
|
||
const lua = getLuaCode(result, "Game/MyActor.lua");
|
||
|
||
assert.match(lua, /local MyActor = UnLua\.Class\(\)/);
|
||
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\(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/);
|
||
assert.doesNotMatch(lua, /__TS__Class/);
|
||
assert.doesNotMatch(lua, /__TS__Decorate/);
|
||
});
|
||
|
||
test("@unlua subclass extending another @unlua TS class compiles to UnLua.Class('Game.BaseActor') + BaseActor.Method(self)", () => {
|
||
const result = transpileWithUnLua({
|
||
"Game/BaseActor.ts": `
|
||
@unlua
|
||
export default class BaseActor extends UE.AActor {
|
||
ReceiveBeginPlay(): void {
|
||
super.ReceiveBeginPlay();
|
||
}
|
||
DoWork(val: number): void {
|
||
this.ReceiveTick(val);
|
||
}
|
||
}
|
||
`,
|
||
"Game/SubActor.ts": `
|
||
import BaseActor from "./BaseActor";
|
||
|
||
@unlua
|
||
export default class SubActor extends BaseActor {
|
||
ReceiveBeginPlay(): void {
|
||
super.ReceiveBeginPlay();
|
||
super.DoWork(42);
|
||
}
|
||
}
|
||
`,
|
||
});
|
||
|
||
assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2));
|
||
const lua = getLuaCode(result, "Game/SubActor.lua");
|
||
|
||
assert.match(lua, /local BaseActor = require\("Game\.BaseActor"\)/);
|
||
assert.doesNotMatch(lua, /\.default\b/);
|
||
assert.match(lua, /local SubActor = UnLua\.Class\("Game\.BaseActor"\)/);
|
||
assert.match(lua, /BaseActor\.ReceiveBeginPlay\(self\)/);
|
||
assert.match(lua, /BaseActor\.DoWork\(self, 42\)/);
|
||
assert.match(lua, /return SubActor\s*$/);
|
||
});
|
||
|
||
test("@unlua supports explicit base module path and standalone blueprint classes without extends", () => {
|
||
const result = transpileWithUnLua({
|
||
"UI/WBP_Main.ts": `
|
||
export interface MainUIData { title: string; }
|
||
|
||
@unlua("UI.WBP_Base")
|
||
export default class WBP_Main {
|
||
Construct(): void {
|
||
const data: MainUIData = { title: "hello" };
|
||
void data;
|
||
}
|
||
}
|
||
`,
|
||
});
|
||
|
||
assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2));
|
||
const lua = getLuaCode(result, "UI/WBP_Main.lua");
|
||
|
||
assert.match(lua, /local WBP_Main = UnLua\.Class\("UI\.WBP_Base"\)/);
|
||
assert.match(lua, /return WBP_Main\s*$/);
|
||
});
|
||
|
||
test("const enum, pure TS class, Delegate member method binding, and @unlua-allow-try are allowed", () => {
|
||
const result = transpileWithUnLua({
|
||
"Logic/State.ts": `
|
||
const enum EState {
|
||
Idle = 0,
|
||
Run = 1,
|
||
}
|
||
|
||
export class PureCounter {
|
||
private count = 0;
|
||
constructor(initial: number) {
|
||
this.count = initial;
|
||
}
|
||
Inc(): number {
|
||
this.count += EState.Run;
|
||
return this.count;
|
||
}
|
||
SafeCall(): boolean {
|
||
/** @unlua-allow-try */
|
||
try {
|
||
return this.count > 0;
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
}
|
||
`,
|
||
"UI/ButtonWidget.ts": `
|
||
@unlua
|
||
export default class ButtonWidget extends UE.UUserWidget {
|
||
OnClicked!: UE.FMulticastScriptDelegate<() => void>;
|
||
|
||
Construct(): void {
|
||
this.OnClicked.Add(this, this.HandleClick);
|
||
}
|
||
|
||
Destruct(): void {
|
||
this.OnClicked.Remove(this, this.HandleClick);
|
||
}
|
||
|
||
HandleClick(): void {
|
||
if (this.IsA(UE.UUserWidget.StaticClass())) {
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
`,
|
||
});
|
||
|
||
assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2));
|
||
});
|
||
|
||
// ============================================================
|
||
// 2. 禁用语言特性拦截(Negative Cases: 90001 - 90016)
|
||
// ============================================================
|
||
|
||
test("forbids get/set accessors in classes and object literals", () => {
|
||
const result = transpileWithUnLua({
|
||
"bad.ts": `
|
||
class Foo {
|
||
private _x = 0;
|
||
get x(): number { return this._x; }
|
||
set x(v: number) { this._x = v; }
|
||
}
|
||
export const o = {
|
||
get a() { return 1; },
|
||
};
|
||
export { Foo };
|
||
`,
|
||
});
|
||
|
||
const codes = getUnLuaErrors(result).map((d) => d.code);
|
||
assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenAccessor));
|
||
assert.ok(codes.filter((c) => c === UnLuaDiagnosticCode.ForbiddenAccessor).length >= 3);
|
||
});
|
||
|
||
test("forbids async/await and Promise", () => {
|
||
const result = transpileWithUnLua({
|
||
"bad.ts": `
|
||
export async function fetchSomething(): Promise<number> {
|
||
const p = new Promise<number>((resolve) => resolve(1));
|
||
const v = await p;
|
||
const v2 = await Promise.resolve(2);
|
||
return v + v2;
|
||
}
|
||
`,
|
||
});
|
||
|
||
const codes = getUnLuaErrors(result).map((d) => d.code);
|
||
assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenAsyncAwait));
|
||
assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenPromise));
|
||
});
|
||
|
||
test("forbids try/catch/finally and throw without @unlua-allow-try", () => {
|
||
const result = transpileWithUnLua({
|
||
"bad.ts": `
|
||
export function risky(flag: boolean): void {
|
||
try {
|
||
if (flag) {
|
||
throw "boom";
|
||
}
|
||
} catch (e) {
|
||
void e;
|
||
}
|
||
}
|
||
`,
|
||
});
|
||
|
||
const codes = getUnLuaErrors(result).map((d) => d.code);
|
||
assert.ok(codes.filter((c) => c === UnLuaDiagnosticCode.ForbiddenTryCatchThrow).length >= 2);
|
||
});
|
||
|
||
test("forbids non-whitelisted runtime decorators", () => {
|
||
const result = transpileWithUnLua({
|
||
"bad.ts": `
|
||
function myDec(target: any) { return target; }
|
||
|
||
@myDec
|
||
export class Foo {}
|
||
`,
|
||
});
|
||
|
||
const codes = getUnLuaErrors(result).map((d) => d.code);
|
||
assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenDecorator));
|
||
});
|
||
|
||
test("forbids RegExp, Map, Set, Proxy, Symbol, Object.defineProperty, Reflect, generator, for..in, runtime enum, eval, arguments", () => {
|
||
const result = transpileWithUnLua({
|
||
"bad.ts": `
|
||
export enum EBadEnum { A = 0, B = 1 }
|
||
|
||
export function* gen() {
|
||
yield 1;
|
||
}
|
||
|
||
export function badBuiltins(obj: Record<string, number>) {
|
||
const r1 = /abc/;
|
||
const r2 = new RegExp("abc");
|
||
const m = new Map<string, number>();
|
||
const s = new Set<number>();
|
||
const p = new Proxy(obj, {});
|
||
const sym = Symbol("x");
|
||
Object.defineProperty(obj, "k", { value: 1 });
|
||
Reflect.get(obj, "k");
|
||
eval("1 + 1");
|
||
for (const k in obj) {
|
||
void k;
|
||
}
|
||
const a = arguments;
|
||
return [r1, r2, m, s, p, sym, a];
|
||
}
|
||
`,
|
||
});
|
||
|
||
const codes = new Set(getUnLuaErrors(result).map((d) => d.code));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenRuntimeEnum));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenGenerator));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenRegExp));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenBuiltinType));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenForIn));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenDynamicEvalOrWith));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenArguments));
|
||
});
|
||
|
||
test("forbids delete on array/UObject, instanceof UObject, and spreading UObject", () => {
|
||
const result = transpileWithUnLua({
|
||
"bad.ts": `
|
||
export function check(arr: number[], actor: UE.AActor): boolean {
|
||
delete arr[0];
|
||
delete (actor as any).SomeProp;
|
||
const copy = { ...actor };
|
||
void copy;
|
||
return actor instanceof UE.AActor;
|
||
}
|
||
`,
|
||
});
|
||
|
||
const codes = new Set(getUnLuaErrors(result).map((d) => d.code));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenDeleteOnArrayOrUObject));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenInstanceOfUObject));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenUObjectSpread));
|
||
});
|
||
|
||
// ============================================================
|
||
// 3. @unlua 绑定类专项拦截(Negative Cases: 90101 - 90110)
|
||
// ============================================================
|
||
|
||
test("forbids missing @unlua decorator on class extending UE.UObject (fail-safe)", () => {
|
||
const result = transpileWithUnLua({
|
||
"Game/ForgotDecorator.ts": `
|
||
export default class ForgotDecorator extends UE.AActor {
|
||
ReceiveBeginPlay(): void {}
|
||
}
|
||
`,
|
||
});
|
||
|
||
const codes = getUnLuaErrors(result).map((d) => d.code);
|
||
assert.ok(codes.includes(UnLuaDiagnosticCode.MissingUnLuaDecorator));
|
||
});
|
||
|
||
test("forbids constructor, field initializer, arrow method, and non-default export in @unlua class", () => {
|
||
const result = transpileWithUnLua({
|
||
"Game/BadActor.ts": `
|
||
export const EXTRA = 1;
|
||
|
||
@unlua
|
||
export class BadActor extends UE.AActor {
|
||
private hp = 100;
|
||
OnClick = () => {};
|
||
constructor() {
|
||
super();
|
||
}
|
||
}
|
||
`,
|
||
});
|
||
|
||
const codes = new Set(getUnLuaErrors(result).map((d) => d.code));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaClassMustBeDefaultExport));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaFileExtraRuntimeExport));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaClassForbiddenConstructor));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaClassForbiddenPropertyInitializer));
|
||
});
|
||
|
||
test("forbids 'new MyUnLuaActor()' instantiation", () => {
|
||
const result = transpileWithUnLua({
|
||
"Game/MyActor.ts": `
|
||
@unlua
|
||
export default class MyActor extends UE.AActor {}
|
||
`,
|
||
"Game/Spawner.ts": `
|
||
import MyActor from "./MyActor";
|
||
export function spawnBad() {
|
||
return new MyActor();
|
||
}
|
||
`,
|
||
});
|
||
|
||
const codes = getUnLuaErrors(result).map((d) => d.code);
|
||
assert.ok(codes.includes(UnLuaDiagnosticCode.UnLuaClassForbiddenNew));
|
||
});
|
||
|
||
test("forbids inline arrow/function expression in UE Delegate Add/Bind", () => {
|
||
const result = transpileWithUnLua({
|
||
"UI/BadWidget.ts": `
|
||
@unlua
|
||
export default class BadWidget extends UE.UUserWidget {
|
||
OnClicked!: UE.FMulticastScriptDelegate<() => void>;
|
||
Construct(): void {
|
||
this.OnClicked.Add(this, () => {
|
||
this.Destruct();
|
||
});
|
||
}
|
||
}
|
||
`,
|
||
});
|
||
|
||
const codes = getUnLuaErrors(result).map((d) => d.code);
|
||
assert.ok(codes.includes(UnLuaDiagnosticCode.UnLuaDelegateForbiddenInlineFunction));
|
||
});
|
||
|
||
test("forbids multiple @unlua classes in one file, invalid @unlua args, and direct super property read", () => {
|
||
const result = transpileWithUnLua({
|
||
"Game/Multi.ts": `
|
||
@unlua(123 as any)
|
||
export default class ActorA extends UE.AActor {
|
||
ReceiveBeginPlay(): void {
|
||
const x = super.GetName;
|
||
void x;
|
||
}
|
||
}
|
||
|
||
@unlua
|
||
class ActorB extends UE.AActor {}
|
||
void ActorB;
|
||
`,
|
||
});
|
||
|
||
const codes = new Set(getUnLuaErrors(result).map((d) => d.code));
|
||
assert.ok(codes.has(UnLuaDiagnosticCode.InvalidUnLuaDecoratorArgs));
|
||
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);
|
||
}
|
||
});
|