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
+749 -31

No files matched your search

+14
View File
@@ -4,6 +4,20 @@ All notable changes to `ts2lua-unreal` will be documented in this file.
The format is based on [Semantic Versioning](https://semver.org/). The format is based on [Semantic Versioning](https://semver.org/).
## [0.2.2] - 2026-11-29
### Fixed
- **修复可选链(`a?.b?.c`)触发插件崩溃**:TSTL 转译可选链时会合成无 `SourceFile` / 无 `parent` 的临时 `Identifier` 节点;为 `tryTransformUnLuaSelfClassIdentifier`、`hasAllowTryComment` 与 `arguments` 校验补齐空值保护。
- **修复 `@unlua` 类静态方法 `self` 参数不匹配 Bug**:移除 `methodHasSelfParam` 中无条件剔除 `static` 方法 `self` 的错误逻辑,使其与 TSTL 调用侧的冒号调用(`ClassName:StaticMethod(...)`)一致,并支持 `this: void`、`/** @noSelf */` 与 `/** @noSelfInFile */` 点号调用;同时在 `super.Method(...)` 调用 `@unlua` 父类方法时尊重目标方法的 `@noSelf` 声明。
- **修复 `@unlua` 类方法解构参数未展开 Bug**:完整支持对象解构、数组解构、重命名、嵌套解构、默认值与剩余元素(`...rest`)展开。
- **修复混合默认导入与纯类型命名导入(`import Base, { type BaseCfg } from "./Base"`)生成 `.default` 的 Bug**:当命名导入全为编译期擦除类型时,仍直接生成 `local Base = require("...")`。
### Added
- **编译期宏 `UnLua.Delegate(target, callback)`**:在 [types/unlua.d.ts](types/unlua.d.ts) 中声明并在插件编译期直接内联为 `{ target, callback }`,用于类型安全且零开销地调用 `K2_SetTimerDelegate` / `LoadAsset` / `BindToAnimationFinished` 等接收 `UE.FScriptDelegate` 参数的 UE API;同时在编译期拦截对 `UnLua.Delegate` 传入箭头函数或匿名函数(`90107`)。
- **补齐 UnLua 全局运行时类型声明**:新增 `UnLua.Log` / `LogWarn` / `LogError`、`UnLua.Input`(`BindKey` / `BindAction` / `BindAxis`)及 `UnLua.EnhancedInput`(`BindAction`),并让 `UE.TArray<T>` / `UE.TMap<K, V>` 继承 `LuaPairsIterable`,支持 `for (const [k, v] of container)` 直接编译为 Lua 原生 `pairs()` 遍历。
- **增强编译期约束检查**:新增拦截 `BigInt` 字面量(`123n`)、`new UE.AActor()` / `new UE.UObject()` 误实例化,以及继承独立 `@unlua` 类时漏标 `@unlua` 的防呆检查。
- **扩展插件测试套件**:[test/plugin.test.mjs](test/plugin.test.mjs) 增至 23 组测试,并结合本机 `lua5.4` 执行编译产物验证运行时语义。
## [0.2.1] - 2026-11-29 ## [0.2.1] - 2026-11-29
### Fixed ### Fixed
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "ts2lua-unreal", "name": "ts2lua-unreal",
"version": "0.2.1", "version": "0.2.2",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ts2lua-unreal", "name": "ts2lua-unreal",
"version": "0.2.1", "version": "0.2.2",
"dependencies": { "dependencies": {
"lua-types": "^2.14.1", "lua-types": "^2.14.1",
"typescript": "6.0.2", "typescript": "6.0.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "ts2lua-unreal", "name": "ts2lua-unreal",
"version": "0.2.1", "version": "0.2.2",
"description": "TypeScript to Lua toolchain and compiler plugin tailored for Unreal Engine + UnLua", "description": "TypeScript to Lua toolchain and compiler plugin tailored for Unreal Engine + UnLua",
"main": "dist/plugin/index.js", "main": "dist/plugin/index.js",
"types": "dist/plugin/index.d.ts", "types": "dist/plugin/index.d.ts",
+5
View File
@@ -6,6 +6,7 @@ import {
transformUnLuaClassDeclaration, transformUnLuaClassDeclaration,
transformUnLuaSourceFile, transformUnLuaSourceFile,
tryTransformUnLuaDefaultImport, tryTransformUnLuaDefaultImport,
tryTransformUnLuaDelegateCall,
tryTransformUnLuaSelfClassIdentifier, tryTransformUnLuaSelfClassIdentifier,
tryTransformUnLuaSuperCall, tryTransformUnLuaSuperCall,
} from "./unlua-transform"; } from "./unlua-transform";
@@ -71,6 +72,10 @@ export function createUnLuaPlugin(): tstl.Plugin {
[ts.SyntaxKind.CallExpression]: (node, context) => { [ts.SyntaxKind.CallExpression]: (node, context) => {
validateCallExpression(node, context); validateCallExpression(node, context);
const delegateCall = tryTransformUnLuaDelegateCall(node, context);
if (delegateCall) {
return delegateCall;
}
const superCall = tryTransformUnLuaSuperCall(node, context); const superCall = tryTransformUnLuaSuperCall(node, context);
if (superCall) { if (superCall) {
return superCall; return superCall;
+26
View File
@@ -186,6 +186,31 @@ export function classExtendsUObject(
return false; return false;
} }
/**
* 判断类的基类是否继承自另一个 @unlua 绑定类。
*/
export function classExtendsUnLuaClass(
node: ts.ClassLikeDeclaration,
checker: ts.TypeChecker
): boolean {
const ext = getExtendsClause(node);
if (!ext) return false;
const baseInstanceType = checker.getTypeFromTypeNode(ext);
if (isUnLuaClassType(baseInstanceType, checker)) {
return true;
}
const baseValueType = checker.getTypeAtLocation(ext);
for (const sig of baseValueType.getConstructSignatures()) {
if (isUnLuaClassType(sig.getReturnType(), checker)) {
return true;
}
}
return false;
}
/** /**
* 判断某个类型对应的类声明是否为 @unlua 类(带 WeakMap 缓存)。 * 判断某个类型对应的类声明是否为 @unlua 类(带 WeakMap 缓存)。
*/ */
@@ -306,6 +331,7 @@ export function resolveLuaModuleName(sourceFile: ts.SourceFile, program: ts.Prog
*/ */
export function hasAllowTryComment(node: ts.Node): boolean { export function hasAllowTryComment(node: ts.Node): boolean {
const sf = node.getSourceFile(); const sf = node.getSourceFile();
if (!sf) return false;
const fullText = sf.getFullText(); const fullText = sf.getFullText();
const ranges = ts.getLeadingCommentRanges(fullText, node.getFullStart()); const ranges = ts.getLeadingCommentRanges(fullText, node.getFullStart());
if (!ranges) return false; if (!ranges) return false;
+312 -16
View File
@@ -38,23 +38,33 @@ function isStaticMember(member: ts.ClassElement): boolean {
return ts.getModifiers(member)?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword) ?? false; return ts.getModifiers(member)?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword) ?? false;
} }
function hasNoSelfJsDoc(node: ts.Node): boolean { function hasJsDocTag(node: ts.Node, tagName: string): boolean {
const tags = ts.getJSDocTags(node); const tags = ts.getJSDocTags(node);
return tags.some((tag) => tag.tagName.text === "noSelf"); return tags.some((tag) => tag.tagName.text === tagName);
}
function fileHasNoSelfInFile(sf: ts.SourceFile): boolean {
const fullText = sf.getFullText();
const ranges = ts.getLeadingCommentRanges(fullText, 0);
if (!ranges) return false;
for (const range of ranges) {
const text = fullText.slice(range.pos, range.end);
if (text.includes("@noSelfInFile")) {
return true;
}
}
return false;
} }
function methodHasSelfParam(method: ts.MethodDeclaration): boolean { function methodHasSelfParam(method: ts.MethodDeclaration): boolean {
if (isStaticMember(method)) return false;
if (hasNoSelfJsDoc(method)) return false;
const firstParam = method.parameters[0]; const firstParam = method.parameters[0];
if ( if (firstParam && ts.isIdentifier(firstParam.name) && firstParam.name.text === "this") {
firstParam && return firstParam.type?.kind !== ts.SyntaxKind.VoidKeyword;
ts.isIdentifier(firstParam.name) &&
firstParam.name.text === "this" &&
firstParam.type?.kind === ts.SyntaxKind.VoidKeyword
) {
return false;
} }
if (hasJsDocTag(method, "noSelf")) return false;
const enclosingClass = findEnclosingClass(method);
if (enclosingClass && hasJsDocTag(enclosingClass, "noSelf")) return false;
if (fileHasNoSelfInFile(method.getSourceFile())) return false;
return true; return true;
} }
@@ -77,6 +87,216 @@ function getPropertyKeyExpression(
return tstl.createStringLiteral(name.getText(), name); return tstl.createStringLiteral(name.getText(), name);
} }
/**
* 将解构参数模式(ObjectBindingPattern / ArrayBindingPattern)展开为 Lua 局部变量声明语句。
*/
function transformBindingPattern(
pattern: ts.BindingName,
sourceExpr: tstl.Expression,
context: tstl.TransformationContext,
outStatements: tstl.Statement[]
): void {
if (ts.isIdentifier(pattern)) {
outStatements.push(
tstl.createVariableDeclarationStatement(
tstl.createIdentifier(pattern.text, pattern),
sourceExpr,
pattern
)
);
return;
}
// 复杂模式先绑定到临时变量,避免重复求值 sourceExpr
let containerId: tstl.Identifier;
if (tstl.isIdentifier(sourceExpr)) {
containerId = tstl.cloneIdentifier(sourceExpr);
} else {
containerId = tstl.createIdentifier(context.createTempName("binding"), pattern);
outStatements.push(
tstl.createVariableDeclarationStatement(containerId, sourceExpr, pattern)
);
}
if (ts.isObjectBindingPattern(pattern)) {
for (const element of pattern.elements) {
if (element.dotDotDotToken) {
// 简化支持:对象剩余属性暂不引入重型 __TS__ObjectRest
if (ts.isIdentifier(element.name)) {
outStatements.push(
tstl.createVariableDeclarationStatement(
tstl.createIdentifier(element.name.text, element.name),
tstl.createTableExpression([], element),
element
)
);
}
continue;
}
const propKey = element.propertyName
? getPropertyKeyExpression(element.propertyName, context)
: ts.isIdentifier(element.name)
? tstl.createStringLiteral(element.name.text, element.name)
: tstl.createStringLiteral(element.name.getText(), element.name);
const accessExpr = tstl.createTableIndexExpression(
tstl.cloneIdentifier(containerId),
propKey,
element
);
if (ts.isIdentifier(element.name)) {
const targetId = tstl.createIdentifier(element.name.text, element.name);
outStatements.push(
tstl.createVariableDeclarationStatement(targetId, accessExpr, element)
);
if (element.initializer) {
const defaultExpr = context.transformExpression(element.initializer);
if (!tstl.isNilLiteral(defaultExpr)) {
const cond = tstl.createBinaryExpression(
tstl.cloneIdentifier(targetId),
tstl.createNilLiteral(),
tstl.SyntaxKind.EqualityOperator
);
const assign = tstl.createAssignmentStatement(
tstl.cloneIdentifier(targetId),
defaultExpr,
element
);
outStatements.push(
tstl.createIfStatement(cond, tstl.createBlock([assign]), undefined, element)
);
}
}
} else {
const nestedTmp = tstl.createIdentifier(context.createTempName("binding"), element);
outStatements.push(
tstl.createVariableDeclarationStatement(nestedTmp, accessExpr, element)
);
if (element.initializer) {
const defaultExpr = context.transformExpression(element.initializer);
if (!tstl.isNilLiteral(defaultExpr)) {
const cond = tstl.createBinaryExpression(
tstl.cloneIdentifier(nestedTmp),
tstl.createNilLiteral(),
tstl.SyntaxKind.EqualityOperator
);
const assign = tstl.createAssignmentStatement(
tstl.cloneIdentifier(nestedTmp),
defaultExpr,
element
);
outStatements.push(
tstl.createIfStatement(cond, tstl.createBlock([assign]), undefined, element)
);
}
}
transformBindingPattern(element.name, nestedTmp, context, outStatements);
}
}
return;
}
if (ts.isArrayBindingPattern(pattern)) {
for (let i = 0; i < pattern.elements.length; i++) {
const element = pattern.elements[i];
if (ts.isOmittedExpression(element)) {
continue;
}
const luaIndex = i + 1;
if (element.dotDotDotToken) {
if (ts.isIdentifier(element.name)) {
const restId = tstl.createIdentifier(element.name.text, element.name);
// local rest = {}; table.move(src, luaIndex, #src, 1, rest)
outStatements.push(
tstl.createVariableDeclarationStatement(
restId,
tstl.createTableExpression([], element),
element
)
);
const moveCall = tstl.createCallExpression(
tstl.createTableIndexExpression(
tstl.createIdentifier("table"),
tstl.createStringLiteral("move")
),
[
tstl.cloneIdentifier(containerId),
tstl.createNumericLiteral(luaIndex),
tstl.createUnaryExpression(
tstl.cloneIdentifier(containerId),
tstl.SyntaxKind.LengthOperator
),
tstl.createNumericLiteral(1),
tstl.cloneIdentifier(restId),
],
element
);
outStatements.push(tstl.createExpressionStatement(moveCall, element));
}
continue;
}
const accessExpr = tstl.createTableIndexExpression(
tstl.cloneIdentifier(containerId),
tstl.createNumericLiteral(luaIndex),
element
);
if (ts.isIdentifier(element.name)) {
const targetId = tstl.createIdentifier(element.name.text, element.name);
outStatements.push(
tstl.createVariableDeclarationStatement(targetId, accessExpr, element)
);
if (element.initializer) {
const defaultExpr = context.transformExpression(element.initializer);
if (!tstl.isNilLiteral(defaultExpr)) {
const cond = tstl.createBinaryExpression(
tstl.cloneIdentifier(targetId),
tstl.createNilLiteral(),
tstl.SyntaxKind.EqualityOperator
);
const assign = tstl.createAssignmentStatement(
tstl.cloneIdentifier(targetId),
defaultExpr,
element
);
outStatements.push(
tstl.createIfStatement(cond, tstl.createBlock([assign]), undefined, element)
);
}
}
} else {
const nestedTmp = tstl.createIdentifier(context.createTempName("binding"), element);
outStatements.push(
tstl.createVariableDeclarationStatement(nestedTmp, accessExpr, element)
);
if (element.initializer) {
const defaultExpr = context.transformExpression(element.initializer);
if (!tstl.isNilLiteral(defaultExpr)) {
const cond = tstl.createBinaryExpression(
tstl.cloneIdentifier(nestedTmp),
tstl.createNilLiteral(),
tstl.SyntaxKind.EqualityOperator
);
const assign = tstl.createAssignmentStatement(
tstl.cloneIdentifier(nestedTmp),
defaultExpr,
element
);
outStatements.push(
tstl.createIfStatement(cond, tstl.createBlock([assign]), undefined, element)
);
}
}
transformBindingPattern(element.name, nestedTmp, context, outStatements);
}
}
}
}
/** /**
* 将 @unlua 类中的 MethodDeclaration 转换为 Lua 赋值函数声明: * 将 @unlua 类中的 MethodDeclaration 转换为 Lua 赋值函数声明:
* function ClassName.MethodName(self, ...) * function ClassName.MethodName(self, ...)
@@ -145,9 +365,28 @@ function transformUnLuaMethod(
} }
} }
} else { } else {
// 解构参数兜底:分配临时形参并展开(尽量少用) // 解构参数:分配临时形参并展开(支持默认值与嵌套解构)
const tmpId = tstl.createIdentifier(context.createTempName("param"), param); const tmpId = tstl.createIdentifier(context.createTempName("param"), param);
params.push(tmpId); params.push(tmpId);
if (param.initializer) {
const defaultExpr = context.transformExpression(param.initializer);
if (!tstl.isNilLiteral(defaultExpr)) {
const cond = tstl.createBinaryExpression(
tstl.cloneIdentifier(tmpId),
tstl.createNilLiteral(),
tstl.SyntaxKind.EqualityOperator
);
const assign = tstl.createAssignmentStatement(
tstl.cloneIdentifier(tmpId),
defaultExpr,
param
);
headerStatements.push(
tstl.createIfStatement(cond, tstl.createBlock([assign]), undefined, param)
);
}
}
transformBindingPattern(param.name, tmpId, context, headerStatements);
} }
} }
@@ -266,10 +505,18 @@ export function tryTransformUnLuaDefaultImport(
return undefined; return undefined;
} }
// 仅处理纯默认导入(@unlua 文件本身禁止额外命名导出) // 若包含命名导入,只要全部是纯类型导入(type-only 或编译期擦除的 interface/type/const enum),仍按纯默认导入处理
if (importClause.namedBindings) { if (importClause.namedBindings) {
if (!ts.isNamedImports(importClause.namedBindings)) {
return undefined; return undefined;
} }
const hasRuntimeNamedImport = importClause.namedBindings.elements.some(
(el) => !el.isTypeOnly && context.resolver.isReferencedAliasDeclaration(el)
);
if (hasRuntimeNamedImport) {
return undefined;
}
}
if (!ts.isStringLiteral(node.moduleSpecifier)) { if (!ts.isStringLiteral(node.moduleSpecifier)) {
return undefined; return undefined;
@@ -334,13 +581,17 @@ export function tryTransformUnLuaSelfClassIdentifier(
node: ts.Identifier, node: ts.Identifier,
context: tstl.TransformationContext context: tstl.TransformationContext
): tstl.Expression | undefined { ): tstl.Expression | undefined {
const sf = node.getSourceFile(); const sf = node.getSourceFile() ?? context.sourceFile;
if (!sf) return undefined;
const className = getFilePrimaryUnLuaClassName(sf); const className = getFilePrimaryUnLuaClassName(sf);
if (!className || node.text !== className) { if (!className || node.text !== className) {
return undefined; return undefined;
} }
const parent = node.parent; const parent = node.parent;
if (!parent) {
return undefined;
}
// 跳过属性名、声明名等非值引用位置 // 跳过属性名、声明名等非值引用位置
if ( if (
(ts.isPropertyAccessExpression(parent) && parent.name === node) || (ts.isPropertyAccessExpression(parent) && parent.name === node) ||
@@ -435,13 +686,24 @@ export function tryTransformUnLuaSuperCall(
} }
if (superInfo.kind === "unlua-ts" && superInfo.baseLocalName) { if (superInfo.kind === "unlua-ts" && superInfo.baseLocalName) {
// ParentClass.Method(self, ...) // 检查被调用的父类方法是否标注了 @noSelf / this: void
const calleeType = context.checker.getTypeAtLocation(callee);
const callSigs = calleeType.getCallSignatures();
let targetHasSelf = true;
if (callSigs.length > 0) {
const decl = callSigs[0].getDeclaration();
if (decl && ts.isMethodDeclaration(decl)) {
targetHasSelf = methodHasSelfParam(decl);
}
}
const finalArgs = targetHasSelf ? callArgs : transformedArgs;
// ParentClass.Method(self, ...) 或 ParentClass.Method(...)
const fnAccess = tstl.createTableIndexExpression( const fnAccess = tstl.createTableIndexExpression(
tstl.createIdentifier(superInfo.baseLocalName), tstl.createIdentifier(superInfo.baseLocalName),
methodKey, methodKey,
callee callee
); );
return tstl.createCallExpression(fnAccess, callArgs, node); return tstl.createCallExpression(fnAccess, finalArgs, node);
} }
context.diagnostics.push( context.diagnostics.push(
@@ -453,3 +715,37 @@ export function tryTransformUnLuaSuperCall(
); );
return tstl.createNilLiteral(node); return tstl.createNilLiteral(node);
} }
/**
* 编译期宏转换:`UnLua.Delegate(target, callback)` -> `{ target, callback }`
* 用于向 `K2_SetTimerDelegate` / `LoadAsset` 等 UE FScriptDelegate 参数传递 UnLua 委托表,零运行时开销。
*/
export function tryTransformUnLuaDelegateCall(
node: ts.CallExpression,
context: tstl.TransformationContext
): tstl.Expression | undefined {
const callee = node.expression;
if (
!ts.isPropertyAccessExpression(callee) ||
!ts.isIdentifier(callee.expression) ||
callee.expression.text !== "UnLua" ||
callee.name.text !== "Delegate"
) {
return undefined;
}
if (node.arguments.length < 2) {
return undefined;
}
const targetExpr = context.transformExpression(node.arguments[0]);
const callbackExpr = context.transformExpression(node.arguments[1]);
return tstl.createTableExpression(
[
tstl.createTableFieldExpression(targetExpr),
tstl.createTableFieldExpression(callbackExpr),
],
node
);
}
+33 -9
View File
@@ -3,6 +3,7 @@ import * as tstl from "typescript-to-lua";
import { createUnLuaDiagnostic, UnLuaDiagnosticCode } from "./diagnostics"; import { createUnLuaDiagnostic, UnLuaDiagnosticCode } from "./diagnostics";
import { import {
ALLOWED_DECORATOR_NAMES, ALLOWED_DECORATOR_NAMES,
classExtendsUnLuaClass,
classExtendsUObject, classExtendsUObject,
getDecoratorName, getDecoratorName,
getUnLuaDecorator, getUnLuaDecorator,
@@ -195,17 +196,17 @@ export function validateClassDeclaration(
} }
} }
} else { } else {
// 漏标防呆:继承了 UE.UObject 却未标注 @unlua // 漏标防呆:继承了 UE.UObject 或另一个 @unlua 类却未标注 @unlua
if (classExtendsUObject(node, context.checker)) { if (classExtendsUObject(node, context.checker) || classExtendsUnLuaClass(node, context.checker)) {
report( report(
context, context,
node.name ?? node, node.name ?? node,
UnLuaDiagnosticCode.MissingUnLuaDecorator, UnLuaDiagnosticCode.MissingUnLuaDecorator,
"该类继承自 UE.UObject(或其派生类),但缺少 '@unlua' 装饰器。请补充 '@unlua' 并使用 'export default class',避免被误编译为普通 __TS__Class。" "该类继承自 UE.UObject 或 @unlua 绑定类,但缺少 '@unlua' 装饰器。请补充 '@unlua' 并使用 'export default class',避免被误编译为普通 __TS__Class。"
); );
} }
// 普通类同样检查成员装饰器与禁用项(get/set 访问器、async/generator 方法等) // 普通类同样检查成员装饰器与禁用项(get/set 访问器、async/generator 方法等;TSTL 不会触发独立的 GetAccessor/SetAccessor visitor)
for (const member of node.members) { for (const member of node.members) {
validateDecorators(member, context); validateDecorators(member, context);
if (ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)) { if (ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)) {
@@ -350,12 +351,12 @@ export function validateNewExpression(
} }
const instanceType = context.checker.getTypeAtLocation(node); const instanceType = context.checker.getTypeAtLocation(node);
if (isUnLuaClassType(instanceType, context.checker)) { if (isUnLuaClassType(instanceType, context.checker) || isUObjectType(instanceType, context.checker)) {
report( report(
context, context,
node, node,
UnLuaDiagnosticCode.UnLuaClassForbiddenNew, UnLuaDiagnosticCode.UnLuaClassForbiddenNew,
"禁止使用 'new' 实例化 @unlua 绑定类。请通过 UE API(如 SpawnActor / UE.NewObject / CreateWidget)创建。" "禁止使用 'new' 实例化 UE.UObject 或 @unlua 绑定类。请通过 UE API(如 SpawnActor / UE.NewObject / CreateWidget)创建。"
); );
} }
} }
@@ -442,6 +443,18 @@ export function validateCallExpression(
); );
return; return;
} }
if (obj.text === "UnLua" && propName === "Delegate" && node.arguments.length >= 2) {
const callbackArg = node.arguments[1];
if (ts.isArrowFunction(callbackArg) || ts.isFunctionExpression(callbackArg)) {
report(
context,
callbackArg,
UnLuaDiagnosticCode.UnLuaDelegateForbiddenInlineFunction,
"UnLua.Delegate 禁止传入箭头函数或匿名函数(无法成对清理且易导致闭包泄漏)。请传入类成员方法引用,如 'this.OnTimer'。"
);
}
return;
}
} }
// Delegate.Add(self, fn) / Delegate.Bind(self, fn) 禁止传入箭头函数或匿名函数 // Delegate.Add(self, fn) / Delegate.Bind(self, fn) 禁止传入箭头函数或匿名函数
@@ -684,13 +697,14 @@ export function createSimpleValidationVisitors(): tstl.Visitors {
if (node.text === "arguments") { if (node.text === "arguments") {
const parent = node.parent; const parent = node.parent;
const isPropertyOrDeclName = const isPropertyOrDeclName =
(ts.isPropertyAccessExpression(parent) && parent.name === node) || parent !== undefined &&
((ts.isPropertyAccessExpression(parent) && parent.name === node) ||
(ts.isPropertyAssignment(parent) && parent.name === node) || (ts.isPropertyAssignment(parent) && parent.name === node) ||
(ts.isPropertySignature(parent) && parent.name === node) || (ts.isPropertySignature(parent) && parent.name === node) ||
(ts.isMethodDeclaration(parent) && parent.name === node) || (ts.isMethodDeclaration(parent) && parent.name === node) ||
(ts.isParameter(parent) && parent.name === node) || (ts.isParameter(parent) && parent.name === node) ||
(ts.isVariableDeclaration(parent) && parent.name === node); (ts.isVariableDeclaration(parent) && parent.name === node));
if (!isPropertyOrDeclName) { if (parent !== undefined && !isPropertyOrDeclName) {
report( report(
context, context,
node, node,
@@ -717,6 +731,16 @@ export function createSimpleValidationVisitors(): tstl.Visitors {
return context.superTransformExpression(node); return context.superTransformExpression(node);
}, },
[ts.SyntaxKind.BigIntLiteral]: (node, context) => {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenBuiltinType,
"禁用 BigInt 字面量(Lua 不支持 JS BigInt)。请使用 number 或字符串表示大整数 ID。"
);
return tstl.createNilLiteral(node);
},
[ts.SyntaxKind.ObjectLiteralExpression]: (node, context) => { [ts.SyntaxKind.ObjectLiteralExpression]: (node, context) => {
for (const prop of node.properties) { for (const prop of node.properties) {
if (ts.isSpreadAssignment(prop)) { if (ts.isSpreadAssignment(prop)) {
+290 -1
View File
@@ -5,8 +5,13 @@ import * as path from "node:path";
import * as ts from "typescript"; import * as ts from "typescript";
import * as tstl from "typescript-to-lua"; import * as tstl from "typescript-to-lua";
import { createRequire } from "node:module"; import { createRequire } from "node:module";
import { spawnSync } from "node:child_process";
const require = createRequire(import.meta.url); 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 projectRoot = path.resolve(import.meta.dirname, "..");
const unluaTypesPath = path.join(projectRoot, "types", "unlua.d.ts"); const unluaTypesPath = path.join(projectRoot, "types", "unlua.d.ts");
const unluaTypesContent = fs.readFileSync(unluaTypesPath, "utf8"); 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 { static Helper(a: number, b = 10): number {
return a + b; 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, /function MyActor\.ReceiveBeginPlay\(self\)/);
assert.match(lua, /self\.Overridden\.ReceiveBeginPlay\(self\)/); assert.match(lua, /self\.Overridden\.ReceiveBeginPlay\(self\)/);
assert.match(lua, /MyActor\.MAX_HP = 100/); 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, /if b == nil then/);
assert.match(lua, /return MyActor\s*$/); assert.match(lua, /return MyActor\s*$/);
assert.doesNotMatch(lua, /____exports/); 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.UnLuaMultipleClassesInFile));
assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaForbiddenSuperUsage)); 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);
}
});
+66 -2
View File
@@ -33,6 +33,70 @@ declare namespace UnLua {
function Unref(obj: UE.UObject): void; function Unref(obj: UE.UObject): void;
/** @noSelf */ /** @noSelf */
function HotReload(moduleNames?: string[]): void; function HotReload(moduleNames?: string[]): void;
/** @noSelf */
function Log(...args: any[]): void;
/** @noSelf */
function LogWarn(...args: any[]): void;
/** @noSelf */
function LogError(...args: any[]): void;
/**
* 编译期宏:生成 UnLua 单播动态委托绑定表 `{ target, callback }`,
* 用于传给 `K2_SetTimerDelegate`、`LoadAsset`、`BindToAnimationFinished` 等接收 `UE.FScriptDelegate` 参数的 UE API。
* 编译后直接内联为 `{ target, callback }`,零运行时开销。
* @noSelf
*/
function Delegate<TCallback extends (...args: any[]) => any>(
target: UE.UObject,
callback: TCallback
): UE.FScriptDelegate<TCallback>;
interface InputBindingArgs {
ConsumeInput?: boolean;
ExecuteWhenPaused?: boolean;
OverrideParentBinding?: boolean;
Ctrl?: boolean;
Alt?: boolean;
Shift?: boolean;
Cmd?: boolean;
}
namespace Input {
/** @noSelf */
function BindKey<TSelf = any>(
module: unknown,
keyName: string,
keyEvent: "Pressed" | "Released" | "Repeat" | "DoubleClick" | "Axis",
handler: (this: TSelf, key: any) => void,
args?: InputBindingArgs
): void;
/** @noSelf */
function BindAction<TSelf = any>(
module: unknown,
actionName: string,
keyEvent: "Pressed" | "Released" | "Repeat" | "DoubleClick" | "Axis",
handler: (this: TSelf, key: any) => void,
args?: InputBindingArgs
): void;
/** @noSelf */
function BindAxis<TSelf = any>(
module: unknown,
axisName: string,
handler: (this: TSelf, axisValue: number) => void,
args?: InputBindingArgs
): void;
}
namespace EnhancedInput {
/** @noSelf */
function BindAction<TSelf = any>(
module: unknown,
actionPath: string,
triggerEvent: "Triggered" | "Started" | "Ongoing" | "Canceled" | "Completed",
handler: (this: TSelf, actionValue: any, elapsedSeconds?: number, triggeredSeconds?: number, sourceAction?: any) => void,
args?: Record<string, unknown>
): void;
}
} }
/** /**
@@ -98,7 +162,7 @@ declare namespace UE {
Execute(...args: Parameters<TCallback>): ReturnType<TCallback>; Execute(...args: Parameters<TCallback>): ReturnType<TCallback>;
} }
interface TArray<T> { interface TArray<T> extends LuaPairsIterable<number, T> {
Length(): number; Length(): number;
Num(): number; Num(): number;
Add(item: T): number; Add(item: T): number;
@@ -124,7 +188,7 @@ declare namespace UE {
} }
function TArray<T>(this: void, elementType: any): TArray<T>; function TArray<T>(this: void, elementType: any): TArray<T>;
interface TMap<K, V> { interface TMap<K, V> extends LuaPairsIterable<K & {}, V> {
Length(): number; Length(): number;
Num(): number; Num(): number;
Add(key: K, value: V): void; Add(key: K, value: V): void;