Files
UnrealLuaDemo/Script/lua/lib/module.lua
T

650 lines
17 KiB
Lua

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__