3 Commits
17 changed files with 891 additions and 428 deletions

No files matched your search

+32
View File
@@ -4,6 +4,38 @@ 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
### Fixed
- 修正 [types/unlua.d.ts](types/unlua.d.ts) 中 `UE.TArray` 与 UnLua `LuaLib_Array.cpp` 不一致的两处签名:
- `RemoveItem(item: T): number`(实际返回移除元素数量 `int32`,而非 `boolean`)。
- `GetData(): unknown`(无参调用,传参会在运行时触发 `luaL_error`)。
### Added
- 在 [types/unlua.d.ts](types/unlua.d.ts) 中补充 UnLua 原生基础类型描述符 Token(`UE.int8`~`UE.uint64`、`UE.float`、`UE.double`、`UE.bool`、`UE.FName`、`UE.FString`),支持直接使用 `UE.TArray(UE.int32)` / `UE.TMap(UE.FString, UE.float)` 构造原生类型容器。
## [0.2.0] - 2026-11-29
### Changed
- **拆分精简 [types/unlua.d.ts](types/unlua.d.ts)**:移除所有 UE 引擎反射类声明(`UObject`/`AActor`/`UWorld`/`FVector`/`UKismetSystemLibrary` 等),仅保留 UE 反射无法自动生成的零冲突核心运行时层(`@unlua` 装饰器、`UnLua` 全局模块、`TArray`/`TMap`/`TSet`、智能指针模板别名、`FScriptDelegate`/`FMulticastScriptDelegate`/`FMulticastSparseDelegate` 以及 `UE.NewObject`/`LoadClass`/`LoadObject`),彻底避免与 UE 项目自动生成的反射 `.d.ts` 冲突。
### Removed
- 移除仓库内置的 `examples/` 示例工程、`examples/types/demo.d.ts` 及 `build:examples` / `watch:examples` 脚本;插件自动化测试保留在 [test/plugin.test.mjs](test/plugin.test.mjs) 中使用内存虚拟声明运行。
## [0.1.0] - 2026-11-29 ## [0.1.0] - 2026-11-29
### Added ### Added
-6
View File
@@ -62,10 +62,4 @@ npm install
# 构建插件并运行全部自动化测试 # 构建插件并运行全部自动化测试
npm test npm test
# 编译示例工程(输出至 examples/out/)
npm run build:examples
# 增量监听模式
npm run watch:examples
``` ```
+3 -3
View File
@@ -34,8 +34,8 @@ YourUEProject/
├── package.json # 声明对 ts2lua-unreal 的 Git Tag 依赖 ├── package.json # 声明对 ts2lua-unreal 的 Git Tag 依赖
├── package-lock.json # 锁定精确依赖与 commit,务必提交 Git ├── package-lock.json # 锁定精确依赖与 commit,务必提交 Git
├── tsconfig.json # 继承 ts2lua-unreal/tsconfig.base.json ├── tsconfig.json # 继承 ts2lua-unreal/tsconfig.base.json
├── types/ # 本项目 UE C++/蓝图类型声明 (.d.ts) ├── types/ # 本项目自动生成的 UE 反射与蓝图类型声明 (.d.ts)
│ └── project.d.ts │ └── ue/ # 由 UnLua 编辑器菜单 "Generate IntelliSense & TS" 一键生成
└── src/ # 业务 TS 源码(目录结构镜像 Content/Script) └── src/ # 业务 TS 源码(目录结构镜像 Content/Script)
├── Framework/ ├── Framework/
└── Game/ └── Game/
@@ -263,7 +263,7 @@ npm install
### 5.4 `ts2lua-unreal` 仓库发版规范(维护者) ### 5.4 `ts2lua-unreal` 仓库发版规范(维护者)
每次向外提供新版本时遵循: 每次向外提供新版本时遵循:
1. 更新 `src/plugin/`、`types/` 或 `docs/` 并补齐 `test/plugin.test.mjs` 自动化测试; 1. 更新 `src/plugin/`、`types/` 或 `docs/` 并补齐 `test/plugin.test.mjs` 自动化测试;
2. 运行 `npm test && npm run build:examples` 确保全部通过; 2. 运行 `npm test` 确保全部通过;
3. 按 SemVer 更新 `package.json` 版本号与 `CHANGELOG.md`(`patch` 修 bug,`minor` 增特性/新校验,`major` 破坏性变更); 3. 按 SemVer 更新 `package.json` 版本号与 `CHANGELOG.md`(`patch` 修 bug,`minor` 增特性/新校验,`major` 破坏性变更);
4. 提交并打 Tag 推送: 4. 提交并打 Tag 推送:
```bash ```bash
-44
View File
@@ -1,44 +0,0 @@
/** @noSelfInFile */
interface ListenerEntry {
callback: (this: any, ...args: any[]) => void;
owner: unknown;
}
const listeners: Record<string, ListenerEntry[] | undefined> = {};
export function On<TOwner>(
eventName: string,
callback: (this: TOwner, ...args: any[]) => void,
owner: TOwner
): void {
let list = listeners[eventName];
if (!list) {
list = [];
listeners[eventName] = list;
}
list.push({ callback, owner });
}
export function Emit(eventName: string, ...args: unknown[]): void {
const list = listeners[eventName];
if (!list) return;
for (let i = 0; i < list.length; i++) {
const entry = list[i];
entry.callback.call(entry.owner, ...args);
}
}
export function OffAllForOwner(owner: unknown): void {
for (const [eventName, list] of pairs(listeners)) {
if (!list) continue;
for (let i = list.length - 1; i >= 0; i--) {
if (list[i].owner === owner) {
table.remove(list, i + 1);
}
}
if (list.length === 0) {
listeners[eventName] = undefined;
}
}
}
-16
View File
@@ -1,16 +0,0 @@
/** @noSelfInFile */
export function Info(fmt: string, ...args: unknown[]): void {
const msg = args.length > 0 ? string.format(fmt, ...args) : fmt;
print("[INFO] " + msg);
}
export function Warn(fmt: string, ...args: unknown[]): void {
const msg = args.length > 0 ? string.format(fmt, ...args) : fmt;
print("[WARN] " + msg);
}
export function Error(fmt: string, ...args: unknown[]): void {
const msg = args.length > 0 ? string.format(fmt, ...args) : fmt;
print("[ERROR] " + msg);
}
-140
View File
@@ -1,140 +0,0 @@
import * as Log from "../Framework/Log";
import * as EventBus from "../Framework/EventBus";
interface DemoColorEntry {
Name: string;
R: number;
G: number;
B: number;
A: number;
}
const DEMO_COLORS: DemoColorEntry[] = [
{ Name: "Cyan", R: 0.08, G: 0.78, B: 0.95, A: 1.0 },
{ Name: "Gold", R: 0.98, G: 0.72, B: 0.12, A: 1.0 },
{ Name: "Magenta", R: 0.92, G: 0.22, B: 0.65, A: 1.0 },
{ Name: "Lime", R: 0.25, G: 0.9, B: 0.35, A: 1.0 },
{ Name: "Orange", R: 0.98, G: 0.42, B: 0.14, A: 1.0 },
];
/** @noSelf */
function MakeLinearColor(c: DemoColorEntry): UE.FLinearColor {
return UE.FLinearColor(c.R, c.G, c.B, c.A);
}
@unlua
export default class LuaDemoActor extends UE.ALuaDemoActor {
protected ElapsedTime!: number;
protected TextRefreshTimer!: number;
protected TickCount!: number;
protected PingCount!: number;
protected ColorIndex!: number;
protected HasLoggedTick!: boolean;
ReceiveBeginPlay(): void {
super.ReceiveBeginPlay();
this.ElapsedTime = 0.0;
this.TextRefreshTimer = 0.0;
this.TickCount = 0;
this.PingCount = 0;
this.ColorIndex = 0;
this.HasLoggedTick = false;
EventBus.On("Demo.Ping", this.OnDemoPing, this);
this.ApplyCurrentColor();
this.RefreshStatusText();
Log.Info("LuaDemoActor:ReceiveBeginPlay() bound successfully! Lua=%s", _VERSION);
const msg = string.format(
"[UnLua Demo] LuaDemoActor active (%s) - Press [Space] to Ping",
_VERSION
);
UE.UKismetSystemLibrary.PrintString(
this,
msg,
true,
true,
UE.FLinearColor(0.2, 1.0, 0.4, 1.0),
8.0
);
}
ReceiveTick(DeltaSeconds: number): void {
this.ElapsedTime = (this.ElapsedTime || 0.0) + DeltaSeconds;
this.TickCount = (this.TickCount || 0) + 1;
if (!this.HasLoggedTick) {
this.HasLoggedTick = true;
Log.Info("LuaDemoActor:ReceiveTick() first tick verified (dt=%.4f)", DeltaSeconds);
}
const yawDelta = (this.SpinSpeed || 60.0) * DeltaSeconds;
const pitchDelta = yawDelta * 0.35;
this.AddCubeLocalRotation(UE.FRotator(pitchDelta, yawDelta, 0.0));
const zOffset =
math.sin(this.ElapsedTime * (this.BobFrequency || 2.0)) * (this.BobAmplitude || 25.0);
this.SetCubeVerticalOffset(zOffset);
this.TextRefreshTimer = (this.TextRefreshTimer || 0.0) + DeltaSeconds;
if (this.TextRefreshTimer >= 0.2) {
this.TextRefreshTimer = 0.0;
this.RefreshStatusText();
}
}
OnDemoPing(sourceName: string): void {
this.PingCount = (this.PingCount || 0) + 1;
this.ColorIndex = (this.ColorIndex + 1) % DEMO_COLORS.length;
const colorEntry = this.ApplyCurrentColor();
this.RefreshStatusText();
const msg = string.format(
"[UnLua Demo] Ping #%d from %s -> Cube color: %s",
this.PingCount,
tostring(sourceName),
colorEntry.Name
);
Log.Info(msg);
UE.UKismetSystemLibrary.PrintString(
this,
msg,
true,
true,
MakeLinearColor(colorEntry),
3.0
);
}
ApplyCurrentColor(): DemoColorEntry {
const colorEntry = DEMO_COLORS[this.ColorIndex] || DEMO_COLORS[0];
this.SetCubeColor(MakeLinearColor(colorEntry));
return colorEntry;
}
RefreshStatusText(): void {
const colorEntry = DEMO_COLORS[this.ColorIndex] || DEMO_COLORS[0];
const text = string.format(
"UnLua Active (%s)\nTime: %.1fs | Pings: %d | Color: %s",
_VERSION,
this.ElapsedTime || 0.0,
this.PingCount || 0,
colorEntry.Name
);
this.SetStatusText(text);
}
ReceiveEndPlay(EndPlayReason: number): void {
EventBus.OffAllForOwner(this);
Log.Info(
"LuaDemoActor:ReceiveEndPlay(ticks=%d, pings=%d, reason=%s)",
this.TickCount || 0,
this.PingCount || 0,
tostring(EndPlayReason)
);
super.ReceiveEndPlay(EndPlayReason);
}
}
-17
View File
@@ -1,17 +0,0 @@
import * as Log from "../Framework/Log";
import LuaDemoActor from "./LuaDemoActor";
@unlua
export default class LuaSpecialDemoActor extends LuaDemoActor {
private BoostMultiplier!: number;
ReceiveBeginPlay(): void {
super.ReceiveBeginPlay();
this.BoostMultiplier = 2.0;
Log.Info("LuaSpecialDemoActor initialized with boost=%.1f", this.BoostMultiplier);
}
ReceiveTick(DeltaSeconds: number): void {
super.ReceiveTick(DeltaSeconds * this.BoostMultiplier);
}
}
-24
View File
@@ -1,24 +0,0 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "out"
},
"include": [
"src/**/*.ts",
"types/**/*.d.ts",
"../types/**/*.d.ts"
],
"tstl": {
"luaTarget": "5.4",
"luaLibImport": "require-minimal",
"noImplicitSelf": false,
"noHeader": true,
"sourceMapTraceback": false,
"luaPlugins": [
{
"name": "../dist/plugin/index.js"
}
]
}
}
-16
View File
@@ -1,16 +0,0 @@
/**
* UnrealLuaDemo 项目自定义 C++ Actor 类型声明示例
*/
declare namespace UE {
class ALuaDemoActor extends AActor {
SpinSpeed: number;
BobFrequency: number;
BobAmplitude: number;
AddCubeLocalRotation(DeltaRotation: FRotator): void;
SetCubeVerticalOffset(ZOffset: number): void;
SetCubeColor(Color: FLinearColor): void;
SetStatusText(Text: string): void;
static StaticClass(this: void): UClass;
}
}
+5 -2
View File
@@ -1,17 +1,20 @@
{ {
"name": "ts2lua-unreal", "name": "ts2lua-unreal",
"version": "0.1.0", "version": "0.2.2",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ts2lua-unreal", "name": "ts2lua-unreal",
"version": "0.1.0", "version": "0.2.2",
"dependencies": { "dependencies": {
"lua-types": "^2.14.1", "lua-types": "^2.14.1",
"typescript": "6.0.2", "typescript": "6.0.2",
"typescript-to-lua": "^1.37.3" "typescript-to-lua": "^1.37.3"
}, },
"bin": {
"ts2lua-unreal": "bin/ts2lua-unreal.js"
},
"devDependencies": { "devDependencies": {
"@types/node": "^22.0.0" "@types/node": "^22.0.0"
} }
+1 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "ts2lua-unreal", "name": "ts2lua-unreal",
"version": "0.1.0", "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",
@@ -32,8 +32,6 @@
"scripts": { "scripts": {
"prepare": "npm run build:plugin", "prepare": "npm run build:plugin",
"build:plugin": "tsc -p tsconfig.plugin.json", "build:plugin": "tsc -p tsconfig.plugin.json",
"build:examples": "npm run build:plugin && tstl -p examples/tsconfig.json",
"watch:examples": "tstl -p examples/tsconfig.json --watch",
"test": "npm run build:plugin && node --test test/*.test.mjs" "test": "npm run build:plugin && node --test test/*.test.mjs"
}, },
"dependencies": { "dependencies": {
+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;
+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; 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,9 +505,17 @@ export function tryTransformUnLuaDefaultImport(
return undefined; return undefined;
} }
// 仅处理纯默认导入(@unlua 文件本身禁止额外命名导出) // 若包含命名导入,只要全部是纯类型导入(type-only 或编译期擦除的 interface/type/const enum),仍按纯默认导入处理
if (importClause.namedBindings) { 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)) { if (!ts.isStringLiteral(node.moduleSpecifier)) {
@@ -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
);
}
+37 -13
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.isPropertyAssignment(parent) && parent.name === node) || ((ts.isPropertyAccessExpression(parent) && parent.name === node) ||
(ts.isPropertySignature(parent) && parent.name === node) || (ts.isPropertyAssignment(parent) && parent.name === node) ||
(ts.isMethodDeclaration(parent) && parent.name === node) || (ts.isPropertySignature(parent) && parent.name === node) ||
(ts.isParameter(parent) && parent.name === node) || (ts.isMethodDeclaration(parent) && parent.name === node) ||
(ts.isVariableDeclaration(parent) && parent.name === node); (ts.isParameter(parent) && parent.name === node) ||
if (!isPropertyOrDeclName) { (ts.isVariableDeclaration(parent) && parent.name === node));
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)) {
+310 -7
View File
@@ -5,20 +5,50 @@ 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");
const pluginPath = path.join(projectRoot, "dist", "plugin", "index.js"); const pluginPath = path.join(projectRoot, "dist", "plugin", "index.js");
const { UnLuaDiagnosticCode } = require(pluginPath); const { UnLuaDiagnosticCode } = require(pluginPath);
const VIRTUAL_UE_REFLECTION_DTS = `
declare namespace UE {
class UObject {
GetName(): string;
GetClass(): UClass;
IsValid(): boolean;
IsA(someBase: UClass): boolean;
static StaticClass(this: void): UClass;
}
class UClass extends UObject {}
class AActor extends UObject {
ReceiveBeginPlay(): void;
ReceiveTick(DeltaSeconds: number): void;
ReceiveEndPlay(EndPlayReason: number): void;
static StaticClass(this: void): UClass;
}
class UUserWidget extends UObject {
Construct(): void;
Destruct(): void;
static StaticClass(this: void): UClass;
}
}
`;
/** /**
* 在内存中编译一组虚拟 TS 文件并启用 UnLua 插件。 * 在内存中编译一组虚拟 TS 文件并启用 UnLua 插件。
*/ */
function transpileWithUnLua(files) { function transpileWithUnLua(files) {
const virtualFiles = { const virtualFiles = {
"unlua.d.ts": unluaTypesContent, "unlua.d.ts": unluaTypesContent,
"ue.generated.d.ts": VIRTUAL_UE_REFLECTION_DTS,
...files, ...files,
}; };
@@ -73,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;
}
} }
`, `,
}); });
@@ -84,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/);
@@ -435,12 +476,274 @@ test("forbids multiple @unlua classes in one file, invalid @unlua args, and dire
}); });
// ============================================================ // ============================================================
// 4. 端到端示例工程编译验证 // 4. 进阶边界与回归测试(v0.2.2+)
// ============================================================ // ============================================================
test("examples/tsconfig.json transpiles cleanly with zero diagnostics", () => { test("@unlua static methods preserve self matching TSTL colon calls, while @noSelf / this:void use dot calls", () => {
const exampleConfigPath = path.join(projectRoot, "examples", "tsconfig.json"); const result = transpileWithUnLua({
const result = tstl.transpileProject(exampleConfigPath); "Game/CalcActor.ts": `
const errors = result.diagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error); @unlua
assert.equal(errors.length, 0, errors.map((e) => ts.flattenDiagnosticMessageText(e.messageText, "\n")).join("\n")); 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);
}
}); });
+159 -120
View File
@@ -1,6 +1,13 @@
/** /**
* UnLua + Unreal Engine 基础编译期类型声明。 * ts2lua-unreal + UnLua 核心运行时编译期类型声明(零冲突层)。
* 实际 UE 项目可在此基础上叠加由 UnLua / UHT 自动导出的完整 UE .d.ts。 *
* 本文件仅包含 UE 反射系统无法自动导出的内容:
* 1. `@unlua` 编译期装饰器
* 2. `UnLua` 全局模块接口
* 3. UnLua 通用容器(TArray / TMap / TSet)、智能指针/模板别名、Delegate 包装与 UE 全局加载/创建函数
*
* 所有 UE 引擎反射类(UObject / AActor / UWorld / FVector / 项目 C++ 与蓝图类等)
* 由 UE 工程中的 UnLua Editor 命令(Generate IntelliSense & TS)自动生成并自动合并至 `UE` 命名空间。
*/ */
/** /**
@@ -15,6 +22,9 @@ declare function unlua(baseModuleName: string): (target: abstract new (...args:
* UnLua 全局模块接口 * UnLua 全局模块接口
*/ */
declare namespace UnLua { declare namespace UnLua {
let PackagePath: string;
let FTextEnabled: boolean;
/** @noSelf */ /** @noSelf */
function Class(superClassName?: string): any; function Class(superClassName?: string): any;
/** @noSelf */ /** @noSelf */
@@ -22,149 +32,169 @@ declare namespace UnLua {
/** @noSelf */ /** @noSelf */
function Unref(obj: UE.UObject): void; function Unref(obj: UE.UObject): void;
/** @noSelf */ /** @noSelf */
function HotReload(): 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;
}
} }
/** /**
* UE 核心反射与容器基础声明(精简基线,供插件校验与示例使用) * UnLua 非反射泛型容器、委托与全局辅助函数(与自动生成的 UE 反射 `.d.ts` 自动合并)
*/ */
declare namespace UE { declare namespace UE {
class UObject { type TSubclassOf<T extends UObject = UObject> = UClass;
GetName(): string;
GetClass(): UClass; interface TSoftClassPtr<T extends UObject = UObject> {
GetWorld(): UWorld | undefined;
IsValid(): boolean; IsValid(): boolean;
IsA(someBase: UClass): boolean; IsNull(): boolean;
Initialize(Initializer?: unknown): void; IsPending(): boolean;
Reset(): void;
Set(obj: UClass | undefined): TSoftClassPtr<T>;
GetAssetName(): string;
GetLongPackageName(): string;
Get(): UClass | undefined;
LoadSynchronous(): UClass | undefined;
} }
class UClass extends UObject {} interface TSoftObjectPtr<T extends UObject = UObject> {
IsValid(): boolean;
class UWorld extends UObject { IsNull(): boolean;
SpawnActor<T extends AActor = AActor>( IsPending(): boolean;
actorClass: UClass, Reset(): void;
transform?: FTransform, Set(obj: T | undefined): TSoftObjectPtr<T>;
collisionHandling?: number, GetAssetName(): string;
owner?: AActor, GetLongPackageName(): string;
instigator?: APawn, Get(): T | undefined;
moduleName?: string LoadSynchronous(): T | undefined;
): T | undefined;
} }
class UActorComponent extends UObject { interface TWeakObjectPtr<T extends UObject = UObject> {
ReceiveBeginPlay(): void; IsValid(): boolean;
ReceiveTick(DeltaSeconds: number): void; Reset(): void;
ReceiveEndPlay(EndPlayReason: number): void; Set(obj: T | undefined): void;
Get(): T | undefined;
} }
class AActor extends UObject { interface TLazyObjectPtr<T extends UObject = UObject> {
ReceiveBeginPlay(): void; IsValid(): boolean;
ReceiveTick(DeltaSeconds: number): void; Reset(): void;
ReceiveEndPlay(EndPlayReason: number): void; Set(obj: T | undefined): void;
K2_GetActorLocation(): FVector; Get(): T | undefined;
K2_SetActorLocation(
NewLocation: FVector,
bSweep?: boolean,
SweepHitResult?: unknown,
bTeleport?: boolean
): boolean;
K2_DestroyActor(): void;
static StaticClass(this: void): UClass;
} }
class APawn extends AActor { type TScriptInterface<T = UObject> = T;
static StaticClass(this: void): UClass;
}
class ACharacter extends APawn { interface FMulticastScriptDelegate<TCallback extends (...args: any[]) => void = (...args: any[]) => void> {
static StaticClass(this: void): UClass;
}
class APlayerController extends AActor {
static StaticClass(this: void): UClass;
}
class AGameModeBase extends AActor {
static StaticClass(this: void): UClass;
}
class UGameInstance extends UObject {
ReceiveInit(): void;
ReceiveShutdown(): void;
static StaticClass(this: void): UClass;
}
class UUserWidget extends UObject {
Construct(): void;
Destruct(): void;
Tick(MyGeometry: unknown, InDeltaTime: number): void;
static StaticClass(this: void): UClass;
}
interface FVector {
X: number;
Y: number;
Z: number;
Add(other: FVector): FVector;
Sub(other: FVector): FVector;
Size(): number;
}
function FVector(this: void, X?: number, Y?: number, Z?: number): FVector;
interface FRotator {
Pitch: number;
Yaw: number;
Roll: number;
}
function FRotator(this: void, Pitch?: number, Yaw?: number, Roll?: number): FRotator;
interface FTransform {
Translation: FVector;
Rotation: unknown;
Scale3D: FVector;
}
function FTransform(this: void): FTransform;
interface FLinearColor {
R: number;
G: number;
B: number;
A: number;
}
function FLinearColor(this: void, R?: number, G?: number, B?: number, A?: number): FLinearColor;
interface FMulticastScriptDelegate<TCallback extends (...args: any[]) => void = () => void> {
Add(target: UObject, callback: TCallback): void; Add(target: UObject, callback: TCallback): void;
Remove(target: UObject, callback: TCallback): void; Remove(target: UObject, callback: TCallback): void;
Clear(): void; Clear(): void;
Broadcast(...args: Parameters<TCallback>): void; Broadcast(...args: Parameters<TCallback>): void;
IsBound(): boolean;
} }
interface FScriptDelegate<TCallback extends (...args: any[]) => void = () => void> { type FMulticastSparseDelegate<TCallback extends (...args: any[]) => void = (...args: any[]) => void> =
FMulticastScriptDelegate<TCallback>;
interface FScriptDelegate<TCallback extends (...args: any[]) => any = (...args: any[]) => any> {
Bind(target: UObject, callback: TCallback): void; Bind(target: UObject, callback: TCallback): void;
Unbind(): void; Unbind(): void;
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;
Get(index: number): T; AddUnique(item: T): number;
Set(index: number, item: T): void; Find(item: T): number;
Insert(item: T, index: number): void;
Remove(index: number): void; Remove(index: number): void;
RemoveItem(item: T): number;
Clear(): void; Clear(): void;
Reserve(size: number): boolean;
Resize(size: number): void;
GetData(): unknown;
Get(index: number): T;
GetRef(index: number): T;
Set(index: number, item: T): void;
Swap(firstIndex: number, secondIndex: number): void;
Shuffle(): void;
LastIndex(): number;
IsValidIndex(index: number): boolean;
Contains(item: T): boolean; Contains(item: T): boolean;
Append(other: TArray<T>): void;
ToTable(): T[]; ToTable(): T[];
} }
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;
Find(key: K): V | undefined;
Remove(key: K): boolean; Remove(key: K): boolean;
Contains(key: K): boolean; Find(key: K): V | undefined;
FindRef(key: K): V | undefined;
Clear(): void; Clear(): void;
Keys(): TArray<K>; Keys(): TArray<K>;
Values(): TArray<V>; Values(): TArray<V>;
@@ -179,29 +209,38 @@ declare namespace UE {
Remove(item: T): boolean; Remove(item: T): boolean;
Contains(item: T): boolean; Contains(item: T): boolean;
Clear(): void; Clear(): void;
ToArray(): TArray<T>;
ToTable(): T[]; ToTable(): T[];
} }
function TSet<T>(this: void, elementType: any): TSet<T>; function TSet<T>(this: void, elementType: any): TSet<T>;
/** @noSelf */ /** UnLua 原生基础类型描述符 Token,用于构造 UE.TArray / UE.TMap / UE.TSet(如 UE.TArray(UE.int32)) */
namespace UKismetSystemLibrary { var int8: unknown;
function PrintString( var int16: unknown;
WorldContextObject: UObject | undefined, var int32: unknown;
InString?: string, var int64: unknown;
bPrintToScreen?: boolean, var uint8: unknown;
bPrintToLog?: boolean, var uint16: unknown;
TextColor?: FLinearColor, var uint32: unknown;
Duration?: number var uint64: unknown;
): void; var float: unknown;
function IsValid(Object: UObject | undefined): boolean; var double: unknown;
function Delay(WorldContextObject: UObject, Duration: number): void; var bool: unknown;
} var FName: unknown;
var FString: unknown;
/** @noSelf */ /** @noSelf */
function NewObject<T extends UObject = UObject>( function NewObject<T extends UObject = UObject>(
outerClass: UClass, outerClass: UClass,
outer?: UObject, outer?: UObject,
name?: string, name?: string,
moduleName?: string moduleName?: string,
initializerTable?: Record<string, unknown>
): T; ): T;
/** @noSelf */
function LoadClass(classPath: string): UClass | undefined;
/** @noSelf */
function LoadObject<T extends UObject = UObject>(objectPath: string): T | undefined;
} }