diff --git a/CHANGELOG.md b/CHANGELOG.md index b69f61a..6d28b47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,24 @@ All notable changes to `ts2lua-unreal` will be documented in this file. The format is based on [Semantic Versioning](https://semver.org/). +## [0.3.0] - 2026-11-30 + +### Added +- **自定义模块化与单文件运行时热更系统**: + - 新增基础运行时 [runtime/Lib/Module.lua](runtime/Lib/Module.lua)(定义 `_G.__MODULE__`,支持隔离 `_ENV`、单文件 `Reimport`/`ReimportSafely`、下游局部 upvalue `UpdateImports()` 刷新、循环依赖等待回填、Barrel 再导出级联、`OnImport`/`OnReimport`/`OnDepModuleReimported` 生命周期钩子、自定义 File/Chunk/Pattern Loader,并默认只读复用 `package.searchers` 无入侵适配 UE/UnLua 与离线 Lua 5.4)。 + - 新增热更类运行时 [runtime/Lib/Class.lua](runtime/Lib/Class.lua)(定义扁平全局函数 `_G.__TS__DefineClass`,零表查询开销,复用 `cls` 与 `cls.prototype` 并在热更时清理已删除方法,100% 兼容 TSTL `lualib_bundle` 的 `__TS__New`/`__TS__ClassExtends`/`__TS__InstanceOf`)。 + - 新增全局类型声明 [types/module.d.ts](types/module.d.ts)(通过 [types/unlua.d.ts](types/unlua.d.ts) 自动引用,无需业务修改 `tsconfig.json`)。 + - 新增编译器转换模块 [src/plugin/module-transform.ts](src/plugin/module-transform.ts): + - 项目内 TS `import` / `export ... from` 自动转换为 `__MODULE__.Import("...", __module)` 与 `__module.UpdateImports()`; + - 常规 TS 模块导出写入 `__module.env`(`local ____exports = __module.env`),实时同步 `export let`; + - 顶层纯 TS 类编译为 `__TS__DefineClass("Name", __module)` 并按需剔除 `lualib_bundle.__TS__Class` 依赖; + - 支持 `/** @module_data */` 顶层状态跨热更保留(带 `__has__` 哨兵,兼顾 `nil` 值与热更新增变量初值); + - 原生插件与 UnLua 内置脚本(如 `const cjson = require("cjson")`、`require("UnLua.*")`)保持原生 `require` 且自动免除 TSTL 100000 路径解析报错; + - 通过 `beforeEmit` 自动产出 `Lib/Module.lua` 与 `Lib/Class.lua`。 + - 插件升级为工厂导出,支持配置项:`moduleSystem?: "hot-reload" | "standard"`(默认 `"hot-reload"`)、`emitRuntime?: boolean`(默认 `true`)、`runtimeDir?: string`(默认 `"Lib"`)。 + - 新增诊断码 `90201 InvalidModuleDataUsage` 与 `90202 ForbiddenExportEqualsInHotReload`。 + - 新增 [test/hot-reload.test.mjs](test/hot-reload.test.mjs) 端到端测试套件(含真实 Lua 5.4 运行时热更、类继承、`@module_data`、Barrel 级联、循环依赖与异常边界测试)。 + ## [0.2.2] - 2026-11-29 ### Fixed diff --git a/README.md b/README.md index 8d759eb..10a2a4a 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ ## 特性概览 +- **自定义模块化与单文件运行时热更(`v0.3.0+`)**:内置 `Lib/Module.lua`(`_G.__MODULE__`)与 `Lib/Class.lua`(扁平全局函数 `_G.__TS__DefineClass`,零表查询开销)。项目内 TS 模块统一编译为 `__MODULE__.Import("...", __module)`、独立 `_ENV` 原地更新、下游 `UpdateImports()` 自动刷新、Barrel 再导出级联、`/** @module_data */` 跨热更状态保留及纯 TS 类原型复用;UnLua 内置脚本与外部原生 Lua/C 插件(如 `const cjson = require("cjson")`)保持原生 `require` 不变,零入侵 UnLua。 - **原生 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, ...)` diff --git a/bin/ts2lua-unreal.js b/bin/ts2lua-unreal.js index 73c151a..6b5cefb 100755 --- a/bin/ts2lua-unreal.js +++ b/bin/ts2lua-unreal.js @@ -27,6 +27,11 @@ function printInfo() { packageRoot: pkgRoot, tsconfigBase: path.join(pkgRoot, "tsconfig.base.json"), unluaTypes: path.join(pkgRoot, "types", "unlua.d.ts"), + moduleTypes: path.join(pkgRoot, "types", "module.d.ts"), + runtime: { + module: path.join(pkgRoot, "runtime", "Lib", "Module.lua"), + class: path.join(pkgRoot, "runtime", "Lib", "Class.lua"), + }, docs: { integrationGuide: path.join(pkgRoot, "docs", "integration-guide.md"), spec: path.join(pkgRoot, "docs", "ts-unlua-spec.md"), diff --git a/docs/ai-rules-template.md b/docs/ai-rules-template.md index 673be8c..ca205b9 100644 --- a/docs/ai-rules-template.md +++ b/docs/ai-rules-template.md @@ -37,9 +37,12 @@ - **禁用对数组或 `UObject` 使用 `delete`** -> 数组删除用 `table.remove` / `splice`。 - **禁用对 `UObject` 使用 `instanceof` 或对象展开 `{ ...obj }`** -> 类型判断用 `obj.IsA(UE.ClassName.StaticClass())`。 -## 4. 纯逻辑模块、容器与性能约定 +## 4. 自定义模块化、纯逻辑模块、容器与性能约定 +- 项目内 TS 模块默认编译为 `__MODULE__.Import` 单文件热更体系(基础库位于 `/Lib/Module.lua` 与 `/Lib/Class.lua`,启动时用原生 `require("Lib.Module"); require("Lib.Class")` 加载)。 +- UnLua 自身脚本与外部 Lua/C 原生插件在 TS 中继续使用原生 `require("cjson")` / `require("UnLua.*")`,不纳入 `__MODULE__` 管理。 +- 需跨单文件热更保留的模块顶层状态必须显式标注 `/** @module_data */`(仅允许模块顶层独立变量,禁止解构);模块生命周期回调使用 `__module.OnImport` / `__module.OnReimport` / `__module.OnDepModuleReimported`。 - 纯函数工具模块文件顶部加 `/** @noSelfInFile */`,编译为点号调用(如 `Log.Info(...)`)。 - 严格区分 TS 数组 `T[]`(0-based,TSTL 自动转 1-based)与 `UE.TArray`(UnLua `Get(i)`/`Set(i, v)` 为 1-based)。 - 跨帧持有的 `UObject` 使用前必须通过 `UE.UKismetSystemLibrary.IsValid(obj)` 判空。 - `ReceiveTick` 等每帧热路径禁止 `.map().filter()` 链式分配与高频临时 `FVector`/`FRotator` 分配。 -- 热重载友好:禁止在模块顶层缓存其他模块的方法引用或 `UObject` 实例引用。 +- 热重载友好:禁止在模块顶层手工赋值缓存其他模块的方法引用(如 `const fn = OtherMod.Foo`,应使用标准 ES `import`)或缓存 `UObject` 实例引用。 diff --git a/docs/integration-guide.md b/docs/integration-guide.md index dfca416..594d7f8 100644 --- a/docs/integration-guide.md +++ b/docs/integration-guide.md @@ -156,7 +156,54 @@ export default class WBP_TempPopup { } ``` -### 3.4 纯逻辑工具模块(非 `UObject`) +### 3.4 自定义模块化与单文件热更(`v0.3.0+` 默认启用) + +`ts2lua-unreal` 默认启用 `moduleSystem: "hot-reload"`,会在编译输出目录自动生成 `Lib/Module.lua` 与 `Lib/Class.lua`(零入侵 UnLua,不劫持 `_G.require`)。 + +**启动引导(`Boot.lua` 或 UE 启动入口)**: +```lua +-- 启动期以原生 require 加载基础库(不热更) +require("Lib.Module") +require("Lib.Class") +-- 进入业务 TS 模块体系 +__MODULE__.Import("Main").Startup() +``` + +**`require` 与 `__MODULE__.Import` 边界**: +- UnLua 自身代码、外部原生 Lua/C 插件:TS 中直接写 `const cjson = require("cjson")` / `require("UnLua.HotReload")`,编译后原样保留 `require(...)`(且不会触发 TSTL 100000 报错); +- 项目内业务/框架 TS 模块之间的 `import` / `export ... from`:自动编译为 `__MODULE__.Import("...", __module)` 并生成 `__module.UpdateImports()`; +- 推荐在 UE C++ 层仅保留少量薄桥接类,通过回调分发至纯 TS 模块与纯 TS 类(`Lib/Class.lua` 的 `__TS__DefineClass` 自动复用类原型表),实现全业务无痛单文件热更。 + +**跨热更保留状态(`@module_data`)与生命周期钩子**: +```ts +/** @noSelfInFile */ + +/** @module_data */ +let counter = 0; + +/** @module_data */ +export let activeTag = "init"; + +export function Inc(): number { + counter = counter + 1; + return counter; +} + +__module.OnImport = () => { /* 仅首次加载触发 */ }; +__module.OnReimport = () => { /* 仅热更后触发 */ }; +__module.OnDepModuleReimported = (depName: string) => { /* 依赖模块热更后触发 */ }; +``` + +**运行时触发单文件热更**: +```ts +const [ok, err] = __MODULE__.ReimportSafely("Framework.Counter"); +// 或按模块路径:__MODULE__.ReimportSafely("@Framework/Counter.lua"); +``` + +> 如需切回传统 TSTL `require` 产物或关闭运行时自动输出,可在 `tsconfig.json` 的 `tstl.luaPlugins` 中传入: +> `{ "name": "ts2lua-unreal", "moduleSystem": "standard" }` 或 `{ "name": "ts2lua-unreal", "emitRuntime": false, "runtimeDir": "Lib" }`。 + +### 3.5 纯逻辑工具模块(非 `UObject`) 文件顶部加 `/** @noSelfInFile */`,编译为点号调用模块(如 `Log.Info(...)`、`EventBus.On(...)`): ```ts @@ -212,6 +259,8 @@ export function Info(fmt: string, ...args: unknown[]): void { | `90108` | `InvalidUnLuaDecoratorArgs` | `@unlua(...)` 传参非法 | 仅支持 `@unlua` 或 `@unlua("Path.To.Base")` | | `90109` | `UnLuaMultipleClassesInFile` | 单文件包含多个 `@unlua` 类 | 拆分为单文件单类 | | `90110` | `UnLuaForbiddenSuperUsage` | `@unlua` 类中调用 `super()` 或直接访问 `super.prop` | 仅支持 `super.Method(...)`;父类属性/组件直接用 `this.prop` | +| `90201` | `InvalidModuleDataUsage` | `@module_data` 标注在非顶层变量或解构声明上 | 仅标注在模块顶层的独立 `let` / `const` 标识符声明上 | +| `90202` | `ForbiddenExportEqualsInHotReload` | `hot-reload` 模式下使用了 CommonJS `export =` | 改用 ES `export` 或 `export default` | --- diff --git a/docs/ts-unlua-spec.md b/docs/ts-unlua-spec.md index 66c06b6..ea85f81 100644 --- a/docs/ts-unlua-spec.md +++ b/docs/ts-unlua-spec.md @@ -269,9 +269,12 @@ StartCoroutine(this, () => { }); ``` -### 5.6 热重载(Hot Reload)友好约定 -- 禁止在模块顶层把其他模块的方法赋值缓存到局部变量(如 `const foo = OtherModule.Foo`),否则 `OtherModule` 热重载后缓存的仍是旧函数闭包。 -- 禁止在模块顶层缓存 `UObject` 实例引用(防止关卡切换后造成内存泄漏或野指针)。 +### 5.6 自定义模块化与单文件热重载(Hot Reload)规范 +- **基础运行时**:`Lib/Module.lua`(`_G.__MODULE__`)与 `Lib/Class.lua`(扁平全局函数 `_G.__TS__DefineClass`)由编译插件自动输出,启动时通过原生 `require("Lib.Module")` / `require("Lib.Class")` 初始化,不劫持 `_G.require`、不入侵 UnLua 自身脚本。 +- **依赖导入边界**:项目内 TS 模块之间一律使用标准 ES `import`(编译为 `__MODULE__.Import("...", __module)` + `__module.UpdateImports()`);外部 Lua/C 插件与 UnLua 内置模块继续使用原生 `require("cjson")` / `require("UnLua.*")`。 +- **模块状态保留**:需要跨单文件热更保留的顶层变量必须标注 `/** @module_data */`(仅支持模块顶层独立标识符,禁用解构);未标注的顶层变量在热更时重置。 +- **类原型复用**:顶层纯 TS 类自动通过扁平全局函数 `__TS__DefineClass("Name", __module)` 定义,热更时原地复用 `cls` 与 `cls.prototype` 并清理已删除方法,保证既有实例与子类继承链无缝生效。 +- **禁忌**:禁止在模块顶层手工赋值缓存其他模块的方法引用(如 `const foo = OtherModule.Foo`),否则无法被编译器登记到 `UpdateImports()`;禁止在模块顶层缓存 `UObject` 实例引用。 --- diff --git a/package.json b/package.json index 8ec9154..d5a2976 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ts2lua-unreal", - "version": "0.2.2", + "version": "0.3.0", "description": "TypeScript to Lua toolchain and compiler plugin tailored for Unreal Engine + UnLua", "main": "dist/plugin/index.js", "types": "dist/plugin/index.d.ts", @@ -14,6 +14,9 @@ }, "./tsconfig.base.json": "./tsconfig.base.json", "./types/unlua.d.ts": "./types/unlua.d.ts", + "./types/module.d.ts": "./types/module.d.ts", + "./runtime/Lib/Module.lua": "./runtime/Lib/Module.lua", + "./runtime/Lib/Class.lua": "./runtime/Lib/Class.lua", "./docs/ts-unlua-spec.md": "./docs/ts-unlua-spec.md", "./docs/integration-guide.md": "./docs/integration-guide.md", "./docs/ai-rules-template.md": "./docs/ai-rules-template.md", @@ -23,6 +26,7 @@ "files": [ "bin/", "dist/", + "runtime/", "types/", "docs/", "tsconfig.base.json", diff --git a/runtime/Lib/Class.lua b/runtime/Lib/Class.lua new file mode 100644 index 0000000..649840f --- /dev/null +++ b/runtime/Lib/Class.lua @@ -0,0 +1,53 @@ +-- 热更友好的纯 TS 类定义运行时(扁平全局函数,零表查询开销,完全兼容 TSTL lualib_bundle) + +local pairs = pairs +local type = type + +local allClassTbl = {} + +local function __TS__DefineClass(name, mod) + local modname = mod and mod.name or "" + local fullName = modname .. ":" .. name + local cls = allClassTbl[fullName] + if cls then + -- 热更重载时清理原型上已删除的旧方法,保持既有实例与子类继承链的原型表引用不变 + local modSys = _G.__MODULE__ + if modSys and modSys.IsReimporting and modSys.IsReimporting(mod) then + local proto = cls.prototype + if proto then + for k, v in pairs(proto) do + if k ~= "__index" and k ~= "constructor" and type(v) == "function" then + proto[k] = nil + end + end + end + end + cls.name = name + return cls + end + + cls = { + __classdefine__ = true, + __fullname__ = fullName, + name = name, + prototype = {}, + } + cls.prototype.__index = cls.prototype + cls.prototype.constructor = cls + + allClassTbl[fullName] = cls + return cls +end + +_G.__TS__DefineClass = __TS__DefineClass + +return { + DefineClass = __TS__DefineClass, + allClassTbl = allClassTbl, + GetClass = function(fullName) + return allClassTbl[fullName] + end, + AllClasses = function() + return allClassTbl + end, +} diff --git a/runtime/Lib/Module.lua b/runtime/Lib/Module.lua new file mode 100644 index 0000000..13bebd9 --- /dev/null +++ b/runtime/Lib/Module.lua @@ -0,0 +1,649 @@ +local __MODULE__ = {} + +__MODULE__.loadedModuleTbl = {} +__MODULE__.loadedPathToModuleTbl = {} +__MODULE__.loadingModuleTbl = {} +__MODULE__.moduleWaitingForLoadingModuleTbl = {} +__MODULE__.loadedModuleNameList = {} +__MODULE__.importingStack = {} +__MODULE__.systemMeta = {} + +local loadedModuleTbl = __MODULE__.loadedModuleTbl +local loadedPathToModuleTbl = __MODULE__.loadedPathToModuleTbl +local loadingModuleTbl = __MODULE__.loadingModuleTbl +local moduleWaitingForLoadingModuleTbl = __MODULE__.moduleWaitingForLoadingModuleTbl +local loadedModuleNameList = __MODULE__.loadedModuleNameList + +local reimportingCount = 0 + +local DEBUG_IMPORT_LOG = false +local DEBUG_IMPORT_STACK = false +local DEBUG_TRACE_MODULE_MEMORY = false +local DEBUG_TRACE_IMPORT_LOOP = false +local DEBUG_WARNING_WAITING_MODULE = false + +local print = print +local pairs = pairs +local ipairs = ipairs +local pcall = pcall +local type = type +local error = error +local assert = assert +local tostring = tostring +local setmetatable = setmetatable +local load = load +local table_insert = table.insert +local table_remove = table.remove +local table_sort = table.sort +local table_concat = table.concat +local string_format = string.format +local string_gsub = string.gsub +local string_sub = string.sub +local string_match = string.match +local string_rep = string.rep +local debug_getupvalue = debug and debug.getupvalue or nil +local debug_setupvalue = debug and debug.setupvalue or nil +local debug_getinfo = debug and debug.getinfo or nil +local debug_traceback = debug and debug.traceback or nil + +local okMd5, md5Mod = pcall(require, "md5") +local md5 = okMd5 and md5Mod or nil + +local ProfileBeginSample = nil +local ProfileEndSample = nil + +local Errorf = function(fmt, ...) + print("ERROR: " .. string_format(fmt, ...)) +end + +local Infof = function(fmt, ...) + print(string_format(fmt, ...)) +end + +local GetTime = function() + return os.time() +end + +local function NormalizeModName(mname) + return (string_gsub(mname, "/", ".")) +end + +local function ModuleNameToPath(modname) + return (string_gsub(NormalizeModName(modname), "%.", "/")) .. ".lua" +end + +local function NormalizeChunkPath(path) + if string_sub(path, 1, 1) == "@" then + return path + end + return "@" .. path +end + +local function OnLoadModuleFileDefault(modname) + local filepath = ModuleNameToPath(modname) + local f = io and io.open and io.open(filepath, "rb") + if f then + local data = f:read("a") + f:close() + local hash = nil + if md5 and md5.sumhexa then + hash = md5.sumhexa(data) + end + return data, filepath, hash + end + return nil, filepath, nil +end + +local OnLoadModuleFile = OnLoadModuleFileDefault +local hasCustomLoadModuleFile = false + +local function LoadModuleChunkFromString(modname, data, chunkname, env) + local chunk, err = load(data, chunkname, nil, env) + if chunk == nil then + error(err) + end + return chunk +end + +local function TryLoadChunkFromSearchers(modname, env) + local searchers = package and (package.searchers or package.loaders) + if type(searchers) ~= "table" then + return nil, nil, nil + end + + for _, searcher in ipairs(searchers) do + if type(searcher) == "function" then + local res, extra = searcher(modname) + if type(res) == "function" then + if debug_getupvalue and debug_setupvalue then + local upName = debug_getupvalue(res, 1) + if upName == "_ENV" then + debug_setupvalue(res, 1, env) + end + end + local chunkname = nil + if type(extra) == "string" and #extra > 0 then + chunkname = NormalizeChunkPath(extra) + elseif debug_getinfo then + local info = debug_getinfo(res, "S") + if info and type(info.source) == "string" and #info.source > 0 then + chunkname = NormalizeChunkPath(info.source) + end + end + if not chunkname then + chunkname = "@" .. ModuleNameToPath(modname) + end + return res, chunkname, nil + end + end + end + + return nil, nil, nil +end + +local function OnLoadModuleChunkDefault(modname, env) + if hasCustomLoadModuleFile then + local data, path, hash = OnLoadModuleFile(modname) + if data == nil then + error("fail to load module: " .. modname) + end + local chunkname = NormalizeChunkPath(path or ModuleNameToPath(modname)) + return LoadModuleChunkFromString(modname, data, chunkname, env), chunkname, hash + end + + local chunk, chunkname, hash = TryLoadChunkFromSearchers(modname, env) + if chunk ~= nil then + return chunk, chunkname, hash + end + + local data, path, fileHash = OnLoadModuleFileDefault(modname) + if data == nil then + error("fail to load module: " .. modname) + end + local fallbackChunkName = NormalizeChunkPath(path or ModuleNameToPath(modname)) + return LoadModuleChunkFromString(modname, data, fallbackChunkName, env), fallbackChunkName, fileHash +end + +local OnLoadModuleChunk = OnLoadModuleChunkDefault + +-- 精确匹配 loader +local exactLoaderTbl = {} +-- pattern -> loader(按 pattern 长度降序排列,最长匹配优先) +local patternLoaderTbl = {} + +local function FindLoader(modname) + local loader = exactLoaderTbl[modname] + if loader then + return loader + end + for _, entry in ipairs(patternLoaderTbl) do + if string_match(modname, entry.pattern) then + return entry.loader + end + end + return nil +end + +local function LoadModuleFile(modname) + return OnLoadModuleFile(modname) +end + +local function LoadModuleChunk(modname, env) + local loader = FindLoader(modname) + if loader then + return loader(modname, env) + end + return OnLoadModuleChunk(modname, env) +end + +__MODULE__.OnLoadModuleFileDefault = OnLoadModuleFileDefault +__MODULE__.OnLoadModuleChunkDefault = OnLoadModuleChunkDefault +__MODULE__.ModuleNameToPath = ModuleNameToPath +__MODULE__.LoadModuleFile = LoadModuleFile +__MODULE__.LoadModuleChunk = LoadModuleChunk +__MODULE__.LoadModuleChunkFromString = LoadModuleChunkFromString + +function __MODULE__.SetOnLoadModuleFile(func) + OnLoadModuleFile = assert(func) + hasCustomLoadModuleFile = true +end + +function __MODULE__.SetOnLoadModuleChunk(func) + OnLoadModuleChunk = assert(func) +end + +local function UpdateExports(M, meta) + if meta.UpdateExports then + meta.UpdateExports(M) + end +end + +local function UpdateImports(M, meta) + if meta.UpdateImports then + meta.UpdateImports(M) + end +end + +local function PushModuleStack(modname) + local ent = { modname = modname } + + if DEBUG_TRACE_MODULE_MEMORY then + collectgarbage("collect") + ent.mem0 = collectgarbage("count") + end + + local maybeLoopPos + if DEBUG_TRACE_IMPORT_LOOP then + for i = #__MODULE__.importingStack, 1, -1 do + if __MODULE__.importingStack[i].modname == modname then + maybeLoopPos = i + break + end + end + end + + table_insert(__MODULE__.importingStack, ent) + + if DEBUG_TRACE_IMPORT_LOOP and maybeLoopPos then + Errorf("!!!! maybe import loopback: %s\n%s", modname, __MODULE__.GetImportingStack(maybeLoopPos)) + end +end + +local function PopModuleStack() + local ent = table_remove(__MODULE__.importingStack) + + if DEBUG_TRACE_MODULE_MEMORY and ent then + local modname = ent.modname + collectgarbage("collect") + local mem1 = collectgarbage("count") + local memDeltaFull = math.max(mem1 - ent.mem0, 0) + local memDelta = math.max(memDeltaFull - (ent.memNoSelf or 0)) + if #__MODULE__.importingStack > 0 then + local parentEnt = __MODULE__.importingStack[#__MODULE__.importingStack] + parentEnt.memNoSelf = (parentEnt.memNoSelf or 0) + memDeltaFull + end + Infof("MODULE_MEMO,%s,%f,%f", modname, mem1, memDelta) + end +end + +local function AddWaitingModule(modname, waitingModule) + if not waitingModule then + return + end + local arr = moduleWaitingForLoadingModuleTbl[modname] + if arr == nil then + arr = {} + moduleWaitingForLoadingModuleTbl[modname] = arr + end + arr[#arr + 1] = waitingModule +end + +local function ReloadWaitingModule(modname) + local arrModuleWaiting = moduleWaitingForLoadingModuleTbl[modname] + if arrModuleWaiting then + moduleWaitingForLoadingModuleTbl[modname] = nil + if DEBUG_WARNING_WAITING_MODULE and #arrModuleWaiting > 10 then + print(string_format("!!! too many waiting module for: %s, waiting count: %d", modname, #arrModuleWaiting)) + end + for _, waitingMeta in ipairs(arrModuleWaiting) do + local updateImports = waitingMeta.UpdateImports + if updateImports then + updateImports(waitingMeta.env) + end + end + end +end + +local function DoInitialImport(modname, loadModuleChunk) + local bt + if DEBUG_IMPORT_LOG then + bt = GetTime() + Infof("{{{ Import: %s", modname) + end + + if ProfileBeginSample then + ProfileBeginSample(modname) + end + + if DEBUG_IMPORT_STACK then + PushModuleStack(modname) + end + + local M = {} + setmetatable(M, { __index = _G, __name = "Module<" .. modname .. ">" }) + + local meta = { + name = modname, + env = M, + imports = {}, + __data__ = {}, + reimporting = false, + hasReexports = false, + } + setmetatable(meta, { __name = "ModuleMeta<" .. modname .. ">" }) + M.__module = meta + + if loadModuleChunk == nil then + loadModuleChunk = LoadModuleChunk + end + + loadingModuleTbl[modname] = M + + local ok, err = pcall(function() + local chunk, path, hash = loadModuleChunk(modname, M) + if chunk == nil or path == nil then + error(string_format("cannot found module file at: %s for module [%s]", tostring(path), modname)) + end + + meta.modulefunc = chunk + meta.filepath = path + meta.hash = hash + meta.__data__ = {} + + chunk() + + loadingModuleTbl[modname] = nil + loadedModuleTbl[modname] = M + loadedPathToModuleTbl[path] = M + + UpdateImports(M, meta) + UpdateExports(M, meta) + + if meta.StashData then + meta.StashData(M, meta.__data__) + end + + if meta.OnImport then + meta.OnImport() + end + + UpdateExports(M, meta) + + -- 刷新因循环依赖而等待本模块加载完成的模块 + ReloadWaitingModule(modname) + + table_insert(loadedModuleNameList, modname) + + if __MODULE__.OnModuleLoaded then + __MODULE__.OnModuleLoaded(modname) + end + end) + + if not ok then + loadingModuleTbl[modname] = nil + moduleWaitingForLoadingModuleTbl[modname] = nil + if loadedModuleTbl[modname] == nil and meta.filepath then + loadedPathToModuleTbl[meta.filepath] = nil + end + end + + if DEBUG_IMPORT_STACK then + PopModuleStack() + end + + if ProfileEndSample then + ProfileEndSample() + end + + if DEBUG_IMPORT_LOG then + local dt = GetTime() - bt + Infof("}}} Import: %s, dt=%f", modname, dt) + end + + if not ok then + error(err, 0) + end + + return M +end + +function __MODULE__.Import(amodname, callerModule, loadModuleChunk) + local modname = NormalizeModName(amodname) + local M = loadedModuleTbl[modname] + + if M == nil then + M = loadingModuleTbl[modname] + if M ~= nil then + AddWaitingModule(modname, callerModule) + end + end + + if M == nil then + M = DoInitialImport(modname, loadModuleChunk) + end + + if callerModule and callerModule.imports then + callerModule.imports[modname] = true + end + + return M +end + +function __MODULE__.GetModuleByName(modname) + return loadedModuleTbl[NormalizeModName(modname)] +end + +function __MODULE__.GetModuleByPath(path) + return loadedPathToModuleTbl[path] +end + +function __MODULE__.GetAllModulePaths() + return loadedPathToModuleTbl +end + +function __MODULE__.AllLoadedModules() + return loadedModuleTbl +end + +local function UpdateDependsLocalImport(modname, visited) + visited = visited or {} + if visited[modname] then + return + end + visited[modname] = true + + local downstreams = {} + for iname, M in pairs(loadedModuleTbl) do + if M.__module.imports[modname] then + downstreams[iname] = M + end + end + + for iname, M in pairs(downstreams) do + local dmeta = M.__module + if dmeta.UpdateImports then + dmeta.UpdateImports(M) + end + if dmeta.OnDepModuleReimported then + dmeta.OnDepModuleReimported(modname) + end + if dmeta.hasReexports then + UpdateDependsLocalImport(iname, visited) + end + end +end + +local function ReimportModule(M, loadModuleChunk) + local meta = M.__module + local modname = meta.name + + if loadModuleChunk == nil then + loadModuleChunk = LoadModuleChunk + end + + local chunk, pathOrErr, hash = loadModuleChunk(modname, M) + if chunk == nil then + local tb = debug_traceback and debug_traceback() or "" + Errorf("%s, %s", tostring(pathOrErr), tb) + return nil, pathOrErr + end + + meta.__data__ = {} + if meta.StashData then + meta.StashData(M, meta.__data__) + end + + local oldImports = meta.imports + local oldHasReexports = meta.hasReexports + meta.imports = {} + meta.hasReexports = false + + if not M.__shared__ then + for k in pairs(M) do + if k ~= "__module" then + M[k] = nil + end + end + end + + local okChunk, chunkErr = pcall(chunk) + if not okChunk then + meta.imports = oldImports + meta.hasReexports = oldHasReexports + error(chunkErr, 0) + end + + meta.modulefunc = chunk + meta.hash = hash + if type(pathOrErr) == "string" and #pathOrErr > 0 then + if meta.filepath and meta.filepath ~= pathOrErr and loadedPathToModuleTbl[meta.filepath] == M then + loadedPathToModuleTbl[meta.filepath] = nil + end + meta.filepath = pathOrErr + loadedPathToModuleTbl[pathOrErr] = M + end + + if meta.RestoreData then + meta.RestoreData(M, meta.__data__) + end + + UpdateImports(M, meta) + UpdateExports(M, meta) + + UpdateDependsLocalImport(modname) + + if meta.OnReimport then + meta.OnReimport() + end + + return M +end + +function __MODULE__.IsReimporting(meta) + if meta then + return meta.reimporting == true + end + return reimportingCount > 0 +end + +function __MODULE__.Reimport(target, loadModuleChunk) + Infof("reimport %s", target) + local M + if string_sub(target, 1, 1) == "@" then + M = loadedPathToModuleTbl[target] + else + M = loadedModuleTbl[NormalizeModName(target)] + end + if M == nil then + local err = string_format("no module loaded: %s", target) + Errorf("%s", err) + return nil, err + end + + local meta = M.__module + local previousReimporting = meta.reimporting + meta.reimporting = true + reimportingCount = reimportingCount + 1 + local ok, result, err = pcall(ReimportModule, M, loadModuleChunk) + reimportingCount = reimportingCount - 1 + meta.reimporting = previousReimporting + if not ok then + error(result, 0) + end + return result, err +end + +function __MODULE__.ReimportSafely(target, loadModuleChunk) + local ok, result, err = pcall(__MODULE__.Reimport, target, loadModuleChunk) + if not ok then + return false, result + end + if result == nil then + return false, err + end + return true, nil +end + +--[[ + RegistryModuleLoader 注册模块加载器 + modpattern: 精确模块名 (如 "Config.Items") 或以 ^ 开头的 Lua pattern (如 "^Config%.") + loader: function(modname, env) -> (chunk, chunkname, hash) +]] +function __MODULE__.RegistryModuleLoader(modpattern, loader) + if string_sub(modpattern, 1, 1) == "^" then + local updated = false + for _, entry in ipairs(patternLoaderTbl) do + if entry.pattern == modpattern then + entry.loader = loader + updated = true + break + end + end + if not updated then + table_insert(patternLoaderTbl, { pattern = modpattern, loader = loader }) + table_sort(patternLoaderTbl, function(a, b) + return #a.pattern > #b.pattern + end) + end + else + exactLoaderTbl[NormalizeModName(modpattern)] = loader + end +end + +function __MODULE__.Config(args) + if args.Errorf then + Errorf = args.Errorf + end + if args.Infof then + Infof = args.Infof + end +end + +function __MODULE__.SetSystemMeta(key, value) + __MODULE__.systemMeta[key] = value +end + +function __MODULE__.GetSystemMeta(key) + return __MODULE__.systemMeta[key] +end + +function __MODULE__.SetProfile(args) + if args.GetTime then + GetTime = args.GetTime + end + if args.ProfileBeginSample then + ProfileBeginSample = args.ProfileBeginSample + end + if args.ProfileEndSample then + ProfileEndSample = args.ProfileEndSample + end +end + +function __MODULE__.GetImportingStack(maybeLoopPos) + local level = 0 + local indent = " " + local T = {} + for i, ent in ipairs(__MODULE__.importingStack) do + local line = string_rep(indent, level) .. ent.modname + if maybeLoopPos and maybeLoopPos == i then + line = line .. " <====" + end + table_insert(T, line) + level = level + 1 + end + return table_concat(T, "\n") +end + +_G.__MODULE__ = __MODULE__ + +return __MODULE__ diff --git a/src/plugin/diagnostics.ts b/src/plugin/diagnostics.ts index f5890f0..d1f2292 100644 --- a/src/plugin/diagnostics.ts +++ b/src/plugin/diagnostics.ts @@ -30,6 +30,10 @@ export enum UnLuaDiagnosticCode { InvalidUnLuaDecoratorArgs = 90108, UnLuaMultipleClassesInFile = 90109, UnLuaForbiddenSuperUsage = 90110, + + // 4.x 模块化与热更系统约束 (90201 - 90299) + InvalidModuleDataUsage = 90201, + ForbiddenExportEqualsInHotReload = 90202, } export function createUnLuaDiagnostic( diff --git a/src/plugin/index.ts b/src/plugin/index.ts index 62deb17..3ea274d 100644 --- a/src/plugin/index.ts +++ b/src/plugin/index.ts @@ -1,6 +1,16 @@ import * as ts from "typescript"; import * as tstl from "typescript-to-lua"; import { createUnLuaDiagnostic, UnLuaDiagnosticCode } from "./diagnostics"; +import { + emitModuleRuntimeFiles, + initFileModuleState, + markRawTstlClassUsed, + transformHotReloadSourceFile, + transformPureClassForHotReload, + tryTransformHotReloadExportDeclaration, + tryTransformHotReloadImport, + tryTransformNativeRequireCall, +} from "./module-transform"; import { findEnclosingClass, hasUnLuaDecorator } from "./type-utils"; import { transformUnLuaClassDeclaration, @@ -14,15 +24,36 @@ import { createSimpleValidationVisitors, validateCallExpression, validateClassDeclaration, + validateHotReloadExportAssignment, + validateModuleDataUsage, validateUnLuaSourceFile, } from "./validators"; +export interface UnLuaPluginOptions { + /** + * 模块化编译模式: + * - `"hot-reload"`(默认):基于 `Lib/Module.lua` + `Lib/Class.lua` 生成支持单文件热更的 `__MODULE__.Import` / `__TS__DefineClass` 产物; + * - `"standard"`:沿用 TSTL 标准 `require` 与 `local ____exports = {}` 产物。 + */ + moduleSystem?: "hot-reload" | "standard"; + /** 是否在 `beforeEmit` 自动产出 `Lib/Module.lua` 与 `Lib/Class.lua`(默认 `true`,仅 `hot-reload` 模式生效)。 */ + emitRuntime?: boolean; + /** 运行时基础库输出相对目录(默认 `"Lib"`)。 */ + runtimeDir?: string; +} + /** * TypeScriptToLua (TSTL) UnLua 定制插件: * 1. 编译期强制执行 ts2lua-unreal 语言子集约束(禁用 get/set、async/await、try/catch 等); - * 2. 将全局 `@unlua` 标记的绑定类转译为原生 UnLua 风格(UnLua.Class / return M / self.Overridden)。 + * 2. 支持自定义模块化单文件运行时热更(`Lib/Module.lua` + `Lib/Class.lua` + `@module_data`); + * 3. 将全局 `@unlua` 标记的绑定类转译为原生 UnLua 风格(UnLua.Class / return M / self.Overridden)。 */ -export function createUnLuaPlugin(): tstl.Plugin { +export function createUnLuaPlugin(options?: UnLuaPluginOptions): tstl.Plugin { + const moduleSystem = options?.moduleSystem ?? "hot-reload"; + const emitRuntime = options?.emitRuntime ?? true; + const runtimeDir = options?.runtimeDir ?? "Lib"; + const isHotReload = moduleSystem === "hot-reload"; + const simpleValidators = createSimpleValidationVisitors(); const visitors: tstl.Visitors = { @@ -31,8 +62,14 @@ export function createUnLuaPlugin(): tstl.Plugin { [ts.SyntaxKind.SourceFile]: (node, context) => { const primaryUnLuaClass = validateUnLuaSourceFile(node, context); if (primaryUnLuaClass) { + if (isHotReload) { + initFileModuleState(node, true); + } return transformUnLuaSourceFile(node, primaryUnLuaClass, context); } + if (isHotReload) { + return transformHotReloadSourceFile(node, context); + } const [luaFile] = context.superTransformNode(node) as [tstl.File]; return luaFile; }, @@ -42,6 +79,36 @@ export function createUnLuaPlugin(): tstl.Plugin { if (customImport !== undefined) { return customImport; } + if (isHotReload) { + const hotImport = tryTransformHotReloadImport(node, context); + if (hotImport !== undefined) { + return hotImport; + } + } + return context.superTransformStatements(node); + }, + + [ts.SyntaxKind.ExportDeclaration]: (node, context) => { + if (isHotReload) { + const hotExport = tryTransformHotReloadExportDeclaration(node, context); + if (hotExport !== undefined) { + return hotExport; + } + } + return context.superTransformStatements(node); + }, + + [ts.SyntaxKind.ExportAssignment]: (node, context) => { + if (isHotReload) { + validateHotReloadExportAssignment(node, context); + } + return context.superTransformStatements(node); + }, + + [ts.SyntaxKind.VariableStatement]: (node, context) => { + if (isHotReload) { + validateModuleDataUsage(node, context); + } return context.superTransformStatements(node); }, @@ -50,11 +117,17 @@ export function createUnLuaPlugin(): tstl.Plugin { if (hasUnLuaDecorator(node)) { return transformUnLuaClassDeclaration(node, context); } + if (isHotReload) { + return transformPureClassForHotReload(node, context); + } return context.superTransformStatements(node); }, [ts.SyntaxKind.ClassExpression]: (node, context) => { validateClassDeclaration(node, context); + if (isHotReload) { + markRawTstlClassUsed(node.getSourceFile() ?? context.sourceFile); + } return context.superTransformExpression(node); }, @@ -80,11 +153,16 @@ export function createUnLuaPlugin(): tstl.Plugin { if (superCall) { return superCall; } + if (isHotReload) { + const nativeReq = tryTransformNativeRequireCall(node, context); + if (nativeReq) { + return nativeReq; + } + } return context.superTransformExpression(node); }, [ts.SyntaxKind.SuperKeyword]: (node, context) => { - // 若 super 未在 CallExpression 中被拦截(如独立访问 super.prop),报错提示 const enclosingClass = findEnclosingClass(node); if (enclosingClass && hasUnLuaDecorator(enclosingClass)) { context.diagnostics.push( @@ -102,10 +180,13 @@ export function createUnLuaPlugin(): tstl.Plugin { return { visitors, + beforeEmit: isHotReload && emitRuntime + ? (program, compilerOptions, emitHost, result) => { + emitModuleRuntimeFiles(program, compilerOptions, result, runtimeDir); + } + : undefined, }; } -const plugin: tstl.Plugin = createUnLuaPlugin(); - -export default plugin; +export default createUnLuaPlugin; export { UnLuaDiagnosticCode } from "./diagnostics"; diff --git a/src/plugin/module-transform.ts b/src/plugin/module-transform.ts new file mode 100644 index 0000000..a20f96c --- /dev/null +++ b/src/plugin/module-transform.ts @@ -0,0 +1,903 @@ +import * as fs from "fs"; +import * as path from "path"; +import * as ts from "typescript"; +import * as tstl from "typescript-to-lua"; +import { + hasJsDocTag, + hasUnLuaDecorator, + makeSafeModuleAlias, + resolveImportTarget, +} from "./type-utils"; + +export interface ModuleImportRefreshEntry { + localVarName: string; + moduleAlias: string; + propertyKey: string; +} + +export interface ReexportEntry { + kind: "named" | "star"; + moduleAlias: string; + exportName?: string; + propertyKey?: string; +} + +export interface ModuleDataEntry { + varName: string; + isExported: boolean; +} + +export interface FileModuleState { + isUnLuaFile: boolean; + /** 已导入的模块名 -> 本文件内对应的局部表变量名(如 M__Framework_Log 或 namespace 名) */ + importedModules: Map; + usedAliases: Set; + /** 需插入文件头部的 __MODULE__.Import 与局部解包语句 */ + moduleImportStatements: tstl.Statement[]; + /** 需在 __module.UpdateImports() 中刷新的局部绑定 */ + importRefreshes: ModuleImportRefreshEntry[]; + /** 需通过 ____syncReexports() 同步的 `export ... from` 再导出 */ + reexports: ReexportEntry[]; + /** `import { x } from "./a"; export { x }` 形式的两步再导出 */ + localReexportExports: Array<{ exportName: string; localVarName: string }>; + /** 通过 `export { x }` 导出的本地非 export 变量(用于 @module_data 恢复后同步) */ + localExportAliases: Map; + /** 模块顶层 @module_data 变量 */ + moduleDataEntries: ModuleDataEntry[]; + /** 记录哪些本地变量名来自 __MODULE__.Import 命名/默认解包 */ + importedLocalNames: Set; + /** 是否替换过顶层类为 __TS__DefineClass */ + replacedTopLevelClass: boolean; + /** 是否存在未替换的匿名/函数内类仍需 lualib.__TS__Class */ + usedRawTstlClass: boolean; +} + +const fileModuleStates = new WeakMap(); + +let cachedRuntimeModuleLua: string | undefined; +let cachedRuntimeClassLua: string | undefined; + +function getRuntimeFileContent(fileName: "Module.lua" | "Class.lua"): string { + if (fileName === "Module.lua" && cachedRuntimeModuleLua !== undefined) { + return cachedRuntimeModuleLua; + } + if (fileName === "Class.lua" && cachedRuntimeClassLua !== undefined) { + return cachedRuntimeClassLua; + } + // dist/plugin/module-transform.js -> ../../runtime/Lib/ + const filePath = path.resolve(__dirname, "..", "..", "runtime", "Lib", fileName); + const content = fs.readFileSync(filePath, "utf8"); + if (fileName === "Module.lua") { + cachedRuntimeModuleLua = content; + } else { + cachedRuntimeClassLua = content; + } + return content; +} + +export function initFileModuleState(sourceFile: ts.SourceFile, isUnLuaFile: boolean): FileModuleState { + const state: FileModuleState = { + isUnLuaFile, + importedModules: new Map(), + usedAliases: new Set(), + moduleImportStatements: [], + importRefreshes: [], + reexports: [], + localReexportExports: [], + localExportAliases: new Map(), + moduleDataEntries: [], + importedLocalNames: new Set(), + replacedTopLevelClass: false, + usedRawTstlClass: false, + }; + + // 预收集模块顶层 @module_data 声明(仅对常规模块启用) + if (!isUnLuaFile) { + for (const stmt of sourceFile.statements) { + if (!ts.isVariableStatement(stmt)) continue; + const stmtTagged = hasJsDocTag(stmt, "module_data"); + const modifiers = ts.canHaveModifiers(stmt) ? ts.getModifiers(stmt) : undefined; + const isExported = modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false; + const isDeclare = modifiers?.some((m) => m.kind === ts.SyntaxKind.DeclareKeyword) ?? false; + if (isDeclare) continue; + + for (const decl of stmt.declarationList.declarations) { + if ((stmtTagged || hasJsDocTag(decl, "module_data")) && ts.isIdentifier(decl.name)) { + state.moduleDataEntries.push({ + varName: decl.name.text, + isExported, + }); + } + } + } + } + + fileModuleStates.set(sourceFile, state); + return state; +} + +export function getFileModuleState(sourceFile: ts.SourceFile): FileModuleState | undefined { + return fileModuleStates.get(sourceFile); +} + +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 createModuleImportCall( + moduleName: string, + includeCallerModule: boolean, + originalNode?: ts.Node +): tstl.CallExpression { + const args: tstl.Expression[] = [tstl.createStringLiteral(moduleName, originalNode)]; + if (includeCallerModule) { + args.push(tstl.createIdentifier("__module")); + } + return tstl.createCallExpression( + tstl.createTableIndexExpression( + tstl.createIdentifier("__MODULE__"), + tstl.createStringLiteral("Import") + ), + args, + originalNode + ); +} + +/** + * 确保目标模块在当前文件中已通过 `__MODULE__.Import` 引入,返回其局部别名(去重复用)。 + */ +function ensureModuleImported( + state: FileModuleState, + moduleName: string, + preferredAlias: string | undefined, + originalNode: ts.Node +): string { + const existing = state.importedModules.get(moduleName); + if (existing) { + if (preferredAlias && preferredAlias !== existing) { + state.moduleImportStatements.push( + tstl.createVariableDeclarationStatement( + tstl.createIdentifier(preferredAlias, originalNode), + tstl.createIdentifier(existing), + originalNode + ) + ); + return preferredAlias; + } + return existing; + } + + let alias: string; + if (preferredAlias && !state.usedAliases.has(preferredAlias)) { + alias = preferredAlias; + state.usedAliases.add(alias); + } else { + alias = makeSafeModuleAlias(moduleName, state.usedAliases); + } + + state.importedModules.set(moduleName, alias); + state.moduleImportStatements.push( + tstl.createVariableDeclarationStatement( + tstl.createIdentifier(alias, originalNode), + createModuleImportCall(moduleName, !state.isUnLuaFile, originalNode), + originalNode + ) + ); + return alias; +} + +function shouldImportRuntimeNode( + context: tstl.TransformationContext, + node: ts.ImportClause | ts.NamespaceImport | ts.ImportSpecifier +): boolean { + if (ts.isTypeOnlyImportOrExportDeclaration(node)) { + return false; + } + return context.resolver.isReferencedAliasDeclaration(node); +} + +/** + * 将指向项目 TS 模块的 ImportDeclaration 转换为 `__MODULE__.Import("...", __module)`, + * 外部 `.d.ts` / `@noResolution` / `@unlua` 目标返回 `undefined` 交给默认逻辑处理。 + */ +export function tryTransformHotReloadImport( + node: ts.ImportDeclaration, + context: tstl.TransformationContext +): tstl.Statement[] | undefined { + const sf = node.getSourceFile() ?? context.sourceFile; + const state = getFileModuleState(sf); + if (!state) return undefined; + + const target = resolveImportTarget(node.moduleSpecifier, context); + if (target.kind === "external" || target.isUnLuaTarget) { + return undefined; + } + + // 副作用导入:import "./init"; + if (!node.importClause) { + state.moduleImportStatements.push( + tstl.createExpressionStatement( + createModuleImportCall(target.moduleName, !state.isUnLuaFile, node), + node + ) + ); + return []; + } + + // import type { ... } from "..." + if (node.importClause.isTypeOnly) { + return []; + } + + const needDefault = + node.importClause.name !== undefined && + shouldImportRuntimeNode(context, node.importClause); + + const namedBindings = node.importClause.namedBindings; + const needNamespace = + namedBindings !== undefined && + ts.isNamespaceImport(namedBindings) && + shouldImportRuntimeNode(context, namedBindings); + + const runtimeNamedSpecifiers = + namedBindings !== undefined && ts.isNamedImports(namedBindings) + ? namedBindings.elements.filter((el) => shouldImportRuntimeNode(context, el)) + : []; + + if (!needDefault && !needNamespace && runtimeNamedSpecifiers.length === 0) { + return []; + } + + // 纯命名空间导入:import * as Log from "./Log" -> local Log = __MODULE__.Import("Framework.Log", __module) + if (needNamespace && !needDefault && runtimeNamedSpecifiers.length === 0 && ts.isNamespaceImport(namedBindings!)) { + ensureModuleImported(state, target.moduleName, namedBindings.name.text, node); + return []; + } + + const moduleAlias = ensureModuleImported( + state, + target.moduleName, + needNamespace && ts.isNamespaceImport(namedBindings!) ? namedBindings.name.text : undefined, + node + ); + + // 默认导入:import Foo from "./foo" -> local Foo = M__foo.default + if (needDefault && node.importClause.name) { + const localName = node.importClause.name.text; + state.moduleImportStatements.push( + tstl.createVariableDeclarationStatement( + tstl.createIdentifier(localName, node.importClause.name), + tstl.createTableIndexExpression( + tstl.createIdentifier(moduleAlias), + tstl.createStringLiteral("default", node.importClause.name) + ), + node.importClause.name + ) + ); + state.importedLocalNames.add(localName); + if (!state.isUnLuaFile) { + state.importRefreshes.push({ + localVarName: localName, + moduleAlias, + propertyKey: "default", + }); + } + } + + // 命名导入:import { A, B as C } from "./foo" -> local A = M__foo.A; local C = M__foo.B + for (const spec of runtimeNamedSpecifiers) { + const localName = spec.name.text; + const propName = (spec.propertyName ?? spec.name).text; + state.moduleImportStatements.push( + tstl.createVariableDeclarationStatement( + tstl.createIdentifier(localName, spec.name), + tstl.createTableIndexExpression( + tstl.createIdentifier(moduleAlias), + tstl.createStringLiteral(propName, spec.propertyName ?? spec.name) + ), + spec + ) + ); + state.importedLocalNames.add(localName); + if (!state.isUnLuaFile) { + state.importRefreshes.push({ + localVarName: localName, + moduleAlias, + propertyKey: propName, + }); + } + } + + return []; +} + +/** + * 转换 `export { ... } from "./sub"`、`export * from "./sub"`、`export * as NS from "./sub"` + * 以及记录本地 `export { A, B as C }`。 + */ +export function tryTransformHotReloadExportDeclaration( + node: ts.ExportDeclaration, + context: tstl.TransformationContext +): tstl.Statement[] | undefined { + const sf = node.getSourceFile() ?? context.sourceFile; + const state = getFileModuleState(sf); + if (!state || state.isUnLuaFile) return undefined; + + if (node.isTypeOnly) { + return []; + } + + // 本地 `export { A, B as C }`(无 from) + if (!node.moduleSpecifier) { + if (node.exportClause && ts.isNamedExports(node.exportClause)) { + for (const spec of node.exportClause.elements) { + if (spec.isTypeOnly || !context.resolver.isValueAliasDeclaration(spec)) continue; + const localName = (spec.propertyName ?? spec.name).text; + const exportName = spec.name.text; + if (state.importedLocalNames.has(localName)) { + state.localReexportExports.push({ exportName, localVarName: localName }); + } else { + const existing = state.localExportAliases.get(localName) ?? []; + existing.push(exportName); + state.localExportAliases.set(localName, existing); + } + } + } + return undefined; // 让 TSTL 正常生成 `____exports.X = X` + } + + const target = resolveImportTarget(node.moduleSpecifier, context); + if (target.kind === "external" || target.isUnLuaTarget) { + return undefined; + } + + // `export * from "./sub"` + if (!node.exportClause) { + const moduleAlias = ensureModuleImported(state, target.moduleName, undefined, node); + state.reexports.push({ + kind: "star", + moduleAlias, + }); + return []; + } + + // `export * as Sub from "./sub"` + if (ts.isNamespaceExport(node.exportClause)) { + const moduleAlias = ensureModuleImported(state, target.moduleName, undefined, node); + return [ + tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("____exports"), + tstl.createStringLiteral(node.exportClause.name.text, node.exportClause.name) + ), + tstl.createIdentifier(moduleAlias), + node + ), + ]; + } + + // `export { A, B as C } from "./sub"` + const runtimeSpecifiers = node.exportClause.elements.filter( + (spec) => !spec.isTypeOnly && context.resolver.isValueAliasDeclaration(spec) + ); + if (runtimeSpecifiers.length === 0) { + return []; + } + + const moduleAlias = ensureModuleImported(state, target.moduleName, undefined, node); + for (const spec of runtimeSpecifiers) { + const propName = (spec.propertyName ?? spec.name).text; + const exportName = spec.name.text; + state.reexports.push({ + kind: "named", + moduleAlias, + exportName, + propertyKey: propName, + }); + } + return []; +} + +function isRawTstlClassCall(expr: tstl.Expression | undefined): boolean { + if (!expr || !tstl.isCallExpression(expr)) return false; + return ( + tstl.isIdentifier(expr.expression) && + expr.expression.text === "__TS__Class" && + expr.params.length === 0 + ); +} + +function createDefineClassCall(classKeyName: string, originalNode?: ts.Node): tstl.CallExpression { + return tstl.createCallExpression( + tstl.createIdentifier("__TS__DefineClass"), + [tstl.createStringLiteral(classKeyName, originalNode), tstl.createIdentifier("__module")], + originalNode + ); +} + +function hasDefaultExportModifier(node: ts.ClassDeclaration): boolean { + if (!ts.canHaveModifiers(node)) return false; + return ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword) ?? false; +} + +/** + * 将顶层纯 TS `ClassDeclaration` 的 `__TS__Class()` 替换为扁平全局调用 `__TS__DefineClass("Name", __module)`, + * 以便运行时单文件热更时复用类与原型表,同时避免额外表查询与 `lualib.__TS__Class` 引入。 + */ +export function transformPureClassForHotReload( + node: ts.ClassDeclaration, + context: tstl.TransformationContext +): tstl.Statement[] { + const sf = node.getSourceFile() ?? context.sourceFile; + const state = getFileModuleState(sf); + const statements = context.superTransformStatements(node); + + if (!state || state.isUnLuaFile || hasUnLuaDecorator(node)) { + return statements; + } + + const isTopLevel = ts.isSourceFile(node.parent); + const classKeyName = node.name?.text ?? (hasDefaultExportModifier(node) ? "default" : undefined); + + if (!isTopLevel || !classKeyName || statements.length === 0) { + state.usedRawTstlClass = true; + return statements; + } + + const first = statements[0]; + if ( + tstl.isVariableDeclarationStatement(first) && + first.right && + first.right.length === 1 && + isRawTstlClassCall(first.right[0]) + ) { + statements[0] = tstl.createVariableDeclarationStatement( + first.left, + [createDefineClassCall(classKeyName, node)], + node + ); + state.replacedTopLevelClass = true; + return statements; + } + + if ( + tstl.isAssignmentStatement(first) && + first.right.length === 1 && + isRawTstlClassCall(first.right[0]) + ) { + statements[0] = tstl.createAssignmentStatement( + first.left, + [createDefineClassCall(classKeyName, node)], + node + ); + state.replacedTopLevelClass = true; + return statements; + } + + state.usedRawTstlClass = true; + return statements; +} + +export function markRawTstlClassUsed(sourceFile: ts.SourceFile): void { + const state = getFileModuleState(sourceFile); + if (state) { + state.usedRawTstlClass = true; + } +} + +/** + * 允许业务 TS 直接书写 `const cjson = require("cjson")`、`require("UnLua.HotReload")` 等外部原生 Lua/C 插件: + * 对非项目内相对路径的 `require("...")` 临时添加 `@NoResolution:` 前缀,由 TSTL resolve 阶段自动剥离并原样输出 `require("cjson")`, + * 避免触发 TSTL 100000 ("Could not resolve lua source files") 报错,无需在 tsconfig 手工枚举 noResolvePaths。 + */ +export function tryTransformNativeRequireCall( + node: ts.CallExpression, + context: tstl.TransformationContext +): tstl.Expression | undefined { + if (!ts.isIdentifier(node.expression) || node.expression.text !== "require") { + return undefined; + } + if (node.arguments.length !== 1) { + return undefined; + } + const arg = node.arguments[0]; + if (!ts.isStringLiteral(arg)) { + return undefined; + } + const text = arg.text; + if (text.startsWith("@NoResolution:") || text.startsWith(".")) { + return undefined; + } + const target = resolveImportTarget(arg, context); + if (target.kind === "project") { + return undefined; + } + return tstl.createCallExpression( + tstl.createIdentifier("require", node.expression), + [tstl.createStringLiteral(`@NoResolution:${text}`, arg)], + node + ); +} + +function createModuleDataAccessExpr(entry: ModuleDataEntry): tstl.AssignmentLeftHandSideExpression { + if (entry.isExported) { + return tstl.createTableIndexExpression( + tstl.createIdentifier("____exports"), + tstl.createStringLiteral(entry.varName) + ); + } + return tstl.createIdentifier(entry.varName); +} + +function buildStashAndRestoreStatements(state: FileModuleState): tstl.Statement[] { + if (state.moduleDataEntries.length === 0) { + return []; + } + + // function __module.StashData(env, to) ... end + const stashBody: tstl.Statement[] = [ + tstl.createVariableDeclarationStatement( + tstl.createIdentifier("____has"), + tstl.createTableIndexExpression( + tstl.createIdentifier("to"), + tstl.createStringLiteral("__has__") + ) + ), + tstl.createIfStatement( + tstl.createUnaryExpression( + tstl.createIdentifier("____has"), + tstl.SyntaxKind.NotOperator + ), + tstl.createBlock([ + tstl.createAssignmentStatement( + tstl.createIdentifier("____has"), + tstl.createTableExpression([]) + ), + tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("to"), + tstl.createStringLiteral("__has__") + ), + tstl.createIdentifier("____has") + ), + ]) + ), + ]; + + for (const entry of state.moduleDataEntries) { + stashBody.push( + tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("to"), + tstl.createStringLiteral(entry.varName) + ), + createModuleDataAccessExpr(entry) + ) + ); + stashBody.push( + tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("____has"), + tstl.createStringLiteral(entry.varName) + ), + tstl.createBooleanLiteral(true) + ) + ); + } + + const stashFn = tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("__module"), + tstl.createStringLiteral("StashData") + ), + tstl.createFunctionExpression( + tstl.createBlock(stashBody), + [tstl.createIdentifier("env"), tstl.createIdentifier("to")], + undefined, + tstl.NodeFlags.Declaration + ) + ); + + // function __module.RestoreData(env, from) ... end + const restoreBody: tstl.Statement[] = [ + tstl.createVariableDeclarationStatement( + tstl.createIdentifier("____has"), + tstl.createTableIndexExpression( + tstl.createIdentifier("from"), + tstl.createStringLiteral("__has__") + ) + ), + tstl.createIfStatement( + tstl.createUnaryExpression( + tstl.createIdentifier("____has"), + tstl.SyntaxKind.NotOperator + ), + tstl.createBlock([tstl.createReturnStatement([])]) + ), + ]; + + for (const entry of state.moduleDataEntries) { + const assignBlockStmts: tstl.Statement[] = [ + tstl.createAssignmentStatement( + createModuleDataAccessExpr(entry), + tstl.createTableIndexExpression( + tstl.createIdentifier("from"), + tstl.createStringLiteral(entry.varName) + ) + ), + ]; + + // 若该本地变量同时通过 `export { x }` 导出,恢复后同步写回 ____exports + if (!entry.isExported) { + const aliasExports = state.localExportAliases.get(entry.varName); + if (aliasExports) { + for (const expName of aliasExports) { + assignBlockStmts.push( + tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("____exports"), + tstl.createStringLiteral(expName) + ), + tstl.createIdentifier(entry.varName) + ) + ); + } + } + } + + restoreBody.push( + tstl.createIfStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("____has"), + tstl.createStringLiteral(entry.varName) + ), + tstl.createBlock(assignBlockStmts) + ) + ); + } + + const restoreFn = tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("__module"), + tstl.createStringLiteral("RestoreData") + ), + tstl.createFunctionExpression( + tstl.createBlock(restoreBody), + [tstl.createIdentifier("env"), tstl.createIdentifier("from")], + undefined, + tstl.NodeFlags.Declaration + ) + ); + + return [stashFn, restoreFn]; +} + +function buildSyncReexportsStatements(state: FileModuleState): tstl.Statement[] { + if (state.reexports.length === 0) { + return []; + } + + const body: tstl.Statement[] = []; + for (const entry of state.reexports) { + if (entry.kind === "named" && entry.exportName && entry.propertyKey) { + body.push( + tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("____exports"), + tstl.createStringLiteral(entry.exportName) + ), + tstl.createTableIndexExpression( + tstl.createIdentifier(entry.moduleAlias), + tstl.createStringLiteral(entry.propertyKey) + ) + ) + ); + } else if (entry.kind === "star") { + const kId = tstl.createIdentifier("____exportKey"); + const vId = tstl.createIdentifier("____exportValue"); + const cond = tstl.createBinaryExpression( + tstl.createBinaryExpression( + tstl.cloneIdentifier(kId), + tstl.createStringLiteral("default"), + tstl.SyntaxKind.InequalityOperator + ), + tstl.createBinaryExpression( + tstl.cloneIdentifier(kId), + tstl.createStringLiteral("__module"), + tstl.SyntaxKind.InequalityOperator + ), + tstl.SyntaxKind.AndOperator + ); + const assign = tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("____exports"), + tstl.cloneIdentifier(kId) + ), + tstl.cloneIdentifier(vId) + ); + body.push( + tstl.createForInStatement( + tstl.createBlock([tstl.createIfStatement(cond, tstl.createBlock([assign]))]), + [kId, vId], + [ + tstl.createCallExpression(tstl.createIdentifier("pairs"), [ + tstl.createIdentifier(entry.moduleAlias), + ]), + ] + ) + ); + } + } + + const fnDecl = tstl.createVariableDeclarationStatement( + tstl.createIdentifier("____syncReexports"), + tstl.createFunctionExpression(tstl.createBlock(body), [], undefined, tstl.NodeFlags.Declaration) + ); + + const initialCall = tstl.createExpressionStatement( + tstl.createCallExpression(tstl.createIdentifier("____syncReexports"), []) + ); + + return [fnDecl, initialCall]; +} + +function buildUpdateImportsStatement(state: FileModuleState): tstl.Statement { + const body: tstl.Statement[] = []; + + for (const ref of state.importRefreshes) { + body.push( + tstl.createAssignmentStatement( + tstl.createIdentifier(ref.localVarName), + tstl.createTableIndexExpression( + tstl.createIdentifier(ref.moduleAlias), + tstl.createStringLiteral(ref.propertyKey) + ) + ) + ); + } + + if (state.reexports.length > 0) { + body.push( + tstl.createExpressionStatement( + tstl.createCallExpression(tstl.createIdentifier("____syncReexports"), []) + ) + ); + } + + for (const localReexp of state.localReexportExports) { + body.push( + tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("____exports"), + tstl.createStringLiteral(localReexp.exportName) + ), + tstl.createIdentifier(localReexp.localVarName) + ) + ); + } + + return tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("__module"), + tstl.createStringLiteral("UpdateImports") + ), + tstl.createFunctionExpression( + tstl.createBlock(body), + [], + undefined, + tstl.NodeFlags.Declaration + ) + ); +} + +/** + * 组装常规 TS 模块的 hot-reload 产物: + * - `local ____exports = {}` -> `local ____exports = __module.env` + * - 移除尾部 `return ____exports` + * - 头部注入 `__MODULE__.Import` 语句(以及 Barrel `__module.hasReexports = true`) + * - 尾部注入 `____syncReexports` / `__module.StashData` / `__module.RestoreData` / `__module.UpdateImports` + * - 按需剔除已完全替换为 `__TS__DefineClass` 的 `LuaLibFeature.Class` + */ +export function transformHotReloadSourceFile( + node: ts.SourceFile, + context: tstl.TransformationContext +): tstl.File { + const state = initFileModuleState(node, false); + const [luaFile] = context.superTransformNode(node) as [tstl.File]; + + const bodyStatements: tstl.Statement[] = []; + let hadExportsDecl = false; + + for (let i = 0; i < luaFile.statements.length; i++) { + const stmt = luaFile.statements[i]; + if (isEmptyExportsDeclaration(stmt)) { + hadExportsDecl = true; + continue; + } + if (i === luaFile.statements.length - 1 && isReturnExportsStatement(stmt)) { + continue; + } + bodyStatements.push(stmt); + } + + const hasReexports = state.reexports.length > 0 || state.localReexportExports.length > 0; + const finalStatements: tstl.Statement[] = []; + + if (hadExportsDecl || hasReexports || state.moduleDataEntries.some((d) => d.isExported)) { + finalStatements.push( + tstl.createVariableDeclarationStatement( + tstl.createIdentifier("____exports"), + tstl.createTableIndexExpression( + tstl.createIdentifier("__module"), + tstl.createStringLiteral("env") + ) + ) + ); + } + + if (hasReexports) { + finalStatements.push( + tstl.createAssignmentStatement( + tstl.createTableIndexExpression( + tstl.createIdentifier("__module"), + tstl.createStringLiteral("hasReexports") + ), + tstl.createBooleanLiteral(true) + ) + ); + } + + finalStatements.push(...state.moduleImportStatements); + finalStatements.push(...bodyStatements); + finalStatements.push(...buildSyncReexportsStatements(state)); + finalStatements.push(...buildStashAndRestoreStatements(state)); + finalStatements.push(buildUpdateImportsStatement(state)); + + const luaLibFeatures = new Set(luaFile.luaLibFeatures); + if (state.replacedTopLevelClass && !state.usedRawTstlClass) { + luaLibFeatures.delete(tstl.LuaLibFeature.Class); + } + + return tstl.createFile(finalStatements, luaLibFeatures, luaFile.trivia, node); +} + +/** + * 在 `beforeEmit` 阶段自动向编译产物目录输出 `Lib/Module.lua` 与 `Lib/Class.lua`(不覆盖已有同名产物)。 + */ +export function emitModuleRuntimeFiles( + _program: ts.Program, + options: tstl.CompilerOptions, + result: tstl.EmitFile[], + runtimeDir: string +): void { + const outDir = options.outDir ?? options.rootDir ?? "."; + const existingPaths = new Set( + result.map((f) => path.normalize(f.outputPath).replace(/\\/g, "/")) + ); + + const filesToEmit: Array<"Module.lua" | "Class.lua"> = ["Module.lua", "Class.lua"]; + for (const fileName of filesToEmit) { + const outputPath = path.join(outDir, runtimeDir, fileName); + const normalized = path.normalize(outputPath).replace(/\\/g, "/"); + if (existingPaths.has(normalized)) { + continue; + } + result.push({ + outputPath, + code: getRuntimeFileContent(fileName), + }); + } +} diff --git a/src/plugin/type-utils.ts b/src/plugin/type-utils.ts index 414f826..66dd6b9 100644 --- a/src/plugin/type-utils.ts +++ b/src/plugin/type-utils.ts @@ -1,5 +1,6 @@ import * as path from "path"; import * as ts from "typescript"; +import * as tstl from "typescript-to-lua"; export interface UnLuaDecoratorInfo { decorator: ts.Decorator; @@ -357,3 +358,171 @@ export function findEnclosingClass(node: ts.Node): ts.ClassLikeDeclaration | und } return undefined; } + +/** + * 检查节点是否带有指定名称的 JSDoc 标签(如 `@module_data`、`@noSelf`)。 + */ +export function hasJsDocTag(node: ts.Node, tagName: string): boolean { + const tags = ts.getJSDocTags(node); + if (tags.some((tag) => tag.tagName.text === tagName)) { + return true; + } + // 兼容单行 JSDoc `/** @module_data*/` 等紧贴尾注形式(严格限定 /** ... */,忽略普通 // 或 /* 注释) + const sf = node.getSourceFile(); + if (!sf) return false; + const fullText = sf.getFullText(); + const ranges = ts.getLeadingCommentRanges(fullText, node.getFullStart()); + if (!ranges) return false; + const pattern = new RegExp(`@${tagName}(?![A-Za-z0-9_])`); + for (const range of ranges) { + const comment = fullText.slice(range.pos, range.end); + if (comment.startsWith("/**") && pattern.test(comment)) { + return true; + } + } + return false; +} + +/** + * 检查源文件中是否存在顶层 @unlua 绑定类。 + */ +export function isUnLuaSourceFile(sourceFile: ts.SourceFile): boolean { + for (const stmt of sourceFile.statements) { + if (ts.isClassDeclaration(stmt) && hasUnLuaDecorator(stmt)) { + return true; + } + } + return false; +} + +export type ImportTargetResolution = + | { + kind: "project"; + moduleName: string; + isUnLuaTarget: boolean; + sourceFile: ts.SourceFile; + } + | { + kind: "external"; + }; + +function hasNoResolutionAnnotation(symbol: ts.Symbol | undefined): boolean { + if (!symbol) return false; + const decls = symbol.getDeclarations(); + if (!decls) return false; + for (const decl of decls) { + if (hasJsDocTag(decl, "noResolution")) { + return true; + } + } + return false; +} + +function findVirtualOrProgramSourceFile( + specifierText: string, + containingFile: ts.SourceFile, + program: ts.Program +): ts.SourceFile | undefined { + const compilerOptions = program.getCompilerOptions(); + const resolved = ts.resolveModuleName(specifierText, containingFile.fileName, compilerOptions, ts.sys); + const resolvedFileName = resolved.resolvedModule?.resolvedFileName; + if (resolvedFileName) { + const direct = program.getSourceFile(resolvedFileName); + if (direct) return direct; + const normalizedResolved = path.resolve(resolvedFileName); + for (const sf of program.getSourceFiles()) { + if (path.resolve(sf.fileName) === normalizedResolved) { + return sf; + } + } + } + + // 兜底:在内存虚拟项目(如 transpileVirtualProject)中直接按相对路径匹配 program.getSourceFiles() + if (specifierText.startsWith(".") || specifierText.startsWith("/")) { + const baseDir = path.dirname(containingFile.fileName); + const rawCandidate = path.normalize(path.join(baseDir, specifierText)).replace(/\\/g, "/"); + const candidates = new Set([ + rawCandidate, + `${rawCandidate}.ts`, + `${rawCandidate}.tsx`, + `${rawCandidate}/index.ts`, + `${rawCandidate}/index.tsx`, + ]); + for (const sf of program.getSourceFiles()) { + const norm = path.normalize(sf.fileName).replace(/\\/g, "/"); + if (candidates.has(norm) || candidates.has(norm.replace(/^\.\//, ""))) { + return sf; + } + const resolvedNorm = path.resolve(sf.fileName); + for (const c of candidates) { + if (resolvedNorm === path.resolve(c)) { + return sf; + } + } + } + } + + return undefined; +} + +/** + * 解析 import/export 的模块说明符: + * - 命中项目内非 `.d.ts` TS 源码 -> 返回 `{ kind: "project", moduleName, isUnLuaTarget, sourceFile }` + * - 命中 `.d.ts`、`@noResolution` 或外部 Lua/C 插件 -> 返回 `{ kind: "external" }`(保留原生 require) + */ +export function resolveImportTarget( + moduleSpecifier: ts.Expression, + context: tstl.TransformationContext +): ImportTargetResolution { + if (!ts.isStringLiteral(moduleSpecifier)) { + return { kind: "external" }; + } + + const specifierText = moduleSpecifier.text; + const symbol = context.checker.getSymbolAtLocation(moduleSpecifier); + if (hasNoResolutionAnnotation(symbol)) { + return { kind: "external" }; + } + + let targetSf: ts.SourceFile | undefined; + const decl = symbol?.valueDeclaration ?? symbol?.declarations?.[0]; + if (decl) { + targetSf = decl.getSourceFile(); + } + + if (!targetSf) { + const containingSf = moduleSpecifier.getSourceFile() ?? context.sourceFile; + targetSf = findVirtualOrProgramSourceFile(specifierText, containingSf, context.program); + } + + if (!targetSf || targetSf.isDeclarationFile) { + return { kind: "external" }; + } + + const moduleName = resolveLuaModuleName(targetSf, context.program); + return { + kind: "project", + moduleName, + isUnLuaTarget: isUnLuaSourceFile(targetSf), + sourceFile: targetSf, + }; +} + +/** + * 为目标模块名生成合法且唯一的局部别名(如 `Framework.Log` -> `M__Framework_Log`)。 + */ +export function makeSafeModuleAlias(moduleName: string, usedAliases: Set): string { + const sanitized = moduleName.replace(/[^A-Za-z0-9_]/g, "_"); + const base = `M__${sanitized}`; + if (!usedAliases.has(base)) { + usedAliases.add(base); + return base; + } + let idx = 2; + while (usedAliases.has(`${base}_${idx}`)) { + idx++; + } + const unique = `${base}_${idx}`; + usedAliases.add(unique); + return unique; +} diff --git a/src/plugin/unlua-transform.ts b/src/plugin/unlua-transform.ts index 413819b..3f5908a 100644 --- a/src/plugin/unlua-transform.ts +++ b/src/plugin/unlua-transform.ts @@ -9,6 +9,7 @@ import { resolveSuperClass, SuperClassResolution, } from "./type-utils"; +import { getFileModuleState } from "./module-transform"; const SCOPE_TYPE_FUNCTION = 2 as Parameters[0]; @@ -478,6 +479,7 @@ export function transformUnLuaSourceFile( ): tstl.File { const [luaFile] = context.superTransformNode(node) as [tstl.File]; const classVarName = getUnLuaClassVarName(primaryClass); + const modState = getFileModuleState(node); const statements = luaFile.statements.filter((stmt) => !isEmptyExportsDeclaration(stmt)); @@ -485,6 +487,10 @@ export function transformUnLuaSourceFile( statements.pop(); } + if (modState && modState.moduleImportStatements.length > 0) { + statements.unshift(...modState.moduleImportStatements); + } + statements.push( tstl.createReturnStatement([tstl.createIdentifier(classVarName, primaryClass.name)]) ); diff --git a/src/plugin/validators.ts b/src/plugin/validators.ts index b25bff2..8959306 100644 --- a/src/plugin/validators.ts +++ b/src/plugin/validators.ts @@ -8,6 +8,7 @@ import { getDecoratorName, getUnLuaDecorator, hasAllowTryComment, + hasJsDocTag, hasUnLuaDecorator, isUnLuaClassType, isUObjectType, @@ -564,6 +565,58 @@ export function validateSpreadAssignment( } } +/** + * 校验 `@module_data` 标注合法性:仅允许标注在模块顶层变量声明上,且禁止解构声明。 + */ +export function validateModuleDataUsage( + node: ts.VariableStatement, + context: tstl.TransformationContext +): void { + const stmtTagged = hasJsDocTag(node, "module_data"); + const isTopLevel = ts.isSourceFile(node.parent); + + for (const decl of node.declarationList.declarations) { + const declTagged = stmtTagged || hasJsDocTag(decl, "module_data"); + if (!declTagged) continue; + + if (!isTopLevel) { + report( + context, + decl, + UnLuaDiagnosticCode.InvalidModuleDataUsage, + "@module_data 仅允许标注在模块顶层变量声明上,禁止在函数或代码块内部使用。" + ); + continue; + } + + if (!ts.isIdentifier(decl.name)) { + report( + context, + decl.name, + UnLuaDiagnosticCode.InvalidModuleDataUsage, + "@module_data 不支持解构变量声明,请拆分为独立的顶层标识符声明。" + ); + } + } +} + +/** + * 校验 hot-reload 模式下禁用 CommonJS `export =`。 + */ +export function validateHotReloadExportAssignment( + node: ts.ExportAssignment, + context: tstl.TransformationContext +): void { + if (node.isExportEquals) { + report( + context, + node, + UnLuaDiagnosticCode.ForbiddenExportEqualsInHotReload, + "hot-reload 模块化模式下禁用 CommonJS 'export =',请改用 ES 'export' 或 'export default'。" + ); + } +} + /** * 校验独立的纯 AST 禁用节点(GetAccessor, SetAccessor, Await, Try, Throw, Yield, ForIn, Enum, RegExp, With, arguments)。 */ diff --git a/test/hot-reload.test.mjs b/test/hot-reload.test.mjs new file mode 100644 index 0000000..b3935f4 --- /dev/null +++ b/test/hot-reload.test.mjs @@ -0,0 +1,760 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import * as ts from "typescript"; +import * as tstl from "typescript-to-lua"; +import { createRequire } from "node:module"; +import { spawnSync } from "node:child_process"; + +const require = createRequire(import.meta.url); +const luaBin = ["lua5.4", "lua"].find((cmd) => { + const probe = spawnSync(cmd, ["-v"], { encoding: "utf8" }); + return probe.status === 0 && /Lua 5\.4/.test((probe.stdout || "") + (probe.stderr || "")); +}); + +const projectRoot = path.resolve(import.meta.dirname, ".."); +const unluaTypesContent = fs.readFileSync(path.join(projectRoot, "types", "unlua.d.ts"), "utf8"); +const moduleTypesContent = fs.readFileSync(path.join(projectRoot, "types", "module.d.ts"), "utf8"); +const pluginPath = path.join(projectRoot, "dist", "plugin", "index.js"); +const { UnLuaDiagnosticCode } = require(pluginPath); + +const VIRTUAL_LUA_GLOBALS_DTS = ` +declare const _G: Record; +declare function tostring(this: void, v: unknown): string; +declare function require(this: void, mod: string): any; +`; + +function transpile(files, pluginOpts = {}) { + const virtualFiles = { + "unlua.d.ts": unluaTypesContent, + "module.d.ts": moduleTypesContent, + "lua.globals.d.ts": VIRTUAL_LUA_GLOBALS_DTS, + ...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, ...pluginOpts }], + }); +} + +function getErrors(result) { + return result.diagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error); +} + +function formatDiagnostics(diags) { + return diags + .map((d) => `${d.file?.fileName ?? ""} [${d.source ?? "ts"}:${d.code}] ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`) + .join("\n"); +} + +function getLuaFile(result, relPath) { + const normalized = relPath.replace(/\\/g, "/"); + return result.transpiledFiles.find((f) => { + const out = (f.outPath || "").replace(/\\/g, "/"); + return out === normalized || out.endsWith("/" + normalized); + }); +} + +function writeTranspiledToDir(result, outDir) { + for (const file of result.transpiledFiles) { + const rel = file.outPath.replace(/^\/+/, ""); + const fullPath = path.join(outDir, rel); + fs.mkdirSync(path.dirname(fullPath), { recursive: true }); + fs.writeFileSync(fullPath, file.lua, "utf8"); + } +} + +function runLuaInDir(dir, script) { + assert.ok(luaBin, "Lua 5.4 binary is required to run runtime tests"); + const wrapped = ` + package.path = ${JSON.stringify(path.join(dir, "?.lua"))} .. ";" .. ${JSON.stringify( + path.join(dir, "?/init.lua") + )} .. ";" .. package.path + require("Lib.Module") + require("Lib.Class") + ${script} + `; + const proc = spawnSync(luaBin, ["-e", wrapped], { encoding: "utf8", cwd: dir }); + assert.equal(proc.status, 0, `Lua execution failed:\nSTDOUT:\n${proc.stdout}\nSTDERR:\n${proc.stderr}`); + return proc.stdout; +} + +function withTempDir(fn) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ts2lua-hotreload-")); + try { + return fn(dir); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +// ============================================================ +// 1. 编译期产物与开关校验 +// ============================================================ + +test("hot-reload mode (default) auto-emits Lib/Module.lua and Lib/Class.lua and transforms imports/exports/classes", () => { + const result = transpile({ + "Framework/Log.ts": ` + /** @noSelfInFile */ + export function Info(msg: string): string { + return "[INFO] " + msg; + } + export default function DefaultTag(): string { + return "LOG"; + } + `, + "Logic/Worker.ts": ` + import DefaultTag, { Info as LogInfo } from "../Framework/Log"; + import * as LogNS from "../Framework/Log"; + + declare function require(this: void, mod: string): any; + const cjson = require("cjson"); + + /** @module_data */ + let count = 0; + + /** @module_data */ + export let activeName = "init"; + + export class Worker { + tag: string; + constructor(tag: string) { + this.tag = tag; + } + Run(): string { + count = count + 1; + activeName = this.tag; + return LogInfo(DefaultTag() + ":" + LogNS.Info(this.tag)) + tostring(cjson); + } + } + `, + }); + + assert.equal(getErrors(result).length, 0, formatDiagnostics(getErrors(result))); + + // 自动产出 Lib/Module.lua 与 Lib/Class.lua + assert.ok(getLuaFile(result, "Lib/Module.lua"), "Expected Lib/Module.lua to be emitted"); + assert.ok(getLuaFile(result, "Lib/Class.lua"), "Expected Lib/Class.lua to be emitted"); + + const workerLua = getLuaFile(result, "Logic/Worker.lua").lua; + assert.match(workerLua, /local ____exports = __module\.env/); + assert.doesNotMatch(workerLua, /return ____exports/); + assert.match(workerLua, /__MODULE__\.Import\("Framework\.Log", __module\)/); + // 保留原生 require("cjson") + assert.match(workerLua, /local cjson = require\("cjson"\)/); + // 顶层纯 TS 类采用扁平全局函数 __TS__DefineClass,且不再从 lualib_bundle 引入 __TS__Class + assert.match(workerLua, /____exports\.Worker = __TS__DefineClass\("Worker", __module\)/); + assert.doesNotMatch(workerLua, /__TS__\.__?Class|____lualib\.__TS__Class/); + // 生成 StashData / RestoreData / UpdateImports + assert.match(workerLua, /function __module\.StashData\(env, to\)/); + assert.match(workerLua, /function __module\.RestoreData\(env, from\)/); + assert.match(workerLua, /function __module\.UpdateImports\(\)/); + assert.match(workerLua, /LogInfo = M__Framework_Log\.Info/); + assert.match(workerLua, /DefaultTag = M__Framework_Log\.default/); +}); + +test("plugin options support emitRuntime: false and moduleSystem: 'standard'", () => { + const noRuntime = transpile( + { "A.ts": `export const x = 1;` }, + { emitRuntime: false } + ); + assert.equal(getErrors(noRuntime).length, 0); + assert.equal(getLuaFile(noRuntime, "Lib/Module.lua"), undefined); + assert.equal(getLuaFile(noRuntime, "Lib/Class.lua"), undefined); + + const standard = transpile( + { + "A.ts": `export function Foo() { return 1; }`, + "B.ts": `import { Foo } from "./A"; export class C { v() { return Foo(); } }`, + }, + { moduleSystem: "standard" } + ); + assert.equal(getErrors(standard).length, 0); + assert.equal(getLuaFile(standard, "Lib/Module.lua"), undefined); + const bLua = getLuaFile(standard, "B.lua").lua; + assert.match(bLua, /local ____exports = \{\}/); + assert.match(bLua, /require\("A"\)/); + assert.match(bLua, /return ____exports/); + assert.doesNotMatch(bLua, /__MODULE__\.Import/); + assert.doesNotMatch(bLua, /__TS__DefineClass/); +}); + +test("diagnostics reject invalid @module_data usage and CommonJS export = in hot-reload mode", () => { + const bad = transpile({ + "Bad.ts": ` + /** @module_data */ + const { a } = { a: 1 }; + void a; + + export function fn() { + /** @module_data */ + let inner = 1; + return inner; + } + `, + "BadCjs.ts": ` + const obj = { x: 1 }; + export = obj; + `, + }); + + const unluaErrors = bad.diagnostics.filter((d) => d.source === "ts2lua-unlua"); + const codes = unluaErrors.map((d) => d.code); + assert.equal( + codes.filter((c) => c === UnLuaDiagnosticCode.InvalidModuleDataUsage).length, + 2, + formatDiagnostics(unluaErrors) + ); + assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenExportEqualsInHotReload)); +}); + +// ============================================================ +// 2. 真实 Lua 5.4 运行时热更端到端验证 +// ============================================================ + +test("Lua 5.4 runtime: single-file Reimport updates downstream named/default/namespace imports and triggers OnDepModuleReimported", () => { + withTempDir((dir) => { + const v1 = transpile({ + "Logic/MathUtil.ts": ` + /** @noSelfInFile */ + export function Add(a: number, b: number): number { + return a + b; + } + export default function Scale(v: number): number { + return v * 2; + } + `, + "Logic/Consumer.ts": ` + /** @noSelfInFile */ + import Scale, { Add } from "./MathUtil"; + import * as MathNS from "./MathUtil"; + + /** @module_data */ + export let notified: string[] = []; + + export function Eval(x: number, y: number): string { + return tostring(Add(x, y)) + ":" + tostring(Scale(x)) + ":" + tostring(MathNS.Add(x, y)); + } + + __module.OnDepModuleReimported = (mname: string) => { + notified[notified.length] = mname + "=" + Eval(3, 4); + }; + `, + }); + assert.equal(getErrors(v1).length, 0, formatDiagnostics(getErrors(v1))); + writeTranspiledToDir(v1, dir); + + const v2Math = transpile({ + "Logic/MathUtil.ts": ` + /** @noSelfInFile */ + export function Add(a: number, b: number): number { + return (a + b) * 10; + } + export default function Scale(v: number): number { + return v * 100; + } + `, + }); + assert.equal(getErrors(v2Math).length, 0); + const mathV2Path = path.join(dir, "Logic", "MathUtil_v2.lua"); + fs.writeFileSync(mathV2Path, getLuaFile(v2Math, "Logic/MathUtil.lua").lua, "utf8"); + + runLuaInDir( + dir, + ` + local consumer = __MODULE__.Import("Logic/Consumer") + assert(__MODULE__.GetModuleByName("Logic.Consumer") == consumer) + assert(consumer.Eval(3, 4) == "7:6:7", "v1 failed: " .. consumer.Eval(3, 4)) + + -- 将 MathUtil.lua 替换为 v2(单文件热更,不重载 Consumer) + local f = assert(io.open("Logic/MathUtil_v2.lua", "rb")) + local v2Code = f:read("a") + f:close() + local fw = assert(io.open("Logic/MathUtil.lua", "wb")) + fw:write(v2Code) + fw:close() + + local ok, err = __MODULE__.ReimportSafely("Logic.MathUtil") + assert(ok, "ReimportSafely failed: " .. tostring(err)) + + -- 命名导入、默认导入、命名空间导入均即时生效 + assert(consumer.Eval(3, 4) == "70:300:70", "v2 failed: " .. consumer.Eval(3, 4)) + -- OnDepModuleReimported 在 UpdateImports 之后触发 + assert(#consumer.notified == 1 and consumer.notified[1] == "Logic.MathUtil=70:300:70", + "notify failed: " .. tostring(consumer.notified[1])) + ` + ); + }); +}); + +test("Lua 5.4 runtime: @module_data preserves local/exported/nil values and keeps initializer for newly added @module_data", () => { + withTempDir((dir) => { + const v1 = transpile({ + "State/Store.ts": ` + /** @noSelfInFile */ + /** @module_data */ + let counter = 1; + /** @module_data */ + const cache: Record = {}; + /** @module_data */ + export let activeTag = "v1"; + /** @module_data */ + let nullable: string | undefined = "present"; + + let ephemeral = "reset-v1"; + + export function Mutate(): void { + counter = 42; + cache["k"] = 99; + activeTag = "mutated"; + nullable = undefined; + ephemeral = "changed"; + } + export function Read() { + return { counter, cache, activeTag, nullable, ephemeral }; + } + `, + }); + assert.equal(getErrors(v1).length, 0, formatDiagnostics(getErrors(v1))); + writeTranspiledToDir(v1, dir); + + const v2 = transpile({ + "State/Store.ts": ` + /** @noSelfInFile */ + /** @module_data */ + let counter = 1; + /** @module_data */ + const cache: Record = {}; + /** @module_data */ + export let activeTag = "v2-default"; + /** @module_data */ + let nullable: string | undefined = "should-stay-nil"; + /** @module_data */ + let addedInV2 = 777; + + let ephemeral = "reset-v2"; + + export function ReadV2() { + return { counter, cache, activeTag, nullable, addedInV2, ephemeral }; + } + `, + }); + assert.equal(getErrors(v2).length, 0, formatDiagnostics(getErrors(v2))); + fs.writeFileSync(path.join(dir, "State", "Store_v2.lua"), getLuaFile(v2, "State/Store.lua").lua, "utf8"); + + runLuaInDir( + dir, + ` + local store = __MODULE__.Import("State.Store") + store.Mutate() + local s1 = store.Read() + assert(s1.counter == 42 and s1.cache.k == 99 and s1.activeTag == "mutated" and store.activeTag == "mutated" and s1.nullable == nil and s1.ephemeral == "changed") + + local f = assert(io.open("State/Store_v2.lua", "rb")) + local code = f:read("a"); f:close() + local fw = assert(io.open("State/Store.lua", "wb")) + fw:write(code); fw:close() + + local ok, err = __MODULE__.ReimportSafely("State.Store") + assert(ok, tostring(err)) + + local s2 = store.ReadV2() + assert(s2.counter == 42, "counter not preserved: " .. tostring(s2.counter)) + assert(s2.cache == s1.cache and s2.cache.k == 99, "cache table identity not preserved") + assert(s2.activeTag == "mutated" and store.activeTag == "mutated", "exported @module_data not preserved") + assert(s2.nullable == nil, "nil @module_data was overwritten: " .. tostring(s2.nullable)) + assert(s2.addedInV2 == 777, "newly added @module_data was clobbered: " .. tostring(s2.addedInV2)) + assert(s2.ephemeral == "reset-v2", "non-@module_data should reset") + ` + ); + }); +}); + +test("Lua 5.4 runtime: Lib/Class.lua hot-reloads pure TS base & child classes preserving instances, inheritance, instanceof, and cleaning removed methods", () => { + withTempDir((dir) => { + const v1 = transpile({ + "Logic/Animal.ts": ` + export class Animal { + name: string; + constructor(name: string) { + this.name = name; + } + Speak(): string { + return "v1:" + this.name; + } + LegacyMethod(): string { + return "legacy"; + } + } + `, + "Logic/Dog.ts": ` + import { Animal } from "./Animal"; + export class Dog extends Animal { + Speak(): string { + return "dog(" + super.Speak() + ")"; + } + } + export function MakePair(this: void) { + const a = new Animal("Cat"); + const d = new Dog("Rex"); + return { a, d }; + } + export function CheckInstanceOf(this: void, a: unknown, d: unknown): boolean { + return a instanceof Animal && d instanceof Dog && d instanceof Animal; + } + `, + }); + assert.equal(getErrors(v1).length, 0, formatDiagnostics(getErrors(v1))); + writeTranspiledToDir(v1, dir); + + const v2Animal = transpile({ + "Logic/Animal.ts": ` + export class Animal { + name: string; + constructor(name: string) { + this.name = name; + } + Speak(): string { + return "v2:" + this.name; + } + Shout(): string { + return "SHOUT:" + this.name; + } + } + `, + }); + assert.equal(getErrors(v2Animal).length, 0); + fs.writeFileSync( + path.join(dir, "Logic", "Animal_v2.lua"), + getLuaFile(v2Animal, "Logic/Animal.lua").lua, + "utf8" + ); + + runLuaInDir( + dir, + ` + local dogMod = __MODULE__.Import("Logic.Dog") + local animalMod = __MODULE__.GetModuleByName("Logic.Animal") + local oldClass = animalMod.Animal + local oldProto = oldClass.prototype + + local pair = dogMod.MakePair() + assert(pair.a:Speak() == "v1:Cat") + assert(pair.d:Speak() == "dog(v1:Rex)") + assert(pair.a:LegacyMethod() == "legacy") + assert(dogMod.CheckInstanceOf(pair.a, pair.d) == true) + + -- 仅热更父类 Animal.lua + local f = assert(io.open("Logic/Animal_v2.lua", "rb")) + local code = f:read("a"); f:close() + local fw = assert(io.open("Logic/Animal.lua", "wb")) + fw:write(code); fw:close() + + local ok, err = __MODULE__.ReimportSafely("Logic.Animal") + assert(ok, tostring(err)) + + -- 类表与原型表引用完全复用 + assert(animalMod.Animal == oldClass) + assert(animalMod.Animal.prototype == oldProto) + -- 已有父类与子类实例立即生效 + assert(pair.a:Speak() == "v2:Cat", "base instance not updated: " .. pair.a:Speak()) + assert(pair.d:Speak() == "dog(v2:Rex)", "child super call not updated: " .. pair.d:Speak()) + assert(pair.a:Shout() == "SHOUT:Cat") + assert(pair.d:Shout() == "SHOUT:Rex") + -- 已删除方法已清理 + assert(pair.a.LegacyMethod == nil, "removed method should be nil") + assert(pair.d.LegacyMethod == nil, "removed inherited method should be nil") + -- instanceof 依然为 true + assert(dogMod.CheckInstanceOf(pair.a, pair.d) == true) + ` + ); + }); +}); + +test("Lua 5.4 runtime: barrel re-exports (export { ... } from & export * from) cascade hot-reload without corrupting __module", () => { + withTempDir((dir) => { + const v1 = transpile({ + "Core/Calc.ts": ` + /** @noSelfInFile */ + export function Compute(n: number): number { return n + 1; } + `, + "Core/Extra.ts": ` + /** @noSelfInFile */ + export const TAG = "v1-tag"; + export function Format(s: string): string { return "[" + s + "]"; } + `, + "Core/index.ts": ` + export { Compute } from "./Calc"; + export * from "./Extra"; + `, + "App/Main.ts": ` + /** @noSelfInFile */ + import { Compute, TAG, Format } from "../Core/index"; + export function Run(n: number): string { + return Format(TAG + ":" + tostring(Compute(n))); + } + `, + }); + assert.equal(getErrors(v1).length, 0, formatDiagnostics(getErrors(v1))); + writeTranspiledToDir(v1, dir); + + const v2Calc = transpile({ + "Core/Calc.ts": ` + /** @noSelfInFile */ + export function Compute(n: number): number { return n * 100; } + `, + }); + const v2Extra = transpile({ + "Core/Extra.ts": ` + /** @noSelfInFile */ + export const TAG = "v2-tag"; + export function Format(s: string): string { return "<" + s + ">"; } + `, + }); + fs.writeFileSync(path.join(dir, "Core", "Calc_v2.lua"), getLuaFile(v2Calc, "Core/Calc.lua").lua, "utf8"); + fs.writeFileSync(path.join(dir, "Core", "Extra_v2.lua"), getLuaFile(v2Extra, "Core/Extra.lua").lua, "utf8"); + + runLuaInDir( + dir, + ` + local app = __MODULE__.Import("App.Main") + local barrel = __MODULE__.GetModuleByName("Core.index") + assert(barrel.__module.name == "Core.index", "export * corrupted __module!") + assert(app.Run(5) == "[v1-tag:6]", "v1 failed: " .. app.Run(5)) + + local function overwrite(src, dst) + local f = assert(io.open(src, "rb")) + local c = f:read("a"); f:close() + local fw = assert(io.open(dst, "wb")) + fw:write(c); fw:close() + end + + overwrite("Core/Calc_v2.lua", "Core/Calc.lua") + assert(__MODULE__.ReimportSafely("Core.Calc")) + assert(app.Run(5) == "[v1-tag:500]", "calc cascade failed: " .. app.Run(5)) + + overwrite("Core/Extra_v2.lua", "Core/Extra.lua") + assert(__MODULE__.ReimportSafely("Core.Extra")) + assert(app.Run(5) == "", "extra star cascade failed: " .. app.Run(5)) + assert(barrel.__module.name == "Core.index", "export * reload corrupted __module!") + ` + ); + }); +}); + +test("Lua 5.4 runtime: circular imports, lifecycle order, failure safety, and all 5 gamelogic defect fixes", () => { + withTempDir((dir) => { + const res = transpile({ + "Cycle/A.ts": ` + /** @noSelfInFile */ + import { GetB } from "./B"; + export const VAL_A = 42; + export function ReadViaB(): number { + return GetB(); + } + `, + "Cycle/B.ts": ` + /** @noSelfInFile */ + import { VAL_A } from "./A"; + export function GetB(): number { + return VAL_A; + } + `, + }); + assert.equal(getErrors(res).length, 0); + writeTranspiledToDir(res, dir); + + runLuaInDir( + dir, + ` + -- 1. 循环依赖回填验证 + local a = __MODULE__.Import("Cycle.A") + assert(a.ReadViaB() == 42, "circular import failed: " .. tostring(a.ReadViaB())) + -- Defect #2: 成功后清理 loadingModuleTbl + assert(__MODULE__.loadingModuleTbl["Cycle.A"] == nil) + assert(__MODULE__.loadingModuleTbl["Cycle.B"] == nil) + + -- 2. Defect #1: waiting refresh 传入 module.env + local function makeLoader(src, p, h) + return function(name, env) + local chunk, err = load(src, p or ("@" .. name .. ".lua"), nil, env) + assert(chunk, err) + return chunk, p or ("@" .. name .. ".lua"), h + end + end + + __MODULE__.RegistryModuleLoader("wait.a", makeLoader([[ + b = __MODULE__.Import("wait.b", __module) + value = 10 + ]], "@wait/a.lua")) + __MODULE__.RegistryModuleLoader("wait.b", makeLoader([[ + local wa = __MODULE__.Import("wait.a", __module) + __module.UpdateImports = function(M) + receivedEnv = (M == _ENV) + seen = wa.value + end + ]], "@wait/b.lua")) + local wa = __MODULE__.Import("wait.a") + assert(wa.b.seen == 10, "waiting seen failed") + assert(wa.b.receivedEnv == true, "Defect #1 regression: UpdateImports did not receive module.env") + + -- 3. Defect #3 & #2: nil-path loader 报错且不残留半初始化模块,重试可成功 + local okNil, errNil = pcall(__MODULE__.Import, "defect.retry", nil, function() + return function() end + end) + assert(not okNil and string.find(tostring(errNil), "cannot found module file at", 1, true)) + assert(__MODULE__.loadingModuleTbl["defect.retry"] == nil) + local recovered = __MODULE__.Import("defect.retry", nil, makeLoader("value = 5", "@defect/retry.lua")) + assert(recovered.value == 5 and __MODULE__.GetModuleByName("defect.retry") == recovered) + + -- 4. Defect #4: 最长 Pattern Loader 优先 + __MODULE__.RegistryModuleLoader("^pkg%.", makeLoader('origin = "short"', "@pattern/short.lua")) + __MODULE__.RegistryModuleLoader("^pkg%.sub%.", makeLoader('origin = "long"', "@pattern/long.lua")) + assert(__MODULE__.Import("pkg.sub.item").origin == "long", "Defect #4 regression: longest pattern did not win") + + -- 5. 失败热更不破坏旧模块 + IsReimporting 生命周期验证 + _G.__TEST_TRACE = {} + local lm = __MODULE__.Import("life.order", nil, makeLoader([[ + __TEST_TRACE[#__TEST_TRACE + 1] = "chunk" + val = 10 + __module.UpdateImports = function() __TEST_TRACE[#__TEST_TRACE + 1] = "imports" end + __module.UpdateExports = function() __TEST_TRACE[#__TEST_TRACE + 1] = "exports" end + __module.StashData = function(M, d) __TEST_TRACE[#__TEST_TRACE + 1] = "stash"; d.val = M.val end + __module.OnImport = function() __TEST_TRACE[#__TEST_TRACE + 1] = "import:" .. tostring(__MODULE__.IsReimporting(__module)) end + ]], "@life/order.lua")) + assert(table.concat(__TEST_TRACE, ",") == "chunk,imports,exports,stash,import:false,exports", + "unexpected initial order: " .. table.concat(__TEST_TRACE, ",")) + + -- 语法/加载失败的 ReimportSafely 不破坏旧模块 + local okFail, failErr = __MODULE__.ReimportSafely("@life/order.lua", function() + return nil, "broken replacement" + end) + assert(okFail == false and failErr == "broken replacement") + assert(lm.val == 10) + + -- 正常按 @path Reimport + _G.__TEST_TRACE = {} + local okReload, reloadErr = __MODULE__.ReimportSafely("@life/order.lua", makeLoader([[ + __TEST_TRACE[#__TEST_TRACE + 1] = "chunk:" .. tostring(__MODULE__.IsReimporting(__module)) + val = 0 + __module.RestoreData = function(M, d) __TEST_TRACE[#__TEST_TRACE + 1] = "restore"; M.val = d.val + 1 end + __module.UpdateImports = function() __TEST_TRACE[#__TEST_TRACE + 1] = "imports" end + __module.UpdateExports = function() __TEST_TRACE[#__TEST_TRACE + 1] = "exports" end + __module.OnReimport = function() __TEST_TRACE[#__TEST_TRACE + 1] = "reimport:" .. tostring(__MODULE__.IsReimporting()) end + ]], "@life/order.lua")) + assert(okReload, tostring(reloadErr)) + assert(lm.val == 11) + assert(__MODULE__.IsReimporting() == false) + assert(table.concat(__TEST_TRACE, ",") == "stash,chunk:true,restore,imports,exports,reimport:true", + "unexpected reload order: " .. table.concat(__TEST_TRACE, ",")) + + -- 6. Defect #5: 移除依赖后不再收到旧依赖的热更通知 + local depA = __MODULE__.Import("dep.a", nil, makeLoader("v = 1", "@dep/a.lua")) + local depCalls = 0 + local user = __MODULE__.Import("dep.user", nil, makeLoader([[ + local a = __MODULE__.Import("dep.a", __module) + __module.OnDepModuleReimported = function() depCalls = depCalls + 1 end + ]], "@dep/user.lua")) + -- 热更 user 移除对 dep.a 的导入 + assert(__MODULE__.ReimportSafely("dep.user", makeLoader([[ + __module.OnDepModuleReimported = function() _G.__STALE_CALLED = true end + ]], "@dep/user.lua"))) + assert(__MODULE__.ReimportSafely("dep.a", makeLoader("v = 2", "@dep/a.lua"))) + assert(_G.__STALE_CALLED == nil, "Defect #5 regression: removed dependency still triggered notification") + ` + ); + }); +}); + +test("Lua 5.4 runtime: default-exported class hot-reload, side-effect import, two-step re-export, and native require()", () => { + withTempDir((dir) => { + const v1 = transpile({ + "Init/SideEffect.ts": ` + /** @noSelfInFile */ + export const loaded = true; + (_G as any).__SIDE_EFFECT_RAN = ((_G as any).__SIDE_EFFECT_RAN ?? 0) + 1; + `, + "Logic/DefaultCls.ts": ` + export default class Greeter { + who: string; + constructor(who: string) { this.who = who; } + Hello(): string { return "hi:" + this.who; } + } + `, + "Logic/ReexportStep.ts": ` + import Greeter from "./DefaultCls"; + export { Greeter }; + `, + "Logic/Entry.ts": ` + /** @noSelfInFile */ + import "../Init/SideEffect"; + import { Greeter } from "./ReexportStep"; + const nativeLib = require("native_mock_plugin") as { ping(this: void): string }; + export function Make(who: string) { + return new Greeter(who); + } + export function NativePing(): string { + return nativeLib.ping(); + } + `, + }); + assert.equal(getErrors(v1).length, 0, formatDiagnostics(getErrors(v1))); + writeTranspiledToDir(v1, dir); + + const v2Cls = transpile({ + "Logic/DefaultCls.ts": ` + export default class Greeter { + who: string; + constructor(who: string) { this.who = who; } + Hello(): string { return "WELCOME:" + this.who; } + } + `, + }); + assert.equal(getErrors(v2Cls).length, 0, formatDiagnostics(getErrors(v2Cls))); + fs.writeFileSync( + path.join(dir, "Logic", "DefaultCls_v2.lua"), + getLuaFile(v2Cls, "Logic/DefaultCls.lua").lua, + "utf8" + ); + + runLuaInDir( + dir, + ` + package.preload["native_mock_plugin"] = function() + return { ping = function() return "pong" end } + end + + local entry = __MODULE__.Import("Logic.Entry") + assert(_G.__SIDE_EFFECT_RAN == 1, "side-effect import did not execute") + assert(entry.NativePing() == "pong") + + local g = entry.Make("UE") + assert(g:Hello() == "hi:UE") + + local f = assert(io.open("Logic/DefaultCls_v2.lua", "rb")) + local code = f:read("a"); f:close() + local fw = assert(io.open("Logic/DefaultCls.lua", "wb")) + fw:write(code); fw:close() + + assert(__MODULE__.ReimportSafely("Logic.DefaultCls")) + assert(g:Hello() == "WELCOME:UE", "default-exported class instance did not hot-reload: " .. g:Hello()) + local g2 = entry.Make("Hot") + assert(g2:Hello() == "WELCOME:Hot") + ` + ); + }); +}); diff --git a/test/plugin.test.mjs b/test/plugin.test.mjs index 287589d..b2e3dee 100644 --- a/test/plugin.test.mjs +++ b/test/plugin.test.mjs @@ -15,6 +15,8 @@ const luaBin = ["lua5.4", "lua"].find((cmd) => { const projectRoot = path.resolve(import.meta.dirname, ".."); const unluaTypesPath = path.join(projectRoot, "types", "unlua.d.ts"); const unluaTypesContent = fs.readFileSync(unluaTypesPath, "utf8"); +const moduleTypesPath = path.join(projectRoot, "types", "module.d.ts"); +const moduleTypesContent = fs.readFileSync(moduleTypesPath, "utf8"); const pluginPath = path.join(projectRoot, "dist", "plugin", "index.js"); const { UnLuaDiagnosticCode } = require(pluginPath); @@ -48,6 +50,7 @@ declare namespace UE { function transpileWithUnLua(files) { const virtualFiles = { "unlua.d.ts": unluaTypesContent, + "module.d.ts": moduleTypesContent, "ue.generated.d.ts": VIRTUAL_UE_REFLECTION_DTS, ...files, }; diff --git a/types/module.d.ts b/types/module.d.ts new file mode 100644 index 0000000..1f9ab93 --- /dev/null +++ b/types/module.d.ts @@ -0,0 +1,175 @@ +/** + * ts2lua-unreal 自定义模块化与单文件运行时热更系统类型声明。 + * 对应运行时基础库:`Lib/Module.lua`(_G.__MODULE__)与 `Lib/Class.lua`(_G.__TS__DefineClass)。 + */ + +declare namespace __MODULE__ { + interface Module extends Record { + __module: ModuleMeta; + } + + type ModuleChunkFunction = (this: void) => void; + + type LoadModuleFileFunc = ( + this: void, + modname: string + ) => LuaMultiReturn<[string | undefined, string, string | undefined]>; + + type LoadModuleChunkFunc = ( + this: void, + modname: string, + env: any + ) => LuaMultiReturn<[ModuleChunkFunction | undefined, string, string | undefined]>; + + interface ModuleMeta { + name: string; + imports: Record; + env: Module; + + /** 该模块当前是否处于 Reimport 流程中(由模块系统维护,业务只读)。 */ + readonly reimporting?: boolean; + + /** 是否包含再导出(Barrel 模块标记,由编译器自动设置)。 */ + hasReexports?: boolean; + + filepath?: string; + hash?: string; + + modulefunc?: ModuleChunkFunction; + UpdateExports?: (this: void, env: Module) => void; + UpdateImports?: (this: void, env?: Module) => void; + StashData?: (this: void, env: Module, to: Record) => void; + RestoreData?: (this: void, env: Module, from: Record) => void; + + /** 当模块首次加载完成后回调;热更时不会再次回调。 */ + OnImport?(this: void): void; + + /** 当模块被 Reimport 热更完成后回调;首次加载时不会回调。 */ + OnReimport?(this: void): void; + + /** + * 当本模块直接依赖的某个模块热更完成且本模块 UpdateImports 刷新完毕后回调。 + * @param mname 已热更完成的依赖模块全名(如 `"Framework.Log"`) + */ + OnDepModuleReimported?(this: void, mname: string): void; + } + + interface ModuleConfig { + Errorf?: (this: void, fmt: string, ...args: any[]) => void; + Infof?: (this: void, fmt: string, ...args: any[]) => void; + } + + interface ModuleProfileConfig { + GetTime?: (this: void) => number; + ProfileBeginSample?: (this: void, key: string) => void; + ProfileEndSample?: (this: void) => void; + } + + /** 任意模块首次加载完成后的全局回调 */ + let OnModuleLoaded: ((this: void, modname: string) => void) | undefined; + + /** @noSelf */ + function Import( + modname: string, + callerModule?: ModuleMeta, + loadModuleChunk?: LoadModuleChunkFunc + ): T; + + /** + * 重新加载(单文件热更)已加载模块。 + * @param pathOrName 以 `@` 开头按模块路径查找,否则按模块全名查找 + * @param loadModuleChunk 可选自定义 chunk 加载器 + * @noSelf + */ + function Reimport( + pathOrName: string, + loadModuleChunk?: LoadModuleChunkFunc + ): LuaMultiReturn<[Module | undefined, string | undefined]>; + + /** + * 与 Reimport 相同但不抛异常,返回 `(ok, err)`。 + * @noSelf + */ + function ReimportSafely( + pathOrName: string, + loadModuleChunk?: LoadModuleChunkFunc + ): LuaMultiReturn<[boolean, any]>; + + /** + * 查询是否处于热更中:不传参查全局,传入 `__module` 仅查当前模块。 + * @noSelf + */ + function IsReimporting(meta?: ModuleMeta): boolean; + + /** @noSelf */ + function GetModuleByName(modname: string): Module | undefined; + + /** @noSelf */ + function GetModuleByPath(modpath: string): Module | undefined; + + /** @noSelf */ + function GetAllModulePaths(): Record; + + /** @noSelf */ + function AllLoadedModules(): Record; + + /** @noSelf */ + function SetSystemMeta(key: string, value: any): void; + + /** @noSelf */ + function GetSystemMeta(key: string): any; + + /** @noSelf */ + function ModuleNameToPath(modname: string): string; + + /** @noSelf */ + function OnLoadModuleFileDefault( + modname: string + ): LuaMultiReturn<[string | undefined, string, string | undefined]>; + + /** @noSelf */ + function OnLoadModuleChunkDefault( + modname: string, + env: any + ): LuaMultiReturn<[ModuleChunkFunction | undefined, string, string | undefined]>; + + /** @noSelf */ + function LoadModuleFile( + modname: string + ): LuaMultiReturn<[string | undefined, string, string | undefined]>; + + /** @noSelf */ + function LoadModuleChunk( + modname: string, + env: any + ): LuaMultiReturn<[ModuleChunkFunction | undefined, string, string | undefined]>; + + /** @noSelf */ + function LoadModuleChunkFromString( + modname: string, + data: string, + chunkname: string, + env: any + ): ModuleChunkFunction; + + /** @noSelf */ + function RegistryModuleLoader(modpattern: string, loader: LoadModuleChunkFunc): void; + + /** @noSelf */ + function SetOnLoadModuleFile(func: LoadModuleFileFunc): void; + + /** @noSelf */ + function SetOnLoadModuleChunk(func: LoadModuleChunkFunc): void; + + /** @noSelf */ + function Config(args: ModuleConfig): void; + + /** @noSelf */ + function SetProfile(args: ModuleProfileConfig): void; + + /** @noSelf */ + function GetImportingStack(maybeLoopPos?: number): string; +} + +/** 当前模块元信息对象(位于模块隔离 _ENV 中,可用于挂载 OnImport / OnReimport / OnDepModuleReimported) */ +declare const __module: __MODULE__.ModuleMeta; diff --git a/types/unlua.d.ts b/types/unlua.d.ts index 2df1e42..5c7a61f 100644 --- a/types/unlua.d.ts +++ b/types/unlua.d.ts @@ -1,3 +1,5 @@ +/// + /** * ts2lua-unreal + UnLua 核心运行时编译期类型声明(零冲突层)。 *