release: v0.3.0 add single-file hot-reload module system (Lib/Module.lua & Lib/Class.lua)

This commit is contained in:
szy73711 committed 2026-11-30 02:42:22 +08:00
1 parent cb1539d738
commit b1a53d8660
19 files changed
+2954 -13

No files matched your search

+4
View File
@@ -30,6 +30,10 @@ export enum UnLuaDiagnosticCode {
InvalidUnLuaDecoratorArgs = 90108,
UnLuaMultipleClassesInFile = 90109,
UnLuaForbiddenSuperUsage = 90110,
// 4.x 模块化与热更系统约束 (90201 - 90299)
InvalidModuleDataUsage = 90201,
ForbiddenExportEqualsInHotReload = 90202,
}
export function createUnLuaDiagnostic(
+87 -6
View File
@@ -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";
+903
View File
@@ -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<string, string>;
usedAliases: Set<string>;
/** 需插入文件头部的 __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<string, string[]>;
/** 模块顶层 @module_data 变量 */
moduleDataEntries: ModuleDataEntry[];
/** 记录哪些本地变量名来自 __MODULE__.Import 命名/默认解包 */
importedLocalNames: Set<string>;
/** 是否替换过顶层类为 __TS__DefineClass */
replacedTopLevelClass: boolean;
/** 是否存在未替换的匿名/函数内类仍需 lualib.__TS__Class */
usedRawTstlClass: boolean;
}
const fileModuleStates = new WeakMap<ts.SourceFile, FileModuleState>();
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/<fileName>
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),
});
}
}
+169
View File
@@ -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<string>([
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>): 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;
}
+6
View File
@@ -9,6 +9,7 @@ import {
resolveSuperClass,
SuperClassResolution,
} from "./type-utils";
import { getFileModuleState } from "./module-transform";
const SCOPE_TYPE_FUNCTION = 2 as Parameters<tstl.TransformationContext["pushScope"]>[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)])
);
+53
View File
@@ -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)。
*/