feat: add UnLua TS spec, TSTL compiler plugin, types, examples, and tests

This commit is contained in:
szy73711 committed 2026-11-28 22:26:22 +08:00
1 parent 68852d049c
commit c0ac6eaad6
19 files changed
+3273 -1

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
import * as ts from "typescript";
export enum UnLuaDiagnosticCode {
// 2.x 禁用 TS/JS 通用语言特性 (90001 - 90099)
ForbiddenAccessor = 90001,
ForbiddenAsyncAwait = 90002,
ForbiddenPromise = 90003,
ForbiddenTryCatchThrow = 90004,
ForbiddenDecorator = 90005,
ForbiddenBuiltinType = 90006,
ForbiddenRegExp = 90007,
ForbiddenGenerator = 90008,
ForbiddenForIn = 90009,
ForbiddenRuntimeEnum = 90010,
ForbiddenDeleteOnArrayOrUObject = 90011,
ForbiddenInstanceOfUObject = 90012,
ForbiddenDynamicEvalOrWith = 90013,
ForbiddenArguments = 90014,
ForbiddenDynamicImport = 90015,
ForbiddenUObjectSpread = 90016,
// 3.x UnLua 绑定类专项约束 (90101 - 90199)
UnLuaClassMustBeDefaultExport = 90101,
UnLuaFileExtraRuntimeExport = 90102,
UnLuaClassForbiddenConstructor = 90103,
UnLuaClassForbiddenPropertyInitializer = 90104,
UnLuaClassForbiddenNew = 90105,
MissingUnLuaDecorator = 90106,
UnLuaDelegateForbiddenInlineFunction = 90107,
InvalidUnLuaDecoratorArgs = 90108,
UnLuaMultipleClassesInFile = 90109,
UnLuaForbiddenSuperUsage = 90110,
}
export function createUnLuaDiagnostic(
node: ts.Node,
code: UnLuaDiagnosticCode,
messageText: string,
category: ts.DiagnosticCategory = ts.DiagnosticCategory.Error
): ts.Diagnostic {
const sourceFile = node.getSourceFile();
const start = node.getStart(sourceFile);
const length = Math.max(1, node.getEnd() - start);
return {
file: sourceFile,
start,
length,
messageText: `[ts2lua-unlua] ${messageText}`,
category,
code,
source: "ts2lua-unlua",
};
}
+106
View File
@@ -0,0 +1,106 @@
import * as ts from "typescript";
import * as tstl from "typescript-to-lua";
import { createUnLuaDiagnostic, UnLuaDiagnosticCode } from "./diagnostics";
import { findEnclosingClass, hasUnLuaDecorator } from "./type-utils";
import {
transformUnLuaClassDeclaration,
transformUnLuaSourceFile,
tryTransformUnLuaDefaultImport,
tryTransformUnLuaSelfClassIdentifier,
tryTransformUnLuaSuperCall,
} from "./unlua-transform";
import {
createSimpleValidationVisitors,
validateCallExpression,
validateClassDeclaration,
validateUnLuaSourceFile,
} from "./validators";
/**
* TypeScriptToLua (TSTL) UnLua 定制插件:
* 1. 编译期强制执行 ts2lua-unreal 语言子集约束(禁用 get/set、async/await、try/catch 等);
* 2. 将全局 `@unlua` 标记的绑定类转译为原生 UnLua 风格(UnLua.Class / return M / self.Overridden)。
*/
export function createUnLuaPlugin(): tstl.Plugin {
const simpleValidators = createSimpleValidationVisitors();
const visitors: tstl.Visitors = {
...simpleValidators,
[ts.SyntaxKind.SourceFile]: (node, context) => {
const primaryUnLuaClass = validateUnLuaSourceFile(node, context);
if (primaryUnLuaClass) {
return transformUnLuaSourceFile(node, primaryUnLuaClass, context);
}
const [luaFile] = context.superTransformNode(node) as [tstl.File];
return luaFile;
},
[ts.SyntaxKind.ImportDeclaration]: (node, context) => {
const customImport = tryTransformUnLuaDefaultImport(node, context);
if (customImport !== undefined) {
return customImport;
}
return context.superTransformStatements(node);
},
[ts.SyntaxKind.ClassDeclaration]: (node, context) => {
validateClassDeclaration(node, context);
if (hasUnLuaDecorator(node)) {
return transformUnLuaClassDeclaration(node, context);
}
return context.superTransformStatements(node);
},
[ts.SyntaxKind.ClassExpression]: (node, context) => {
validateClassDeclaration(node, context);
return context.superTransformExpression(node);
},
[ts.SyntaxKind.Identifier]: (node, context) => {
const selfClassId = tryTransformUnLuaSelfClassIdentifier(node, context);
if (selfClassId) {
return selfClassId;
}
const validator = simpleValidators[ts.SyntaxKind.Identifier];
if (typeof validator === "function") {
return validator(node, context);
}
return context.superTransformExpression(node);
},
[ts.SyntaxKind.CallExpression]: (node, context) => {
validateCallExpression(node, context);
const superCall = tryTransformUnLuaSuperCall(node, context);
if (superCall) {
return superCall;
}
return context.superTransformExpression(node);
},
[ts.SyntaxKind.SuperKeyword]: (node, context) => {
// 若 super 未在 CallExpression 中被拦截(如独立访问 super.prop),报错提示
const enclosingClass = findEnclosingClass(node);
if (enclosingClass && hasUnLuaDecorator(enclosingClass)) {
context.diagnostics.push(
createUnLuaDiagnostic(
node,
UnLuaDiagnosticCode.UnLuaForbiddenSuperUsage,
"@unlua 绑定类中仅支持通过 'super.Method(...)' 调用父类方法,禁止直接读写 'super.prop'(UnLua 中访问父类组件/属性请直接用 'this.prop')。"
)
);
return tstl.createNilLiteral(node);
}
return context.superTransformExpression(node);
},
};
return {
visitors,
};
}
const plugin: tstl.Plugin = createUnLuaPlugin();
export default plugin;
export { UnLuaDiagnosticCode } from "./diagnostics";
+333
View File
@@ -0,0 +1,333 @@
import * as path from "path";
import * as ts from "typescript";
export interface UnLuaDecoratorInfo {
decorator: ts.Decorator;
explicitBaseModule?: string;
invalidArgumentNode?: ts.Node;
}
export const ALLOWED_DECORATOR_NAMES = new Set<string>(["unlua"]);
/**
* 缓存 Type -> 是否为 UE.UObject 或其派生类,避免大型项目重复递归遍历继承链。
*/
const uObjectTypeCache = new WeakMap<ts.Type, boolean>();
/**
* 缓存 Type -> 是否为 @unlua 绑定类。
*/
const unLuaClassTypeCache = new WeakMap<ts.Type, boolean>();
/**
* 纯 AST 获取装饰器名称(不依赖 TypeChecker)。
*/
export function getDecoratorName(decorator: ts.Decorator): string | undefined {
const expr = decorator.expression;
if (ts.isIdentifier(expr)) {
return expr.text;
}
if (ts.isCallExpression(expr) && ts.isIdentifier(expr.expression)) {
return expr.expression.text;
}
return undefined;
}
/**
* 纯 AST 获取类上的 @unlua 装饰器信息。
*/
export function getUnLuaDecorator(node: ts.ClassLikeDeclaration): UnLuaDecoratorInfo | undefined {
const decorators = ts.canHaveDecorators(node) ? ts.getDecorators(node) : undefined;
if (!decorators) return undefined;
for (const decorator of decorators) {
const expr = decorator.expression;
if (ts.isIdentifier(expr) && expr.text === "unlua") {
return { decorator };
}
if (ts.isCallExpression(expr) && ts.isIdentifier(expr.expression) && expr.expression.text === "unlua") {
if (expr.arguments.length === 0) {
return { decorator };
}
if (expr.arguments.length === 1 && ts.isStringLiteralLike(expr.arguments[0])) {
return {
decorator,
explicitBaseModule: expr.arguments[0].text,
};
}
return {
decorator,
invalidArgumentNode: expr,
};
}
}
return undefined;
}
/**
* 纯 AST 快速判断节点是否带有 @unlua 装饰器。
*/
export function hasUnLuaDecorator(node: ts.ClassLikeDeclaration): boolean {
return getUnLuaDecorator(node) !== undefined;
}
/**
* 判断声明是否来自 .d.ts 或具有 declare 修饰符(即 UE C++/蓝图外部声明)。
*/
export function isAmbientClassDeclaration(decl: ts.Declaration): boolean {
const sf = decl.getSourceFile();
if (sf.isDeclarationFile) return true;
if (ts.canHaveModifiers(decl)) {
const modifiers = ts.getModifiers(decl);
if (modifiers?.some((m) => m.kind === ts.SyntaxKind.DeclareKeyword)) {
return true;
}
}
return false;
}
function isUObjectSymbol(symbol: ts.Symbol | undefined): boolean {
if (!symbol || symbol.getName() !== "UObject") return false;
const decls = symbol.getDeclarations();
if (!decls || decls.length === 0) return false;
// 支持全局 namespace UE { class UObject } 或直接 declare class UObject
for (const decl of decls) {
if (!isAmbientClassDeclaration(decl)) continue;
const parent = decl.parent;
if (
ts.isModuleBlock(parent) &&
ts.isModuleDeclaration(parent.parent) &&
parent.parent.name.text === "UE"
) {
return true;
}
if (ts.isSourceFile(parent)) {
return true;
}
}
return false;
}
/**
* 判断给定 TS 类型是否为 UE.UObject 或其派生类(带 WeakMap 缓存)。
*/
export function isUObjectType(type: ts.Type | undefined, checker: ts.TypeChecker): boolean {
if (!type) return false;
const cached = uObjectTypeCache.get(type);
if (cached !== undefined) return cached;
// 先写入 false 防止循环引用导致无限递归
uObjectTypeCache.set(type, false);
let result = false;
if (type.isUnionOrIntersection()) {
result = type.types.some((t) => isUObjectType(t, checker));
} else {
const symbol = type.getSymbol();
if (isUObjectSymbol(symbol)) {
result = true;
} else {
const baseTypes = type.getBaseTypes();
if (baseTypes && baseTypes.length > 0) {
for (const base of baseTypes) {
if (isUObjectType(base, checker)) {
result = true;
break;
}
}
}
}
}
uObjectTypeCache.set(type, result);
return result;
}
/**
* 获取类的 extends 表达式节点(如果存在)。
*/
export function getExtendsClause(
node: ts.ClassLikeDeclaration
): ts.ExpressionWithTypeArguments | undefined {
if (!node.heritageClauses) return undefined;
for (const clause of node.heritageClauses) {
if (clause.token === ts.SyntaxKind.ExtendsKeyword && clause.types.length > 0) {
return clause.types[0];
}
}
return undefined;
}
/**
* 判断类的基类是否继承自 UE.UObject。
*/
export function classExtendsUObject(
node: ts.ClassLikeDeclaration,
checker: ts.TypeChecker
): boolean {
const ext = getExtendsClause(node);
if (!ext) return false;
// 优先通过 getTypeFromTypeNode 获取基类的实例类型(而非构造函数静态类型)
const baseInstanceType = checker.getTypeFromTypeNode(ext);
if (isUObjectType(baseInstanceType, checker)) {
return true;
}
// 兜底:若为构造函数类型,检查其构造签名的返回实例类型
const baseValueType = checker.getTypeAtLocation(ext);
for (const sig of baseValueType.getConstructSignatures()) {
if (isUObjectType(sig.getReturnType(), checker)) {
return true;
}
}
return false;
}
/**
* 判断某个类型对应的类声明是否为 @unlua 类(带 WeakMap 缓存)。
*/
export function isUnLuaClassType(type: ts.Type | undefined, checker: ts.TypeChecker): boolean {
if (!type) return false;
const cached = unLuaClassTypeCache.get(type);
if (cached !== undefined) return cached;
unLuaClassTypeCache.set(type, false);
let result = false;
const symbol = type.getSymbol();
const decls = symbol?.getDeclarations();
if (decls) {
for (const decl of decls) {
if (ts.isClassLike(decl) && hasUnLuaDecorator(decl)) {
result = true;
break;
}
}
}
if (!result) {
const baseTypes = type.getBaseTypes();
if (baseTypes) {
for (const base of baseTypes) {
if (isUnLuaClassType(base, checker)) {
result = true;
break;
}
}
}
}
unLuaClassTypeCache.set(type, result);
return result;
}
export interface SuperClassResolution {
kind: "none" | "ue-native" | "unlua-ts" | "other-ts";
/** 若为 unlua-ts,指向父类声明所在的 SourceFile 与本地导入标识符名 */
baseDeclaration?: ts.ClassLikeDeclaration;
baseLocalName?: string;
baseModuleName?: string;
}
/**
* 解析 @unlua 类的父类信息,用于决定 UnLua.Class(...) 参数与 super.Method() 映射目标。
*/
export function resolveSuperClass(
classNode: ts.ClassLikeDeclaration,
checker: ts.TypeChecker,
program: ts.Program
): SuperClassResolution {
const ext = getExtendsClause(classNode);
if (!ext) {
return { kind: "none" };
}
const baseType = checker.getTypeAtLocation(ext);
const symbol = baseType.getSymbol();
const decls = symbol?.getDeclarations() ?? [];
for (const decl of decls) {
if (ts.isClassLike(decl)) {
if (isAmbientClassDeclaration(decl)) {
return { kind: "ue-native", baseDeclaration: decl };
}
if (hasUnLuaDecorator(decl)) {
const baseLocalName = ts.isIdentifier(ext.expression)
? ext.expression.text
: ext.expression.getText();
const baseModuleName = resolveLuaModuleName(decl.getSourceFile(), program);
return {
kind: "unlua-ts",
baseDeclaration: decl,
baseLocalName,
baseModuleName,
};
}
return { kind: "other-ts", baseDeclaration: decl };
}
}
if (isUObjectType(baseType, checker)) {
return { kind: "ue-native" };
}
return { kind: "other-ts" };
}
/**
* 将 TS 源文件路径映射为 UnLua 的点号模块路径(如 Game/LuaDemoActor.ts -> Game.LuaDemoActor)。
*/
export function resolveLuaModuleName(sourceFile: ts.SourceFile, program: ts.Program): string {
const options = program.getCompilerOptions();
const filePath = path.resolve(sourceFile.fileName);
let rootDir = options.rootDir ? path.resolve(options.rootDir) : undefined;
if (!rootDir) {
// 回退到项目公共源码目录或当前目录
const commonRoot = (program as unknown as { getCommonSourceDirectory?: () => string })
.getCommonSourceDirectory?.();
rootDir = commonRoot ? path.resolve(commonRoot) : process.cwd();
}
let rel = path.relative(rootDir, filePath);
// 统一路径分隔符并去除扩展名
rel = rel.replace(/\\/g, "/").replace(/\.(ts|tsx|mts|cts)$/, "");
// 去掉可能残留的开头 ./ 或 ../
rel = rel.replace(/^(\.\.\/|\.\/)+/, "");
return rel.split("/").filter(Boolean).join(".");
}
/**
* 检查节点前导注释是否包含 @unlua-allow-try(仅限框架层边界使用)。
*/
export function hasAllowTryComment(node: ts.Node): boolean {
const sf = node.getSourceFile();
const fullText = sf.getFullText();
const ranges = ts.getLeadingCommentRanges(fullText, node.getFullStart());
if (!ranges) return false;
for (const range of ranges) {
const text = fullText.slice(range.pos, range.end);
if (text.includes("@unlua-allow-try")) {
return true;
}
}
return false;
}
/**
* 向上查找节点最近的包裹类声明。
*/
export function findEnclosingClass(node: ts.Node): ts.ClassLikeDeclaration | undefined {
let cur: ts.Node | undefined = node.parent;
while (cur) {
if (ts.isClassLike(cur)) {
return cur;
}
cur = cur.parent;
}
return undefined;
}
+455
View File
@@ -0,0 +1,455 @@
import * as ts from "typescript";
import * as tstl from "typescript-to-lua";
import { createUnLuaDiagnostic, UnLuaDiagnosticCode } from "./diagnostics";
import {
findEnclosingClass,
getUnLuaDecorator,
hasUnLuaDecorator,
isUnLuaClassType,
resolveSuperClass,
SuperClassResolution,
} from "./type-utils";
const SCOPE_TYPE_FUNCTION = 2 as Parameters<tstl.TransformationContext["pushScope"]>[0];
function isExportsIdentifier(expr: tstl.Node | undefined): boolean {
return expr !== undefined && tstl.isIdentifier(expr) && expr.text === "____exports";
}
function isEmptyExportsDeclaration(stmt: tstl.Statement): boolean {
if (!tstl.isVariableDeclarationStatement(stmt)) return false;
if (stmt.left.length !== 1 || !isExportsIdentifier(stmt.left[0])) return false;
if (!stmt.right || stmt.right.length !== 1) return false;
const rhs = stmt.right[0];
return tstl.isTableExpression(rhs) && rhs.fields.length === 0;
}
function isReturnExportsStatement(stmt: tstl.Statement): boolean {
if (!tstl.isReturnStatement(stmt)) return false;
return stmt.expressions.length === 1 && isExportsIdentifier(stmt.expressions[0]);
}
function getUnLuaClassVarName(classDecl: ts.ClassDeclaration): string {
return classDecl.name?.text ?? "M";
}
function isStaticMember(member: ts.ClassElement): boolean {
if (!ts.canHaveModifiers(member)) return false;
return ts.getModifiers(member)?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword) ?? false;
}
function hasNoSelfJsDoc(node: ts.Node): boolean {
const tags = ts.getJSDocTags(node);
return tags.some((tag) => tag.tagName.text === "noSelf");
}
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;
}
return true;
}
function getPropertyKeyExpression(
name: ts.PropertyName,
context: tstl.TransformationContext
): tstl.Expression {
if (ts.isIdentifier(name)) {
return tstl.createStringLiteral(name.text, name);
}
if (ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name)) {
return tstl.createStringLiteral(name.text, name);
}
if (ts.isNumericLiteral(name)) {
return tstl.createNumericLiteral(Number(name.text), name);
}
if (ts.isComputedPropertyName(name)) {
return context.transformExpression(name.expression);
}
return tstl.createStringLiteral(name.getText(), name);
}
/**
* 将 @unlua 类中的 MethodDeclaration 转换为 Lua 赋值函数声明:
* function ClassName.MethodName(self, ...)
* ...
* end
* (在 Lua 字节码中与 `function ClassName:MethodName(...)` 完全等价)
*/
function transformUnLuaMethod(
classVarName: string,
method: ts.MethodDeclaration,
context: tstl.TransformationContext
): tstl.Statement | undefined {
if (!method.body) return undefined;
const params: tstl.Identifier[] = [];
const headerStatements: tstl.Statement[] = [];
let dots: tstl.DotsLiteral | undefined;
if (methodHasSelfParam(method)) {
params.push(tstl.createIdentifier("self"));
}
context.pushScope(SCOPE_TYPE_FUNCTION, method);
for (const param of method.parameters) {
// 跳过 TS 虚拟 `this: ...` 参数声明
if (ts.isIdentifier(param.name) && param.name.text === "this") {
continue;
}
if (param.dotDotDotToken) {
dots = tstl.createDotsLiteral(param);
if (ts.isIdentifier(param.name)) {
const restId = tstl.createIdentifier(param.name.text, param.name);
const restTable = tstl.createTableExpression(
[tstl.createTableFieldExpression(tstl.createDotsLiteral(param))],
param
);
headerStatements.push(
tstl.createVariableDeclarationStatement(restId, restTable, param)
);
}
continue;
}
if (ts.isIdentifier(param.name)) {
const paramId = tstl.createIdentifier(param.name.text, param.name);
params.push(paramId);
if (param.initializer) {
const defaultExpr = context.transformExpression(param.initializer);
if (!tstl.isNilLiteral(defaultExpr)) {
const cond = tstl.createBinaryExpression(
tstl.cloneIdentifier(paramId),
tstl.createNilLiteral(),
tstl.SyntaxKind.EqualityOperator
);
const assign = tstl.createAssignmentStatement(
tstl.cloneIdentifier(paramId),
defaultExpr,
param
);
headerStatements.push(
tstl.createIfStatement(cond, tstl.createBlock([assign]), undefined, param)
);
}
}
} else {
// 解构参数兜底:分配临时形参并展开(尽量少用)
const tmpId = tstl.createIdentifier(context.createTempName("param"), param);
params.push(tmpId);
}
}
const bodyStatements = context.transformStatements(method.body.statements);
context.popScope();
const fnExpr = tstl.createFunctionExpression(
tstl.createBlock([...headerStatements, ...bodyStatements], method.body),
params,
dots,
tstl.NodeFlags.Declaration,
method
);
const lhs = tstl.createTableIndexExpression(
tstl.createIdentifier(classVarName),
getPropertyKeyExpression(method.name, context),
method.name
);
return tstl.createAssignmentStatement(lhs, fnExpr, method);
}
/**
* 转换 @unlua 标注的 ClassDeclaration:
* local ClassName = UnLua.Class(...)
* function ClassName.Method(self, ...) ... end
*/
export function transformUnLuaClassDeclaration(
node: ts.ClassDeclaration,
context: tstl.TransformationContext
): tstl.Statement[] {
const classVarName = getUnLuaClassVarName(node);
const unluaInfo = getUnLuaDecorator(node);
const superResolution = resolveSuperClass(node, context.checker, context.program);
const classArgs: tstl.Expression[] = [];
if (unluaInfo?.explicitBaseModule) {
classArgs.push(tstl.createStringLiteral(unluaInfo.explicitBaseModule, unluaInfo.decorator));
} else if (superResolution.kind === "unlua-ts" && superResolution.baseModuleName) {
classArgs.push(tstl.createStringLiteral(superResolution.baseModuleName, node));
}
const unluaClassCall = tstl.createCallExpression(
tstl.createTableIndexExpression(
tstl.createIdentifier("UnLua"),
tstl.createStringLiteral("Class")
),
classArgs,
node
);
const statements: tstl.Statement[] = [
tstl.createVariableDeclarationStatement(
tstl.createIdentifier(classVarName, node.name),
unluaClassCall,
node
),
];
for (const member of node.members) {
if (ts.isMethodDeclaration(member)) {
const methodStmt = transformUnLuaMethod(classVarName, member, context);
if (methodStmt) {
statements.push(methodStmt);
}
} else if (ts.isPropertyDeclaration(member) && isStaticMember(member) && member.initializer) {
const lhs = tstl.createTableIndexExpression(
tstl.createIdentifier(classVarName),
getPropertyKeyExpression(member.name, context),
member.name
);
const rhs = context.transformExpression(member.initializer);
statements.push(tstl.createAssignmentStatement(lhs, rhs, member));
}
}
return statements;
}
/**
* 转换包含 @unlua 类的 SourceFile:
* 去除 TSTL 自动包裹的 `local ____exports = {}` 与 `return ____exports`,改为直接 `return <ClassName>`。
*/
export function transformUnLuaSourceFile(
node: ts.SourceFile,
primaryClass: ts.ClassDeclaration,
context: tstl.TransformationContext
): tstl.File {
const [luaFile] = context.superTransformNode(node) as [tstl.File];
const classVarName = getUnLuaClassVarName(primaryClass);
const statements = luaFile.statements.filter((stmt) => !isEmptyExportsDeclaration(stmt));
if (statements.length > 0 && isReturnExportsStatement(statements[statements.length - 1])) {
statements.pop();
}
statements.push(
tstl.createReturnStatement([tstl.createIdentifier(classVarName, primaryClass.name)])
);
return tstl.createFile(statements, luaFile.luaLibFeatures, luaFile.trivia, node);
}
/**
* 若默认导入的目标是 @unlua 类(直接 return M,没有 .default 包装),
* 将 `import Base from "./Base"` 编译为 `local Base = require("./Base")`(由 TSTL 自动解析相对路径)。
*/
export function tryTransformUnLuaDefaultImport(
node: ts.ImportDeclaration,
context: tstl.TransformationContext
): tstl.Statement[] | undefined {
const importClause = node.importClause;
if (!importClause || importClause.isTypeOnly || !importClause.name) {
return undefined;
}
// 仅处理纯默认导入(@unlua 文件本身禁止额外命名导出)
if (importClause.namedBindings) {
return undefined;
}
if (!ts.isStringLiteral(node.moduleSpecifier)) {
return undefined;
}
const importedType = context.checker.getTypeAtLocation(importClause.name);
const constructInstanceTypes = importedType
.getConstructSignatures()
.map((sig) => sig.getReturnType());
const targetsUnLuaClass =
isUnLuaClassType(importedType, context.checker) ||
constructInstanceTypes.some((t) => isUnLuaClassType(t, context.checker));
if (!targetsUnLuaClass) {
return undefined;
}
// 若 TS 判断该导入仅用于类型(未在值位置引用),交给默认逻辑忽略
if (!context.resolver.isReferencedAliasDeclaration(importClause)) {
return [];
}
const requireCall = tstl.createCallExpression(
tstl.createIdentifier("require"),
[tstl.createStringLiteral(node.moduleSpecifier.text, node.moduleSpecifier)],
node.moduleSpecifier
);
return [
tstl.createVariableDeclarationStatement(
tstl.createIdentifier(importClause.name.text, importClause.name),
requireCall,
node
),
];
}
const fileUnLuaClassNameCache = new WeakMap<ts.SourceFile, string | null>();
function getFilePrimaryUnLuaClassName(sf: ts.SourceFile): string | null {
const cached = fileUnLuaClassNameCache.get(sf);
if (cached !== undefined) return cached;
let name: string | null = null;
for (const stmt of sf.statements) {
if (ts.isClassDeclaration(stmt) && hasUnLuaDecorator(stmt)) {
name = getUnLuaClassVarName(stmt);
break;
}
}
fileUnLuaClassNameCache.set(sf, name);
return name;
}
/**
* 在 @unlua 类所在文件内引用该类自身(如 `MyActor.MAX_HP` / `MyActor.Helper()`)时,
* 避免 TSTL 将 `export default class MyActor` 改写为 `____exports.default`。
* 使用 SourceFile -> 类名 WeakMap 缓存短路,避免对无关标识符触发 TypeChecker。
*/
export function tryTransformUnLuaSelfClassIdentifier(
node: ts.Identifier,
context: tstl.TransformationContext
): tstl.Expression | undefined {
const sf = node.getSourceFile();
const className = getFilePrimaryUnLuaClassName(sf);
if (!className || node.text !== className) {
return undefined;
}
const parent = node.parent;
// 跳过属性名、声明名等非值引用位置
if (
(ts.isPropertyAccessExpression(parent) && parent.name === node) ||
(ts.isClassDeclaration(parent) && parent.name === node) ||
(ts.isMethodDeclaration(parent) && parent.name === node) ||
(ts.isPropertyDeclaration(parent) && parent.name === node)
) {
return undefined;
}
const symbol = context.checker.getSymbolAtLocation(node);
const decls = symbol?.getDeclarations();
if (!decls || decls.length === 0) return undefined;
for (const decl of decls) {
if (
ts.isClassDeclaration(decl) &&
decl.getSourceFile() === sf &&
hasUnLuaDecorator(decl)
) {
return tstl.createIdentifier(className, node);
}
}
return undefined;
}
/**
* 转换 @unlua 类方法内的 `super.Method(...)` 调用:
* - 继承 UE 原生 C++/蓝图基类 -> `self.Overridden.Method(self, ...)`
* - 继承另一个 @unlua TS 父类 -> `<ParentLocalName>.Method(self, ...)`
*/
export function tryTransformUnLuaSuperCall(
node: ts.CallExpression,
context: tstl.TransformationContext
): tstl.Expression | undefined {
const callee = node.expression;
// 拦截直接 super() 调用
if (callee.kind === ts.SyntaxKind.SuperKeyword) {
const enclosingClass = findEnclosingClass(node);
if (enclosingClass && hasUnLuaDecorator(enclosingClass)) {
context.diagnostics.push(
createUnLuaDiagnostic(
node,
UnLuaDiagnosticCode.UnLuaForbiddenSuperUsage,
"@unlua 绑定类中禁止调用 super()。"
)
);
return tstl.createNilLiteral(node);
}
return undefined;
}
if (
!ts.isPropertyAccessExpression(callee) &&
!ts.isElementAccessExpression(callee)
) {
return undefined;
}
if (callee.expression.kind !== ts.SyntaxKind.SuperKeyword) {
return undefined;
}
const enclosingClass = findEnclosingClass(node);
if (!enclosingClass || !hasUnLuaDecorator(enclosingClass)) {
return undefined;
}
const superInfo: SuperClassResolution = resolveSuperClass(
enclosingClass,
context.checker,
context.program
);
const methodKey: tstl.Expression = ts.isPropertyAccessExpression(callee)
? tstl.createStringLiteral(callee.name.text, callee.name)
: context.transformExpression(callee.argumentExpression);
const transformedArgs = node.arguments.map((arg) => context.transformExpression(arg));
const callArgs: tstl.Expression[] = [tstl.createIdentifier("self"), ...transformedArgs];
if (superInfo.kind === "ue-native") {
// self.Overridden.Method(self, ...)
const overriddenTable = tstl.createTableIndexExpression(
tstl.createIdentifier("self"),
tstl.createStringLiteral("Overridden")
);
const fnAccess = tstl.createTableIndexExpression(overriddenTable, methodKey, callee);
return tstl.createCallExpression(fnAccess, callArgs, node);
}
if (superInfo.kind === "unlua-ts" && superInfo.baseLocalName) {
// ParentClass.Method(self, ...)
const fnAccess = tstl.createTableIndexExpression(
tstl.createIdentifier(superInfo.baseLocalName),
methodKey,
callee
);
return tstl.createCallExpression(fnAccess, callArgs, node);
}
context.diagnostics.push(
createUnLuaDiagnostic(
node,
UnLuaDiagnosticCode.UnLuaForbiddenSuperUsage,
"@unlua 绑定类中的 super 调用仅支持继承自 UE 原生基类(生成 self.Overridden)或另一个 @unlua TS 绑定类(生成父类模块调用)。"
)
);
return tstl.createNilLiteral(node);
}
+736
View File
@@ -0,0 +1,736 @@
import * as ts from "typescript";
import * as tstl from "typescript-to-lua";
import { createUnLuaDiagnostic, UnLuaDiagnosticCode } from "./diagnostics";
import {
ALLOWED_DECORATOR_NAMES,
classExtendsUObject,
getDecoratorName,
getUnLuaDecorator,
hasAllowTryComment,
hasUnLuaDecorator,
isUnLuaClassType,
isUObjectType,
} from "./type-utils";
const FORBIDDEN_CONSTRUCTORS = new Set<string>([
"Map",
"Set",
"WeakMap",
"WeakSet",
"Proxy",
"Function",
]);
const FORBIDDEN_OBJECT_METHODS = new Set<string>([
"defineProperty",
"defineProperties",
"setPrototypeOf",
"create",
"freeze",
]);
const DELEGATE_TYPE_NAMES = new Set<string>([
"FMulticastScriptDelegate",
"FScriptDelegate",
]);
function report(
context: tstl.TransformationContext,
node: ts.Node,
code: UnLuaDiagnosticCode,
message: string
): void {
context.diagnostics.push(createUnLuaDiagnostic(node, code, message));
}
/**
* 校验节点上是否存在非白名单装饰器。
*/
export function validateDecorators(
node: ts.Node,
context: tstl.TransformationContext
): void {
if (!ts.canHaveDecorators(node)) return;
const decorators = ts.getDecorators(node);
if (!decorators || decorators.length === 0) return;
for (const dec of decorators) {
const name = getDecoratorName(dec);
if (!name || !ALLOWED_DECORATOR_NAMES.has(name)) {
report(
context,
dec,
UnLuaDiagnosticCode.ForbiddenDecorator,
`禁用运行时装饰器 '@${name ?? "unknown"}'(会引入 __TS__Decorate 垫片并破坏 UnLua 绑定)。仅允许白名单编译期装饰器:${Array.from(ALLOWED_DECORATOR_NAMES)
.map((n) => "@" + n)
.join(", ")}。`
);
} else if (name === "unlua" && !ts.isClassLike(node)) {
report(
context,
dec,
UnLuaDiagnosticCode.ForbiddenDecorator,
`装饰器 '@unlua' 只能用于 class 声明。`
);
}
}
}
/**
* 校验函数类节点是否使用了 async / generator / 非白名单装饰器。
*/
export function validateFunctionLike(
node: ts.FunctionLikeDeclaration,
context: tstl.TransformationContext
): void {
validateDecorators(node, context);
const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined;
if (modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword)) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenAsyncAwait,
"禁用 async 函数(避免引入 Promise 状态机垫片)。请使用 Lua coroutine 封装或回调 + IsValid() 检查。"
);
}
if (node.asteriskToken) {
report(
context,
node.asteriskToken,
UnLuaDiagnosticCode.ForbiddenGenerator,
"禁用生成器函数 function* / yield。请直接使用 Lua coroutine。"
);
}
for (const param of node.parameters) {
validateDecorators(param, context);
}
}
/**
* 校验单个 class 声明(区分 @unlua 类与普通类)。
*/
export function validateClassDeclaration(
node: ts.ClassLikeDeclaration,
context: tstl.TransformationContext
): void {
validateDecorators(node, context);
const unluaInfo = getUnLuaDecorator(node);
if (unluaInfo) {
if (unluaInfo.invalidArgumentNode) {
report(
context,
unluaInfo.invalidArgumentNode,
UnLuaDiagnosticCode.InvalidUnLuaDecoratorArgs,
"@unlua 装饰器仅支持无参写法 '@unlua' 或单个字符串字面量参数 '@unlua(\"Path.To.Base\")'。"
);
}
// 校验 @unlua 必须是 export default class
if (ts.isClassDeclaration(node)) {
const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined;
const hasExport = modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false;
const hasDefault = modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword) ?? false;
if (!hasExport || !hasDefault) {
report(
context,
node.name ?? node,
UnLuaDiagnosticCode.UnLuaClassMustBeDefaultExport,
"标注了 @unlua 的绑定类必须使用 'export default class ...' 导出,以便生成 'return M' 供 UnLua 直接加载。"
);
}
} else {
report(
context,
node,
UnLuaDiagnosticCode.UnLuaClassMustBeDefaultExport,
"@unlua 不能用于类表达式,请使用顶层 'export default class ...'。"
);
}
// 校验 @unlua 类内部成员约束
for (const member of node.members) {
validateDecorators(member, context);
if (ts.isConstructorDeclaration(member)) {
report(
context,
member,
UnLuaDiagnosticCode.UnLuaClassForbiddenConstructor,
"@unlua 绑定类禁止定义 constructor(UE 实例化不会调用 JS 构造函数)。请在 Initialize / Construct / ReceiveBeginPlay 中初始化。"
);
continue;
}
if (ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)) {
report(
context,
member,
UnLuaDiagnosticCode.ForbiddenAccessor,
"禁用 get/set 属性访问器(会生成 __TS__SetDescriptor 破坏 UnLua 元表)。请改为 GetXxx() / SetXxx() 方法。"
);
continue;
}
if (ts.isPropertyDeclaration(member)) {
const isStatic =
ts.canHaveModifiers(member) &&
ts.getModifiers(member)?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword);
if (!isStatic && member.initializer) {
report(
context,
member,
UnLuaDiagnosticCode.UnLuaClassForbiddenPropertyInitializer,
"@unlua 绑定类禁止实例字段初始化器(含箭头函数类方法)。请仅做类型声明(如 'private hp!: number;'),并在 ReceiveBeginPlay / Initialize 中赋值。"
);
}
continue;
}
if (ts.isMethodDeclaration(member)) {
validateFunctionLike(member, context);
}
}
} else {
// 漏标防呆:继承了 UE.UObject 却未标注 @unlua
if (classExtendsUObject(node, context.checker)) {
report(
context,
node.name ?? node,
UnLuaDiagnosticCode.MissingUnLuaDecorator,
"该类继承自 UE.UObject(或其派生类),但缺少 '@unlua' 装饰器。请补充 '@unlua' 并使用 'export default class',避免被误编译为普通 __TS__Class。"
);
}
// 普通类同样检查成员装饰器与禁用项(get/set 访问器、async/generator 方法等)
for (const member of node.members) {
validateDecorators(member, context);
if (ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)) {
report(
context,
member,
UnLuaDiagnosticCode.ForbiddenAccessor,
"禁用 get/set 属性访问器(会生成 __TS__SetDescriptor 破坏元表)。请改为 GetXxx() / SetXxx() 方法。"
);
} else if (ts.isMethodDeclaration(member)) {
validateFunctionLike(member, context);
}
}
}
}
/**
* 校验 @unlua 文件顶层是否包含多个 @unlua 类或额外的运行时 export。
*/
export function validateUnLuaSourceFile(
sourceFile: ts.SourceFile,
context: tstl.TransformationContext
): ts.ClassDeclaration | undefined {
const unluaClasses: ts.ClassDeclaration[] = [];
for (const stmt of sourceFile.statements) {
if (ts.isClassDeclaration(stmt) && hasUnLuaDecorator(stmt)) {
unluaClasses.push(stmt);
}
}
if (unluaClasses.length === 0) {
return undefined;
}
if (unluaClasses.length > 1) {
for (let i = 1; i < unluaClasses.length; i++) {
report(
context,
unluaClasses[i].name ?? unluaClasses[i],
UnLuaDiagnosticCode.UnLuaMultipleClassesInFile,
"每个文件最多只能包含一个 @unlua 绑定类。"
);
}
}
const primaryClass = unluaClasses[0];
// 检查是否包含额外运行时导出(允许 export type / export interface)
for (const stmt of sourceFile.statements) {
if (stmt === primaryClass) continue;
if (ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)) continue;
if (ts.isExportDeclaration(stmt)) {
if (!stmt.isTypeOnly) {
const allSpecifiersTypeOnly =
stmt.exportClause &&
ts.isNamedExports(stmt.exportClause) &&
stmt.exportClause.elements.every((el) => el.isTypeOnly);
if (!allSpecifiersTypeOnly) {
report(
context,
stmt,
UnLuaDiagnosticCode.UnLuaFileExtraRuntimeExport,
"@unlua 绑定类文件禁止导出除默认绑定类以外的运行时符号(仅允许 export type / export interface)。"
);
}
}
continue;
}
if (ts.isExportAssignment(stmt)) {
report(
context,
stmt,
UnLuaDiagnosticCode.UnLuaFileExtraRuntimeExport,
"@unlua 绑定类文件禁止额外的 export default / export = 语句。"
);
continue;
}
if (ts.canHaveModifiers(stmt)) {
const modifiers = ts.getModifiers(stmt);
const hasExport = modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
const hasDeclare = modifiers?.some((m) => m.kind === ts.SyntaxKind.DeclareKeyword);
if (hasExport && !hasDeclare) {
// const enum 在运行时擦除,但普通运行时导出禁止
const isConstEnum =
ts.isEnumDeclaration(stmt) &&
modifiers?.some((m) => m.kind === ts.SyntaxKind.ConstKeyword);
if (!isConstEnum) {
report(
context,
stmt,
UnLuaDiagnosticCode.UnLuaFileExtraRuntimeExport,
"@unlua 绑定类文件禁止导出额外的运行时变量、函数或类(因为文件顶层直接 'return M')。请将其移至独立模块或改为非导出的本地定义。"
);
}
}
}
}
return primaryClass;
}
/**
* 校验 new 表达式(禁止 new Promise / Map / Set / RegExp / Proxy / @unlua 类)。
*/
export function validateNewExpression(
node: ts.NewExpression,
context: tstl.TransformationContext
): void {
if (ts.isIdentifier(node.expression)) {
const name = node.expression.text;
if (name === "Promise") {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenPromise,
"禁用 Promise(避免重型垫片及与 UE 生命周期冲突)。请改用 Lua coroutine 或显式回调。"
);
return;
}
if (name === "RegExp") {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenRegExp,
"禁用 RegExp(Lua 无标准正则引擎)。请使用 Lua Pattern(string.match / string.gsub / string.gmatch)。"
);
return;
}
if (FORBIDDEN_CONSTRUCTORS.has(name)) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenBuiltinType,
`禁用 'new ${name}()'(会引入重型 JS 运行时垫片或 Lua 不支持)。Map/Set 请改用 Record<K, V> / LuaTable 或 UE.TMap / UE.TSet。`
);
return;
}
}
const instanceType = context.checker.getTypeAtLocation(node);
if (isUnLuaClassType(instanceType, context.checker)) {
report(
context,
node,
UnLuaDiagnosticCode.UnLuaClassForbiddenNew,
"禁止使用 'new' 实例化 @unlua 绑定类。请通过 UE API(如 SpawnActor / UE.NewObject / CreateWidget)创建。"
);
}
}
/**
* 校验函数调用表达式(eval / Symbol / BigInt / Promise.* / Object.defineProperty / Reflect.* / import() / Delegate 匿名回调)。
*/
export function validateCallExpression(
node: ts.CallExpression,
context: tstl.TransformationContext
): void {
const callee = node.expression;
if (callee.kind === ts.SyntaxKind.ImportKeyword) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenDynamicImport,
"禁用动态 import()(返回 Promise 且不符合 Lua 同步 require 模型)。请使用静态 import。"
);
return;
}
if (ts.isIdentifier(callee)) {
const name = callee.text;
if (name === "eval") {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenDynamicEvalOrWith,
"禁用 eval()。"
);
return;
}
if (name === "RegExp") {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenRegExp,
"禁用 RegExp(),请使用 Lua Pattern(string.match / string.gsub)。"
);
return;
}
if (name === "Symbol" || name === "BigInt") {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenBuiltinType,
`禁用 '${name}()'(Lua 运行时不兼容或会产生重型垫片)。`
);
return;
}
}
if (ts.isPropertyAccessExpression(callee)) {
const obj = callee.expression;
const propName = callee.name.text;
if (ts.isIdentifier(obj)) {
if (obj.text === "Promise") {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenPromise,
`禁用 'Promise.${propName}()'。请改用 Lua coroutine 或显式回调。`
);
return;
}
if (obj.text === "Reflect") {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenBuiltinType,
`禁用 'Reflect.${propName}()'。`
);
return;
}
if (obj.text === "Object" && FORBIDDEN_OBJECT_METHODS.has(propName)) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenBuiltinType,
`禁用 'Object.${propName}()'(涉及元表/属性描述符操作,与 UnLua 不兼容)。`
);
return;
}
}
// Delegate.Add(self, fn) / Delegate.Bind(self, fn) 禁止传入箭头函数或匿名函数
if ((propName === "Add" || propName === "Bind") && node.arguments.length >= 2) {
const receiverType = context.checker.getTypeAtLocation(obj);
const receiverSymbolName = receiverType.getSymbol()?.getName();
if (receiverSymbolName && DELEGATE_TYPE_NAMES.has(receiverSymbolName)) {
const callbackArg = node.arguments[1];
if (ts.isArrowFunction(callbackArg) || ts.isFunctionExpression(callbackArg)) {
report(
context,
callbackArg,
UnLuaDiagnosticCode.UnLuaDelegateForbiddenInlineFunction,
`UE Delegate '${propName}' 禁止传入箭头函数或匿名函数(无法成对 Remove 且易导致闭包泄漏)。请传入类成员方法引用,如 'this.OnClicked'。`
);
}
}
}
}
}
/**
* 校验 delete 表达式:禁止对数组或 UObject 使用 delete。
*/
export function validateDeleteExpression(
node: ts.DeleteExpression,
context: tstl.TransformationContext
): void {
const target = node.expression;
if (ts.isElementAccessExpression(target)) {
const containerType = context.checker.getTypeAtLocation(target.expression);
if (
context.checker.isArrayType(containerType) ||
context.checker.isTupleType(containerType)
) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenDeleteOnArrayOrUObject,
"禁止对数组使用 'delete arr[i]'(会产生 Lua 稀疏表破坏 #arr 长度)。请使用 table.remove / splice。"
);
return;
}
if (isUObjectType(containerType, context.checker)) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenDeleteOnArrayOrUObject,
"禁止对 UObject 使用 delete。"
);
return;
}
} else if (ts.isPropertyAccessExpression(target)) {
const containerType = context.checker.getTypeAtLocation(target.expression);
if (isUObjectType(containerType, context.checker)) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenDeleteOnArrayOrUObject,
"禁止对 UObject 反射属性使用 delete。"
);
}
}
}
/**
* 校验二元表达式:禁止对 UObject 使用 instanceof。
*/
export function validateBinaryExpression(
node: ts.BinaryExpression,
context: tstl.TransformationContext
): void {
if (node.operatorToken.kind !== ts.SyntaxKind.InstanceOfKeyword) return;
const leftType = context.checker.getTypeAtLocation(node.left);
const rightType = context.checker.getTypeAtLocation(node.right);
const rightInstanceTypes = rightType.getConstructSignatures().map((sig) => sig.getReturnType());
const isLeftUObj = isUObjectType(leftType, context.checker);
const isRightUObj = rightInstanceTypes.some((t) => isUObjectType(t, context.checker));
if (isLeftUObj || isRightUObj) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenInstanceOfUObject,
"禁止对 UObject 使用 'instanceof'(无法识别 UE 反射继承树)。请改用 'obj.IsA(UE.ClassName.StaticClass())'。"
);
}
}
/**
* 校验对象展开:禁止对 UObject 使用 { ...actor }。
*/
export function validateSpreadAssignment(
node: ts.SpreadAssignment,
context: tstl.TransformationContext
): void {
const exprType = context.checker.getTypeAtLocation(node.expression);
if (isUObjectType(exprType, context.checker)) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenUObjectSpread,
"禁止对 UObject 使用对象展开 '{ ...obj }'(无法枚举 C++ 反射属性)。"
);
}
}
/**
* 校验独立的纯 AST 禁用节点(GetAccessor, SetAccessor, Await, Try, Throw, Yield, ForIn, Enum, RegExp, With, arguments)。
*/
export function createSimpleValidationVisitors(): tstl.Visitors {
return {
[ts.SyntaxKind.GetAccessor]: (node, context) => {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenAccessor,
"禁用 getter 属性访问器(会生成 __TS__SetDescriptor 破坏元表)。请改用 GetXxx() 方法。"
);
return context.superTransformNode(node);
},
[ts.SyntaxKind.SetAccessor]: (node, context) => {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenAccessor,
"禁用 setter 属性访问器(会生成 __TS__SetDescriptor 破坏元表)。请改用 SetXxx(v) 方法。"
);
return context.superTransformNode(node);
},
[ts.SyntaxKind.AwaitExpression]: (node, context) => {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenAsyncAwait,
"禁用 await 表达式。请使用 Lua coroutine 封装或显式回调。"
);
return context.superTransformExpression(node);
},
[ts.SyntaxKind.TryStatement]: (node, context) => {
if (!hasAllowTryComment(node)) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenTryCatchThrow,
"业务代码禁用 try/catch/finally(会产生 pcall 闭包与表分配开销)。请改用错误码/防御性返回;框架层边界需显式标注 '/** @unlua-allow-try */'。"
);
}
return context.superTransformStatements(node);
},
[ts.SyntaxKind.ThrowStatement]: (node, context) => {
if (!hasAllowTryComment(node)) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenTryCatchThrow,
"业务代码禁用 throw 语句。请改用显式错误返回值;框架层边界需显式标注 '/** @unlua-allow-try */'。"
);
}
return context.superTransformStatements(node);
},
[ts.SyntaxKind.YieldExpression]: (node, context) => {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenGenerator,
"禁用 yield 表达式。请改用 Lua coroutine.yield。"
);
return context.superTransformExpression(node);
},
[ts.SyntaxKind.ForInStatement]: (node, context) => {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenForIn,
"禁用 'for ... in' 语句。遍历 Lua 表请使用 'for (const [k, v] of pairs(tbl))',遍历数组请使用普通 for 循环或 'for ... of'。"
);
return context.superTransformStatements(node);
},
[ts.SyntaxKind.EnumDeclaration]: (node, context) => {
const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined;
const isConst = modifiers?.some((m) => m.kind === ts.SyntaxKind.ConstKeyword) ?? false;
const isDeclare = modifiers?.some((m) => m.kind === ts.SyntaxKind.DeclareKeyword) ?? false;
if (!isConst && !isDeclare) {
report(
context,
node.name,
UnLuaDiagnosticCode.ForbiddenRuntimeEnum,
"禁用运行时普通 enum(会生成双向映射表)。请改用 'const enum'、字符串联合类型或通过 'declare enum' 引用 UE 原生枚举。"
);
}
return context.superTransformStatements(node);
},
[ts.SyntaxKind.RegularExpressionLiteral]: (node, context) => {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenRegExp,
"禁用正则字面量(Lua 无标准正则引擎)。请使用 Lua Pattern(string.match / string.gsub / string.gmatch)。"
);
return tstl.createNilLiteral(node);
},
[ts.SyntaxKind.WithStatement]: (node, context) => {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenDynamicEvalOrWith,
"禁用 with 语句。"
);
return [];
},
[ts.SyntaxKind.FunctionDeclaration]: (node, context) => {
validateFunctionLike(node, context);
return context.superTransformStatements(node);
},
[ts.SyntaxKind.FunctionExpression]: (node, context) => {
validateFunctionLike(node, context);
return context.superTransformExpression(node);
},
[ts.SyntaxKind.ArrowFunction]: (node, context) => {
validateFunctionLike(node, context);
return context.superTransformExpression(node);
},
[ts.SyntaxKind.Identifier]: (node, context) => {
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) {
report(
context,
node,
UnLuaDiagnosticCode.ForbiddenArguments,
"禁用 'arguments' 对象。请使用显式 rest 参数 '...args'。"
);
}
}
return context.superTransformExpression(node);
},
[ts.SyntaxKind.NewExpression]: (node, context) => {
validateNewExpression(node, context);
return context.superTransformExpression(node);
},
[ts.SyntaxKind.DeleteExpression]: (node, context) => {
validateDeleteExpression(node, context);
return context.superTransformExpression(node);
},
[ts.SyntaxKind.BinaryExpression]: (node, context) => {
validateBinaryExpression(node, context);
return context.superTransformExpression(node);
},
[ts.SyntaxKind.ObjectLiteralExpression]: (node, context) => {
for (const prop of node.properties) {
if (ts.isSpreadAssignment(prop)) {
validateSpreadAssignment(prop, context);
} else if (ts.isGetAccessorDeclaration(prop) || ts.isSetAccessorDeclaration(prop)) {
report(
context,
prop,
UnLuaDiagnosticCode.ForbiddenAccessor,
"禁用对象字面量中的 get/set 属性访问器(会生成 __TS__SetDescriptor)。请改用普通方法。"
);
}
}
return context.superTransformExpression(node);
},
};
}