local fs = vim.fs
local uv = vim.uv
local uri_encode = vim.uri_encode
local loaders = package.loaders
local _loadfile = loadfile
local VERSION = 4
local M = {}
M.path = vim.fn.stdpath('cache') .. '/luac'
M.enabled = false
local stats = { find = { total = 0, time = 0, not_found = 0 } }
local fs_stat_cache
local indexed = {}
local function fs_stat_cached(path)
if not fs_stat_cache then
return (uv.fs_stat(path))
end
if not fs_stat_cache[path] then
fs_stat_cache[path] = uv.fs_stat(path)
end
return fs_stat_cache[path]
end
local function normalize(path)
return fs.normalize(path, { expand_env = false, _fast = true })
end
local rtp_cached = {}
local rtp_cache_key
local function get_rtp()
if vim.in_fast_event() then
return (rtp_cached or {}), false
end
local updated = false
local key = vim.go.rtp
if key ~= rtp_cache_key then
rtp_cached = {}
for _, path in ipairs(vim.api.nvim_get_runtime_file('', true)) do
path = normalize(path)
if
path:sub(-6, -1) ~= '/after'
and not (indexed[path] and vim.tbl_isempty(indexed[path]))
then
rtp_cached[#rtp_cached + 1] = path
end
end
updated = true
rtp_cache_key = key
end
return rtp_cached, updated
end
local function cache_filename(name)
local ret = ('%s/%s'):format(M.path, uri_encode(name, 'rfc2396'))
return ret:sub(-4) == '.lua' and (ret .. 'c') or (ret .. '.luac')
end
local function write_cachefile(cname, hash, chunk)
local f = assert(uv.fs_open(cname, 'w', 438))
local header = {
VERSION,
hash.size,
hash.mtime.sec,
hash.mtime.nsec,
}
uv.fs_write(f, table.concat(header, ',') .. '\0')
uv.fs_write(f, string.dump(chunk))
uv.fs_close(f)
end
local function readfile(path, mode)
local f = uv.fs_open(path, 'r', mode)
if f then
local size = assert(uv.fs_fstat(f)).size
local data = uv.fs_read(f, size, 0)
uv.fs_close(f)
return data
end
end
local function read_cachefile(cname)
local data = readfile(cname, 438)
if not data then
return
end
local zero = data:find('\0', 1, true)
if not zero then
return
end
local header = vim.split(data:sub(1, zero - 1), ',')
if tonumber(header[1]) ~= VERSION then
return
end
local hash = {
size = tonumber(header[2]),
mtime = { sec = tonumber(header[3]), nsec = tonumber(header[4]) },
}
local chunk = data:sub(zero + 1)
return hash, chunk
end
local function loader_cached(modname)
fs_stat_cache = {}
local ret = M.find(modname)[1]
if ret then
local chunk, err = loadfile(ret.modpath)
fs_stat_cache = nil
return chunk or error(err)
end
fs_stat_cache = nil
return ("\n\tcache_loader: module '%s' not found"):format(modname)
end
local is_win = vim.fn.has('win32') == 1
local function loader_lib_cached(modname)
local ret = M.find(modname, { patterns = { is_win and '.dll' or '.so' } })[1]
if not ret then
return ("\n\tcache_loader_lib: module '%s' not found"):format(modname)
end
local dash = modname:find('-', 1, true)
local funcname = dash and modname:sub(dash + 1) or modname
local chunk, err = package.loadlib(ret.modpath, 'luaopen_' .. funcname:gsub('%.', '_'))
return chunk or error(err)
end
local function hash_eq(a, b)
return a
and b
and a.size == b.size
and a.mtime.sec == b.mtime.sec
and a.mtime.nsec == b.mtime.nsec
end
local function loadfile_cached(filename, mode, env)
local modpath = normalize(filename)
local stat = fs_stat_cached(modpath)
local cname = cache_filename(modpath)
if stat then
local e_hash, e_chunk = read_cachefile(cname)
if hash_eq(e_hash, stat) and e_chunk then
local chunk, err = load(e_chunk, '@' .. modpath, mode, env)
if not (err and err:find('cannot load incompatible bytecode', 1, true)) then
return chunk, err
end
end
end
local chunk, err = _loadfile(modpath, mode, env)
if chunk and stat then
write_cachefile(cname, stat, chunk)
end
return chunk, err
end
local function lsmod(path)
if not indexed[path] then
indexed[path] = {}
for name, t in fs.dir(path .. '/lua') do
local modpath = path .. '/lua/' .. name
t = t or fs_stat_cached(modpath).type
local topname
local ext = name:sub(-4)
if ext == '.lua' or ext == '.dll' then
topname = name:sub(1, -5)
elseif name:sub(-3) == '.so' then
topname = name:sub(1, -4)
elseif t == 'link' or t == 'directory' then
topname = name
end
if topname then
indexed[path][topname] = { modpath = modpath, modname = topname }
end
end
end
return indexed[path]
end
function M.find(modname, opts)
opts = opts or {}
modname = modname:gsub('/', '.')
local basename = modname:gsub('%.', '/')
local idx = modname:find('.', 1, true)
if idx == 1 then
modname = modname:gsub('^%.+', '')
basename = modname:gsub('%.', '/')
idx = modname:find('.', 1, true)
end
local topmod = idx and modname:sub(1, idx - 1) or modname
local patterns = opts.patterns
or (topmod == modname and { '/init.lua', '.lua' } or { '.lua', '/init.lua' })
for p, pattern in ipairs(patterns) do
patterns[p] = '/lua/' .. basename .. pattern
end
local results = {}
local function continue()
return #results == 0 or opts.all
end
local function _find(paths)
for _, path in ipairs(paths) do
if topmod == '*' then
for _, r in pairs(lsmod(path)) do
results[#results + 1] = r
if not continue() then
return
end
end
elseif lsmod(path)[topmod] then
for _, pattern in ipairs(patterns) do
local modpath = path .. pattern
stats.find.stat = (stats.find.stat or 0) + 1
local stat = fs_stat_cached(modpath)
if stat then
results[#results + 1] = { modpath = modpath, stat = stat, modname = modname }
if not continue() then
return
end
end
end
end
end
end
if opts.rtp ~= false then
_find(rtp_cached or {})
if continue() then
local rtp, updated = get_rtp()
if updated then
_find(rtp)
end
end
end
if continue() and opts.paths then
_find(opts.paths)
end
if #results == 0 then
stats.find.not_found = stats.find.not_found + 1
end
return results
end
function M.reset(path)
if path then
indexed[normalize(path)] = nil
else
indexed = {}
end
if fs_stat_cache then
fs_stat_cache = {}
end
end
function M.enable(enable)
enable = enable == nil and true or enable
if enable == M.enabled then
return
end
M.enabled = enable
if enable then
vim.fn.mkdir(vim.fn.fnamemodify(M.path, ':p'), 'p')
_G.loadfile = loadfile_cached
table.insert(loaders, 2, loader_cached)
table.insert(loaders, 3, loader_lib_cached)
for l, loader in ipairs(loaders) do
if loader == vim._load_package then
table.remove(loaders, l)
break
end
end
else
_G.loadfile = _loadfile
for l, loader in ipairs(loaders) do
if loader == loader_cached or loader == loader_lib_cached then
table.remove(loaders, l)
end
end
table.insert(loaders, 2, vim._load_package)
end
end
function M.disable()
vim.deprecate('vim.loader.disable', 'vim.loader.enable(false)', '0.12')
vim.loader.enable(false)
end
local function track(stat, f)
return function(...)
local start = uv.hrtime()
local r = { f(...) }
stats[stat] = stats[stat] or { total = 0, time = 0 }
stats[stat].total = stats[stat].total + 1
stats[stat].time = stats[stat].time + uv.hrtime() - start
return unpack(r, 1, table.maxn(r))
end
end
function M._profile(opts)
get_rtp = track('get_rtp', get_rtp)
read_cachefile = track('read', read_cachefile)
loader_cached = track('loader', loader_cached)
loader_lib_cached = track('loader_lib', loader_lib_cached)
loadfile_cached = track('loadfile', loadfile_cached)
M.find = track('find', M.find)
lsmod = track('lsmod', lsmod)
if opts and opts.loaders then
for l, loader in pairs(loaders) do
local loc = debug.getinfo(loader, 'Sn').source:sub(2)
loaders[l] = track('loader ' .. l .. ': ' .. loc, loader)
end
end
end
function M._inspect(opts)
if opts and opts.print then
local function ms(nsec)
return math.floor(nsec / 1e6 * 1000 + 0.5) / 1000 .. 'ms'
end
local chunks = {}
for _, stat in vim.spairs(stats) do
vim.list_extend(chunks, {
{ '\n' .. stat .. '\n', 'Title' },
{ '* total: ' },
{ tostring(stat.total) .. '\n', 'Number' },
{ '* time: ' },
{ ms(stat.time) .. '\n', 'Bold' },
{ '* avg time: ' },
{ ms(stat.time / stat.total) .. '\n', 'Bold' },
})
for k, v in pairs(stat) do
if not vim.list_contains({ 'time', 'total' }, k) then
chunks[#chunks + 1] = { '* ' .. k .. ':' .. string.rep(' ', 9 - #k) }
chunks[#chunks + 1] = { tostring(v) .. '\n', 'Number' }
end
end
end
vim.api.nvim_echo(chunks, true, {})
end
return stats
end
return M