diff --git a/README.md b/README.md index fe3db85..a0806c5 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,58 @@ # ts2lua-unreal -面向 Unreal Engine + UnLua 项目的 TypeScript 开发工程。通过 TypeScript 编写业务逻辑,再经由 `ts2lua` 转换为 Unreal / UnLua 使用的 Lua 脚本。 +面向 **Unreal Engine 5.8 + UnLua 2.3.6(Lua 5.4)** 的 TypeScript 开发工具链与编译器插件,基于官方 [TypeScriptToLua (TSTL)](https://github.com/TypeScriptToLua/TypeScriptToLua) 插件机制实现(无需 Fork TSTL 源码)。 + +## 特性概览 + +- **原生 UnLua 代码生成**:通过全局免 `import` 编译期装饰器 `@unlua` 标记绑定类,直接输出 `local M = UnLua.Class(...)`、`function M.Method(self, ...)` 与 `return M`,零 `__TS__Class` / `__TS__Decorate` / `____exports` 垫片污染。 +- **精确的 `super` 映射**: + - 继承 UE C++/蓝图原生基类 -> `self.Overridden.Method(self, ...)` + - 继承另一个 `@unlua` TS 绑定类 -> `BaseClass.Method(self, ...)`(规避多层继承 `self.Super` 递归坑) +- **编译期强约束(Fail Fast)**:在 TSTL AST 阶段直接阻断 `get/set` 访问器、`async/await`/`Promise`、`try/catch/throw`、`RegExp`/`Map`/`Set`/`Proxy`/`Symbol`、普通运行时 `enum`、`@unlua` 类 `constructor`/字段初始化器/`new` 实例化、UE Delegate 匿名函数回调、`UObject` 的 `instanceof`/`delete`/对象展开以及继承 `UE.UObject` 漏标 `@unlua` 等问题。 +- **面向大型项目(3000~5000+ 文件)优化**:插件预编译为 JS、复用 TSTL 单次 AST 遍历、`WeakMap` 缓存类型查询、`skipLibCheck: true` 与增量 Watch 模式支持。 + +## 目录结构 + +```text +ts2lua-unreal/ +├── docs/ +│ └── ts-unlua-spec.md # TypeScript -> UnLua 开发与语言约束规范 +├── types/ +│ └── unlua.d.ts # 全局 @unlua 装饰器与 UnLua/UE 基础类型声明 +├── src/plugin/ # TSTL UnLua 编译器插件源码 +│ ├── index.ts # 插件入口 +│ ├── diagnostics.ts # 自定义编译错误码(90001-90110) +│ ├── type-utils.ts # WeakMap 缓存的 TypeChecker 工具 +│ ├── validators.ts # 语言子集与 UnLua 约束校验 +│ └── unlua-transform.ts # UnLua.Class / return M / super / default import 转换 +├── examples/ # 对齐 UnrealLuaDemo 的端到端示例 +│ ├── tsconfig.json +│ ├── types/demo.d.ts +│ └── src/ +│ ├── Framework/ # 纯工具模块(Log / EventBus) +│ └── Game/ # UnLua 绑定类(LuaDemoActor / LuaSpecialDemoActor) +├── test/ +│ └── plugin.test.mjs # Node 原生自动化测试套件 +├── tsconfig.base.json # 业务项目可继承的 TSTL 基础配置(Lua 5.4) +└── tsconfig.plugin.json # 插件构建配置 +``` + +## 快速开始 + +```bash +# 安装依赖 +npm install + +# 构建插件并运行全部自动化测试 +npm test + +# 编译示例工程(输出至 examples/out/) +npm run build:examples + +# 增量监听模式(适配 UnLua HotReload) +npm run watch:examples +``` + +## 文档 + +- [TypeScript to UnLua 开发与语言约束规范](docs/ts-unlua-spec.md) diff --git a/docs/ts-unlua-spec.md b/docs/ts-unlua-spec.md new file mode 100644 index 0000000..75754fc --- /dev/null +++ b/docs/ts-unlua-spec.md @@ -0,0 +1,335 @@ +# TypeScript to UnLua (`ts2lua-unreal`) 开发与语言约束规范 + +> 本文档参考 [TypeScriptToLua (TSTL)](https://github.com/TypeScriptToLua/TypeScriptToLua) 的转译机制,结合 **Unreal Engine + UnLua** 的运行时模型,定义本项目允许与禁止使用的 TypeScript 语言子集、编码约定以及编译器/Lint 强制检查策略。 + +--- + +## 1. 设计原则与基线环境 + +### 1.1 目标运行环境(对齐 `UnrealLuaDemo` 基线) +- **Unreal Engine**:UE 5.8 +- **UnLua**:2.3.6(`bEnableCallOverriddenFunction=True`、`bEnableTypeChecking=True`、`bWithUE4Namespace=True`、`bLegacyReturnOrder=False`、`HotReloadMode=Manual`) +- **目标 Lua 版本**:**Lua 5.4**(`lua-5.4.3`,TSTL 锁定 `luaTarget: "5.4"`) + +### 1.2 核心设计原则 +1. **贴近 UnLua 原生运行模型**:生成的 Lua 代码应与手写 UnLua 风格一致(如 `local M = UnLua.Class(...)`、`return M`、原生冒号/点号调用、`self.Overridden`),避免 TSTL 默认 JS 运行时模拟破坏 UnLua 元表与绑定机制。 +2. **零/极小化运行时垫片(Minimal `lualib`)**:禁止引入重型 JS polyfill(如 `Promise`、`Map`、`Set`、`__TS__SetDescriptor`、`__TS__Decorate`),保证运行性能、低 GC 压力与良好的断点调试体验(EmmyLua / LuaPanda)。 +3. **编译期强约束(Fail Fast)**:所有不兼容特性在 **TSTL 自定义插件(AST 检查)+ ESLint(纯 AST 规则)** 阶段直接报错阻断,不把隐患留到 UE 运行时。 +4. **明确区分两类代码**: + - **UnLua 绑定类(`@unlua` 标记类)**:挂载到 `UObject` / `AActor` / `UActorComponent` / `UUserWidget` / `USubsystem` 等蓝图或 C++ 类的脚本,由 UE 引擎实例化。 + - **纯逻辑模块/类(Pure TS/Lua Module)**:不绑定 `UObject` 的工具库(如 `Framework/Log`、`Framework/EventBus`)、数据结构、纯逻辑管理器。 +5. **面向大型项目(3000~5000+ 文件)的性能架构**: + - 基于原版 `typescript-to-lua` + 预编译的 TS 插件(无需 Fork TSTL 源码); + - 插件复用 TSTL 单次 AST 遍历,纯语法规则不碰 `TypeChecker`,类型查询结果使用 `WeakMap` 缓存; + - 强制开启 `skipLibCheck: true` 与按模块裁剪 UE `.d.ts`,开发期使用增量 Watch 编译联动 UnLua HotReload。 + +--- + +## 2. 强制禁用的 TypeScript / JavaScript 特性 + +以下特性在编译插件与 ESLint 中均设为 **Error(编译阻断)**: + +### 2.1 禁用属性访问器(`get` / `set`) +- **规则**:禁止在 `class` 和对象字面量中使用 `get foo()` / `set foo(v)`。 +- **原因**:TSTL 会生成 `__TS__SetDescriptor` 并改写原型表的 `__index` / `__newindex` 元方法。在 UnLua 中,绑定类的元表由 UnLua C++ 层接管以映射 `UPROPERTY` / `UFUNCTION`,改写元表会导致属性查找失效、死循环或严重的运行时性能开销。 +- **替代方案**:显式编写 `GetFoo()` / `SetFoo(v)` 方法。 + +```ts +// ❌ 禁止 +class PlayerController { + get hp(): number { return this._hp; } + set hp(v: number) { this._hp = v; } +} + +// ✅ 推荐 +class PlayerController { + GetHp(): number { return this._hp; } + SetHp(v: number): void { this._hp = v; } +} +``` + +### 2.2 禁用 `async` / `await` 与 `Promise` +- **规则**:禁止使用 `async` 函数、`await` 表达式及 `new Promise(...)`。 +- **原因**: + 1. TSTL 需要注入庞大的 `Promise` 垫片及闭包状态机,GC 开销大; + 2. 与 UnLua 原生基于 Lua 协程(`coroutine`)驱动 UE Latent 函数(如 `Delay`、异步加载)的机制割裂; + 3. UE `UObject` 可能在异步等待期间被销毁,原生 Promise 链缺乏与 `UObject` 生命周期绑定的自动取消/判空保护。 +- **替代方案**:使用项目封装的 Lua `coroutine` 工具(见第 5.5 节)或显式回调 + `IsValid(this)` 校验。 + +### 2.3 禁用常规 `try` / `catch` / `finally` 与 `throw` +- **规则**:业务代码中禁止使用 `try / catch / finally` 和 `throw`。仅允许在底层框架边界(如消息分发入口、测试框架)使用封装好的 `pcall` / `xpcall`。 +- **原因**:TSTL 将 `try` 块编译为匿名闭包 + `pcall` + 结果表分配,每次执行都会触发内存分配与 GC;此外跨 `pcall` 边界的协程 `yield` 在部分场景受限。 +- **替代方案**:使用显式返回值 / 错误码 / 防御性判空(`if (!IsValid(target)) return;`)。 + +### 2.4 禁用任意运行时装饰器(Decorators) +- **规则**:禁止自定义会在运行时执行的装饰器(会生成 `__TS__Decorate`);**仅允许使用工具链白名单内的编译期装饰器**(如 `@uclass`、`@unlua` 等,由 TSTL 插件在编译期消费并完全擦除,不输出任何运行时代码)。 +- **原因**:运行时装饰器会引入 `__TS__Decorate` 垫片,并破坏 UnLua 模块顶层定义结构与热重载。 + +### 2.5 禁用不兼容的 JS 内建对象与元编程特性 +- **禁用列表**: + - `RegExp` 及正则字面量 `/abc/`(Lua 无标准正则引擎,仅支持 Lua Pattern,请使用 `string.match` / `string.gmatch` / `string.gsub`) + - `Proxy`、`Reflect`、`Symbol`、`BigInt` + - `Map`、`Set`、`WeakMap`、`WeakSet`(避免 `__TS__Map` / `__TS__Set` 垫片,改用原生 `Record` / `LuaTable` 或 `UE.TMap` / `UE.TSet`) + - `eval`、`new Function`、`with`、`arguments` + - `Object.defineProperty`、`Object.defineProperties`、`Object.setPrototypeOf`、`Object.create`、`Object.freeze` + - 生成器 `function*` / `yield`(改用 Lua `coroutine`) + - `for ... in`(禁止用于数组或 UObject;遍历原生 Lua 表请使用 TSTL 的 `for (const [k, v] of pairs(tbl))`) + - 动态 `import()`、命名空间合并(`namespace` 与 `class` 合并) + +### 2.6 禁用运行时普通 `enum`(限制为 `const enum` 或联合类型) +- **规则**:业务定义的枚举禁止使用普通 `enum`(无 `const` 修饰),除非是 `declare enum`(用于映射 UE C++ 侧已有枚举,如 `UE.ECollisionChannel`)。 +- **原因**:TS 普通数字 `enum` 会生成双向映射表(`E[E["A"] = 0] = "A"`),增加内存占用且在遍历/序列化时容易出错。 +- **替代方案**: + - 数值枚举:`const enum EMyState { Idle = 0, Run = 1 }`(编译期直接内联为数字常量,零运行时开销); + - 字符串枚举:字符串字面量联合类型 `type State = "Idle" | "Run"` 或 `const` 只读对象; + - UE 原生枚举:通过 `.d.ts` 中的 `declare enum` 直接引用 `UE.EXxx`。 + +### 2.7 禁用 `null` 与 `undefined` 的语义区分 +- **规则**:代码中统一使用 `undefined`(或统一约定单一方,推荐 `undefined`)表示 Lua 的 `nil`,禁止依赖 `a === null` 与 `a === undefined` 的区别,禁止用 `typeof x === "undefined"` 区分“键不存在”和“键值为 `nil`”。 +- **原因**:在 Lua 中 `null` 和 `undefined` 均编译为 `nil`,表中赋值为 `nil` 等价于删除该键。 + +### 2.8 禁用 `delete` 操作符用于数组或 `UObject` 属性 +- **规则**:禁止对数组使用 `delete arr[i]`(会产生稀疏数组导致 `#arr` 长度错乱);禁止对 `UObject` 反射属性使用 `delete`。 +- **替代方案**:数组删除使用 `table.remove` / `splice`(或 swap-remove);Lua 表移除键直接赋值 `tbl[k] = undefined`。 + +### 2.9 禁用 `instanceof` 用于 `UObject` 类型判断 +- **规则**:禁止对 UE 对象使用 `obj instanceof UE.AActor`。 +- **原因**:`instanceof` 会编译为 `__TS__InstanceOf` 检查 JS 原型链,无法识别 UE 反射继承树。 +- **替代方案**:使用 UE 反射方法 `obj.IsA(UE.AActor.StaticClass())` 或 `Cast`。 + +### 2.10 禁用对象/数组解构的隐式展开滥用(限制 `...` Spread) +- **规则**:禁止在热路径(如 `ReceiveTick`)使用 `{ ...obj }`、`[...arr]`、可变参数大量展开;禁止对 `UObject` 使用对象展开 `{ ...actor }`。 +- **原因**:对象/数组展开会生成新表拷贝并引入 `__TS__ObjectAssign` / `__TS__Spread`;对 `UObject` 展开无法遍历 C++ 反射属性。 + +--- + +## 3. UnLua 绑定类(UObject 派生类)专项规范 + +UnLua 绑定类指挂载在蓝图/C++ 上(通过 `UnLuaInterface::GetModuleName()` 返回路径加载)的脚本类。 + +### 3.1 文件结构、识别方式(方案 B)与导出规范(强校验) +- **规则**: + 1. **显式全局 `@unlua` 标记**:所有 UnLua 绑定类**必须**使用全局编译期装饰器 `@unlua`(或 `@unlua("Custom.BaseModule")`)标注,业务文件**无需额外 `import`**,装饰器在编译期完全擦除,不产生任何运行时代码。 + 2. **漏标防呆**:若某个类继承自 `UE.UObject`(或其任意派生类)但未标注 `@unlua`,编译器将直接报错提示补加 `@unlua`,防止被误编译为普通 `__TS__Class`。 + 3. **单文件单默认导出**:每个 `@unlua` 类文件**必须且只能**包含一个默认导出的类(`@unlua export default class Xxx ...`)。禁止在同一文件中额外 `export` 其他运行时变量/函数(仅允许 `export type` / `export interface` 纯类型导出)。 +- **原因**:UnLua 加载脚本时执行 `local M = require("Path.To.Script")`,期望模块返回值 `M` **直接就是 `UnLua.Class()` 创建的 Lua table**。TSTL 默认的命名导出会包装为 `{ Xxx = ... }`,导致 UnLua 无法绑定生命周期函数;同时纯语法的 `@unlua` 标记可让 ESLint 在大型项目中无需加载 TypeChecker 也能毫秒级校验。 +- **转译目标(由自定义 TSTL 插件实现)**: + +```ts +// TypeScript 源码(Game/LuaDemoActor.ts) +@unlua +export default class LuaDemoActor extends UE.ALuaDemoActor { + ReceiveBeginPlay(): void { + super.ReceiveBeginPlay(); + } +} +``` + +```lua +-- 目标生成的 UnLua 代码(Game/LuaDemoActor.lua) +local M = UnLua.Class() + +function M:ReceiveBeginPlay() + self.Overridden.ReceiveBeginPlay(self) +end + +return M +``` + +### 3.2 禁用 `constructor` 与类字段初始化器 +- **规则**:UnLua 绑定类中**严禁**定义 `constructor()`,也**严禁**在类属性声明处直接写初始化赋值(如 `private count = 0;` 或 `private items: number[] = [];`)。 +- **原因**:UnLua 绑定对象由 UE 引擎创建,不会调用 JS/TSTL 的 `____constructor`,导致构造逻辑和字段默认值完全不执行;若放在模块表 `M` 上又会导致所有实例共享同一个引用(尤其是 table/数组引发严重串数据 Bug)。 +- **替代方案**: + - 类字段仅做类型声明(使用 `declare` 或 TS 非空断言 `!:`,且不带初始值); + - 实例状态统一在 `Initialize(Initializer)`(UObject/UMG)、`Construct()`(UMG)或 `ReceiveBeginPlay()`(Actor/Component)中初始化。 + +```ts +// ❌ 禁止 +export default class BP_Player extends UE.ACharacter { + private hp = 100; // 不会在实例化时执行,或在原型上共享 + private buffs: number[] = []; // 危险! + constructor() { super(); } // 永远不会被 UE 调用 +} + +// ✅ 推荐 +export default class BP_Player extends UE.ACharacter { + private hp!: number; + private buffs!: number[]; + + ReceiveBeginPlay(): void { + this.hp = 100; + this.buffs = []; + } +} +``` + +### 3.3 继承与 `super` 调用规则 +UnLua 中存在两种“父类方法调用”语义,规范与插件必须明确区分: + +1. **继承自 UE 原生 C++/蓝图类**(`class BP_MyActor extends UE.AActor`): + - `UnLua.Class()` 不传 Lua 父类路径; + - `super.Method(...)` 由插件编译为 **`self.Overridden.Method(self, ...)`**(调用被 Lua 覆写的 C++/蓝图版本)。 +2. **继承自另一个 Lua/TS 绑定类**(`class BP_SubActor extends BP_BaseActor`): + - 编译为 `UnLua.Class("Path.To.BP_BaseActor")`; + - `super.Method(...)` 调用父 Lua 类方法,编译为 **`BP_BaseActor.Method(self, ...)`** 或 `self.Super.Method(self, ...)`(推荐直接引用父类模块表 `SuperModule.Method(self, ...)`,规避 UnLua 多层继承下 `self.Super` 无限递归的经典坑)。 +3. **禁止多继承与超过 3 层的深继承链**:建议组合优于继承(使用 `UActorComponent` 或纯逻辑 Helper 类)。 +4. **禁止 `new BP_MyActor()`**:UnLua 绑定类不可用 `new` 实例化,必须通过 `UE.UWorld.SpawnActor`、`UE.NewObject`、`UE.UWidgetBlueprintLibrary.Create` 等 UE API 创建(可在插件中校验并报错)。 + +### 3.4 `UPROPERTY` 与蓝图组件访问规则 +- 蓝图/C++ 中已定义的 `UPROPERTY` 与组件,在 `.d.ts` 中声明后直接通过 `this.Health`、`this.RootComponent` 访问。 +- 避免 Lua 侧私有字段与 C++/蓝图 `UPROPERTY` / `UFUNCTION` 重名(否则 Lua table 键会遮蔽 C++ 反射属性或导致写入行为异常)。建议 Lua 内部私有变量统一加下划线前缀(如 `_state`、`_timerHandle`)。 +- 访问 UE 对象属性或方法前,对于跨帧持有或外部传入的 `UObject` 引用,**必须**先通过 `IsValid(obj)` 检查有效性(防止访问已被 UE GC 回收或 PendingKill 的对象导致崩溃)。 + +### 3.5 Delegate / Event Dispatcher 绑定规范 +- **禁止**在 `Add` / `Bind` 中传入箭头函数或匿名函数: + ```ts + // ❌ 禁止:无法 Remove,每次调用产生新闭包,且 UnLua Add 签名不匹配 + this.BtnStart.OnClicked.Add(this, () => { this.OnStartClicked(); }); + ``` +- **必须**传入类成员方法引用,并在 `ReceiveEndPlay` / `Destruct` 中成对 `Remove` 或 `Clear`: + ```ts + // ✅ 推荐 + Construct(): void { + this.BtnStart.OnClicked.Add(this, this.OnStartClicked); + } + + Destruct(): void { + this.BtnStart.OnClicked.Remove(this, this.OnStartClicked); + } + + private OnStartClicked(): void { + // ... + } + ``` +- **严格匹配签名**:回调函数的参数个数与类型必须与 Delegate 声明完全一致,禁止省略或增加无关参数(UnLua 反射校验签名不匹配会在运行时报错)。 + +### 3.6 禁止在绑定类中使用箭头函数作为类方法 +- **规则**:禁止 `OnClick = () => { ... }` 写法(属于类字段初始化器,且不会挂在 `M` 表上,UnLua 反射/热重载均无法识别)。 +- **要求**:所有类成员方法必须使用标准方法声明 `OnClick(): void { ... }`。 + +--- + +## 4. 纯逻辑模块、函数调用约定与 `self` 规范 + +### 4.1 冒号调用(`:`)与点号调用(`.`) +- TSTL 默认遵循: + - 类实例方法与带 `this` 的函数 -> 冒号调用 `obj:Method(a)`(隐式传递 `self`); + - 声明了 `this: void` 或带 `/** @noSelf */` / `/** @noSelfInFile */` 的函数 -> 点号调用 `Lib.Func(a)`(不传递 `self`)。 +- **规范**: + 1. **不全局开启 `noImplicitSelf: true`**(因为 UnLua 的 `UObject` 成员方法、绑定类方法、组件/容器方法绝大部分都是 `:` 冒号调用)。 + 2. 所有 **UE 静态函数 / 蓝图函数库(`UBlueprintFunctionLibrary`)** 在 `.d.ts` 中必须标注 `this: void`(或 `@noSelf`),确保编译为 `UE.UKismetSystemLibrary.PrintString(...)` 而非 `:` 调用。 + 3. 纯工具函数文件(无类状态)应在文件顶部添加 `/** @noSelfInFile */`,避免多余的 `self` 占位参数。 + 4. **禁止**将实例方法当作普通回调直接传给期望无 `self` 函数的 API(TS 开启 `strict` + TSTL 的 `self` 校验会在编译期捕获此错误)。 + +### 4.2 纯逻辑类规范 +- 允许使用普通 `class` 封装纯数据或服务逻辑,但仍须遵守第 2 节全部禁用规则(禁用 `get/set`、禁用 `async/await`、禁用 `try/catch` 等)。 +- 推荐优先使用 **接口(`interface`)+ 纯函数模块** 或 **扁平无继承的轻量类**,减少 `__TS__ClassExtends` 链式查找开销。 + +--- + +## 5. 类型、数据结构、协程与性能/GC 规范 + +### 5.1 严格区分 Lua 数组(`T[]`)与 UE 容器(`UE.TArray` / `TMap` / `TSet`) +| 维度 | TS/Lua 数组 (`T[]`) | `UE.TArray` | +| :--- | :--- | :--- | +| 底层结构 | 原生 Lua table | UE C++ 原生 `TArray` | +| 索引基准 | TS 中 **0-based**(TSTL 自动 `+1` 转为 Lua 1-based) | UnLua `Get(i)` / `Set(i, v)` 为 **1-based**(以项目 UnLua 版本 `.d.ts` 为准) | +| 长度获取 | `arr.length`(编译为 `#arr`) | `tarr.Length()` | +| 推荐遍历 | `for (let i = 0; i < arr.length; i++)` 或 `for (const v of arr)` | `for (let i = 1; i <= tarr.Length(); i++) { const v = tarr.Get(i); }` | + +- **规则**: + 1. 禁止在数组中间存入 `undefined`(Lua table 出现空洞会导致 `#arr` 行为未定义)。 + 2. 禁止在 `ReceiveTick` 等每帧热路径中使用 `arr.map(...).filter(...)` 等链式高阶函数(会分配多个临时 table 与闭包)。请使用普通 `for` 循环。 + 3. 与 UE C++/蓝图交互传递大量数据时,优先直接使用 `UE.TArray` / `UE.TMap` / `UE.TSet`,避免每帧在 Lua table 和 UE 容器之间来回转换(`ToTable()` 仅用于低频场景)。 + +### 5.2 字典与集合 +- 使用 `Record` 或 TSTL 内置 `LuaTable` 代替 JS 的 `Map` / `Set`。 +- 键遍历统一使用 `pairs(map)`(不要使用 `Object.keys(map)`,避免分配临时 key 数组)。 + +### 5.3 UE 结构体(`FVector`、`FRotator`、`FTransform` 等)性能规范 +- 禁止在 `ReceiveTick` 中高频创建临时结构体并依赖 GC 回收,推荐: + - 使用 UnLua 支持的 **复用输出参数** 写法(若 C++ API 支持 `Out` 参数复用结构体); + - 或在类实例上缓存临时结构体(如 `private _tmpVec!: UE.FVector`)并在 Tick 中复用修改其分量。 +- 结构体为值语义或 C++ 引用语义取决于来源(从 `UPROPERTY` 取出的结构体修改其分量可能直接影响原属性或需要回写),规范中对结构体修改建议显式调用 Setter(如 `this.K2_SetActorLocation(pos, ...)`)。 + +### 5.4 数值类型与位运算 +- 目标 Lua 版本统一锁定为 **Lua 5.4**(或按项目 UE 集成的 UnLua 版本锁定为 **Lua 5.3**,见第 6 节)。 +- Lua 5.3/5.4 支持原生 64 位整数与双精度浮点及原生位运算符(`&`, `|`, `~`, `<<`, `>>`),无需位运算 polyfill。 +- 注意 JS `number` 为 `double`(53 位精确整数),涉及 UE `int64` / `uint64` 大整数(如唯一 ID、时间戳、Bitmask)时,禁止在 TS 中直接做浮点算术,应使用字符串或专门的 64 位封装类型。 + +### 5.5 协程与 Latent 函数(替代 `async / await`) +- 需要等待 `UE.UKismetSystemLibrary.Delay` 或异步资源加载时,统一通过项目封装的协程启动器执行: + +```ts +// 示例:通过框架协程封装执行 Latent 逻辑,自动处理 Resume 与 UObject 存活检查 +StartCoroutine(this, () => { + UE.UKismetSystemLibrary.Delay(this, 1.5); + if (!IsValid(this)) return; + this.DoSomethingAfterDelay(); +}); +``` + +### 5.6 热重载(Hot Reload)友好约定 +- 禁止在模块顶层把其他模块的方法赋值缓存到局部变量(如 `const foo = OtherModule.Foo`),否则 `OtherModule` 热重载后缓存的仍是旧函数闭包。 +- 禁止在模块顶层缓存 `UObject` 实例引用(防止关卡切换后造成内存泄漏或野指针)。 + +--- + +## 6. TSTL 编译器配置基线(`tsconfig.json`) + +```json +{ + "$schema": "https://raw.githubusercontent.com/TypeScriptToLua/TypeScriptToLua/master/tsconfig-schema.json", + "compilerOptions": { + "target": "ESNext", + "module": "CommonJS", + "lib": ["ESNext"], + "strict": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "skipLibCheck": true, + "experimentalDecorators": true, + "types": ["@typescript-to-lua/language-extensions", "lua-types/5.4"] + }, + "tstl": { + "luaTarget": "5.4", + "luaLibImport": "require-minimal", + "noImplicitSelf": false, + "noHeader": true, + "sourceMapTraceback": false, + "luaPlugins": [ + { "name": "./dist/plugin/index.js" } + ] + } +} +``` + +> **说明**: +> - `luaTarget`:已对齐 `UnrealLuaDemo` 配置(`LuaVersion=lua-5.4.3`),锁定为 `"5.4"`。 +> - `skipLibCheck`:大型 UE 项目必须设为 `true`,跳过对庞大 UE `.d.ts` 的重复语义校验,显著加快冷启动编译速度。 +> - `luaPlugins`:加载预编译后的 JS 插件(`./dist/plugin/index.js`),避免运行时动态转译插件带来额外启动耗时。 +> - `luaLibImport`:设为 `"require-minimal"`,并由自定义插件进一步审计允许引入的 lualib 符号白名单。 +> - `sourceMapTraceback`:开发期可按需开启便于排查堆栈,发布包(Shipping)务必关闭以减少开销。 + +--- + +## 7. 规范强制落地策略(检查矩阵) + +为确保规范可执行而非一纸空文,按三层防线落实: + +| 规则类别 | `tsconfig` 校验 | ESLint 静态规则(编码期即时提示) | TSTL 自定义插件(编译期强阻断 + 转换) | +| :--- | :---: | :---: | :---: | +| 禁用 `get`/`set` 访问器 | - | ✅ 报错 | ✅ AST 拦截报错 | +| 禁用 `async`/`await`/`Promise` | - | ✅ 报错 | ✅ AST 拦截报错 | +| 禁用 `try`/`catch`/`finally`/`throw` | - | ✅ 报错 | ✅ AST 拦截报错 | +| 禁用 `RegExp`/`Map`/`Set`/`Proxy`/`Symbol` 等 | ✅ `lib` 裁剪 | ✅ 报错 | ✅ AST / lualib 白名单拦截 | +| 禁用普通 `enum`(仅限 `const enum` / `declare enum`) | - | ✅ 报错 | ✅ AST 拦截报错 | +| 禁用运行时装饰器(仅白名单编译期装饰器) | - | ✅ 报错 | ✅ 拦截非白名单装饰器并擦除 | +| UnLua 绑定类单文件单默认导出 + `UnLua.Class()` 转换 | - | ✅ 报错 | ✅ 校验并重写模块导出 | +| UnLua 绑定类禁用 `constructor` 与字段初始化器 | - | ✅ 报错 | ✅ AST 拦截报错 | +| UnLua 绑定类禁止 `new` 实例化 | - | ✅ 报错 | ✅ 类型检查拦截报错 | +| UnLua `super` -> `self.Overridden` / `SuperModule` 转换 | - | - | ✅ 符号解析并精确生成 | +| Delegate 禁止传入箭头函数/匿名函数 | - | ✅ 报错 | ✅ AST 拦截报错 | +| 禁用 `instanceof` 用于 `UObject` | - | ✅ 报错 | ✅ 类型检查拦截报错 | +| `this` / `self` 调用约定匹配 | ✅ `strict` | - | ✅ TSTL 内置校验 | diff --git a/examples/src/Framework/EventBus.ts b/examples/src/Framework/EventBus.ts new file mode 100644 index 0000000..b306f8f --- /dev/null +++ b/examples/src/Framework/EventBus.ts @@ -0,0 +1,44 @@ +/** @noSelfInFile */ + +interface ListenerEntry { + callback: (this: any, ...args: any[]) => void; + owner: unknown; +} + +const listeners: Record = {}; + +export function On( + 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; + } + } +} diff --git a/examples/src/Framework/Log.ts b/examples/src/Framework/Log.ts new file mode 100644 index 0000000..2ca5dcf --- /dev/null +++ b/examples/src/Framework/Log.ts @@ -0,0 +1,16 @@ +/** @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); +} diff --git a/examples/src/Game/LuaDemoActor.ts b/examples/src/Game/LuaDemoActor.ts new file mode 100644 index 0000000..f6fa55e --- /dev/null +++ b/examples/src/Game/LuaDemoActor.ts @@ -0,0 +1,140 @@ +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); + } +} diff --git a/examples/src/Game/LuaSpecialDemoActor.ts b/examples/src/Game/LuaSpecialDemoActor.ts new file mode 100644 index 0000000..a32f83a --- /dev/null +++ b/examples/src/Game/LuaSpecialDemoActor.ts @@ -0,0 +1,17 @@ +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); + } +} diff --git a/examples/tsconfig.json b/examples/tsconfig.json new file mode 100644 index 0000000..ef5784e --- /dev/null +++ b/examples/tsconfig.json @@ -0,0 +1,24 @@ +{ + "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" + } + ] + } +} diff --git a/examples/types/demo.d.ts b/examples/types/demo.d.ts new file mode 100644 index 0000000..76978b3 --- /dev/null +++ b/examples/types/demo.d.ts @@ -0,0 +1,16 @@ +/** + * 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; + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..0a06159 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,221 @@ +{ + "name": "ts2lua-unreal", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ts2lua-unreal", + "version": "0.1.0", + "dependencies": { + "lua-types": "^2.14.1", + "typescript": "6.0.2", + "typescript-to-lua": "^1.37.3" + }, + "devDependencies": { + "@types/node": "^22.0.0" + } + }, + "node_modules/@types/node": { + "version": "22.20.7", + "resolved": "https://registry.npmmirror.com/@types/node/-/node-22.20.7.tgz", + "integrity": "sha512-F/Mcc4pD3YwXQCG50hb8BjB5RmrOere6hge7n2XHf0V8tpkZOVEjwYv9Ql7n0MpMn8Bv7+q12P9w6UHsBm0Sfw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@typescript-to-lua/language-extensions": { + "version": "1.19.0", + "resolved": "https://registry.npmmirror.com/@typescript-to-lua/language-extensions/-/language-extensions-1.19.0.tgz", + "integrity": "sha512-Os5wOKwviTD4LeqI29N0btYOjokSJ97iCf45EOjIABlb5IwNQy7AE/AqZJobRw3ywHH8+KzJUMkEirWPzh2tUA==", + "license": "MIT" + }, + "node_modules/enhanced-resolve": { + "version": "5.8.2", + "resolved": "https://registry.npmmirror.com/enhanced-resolve/-/enhanced-resolve-5.8.2.tgz", + "integrity": "sha512-F27oB3WuHDzvR2DOGNTaYy0D5o0cnrv8TeI482VM4kYgQd/FT9lUQwuNsJ0oOHtBUq7eiW5ytqzp7nBFknL+GA==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmmirror.com/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "license": "BlueOak-1.0.0" + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmmirror.com/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-core-module": { + "version": "2.18.0", + "resolved": "https://registry.npmmirror.com/is-core-module/-/is-core-module-2.18.0.tgz", + "integrity": "sha512-qyax9fgaKOEC4qK8WZn7Q4IcoZC9RC1O1fFxRcRTq/oMMkWT/uXpqpXa12kzWR409zAt1drYN9N9BO26UmBCmw==", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/lua-types": { + "version": "2.14.1", + "resolved": "https://registry.npmmirror.com/lua-types/-/lua-types-2.14.1.tgz", + "integrity": "sha512-+EbnTjF+Bbfp5xmpfT0O9AZgC5J6Oq6jRnZei3HLb0pbWuCRHmdnIVRPIgEpUncWvHq21DHB2qTHhA4xGceHHg==", + "license": "MIT" + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmmirror.com/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "license": "MIT" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmmirror.com/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/resolve": { + "version": "1.22.14", + "resolved": "https://registry.npmmirror.com/resolve/-/resolve-1.22.14.tgz", + "integrity": "sha512-1ZjYvR9sbkiwC5+9QHetqW5HmA2pHRMaoupD01t2HlYnV/vydC2zPwLixhsMieSWVZt0JJRg5LVIk0Ow1D/TrA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.18.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmmirror.com/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tapable": { + "version": "2.3.4", + "resolved": "https://registry.npmmirror.com/tapable/-/tapable-2.3.4.tgz", + "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/typescript": { + "version": "6.0.2", + "resolved": "https://registry.npmmirror.com/typescript/-/typescript-6.0.2.tgz", + "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==", + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-to-lua": { + "version": "1.37.3", + "resolved": "https://registry.npmmirror.com/typescript-to-lua/-/typescript-to-lua-1.37.3.tgz", + "integrity": "sha512-w0V2ysaBMfoJq1rlDwl+gv+EmSvaAZtMgSl3xb0uj63wR2m5FezNHk+wHJeL+2JuRilOJHa5GB6c+dooCKme1g==", + "license": "MIT", + "dependencies": { + "@typescript-to-lua/language-extensions": "1.19.0", + "enhanced-resolve": "5.8.2", + "picomatch": "^2.3.1", + "resolve": "^1.15.1", + "source-map": "^0.7.3" + }, + "bin": { + "tstl": "dist/tstl.js" + }, + "engines": { + "node": ">=16.10.0" + }, + "peerDependencies": { + "typescript": "6.0.2" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..7ee0a76 --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "ts2lua-unreal", + "version": "0.1.0", + "description": "TypeScript to Lua toolchain and compiler plugin tailored for Unreal Engine + UnLua", + "private": true, + "main": "dist/plugin/index.js", + "types": "dist/plugin/index.d.ts", + "scripts": { + "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" + }, + "dependencies": { + "lua-types": "^2.14.1", + "typescript": "6.0.2", + "typescript-to-lua": "^1.37.3" + }, + "devDependencies": { + "@types/node": "^22.0.0" + } +} diff --git a/src/plugin/diagnostics.ts b/src/plugin/diagnostics.ts new file mode 100644 index 0000000..f5890f0 --- /dev/null +++ b/src/plugin/diagnostics.ts @@ -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", + }; +} diff --git a/src/plugin/index.ts b/src/plugin/index.ts new file mode 100644 index 0000000..136325d --- /dev/null +++ b/src/plugin/index.ts @@ -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"; diff --git a/src/plugin/type-utils.ts b/src/plugin/type-utils.ts new file mode 100644 index 0000000..e5f57dc --- /dev/null +++ b/src/plugin/type-utils.ts @@ -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(["unlua"]); + +/** + * 缓存 Type -> 是否为 UE.UObject 或其派生类,避免大型项目重复递归遍历继承链。 + */ +const uObjectTypeCache = new WeakMap(); + +/** + * 缓存 Type -> 是否为 @unlua 绑定类。 + */ +const unLuaClassTypeCache = new WeakMap(); + +/** + * 纯 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; +} diff --git a/src/plugin/unlua-transform.ts b/src/plugin/unlua-transform.ts new file mode 100644 index 0000000..88228e3 --- /dev/null +++ b/src/plugin/unlua-transform.ts @@ -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[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 `。 + */ +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(); + +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 父类 -> `.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); +} diff --git a/src/plugin/validators.ts b/src/plugin/validators.ts new file mode 100644 index 0000000..c26d6b9 --- /dev/null +++ b/src/plugin/validators.ts @@ -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([ + "Map", + "Set", + "WeakMap", + "WeakSet", + "Proxy", + "Function", +]); + +const FORBIDDEN_OBJECT_METHODS = new Set([ + "defineProperty", + "defineProperties", + "setPrototypeOf", + "create", + "freeze", +]); + +const DELEGATE_TYPE_NAMES = new Set([ + "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 / 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); + }, + }; +} diff --git a/test/plugin.test.mjs b/test/plugin.test.mjs new file mode 100644 index 0000000..e507484 --- /dev/null +++ b/test/plugin.test.mjs @@ -0,0 +1,446 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import * as fs from "node:fs"; +import * as path from "node:path"; +import * as ts from "typescript"; +import * as tstl from "typescript-to-lua"; +import { createRequire } from "node:module"; + +const require = createRequire(import.meta.url); +const projectRoot = path.resolve(import.meta.dirname, ".."); +const unluaTypesPath = path.join(projectRoot, "types", "unlua.d.ts"); +const unluaTypesContent = fs.readFileSync(unluaTypesPath, "utf8"); +const pluginPath = path.join(projectRoot, "dist", "plugin", "index.js"); +const { UnLuaDiagnosticCode } = require(pluginPath); + +/** + * 在内存中编译一组虚拟 TS 文件并启用 UnLua 插件。 + */ +function transpileWithUnLua(files) { + const virtualFiles = { + "unlua.d.ts": unluaTypesContent, + ...files, + }; + + return tstl.transpileVirtualProject(virtualFiles, { + target: ts.ScriptTarget.ESNext, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + lib: ["lib.esnext.d.ts"], + strict: true, + skipLibCheck: true, + experimentalDecorators: true, + rootDir: ".", + luaTarget: tstl.LuaTarget.Lua54, + luaLibImport: tstl.LuaLibImportKind.RequireMinimal, + noImplicitSelf: false, + noHeader: true, + luaPlugins: [{ name: pluginPath }], + }); +} + +function getUnLuaErrors(result) { + return result.diagnostics.filter((d) => d.source === "ts2lua-unlua"); +} + +function getLuaCode(result, luaPath) { + const normalized = luaPath.replace(/\\/g, "/"); + const found = result.transpiledFiles.find((f) => { + const out = (f.outPath || "").replace(/\\/g, "/"); + return out === normalized || out.endsWith("/" + normalized); + }); + assert.ok(found, `Expected emitted file '${luaPath}', got: ${result.transpiledFiles.map((f) => f.outPath).join(", ")}`); + return found.lua; +} + +// ============================================================ +// 1. 正常转译(Positive Cases) +// ============================================================ + +test("@unlua class extending UE native class compiles to UnLua.Class() + self.Overridden + return ClassName", () => { + const result = transpileWithUnLua({ + "Game/MyActor.ts": ` + @unlua + export default class MyActor extends UE.AActor { + private hp!: number; + static readonly MAX_HP = 100; + + ReceiveBeginPlay(): void { + super.ReceiveBeginPlay(); + this.hp = MyActor.MAX_HP; + } + + static Helper(a: number, b = 10): number { + return a + b; + } + } + `, + }); + + assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2)); + const lua = getLuaCode(result, "Game/MyActor.lua"); + + assert.match(lua, /local MyActor = UnLua\.Class\(\)/); + assert.match(lua, /function MyActor\.ReceiveBeginPlay\(self\)/); + assert.match(lua, /self\.Overridden\.ReceiveBeginPlay\(self\)/); + assert.match(lua, /MyActor\.MAX_HP = 100/); + assert.match(lua, /function MyActor\.Helper\(a, b\)/); + assert.match(lua, /if b == nil then/); + assert.match(lua, /return MyActor\s*$/); + assert.doesNotMatch(lua, /____exports/); + assert.doesNotMatch(lua, /__TS__Class/); + assert.doesNotMatch(lua, /__TS__Decorate/); +}); + +test("@unlua subclass extending another @unlua TS class compiles to UnLua.Class('Game.BaseActor') + BaseActor.Method(self)", () => { + const result = transpileWithUnLua({ + "Game/BaseActor.ts": ` + @unlua + export default class BaseActor extends UE.AActor { + ReceiveBeginPlay(): void { + super.ReceiveBeginPlay(); + } + DoWork(val: number): void { + this.ReceiveTick(val); + } + } + `, + "Game/SubActor.ts": ` + import BaseActor from "./BaseActor"; + + @unlua + export default class SubActor extends BaseActor { + ReceiveBeginPlay(): void { + super.ReceiveBeginPlay(); + super.DoWork(42); + } + } + `, + }); + + assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2)); + const lua = getLuaCode(result, "Game/SubActor.lua"); + + assert.match(lua, /local BaseActor = require\("Game\.BaseActor"\)/); + assert.doesNotMatch(lua, /\.default\b/); + assert.match(lua, /local SubActor = UnLua\.Class\("Game\.BaseActor"\)/); + assert.match(lua, /BaseActor\.ReceiveBeginPlay\(self\)/); + assert.match(lua, /BaseActor\.DoWork\(self, 42\)/); + assert.match(lua, /return SubActor\s*$/); +}); + +test("@unlua supports explicit base module path and standalone blueprint classes without extends", () => { + const result = transpileWithUnLua({ + "UI/WBP_Main.ts": ` + export interface MainUIData { title: string; } + + @unlua("UI.WBP_Base") + export default class WBP_Main { + Construct(): void { + const data: MainUIData = { title: "hello" }; + void data; + } + } + `, + }); + + assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2)); + const lua = getLuaCode(result, "UI/WBP_Main.lua"); + + assert.match(lua, /local WBP_Main = UnLua\.Class\("UI\.WBP_Base"\)/); + assert.match(lua, /return WBP_Main\s*$/); +}); + +test("const enum, pure TS class, Delegate member method binding, and @unlua-allow-try are allowed", () => { + const result = transpileWithUnLua({ + "Logic/State.ts": ` + const enum EState { + Idle = 0, + Run = 1, + } + + export class PureCounter { + private count = 0; + constructor(initial: number) { + this.count = initial; + } + Inc(): number { + this.count += EState.Run; + return this.count; + } + SafeCall(): boolean { + /** @unlua-allow-try */ + try { + return this.count > 0; + } catch { + return false; + } + } + } + `, + "UI/ButtonWidget.ts": ` + @unlua + export default class ButtonWidget extends UE.UUserWidget { + OnClicked!: UE.FMulticastScriptDelegate<() => void>; + + Construct(): void { + this.OnClicked.Add(this, this.HandleClick); + } + + Destruct(): void { + this.OnClicked.Remove(this, this.HandleClick); + } + + HandleClick(): void { + if (this.IsA(UE.UUserWidget.StaticClass())) { + return; + } + } + } + `, + }); + + assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2)); +}); + +// ============================================================ +// 2. 禁用语言特性拦截(Negative Cases: 90001 - 90016) +// ============================================================ + +test("forbids get/set accessors in classes and object literals", () => { + const result = transpileWithUnLua({ + "bad.ts": ` + class Foo { + private _x = 0; + get x(): number { return this._x; } + set x(v: number) { this._x = v; } + } + export const o = { + get a() { return 1; }, + }; + export { Foo }; + `, + }); + + const codes = getUnLuaErrors(result).map((d) => d.code); + assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenAccessor)); + assert.ok(codes.filter((c) => c === UnLuaDiagnosticCode.ForbiddenAccessor).length >= 3); +}); + +test("forbids async/await and Promise", () => { + const result = transpileWithUnLua({ + "bad.ts": ` + export async function fetchSomething(): Promise { + const p = new Promise((resolve) => resolve(1)); + const v = await p; + const v2 = await Promise.resolve(2); + return v + v2; + } + `, + }); + + const codes = getUnLuaErrors(result).map((d) => d.code); + assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenAsyncAwait)); + assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenPromise)); +}); + +test("forbids try/catch/finally and throw without @unlua-allow-try", () => { + const result = transpileWithUnLua({ + "bad.ts": ` + export function risky(flag: boolean): void { + try { + if (flag) { + throw "boom"; + } + } catch (e) { + void e; + } + } + `, + }); + + const codes = getUnLuaErrors(result).map((d) => d.code); + assert.ok(codes.filter((c) => c === UnLuaDiagnosticCode.ForbiddenTryCatchThrow).length >= 2); +}); + +test("forbids non-whitelisted runtime decorators", () => { + const result = transpileWithUnLua({ + "bad.ts": ` + function myDec(target: any) { return target; } + + @myDec + export class Foo {} + `, + }); + + const codes = getUnLuaErrors(result).map((d) => d.code); + assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenDecorator)); +}); + +test("forbids RegExp, Map, Set, Proxy, Symbol, Object.defineProperty, Reflect, generator, for..in, runtime enum, eval, arguments", () => { + const result = transpileWithUnLua({ + "bad.ts": ` + export enum EBadEnum { A = 0, B = 1 } + + export function* gen() { + yield 1; + } + + export function badBuiltins(obj: Record) { + const r1 = /abc/; + const r2 = new RegExp("abc"); + const m = new Map(); + const s = new Set(); + const p = new Proxy(obj, {}); + const sym = Symbol("x"); + Object.defineProperty(obj, "k", { value: 1 }); + Reflect.get(obj, "k"); + eval("1 + 1"); + for (const k in obj) { + void k; + } + const a = arguments; + return [r1, r2, m, s, p, sym, a]; + } + `, + }); + + const codes = new Set(getUnLuaErrors(result).map((d) => d.code)); + assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenRuntimeEnum)); + assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenGenerator)); + assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenRegExp)); + assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenBuiltinType)); + assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenForIn)); + assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenDynamicEvalOrWith)); + assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenArguments)); +}); + +test("forbids delete on array/UObject, instanceof UObject, and spreading UObject", () => { + const result = transpileWithUnLua({ + "bad.ts": ` + export function check(arr: number[], actor: UE.AActor): boolean { + delete arr[0]; + delete (actor as any).SomeProp; + const copy = { ...actor }; + void copy; + return actor instanceof UE.AActor; + } + `, + }); + + const codes = new Set(getUnLuaErrors(result).map((d) => d.code)); + assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenDeleteOnArrayOrUObject)); + assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenInstanceOfUObject)); + assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenUObjectSpread)); +}); + +// ============================================================ +// 3. @unlua 绑定类专项拦截(Negative Cases: 90101 - 90110) +// ============================================================ + +test("forbids missing @unlua decorator on class extending UE.UObject (fail-safe)", () => { + const result = transpileWithUnLua({ + "Game/ForgotDecorator.ts": ` + export default class ForgotDecorator extends UE.AActor { + ReceiveBeginPlay(): void {} + } + `, + }); + + const codes = getUnLuaErrors(result).map((d) => d.code); + assert.ok(codes.includes(UnLuaDiagnosticCode.MissingUnLuaDecorator)); +}); + +test("forbids constructor, field initializer, arrow method, and non-default export in @unlua class", () => { + const result = transpileWithUnLua({ + "Game/BadActor.ts": ` + export const EXTRA = 1; + + @unlua + export class BadActor extends UE.AActor { + private hp = 100; + OnClick = () => {}; + constructor() { + super(); + } + } + `, + }); + + const codes = new Set(getUnLuaErrors(result).map((d) => d.code)); + assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaClassMustBeDefaultExport)); + assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaFileExtraRuntimeExport)); + assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaClassForbiddenConstructor)); + assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaClassForbiddenPropertyInitializer)); +}); + +test("forbids 'new MyUnLuaActor()' instantiation", () => { + const result = transpileWithUnLua({ + "Game/MyActor.ts": ` + @unlua + export default class MyActor extends UE.AActor {} + `, + "Game/Spawner.ts": ` + import MyActor from "./MyActor"; + export function spawnBad() { + return new MyActor(); + } + `, + }); + + const codes = getUnLuaErrors(result).map((d) => d.code); + assert.ok(codes.includes(UnLuaDiagnosticCode.UnLuaClassForbiddenNew)); +}); + +test("forbids inline arrow/function expression in UE Delegate Add/Bind", () => { + const result = transpileWithUnLua({ + "UI/BadWidget.ts": ` + @unlua + export default class BadWidget extends UE.UUserWidget { + OnClicked!: UE.FMulticastScriptDelegate<() => void>; + Construct(): void { + this.OnClicked.Add(this, () => { + this.Destruct(); + }); + } + } + `, + }); + + const codes = getUnLuaErrors(result).map((d) => d.code); + assert.ok(codes.includes(UnLuaDiagnosticCode.UnLuaDelegateForbiddenInlineFunction)); +}); + +test("forbids multiple @unlua classes in one file, invalid @unlua args, and direct super property read", () => { + const result = transpileWithUnLua({ + "Game/Multi.ts": ` + @unlua(123 as any) + export default class ActorA extends UE.AActor { + ReceiveBeginPlay(): void { + const x = super.GetName; + void x; + } + } + + @unlua + class ActorB extends UE.AActor {} + void ActorB; + `, + }); + + const codes = new Set(getUnLuaErrors(result).map((d) => d.code)); + assert.ok(codes.has(UnLuaDiagnosticCode.InvalidUnLuaDecoratorArgs)); + assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaMultipleClassesInFile)); + assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaForbiddenSuperUsage)); +}); + +// ============================================================ +// 4. 端到端示例工程编译验证 +// ============================================================ + +test("examples/tsconfig.json transpiles cleanly with zero diagnostics", () => { + const exampleConfigPath = path.join(projectRoot, "examples", "tsconfig.json"); + const result = tstl.transpileProject(exampleConfigPath); + const errors = result.diagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error); + assert.equal(errors.length, 0, errors.map((e) => ts.flattenDiagnosticMessageText(e.messageText, "\n")).join("\n")); +}); diff --git a/tsconfig.base.json b/tsconfig.base.json new file mode 100644 index 0000000..86305b2 --- /dev/null +++ b/tsconfig.base.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://raw.githubusercontent.com/TypeScriptToLua/TypeScriptToLua/master/tsconfig-schema.json", + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ESNext"], + "strict": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "skipLibCheck": true, + "experimentalDecorators": true, + "types": ["@typescript-to-lua/language-extensions", "lua-types/5.4"] + }, + "tstl": { + "luaTarget": "5.4", + "luaLibImport": "require-minimal", + "noImplicitSelf": false, + "noHeader": true, + "sourceMapTraceback": false, + "luaPlugins": [ + { + "name": "./dist/plugin/index.js" + } + ] + } +} diff --git a/tsconfig.plugin.json b/tsconfig.plugin.json new file mode 100644 index 0000000..5766080 --- /dev/null +++ b/tsconfig.plugin.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "CommonJS", + "ignoreDeprecations": "6.0", + "lib": ["ES2022"], + "types": ["node"], + "rootDir": "src", + "outDir": "dist", + "declaration": true, + "sourceMap": true, + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true + }, + "include": ["src/**/*.ts"] +} diff --git a/types/unlua.d.ts b/types/unlua.d.ts new file mode 100644 index 0000000..2fa92f9 --- /dev/null +++ b/types/unlua.d.ts @@ -0,0 +1,207 @@ +/** + * UnLua + Unreal Engine 基础编译期类型声明。 + * 实际 UE 项目可在此基础上叠加由 UnLua / UHT 自动导出的完整 UE .d.ts。 + */ + +/** + * 全局编译期装饰器:标记一个类为 UnLua 绑定类(编译后完全擦除,无运行时代码)。 + * - `@unlua`:自动生成 `UnLua.Class()`(继承 UE 原生类或无父类)或 `UnLua.Class("Path.To.Base")`(继承另一个 `@unlua` TS 类)。 + * - `@unlua("Path.To.Base")`:显式指定 UnLua 父类模块名。 + */ +declare function unlua(target: abstract new (...args: any[]) => any): void; +declare function unlua(baseModuleName: string): (target: abstract new (...args: any[]) => any) => void; + +/** + * UnLua 全局模块接口 + */ +declare namespace UnLua { + /** @noSelf */ + function Class(superClassName?: string): any; + /** @noSelf */ + function Ref(obj: UE.UObject): any; + /** @noSelf */ + function Unref(obj: UE.UObject): void; + /** @noSelf */ + function HotReload(): void; +} + +/** + * UE 核心反射与容器基础声明(精简基线,供插件校验与示例使用) + */ +declare namespace UE { + class UObject { + GetName(): string; + GetClass(): UClass; + GetWorld(): UWorld | undefined; + IsValid(): boolean; + IsA(someBase: UClass): boolean; + Initialize(Initializer?: unknown): void; + } + + class UClass extends UObject {} + + class UWorld extends UObject { + SpawnActor( + actorClass: UClass, + transform?: FTransform, + collisionHandling?: number, + owner?: AActor, + instigator?: APawn, + moduleName?: string + ): T | undefined; + } + + class UActorComponent extends UObject { + ReceiveBeginPlay(): void; + ReceiveTick(DeltaSeconds: number): void; + ReceiveEndPlay(EndPlayReason: number): void; + } + + class AActor extends UObject { + ReceiveBeginPlay(): void; + ReceiveTick(DeltaSeconds: number): void; + ReceiveEndPlay(EndPlayReason: number): void; + K2_GetActorLocation(): FVector; + K2_SetActorLocation( + NewLocation: FVector, + bSweep?: boolean, + SweepHitResult?: unknown, + bTeleport?: boolean + ): boolean; + K2_DestroyActor(): void; + static StaticClass(this: void): UClass; + } + + class APawn extends AActor { + static StaticClass(this: void): UClass; + } + + class ACharacter extends APawn { + 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 void = () => void> { + Add(target: UObject, callback: TCallback): void; + Remove(target: UObject, callback: TCallback): void; + Clear(): void; + Broadcast(...args: Parameters): void; + } + + interface FScriptDelegate void = () => void> { + Bind(target: UObject, callback: TCallback): void; + Unbind(): void; + } + + interface TArray { + Length(): number; + Num(): number; + Add(item: T): number; + Get(index: number): T; + Set(index: number, item: T): void; + Remove(index: number): void; + Clear(): void; + Contains(item: T): boolean; + ToTable(): T[]; + } + function TArray(this: void, elementType: any): TArray; + + interface TMap { + Length(): number; + Num(): number; + Add(key: K, value: V): void; + Find(key: K): V | undefined; + Remove(key: K): boolean; + Contains(key: K): boolean; + Clear(): void; + Keys(): TArray; + Values(): TArray; + ToTable(): Record; + } + function TMap(this: void, keyType: any, valueType: any): TMap; + + interface TSet { + Length(): number; + Num(): number; + Add(item: T): void; + Remove(item: T): boolean; + Contains(item: T): boolean; + Clear(): void; + ToTable(): T[]; + } + function TSet(this: void, elementType: any): TSet; + + /** @noSelf */ + namespace UKismetSystemLibrary { + function PrintString( + WorldContextObject: UObject | undefined, + InString?: string, + bPrintToScreen?: boolean, + bPrintToLog?: boolean, + TextColor?: FLinearColor, + Duration?: number + ): void; + function IsValid(Object: UObject | undefined): boolean; + function Delay(WorldContextObject: UObject, Duration: number): void; + } + + /** @noSelf */ + function NewObject( + outerClass: UClass, + outer?: UObject, + name?: string, + moduleName?: string + ): T; +}