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

+5
View File
@@ -6,6 +6,7 @@ import {
transformUnLuaClassDeclaration,
transformUnLuaSourceFile,
tryTransformUnLuaDefaultImport,
tryTransformUnLuaDelegateCall,
tryTransformUnLuaSelfClassIdentifier,
tryTransformUnLuaSuperCall,
} from "./unlua-transform";
@@ -71,6 +72,10 @@ export function createUnLuaPlugin(): tstl.Plugin {
[ts.SyntaxKind.CallExpression]: (node, context) => {
validateCallExpression(node, context);
const delegateCall = tryTransformUnLuaDelegateCall(node, context);
if (delegateCall) {
return delegateCall;
}
const superCall = tryTransformUnLuaSuperCall(node, context);
if (superCall) {
return superCall;
+26
View File
@@ -186,6 +186,31 @@ export function classExtendsUObject(
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 缓存)。
*/
@@ -306,6 +331,7 @@ export function resolveLuaModuleName(sourceFile: ts.SourceFile, program: ts.Prog
*/
export function hasAllowTryComment(node: ts.Node): boolean {
const sf = node.getSourceFile();
if (!sf) return false;
const fullText = sf.getFullText();
const ranges = ts.getLeadingCommentRanges(fullText, node.getFullStart());
if (!ranges) return false;
+313 -17
View File
@@ -38,23 +38,33 @@ function isStaticMember(member: ts.ClassElement): boolean {
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);
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 {
if (isStaticMember(method)) return false;
if (hasNoSelfJsDoc(method)) return false;
const firstParam = method.parameters[0];
if (
firstParam &&
ts.isIdentifier(firstParam.name) &&
firstParam.name.text === "this" &&
firstParam.type?.kind === ts.SyntaxKind.VoidKeyword
) {
return false;
if (firstParam && ts.isIdentifier(firstParam.name) && firstParam.name.text === "this") {
return firstParam.type?.kind !== ts.SyntaxKind.VoidKeyword;
}
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;
}
@@ -77,6 +87,216 @@ function getPropertyKeyExpression(
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 赋值函数声明:
* function ClassName.MethodName(self, ...)
@@ -145,9 +365,28 @@ function transformUnLuaMethod(
}
}
} else {
// 解构参数兜底:分配临时形参并展开(尽量少用)
// 解构参数:分配临时形参并展开(支持默认值与嵌套解构)
const tmpId = tstl.createIdentifier(context.createTempName("param"), param);
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,9 +505,17 @@ export function tryTransformUnLuaDefaultImport(
return undefined;
}
// 仅处理纯默认导入(@unlua 文件本身禁止额外命名导出)
// 若包含命名导入,只要全部是纯类型导入(type-only 或编译期擦除的 interface/type/const enum),仍按纯默认导入处理
if (importClause.namedBindings) {
return undefined;
if (!ts.isNamedImports(importClause.namedBindings)) {
return undefined;
}
const hasRuntimeNamedImport = importClause.namedBindings.elements.some(
(el) => !el.isTypeOnly && context.resolver.isReferencedAliasDeclaration(el)
);
if (hasRuntimeNamedImport) {
return undefined;
}
}
if (!ts.isStringLiteral(node.moduleSpecifier)) {
@@ -334,13 +581,17 @@ export function tryTransformUnLuaSelfClassIdentifier(
node: ts.Identifier,
context: tstl.TransformationContext
): tstl.Expression | undefined {
const sf = node.getSourceFile();
const sf = node.getSourceFile() ?? context.sourceFile;
if (!sf) return undefined;
const className = getFilePrimaryUnLuaClassName(sf);
if (!className || node.text !== className) {
return undefined;
}
const parent = node.parent;
if (!parent) {
return undefined;
}
// 跳过属性名、声明名等非值引用位置
if (
(ts.isPropertyAccessExpression(parent) && parent.name === node) ||
@@ -435,13 +686,24 @@ export function tryTransformUnLuaSuperCall(
}
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(
tstl.createIdentifier(superInfo.baseLocalName),
methodKey,
callee
);
return tstl.createCallExpression(fnAccess, callArgs, node);
return tstl.createCallExpression(fnAccess, finalArgs, node);
}
context.diagnostics.push(
@@ -453,3 +715,37 @@ export function tryTransformUnLuaSuperCall(
);
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
);
}
+37 -13
View File
@@ -3,6 +3,7 @@ import * as tstl from "typescript-to-lua";
import { createUnLuaDiagnostic, UnLuaDiagnosticCode } from "./diagnostics";
import {
ALLOWED_DECORATOR_NAMES,
classExtendsUnLuaClass,
classExtendsUObject,
getDecoratorName,
getUnLuaDecorator,
@@ -195,17 +196,17 @@ export function validateClassDeclaration(
}
}
} else {
// 漏标防呆:继承了 UE.UObject 却未标注 @unlua
if (classExtendsUObject(node, context.checker)) {
// 漏标防呆:继承了 UE.UObject 或另一个 @unlua 类却未标注 @unlua
if (classExtendsUObject(node, context.checker) || classExtendsUnLuaClass(node, context.checker)) {
report(
context,
node.name ?? node,
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) {
validateDecorators(member, context);
if (ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)) {
@@ -350,12 +351,12 @@ export function validateNewExpression(
}
const instanceType = context.checker.getTypeAtLocation(node);
if (isUnLuaClassType(instanceType, context.checker)) {
if (isUnLuaClassType(instanceType, context.checker) || isUObjectType(instanceType, context.checker)) {
report(
context,
node,
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;
}
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) 禁止传入箭头函数或匿名函数
@@ -684,13 +697,14 @@ export function createSimpleValidationVisitors(): tstl.Visitors {
if (node.text === "arguments") {
const parent = node.parent;
const isPropertyOrDeclName =
(ts.isPropertyAccessExpression(parent) && parent.name === node) ||
(ts.isPropertyAssignment(parent) && parent.name === node) ||
(ts.isPropertySignature(parent) && parent.name === node) ||
(ts.isMethodDeclaration(parent) && parent.name === node) ||
(ts.isParameter(parent) && parent.name === node) ||
(ts.isVariableDeclaration(parent) && parent.name === node);
if (!isPropertyOrDeclName) {
parent !== undefined &&
((ts.isPropertyAccessExpression(parent) && parent.name === node) ||
(ts.isPropertyAssignment(parent) && parent.name === node) ||
(ts.isPropertySignature(parent) && parent.name === node) ||
(ts.isMethodDeclaration(parent) && parent.name === node) ||
(ts.isParameter(parent) && parent.name === node) ||
(ts.isVariableDeclaration(parent) && parent.name === node));
if (parent !== undefined && !isPropertyOrDeclName) {
report(
context,
node,
@@ -717,6 +731,16 @@ export function createSimpleValidationVisitors(): tstl.Visitors {
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) => {
for (const prop of node.properties) {
if (ts.isSpreadAssignment(prop)) {