robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
15.2 KiB543 linesraw
1local fs = vim.fs -- "vim.fs" is a dependency, so must be loaded early.
2local uv = vim.uv
3local uri_encode = vim.uri_encode --- @type function
4
5--- @type (fun(modename: string): fun()|string)[]
6local loaders = package.loaders
7local _loadfile = loadfile
8
9local VERSION = 4
10local is_appimage = (os.getenv('APPIMAGE') ~= nil)
11
12local M = {}
13
14--- @alias vim.loader.CacheHash {mtime: {nsec: integer, sec: integer}, size: integer, type?: string}
15--- @alias vim.loader.CacheEntry {hash:vim.loader.CacheHash, chunk:string}
16
17--- @class vim.loader.find.Opts
18--- @inlinedoc
19---
20--- Search for modname in the runtime path.
21--- (default: `true`)
22--- @field rtp? boolean
23---
24--- Extra paths to search for modname
25--- (default: `{}`)
26--- @field paths? string[]
27---
28--- List of patterns to use when searching for modules.
29--- A pattern is a string added to the basename of the Lua module being searched.
30--- (default: `{"/init.lua", ".lua"}`)
31--- @field patterns? string[]
32---
33--- Search for all matches.
34--- (default: `false`)
35--- @field all? boolean
36
37--- @class vim.loader.ModuleInfo
38--- @inlinedoc
39---
40--- Path of the module
41--- @field modpath string
42---
43--- Name of the module
44--- @field modname string
45---
46--- The fs_stat of the module path. Won't be returned for `modname="*"`
47--- @field stat? uv.fs_stat.result
48
49--- @class (private) vim.loader.Stats
50--- @field [string] {total:number, time:number, [string]:number?}?>
51--- @field find {total:number, time:number, not_found:number, stat?:number}
52
53--- @private
54M.path = vim.fn.stdpath('cache') .. '/luac'
55
56--- @private
57M.enabled = false
58
59--- @type vim.loader.Stats
60local stats = { find = { total = 0, time = 0, not_found = 0 } }
61
62--- @type table<string, uv.fs_stat.result>?
63local fs_stat_cache
64
65--- @type table<string, table<string,vim.loader.ModuleInfo>?>
66local indexed = {}
67
68--- @param path string
69--- @return uv.fs_stat.result?
70local function fs_stat_cached(path)
71  if not fs_stat_cache then
72    return (uv.fs_stat(path))
73  end
74
75  if not fs_stat_cache[path] then
76    -- Note we must never save a stat for a non-existent path.
77    -- For non-existent paths fs_stat() will return nil.
78    fs_stat_cache[path] = uv.fs_stat(path)
79  end
80  return fs_stat_cache[path]
81end
82
83--- @param path string
84local function normalize(path)
85  return fs.normalize(path, { plain = true, _fast = true })
86end
87
88local rtp_cached = {} --- @type string[]
89local rtp_cache_key --- @type  string?
90
91--- Gets the rtp excluding after directories.
92--- The result is cached, and will be updated if the runtime path changes.
93--- When called from a fast event, the cached value will be returned.
94--- @return string[] rtp, boolean updated
95local function get_rtp()
96  if vim.in_fast_event() then
97    return (rtp_cached or {}), false
98  end
99  local updated = false
100  local key = vim.go.rtp
101  if key ~= rtp_cache_key then
102    rtp_cached = {}
103    for _, path in ipairs(vim.api.nvim_get_runtime_file('', true)) do
104      path = normalize(path)
105      -- skip after directories
106      if
107        path:sub(-6, -1) ~= '/after'
108        and not (indexed[path] and vim.tbl_isempty(indexed[path]))
109      then
110        rtp_cached[#rtp_cached + 1] = path
111      end
112    end
113    updated = true
114    rtp_cache_key = key
115  end
116  return rtp_cached, updated
117end
118
119--- Returns the cache file name
120--- @param name string can be a module name, or a file name
121--- @return string file_name
122local function cache_filename(name)
123  if is_appimage then
124    -- Avoid cache pollution caused by AppImage randomizing the program root. #31165
125    -- "/tmp/.mount_nvimAmpHPH/usr/share/nvim/runtime" => "/usr/share/nvim/runtime"
126    name = name:match('(/usr/.*)') or name
127  end
128
129  local ret = ('%s/%s'):format(M.path, uri_encode(name, 'rfc2396'))
130  return ret:sub(-4) == '.lua' and (ret .. 'c') or (ret .. '.luac')
131end
132
133--- Saves the cache entry for a given module or file
134--- @param cname string cache filename
135--- @param hash vim.loader.CacheHash
136--- @param chunk function
137local function write_cachefile(cname, hash, chunk)
138  local f = assert(uv.fs_open(cname, 'w', 438))
139  local header = {
140    VERSION,
141    hash.size,
142    hash.mtime.sec,
143    hash.mtime.nsec,
144  }
145  uv.fs_write(f, table.concat(header, ',') .. '\0')
146  uv.fs_write(f, string.dump(chunk))
147  uv.fs_close(f)
148end
149
150--- @param path string
151--- @param mode integer
152--- @return string? data
153local function readfile(path, mode)
154  local f = uv.fs_open(path, 'r', mode)
155  if f then
156    local size = assert(uv.fs_fstat(f)).size
157    local data = uv.fs_read(f, size, 0)
158    uv.fs_close(f)
159    return data
160  end
161end
162
163--- Loads the cache entry for a given module or file
164--- @param cname string cache filename
165--- @return vim.loader.CacheHash? hash
166--- @return string? chunk
167local function read_cachefile(cname)
168  local data = readfile(cname, 438)
169  if not data then
170    return
171  end
172
173  local zero = data:find('\0', 1, true)
174  if not zero then
175    return
176  end
177
178  local header = vim.split(data:sub(1, zero - 1), ',')
179  local version = vim._tointeger(header[1])
180  if version ~= VERSION then
181    return
182  end
183
184  local size = vim._tointeger(header[2])
185  local sec = vim._tointeger(header[3])
186  local nsec = vim._tointeger(header[4])
187  if not (size and sec and nsec) then
188    return
189  end
190
191  local hash = {
192    size = size,
193    mtime = { sec = sec, nsec = nsec },
194  }
195
196  local chunk = data:sub(zero + 1)
197
198  return hash, chunk
199end
200
201--- The `package.loaders` loader for Lua files using the cache.
202--- @param modname string module name
203--- @return string|function
204local function loader_cached(modname)
205  fs_stat_cache = {}
206  local ret = M.find(modname)[1]
207  if ret then
208    -- Make sure to call the global loadfile so we respect any augmentations done elsewhere.
209    -- E.g. profiling
210    local chunk, err = loadfile(ret.modpath)
211    fs_stat_cache = nil
212    return chunk or error(err)
213  end
214  fs_stat_cache = nil
215  return ("\n\tcache_loader: module '%s' not found"):format(modname)
216end
217
218local is_win = vim.fn.has('win32') == 1
219
220--- The `package.loaders` loader for libs
221--- @param modname string module name
222--- @return string|function
223local function loader_lib_cached(modname)
224  local ret = M.find(modname, { patterns = { is_win and '.dll' or '.so' } })[1]
225  if not ret then
226    return ("\n\tcache_loader_lib: module '%s' not found"):format(modname)
227  end
228
229  -- Making function name in Lua 5.1 (see src/loadlib.c:mkfuncname) is
230  -- a) strip prefix up to and including the first dash, if any
231  -- b) replace all dots by underscores
232  -- c) prepend "luaopen_"
233  -- So "foo-bar.baz" should result in "luaopen_bar_baz"
234  local dash = modname:find('-', 1, true)
235  local funcname = dash and modname:sub(dash + 1) or modname
236  local chunk, err = package.loadlib(ret.modpath, 'luaopen_' .. funcname:gsub('%.', '_'))
237  return chunk or error(err)
238end
239
240--- Checks whether two cache hashes are the same based on:
241--- * file size
242--- * mtime in seconds
243--- * mtime in nanoseconds
244--- @param a? vim.loader.CacheHash
245--- @param b? vim.loader.CacheHash
246local function hash_eq(a, b)
247  return a
248    and b
249    and a.size == b.size
250    and a.mtime.sec == b.mtime.sec
251    and a.mtime.nsec == b.mtime.nsec
252end
253
254--- `loadfile` using the cache
255--- Note this has the mode and env arguments which is supported by LuaJIT and is 5.1 compatible.
256--- @param filename? string
257--- @param mode? "b"|"t"|"bt"
258--- @param env? table
259--- @return_overload function chunk
260--- @return_overload nil, string error_message
261local function loadfile_cached(filename, mode, env)
262  local modpath = normalize(assert(filename))
263  local stat = fs_stat_cached(modpath)
264  local cname = cache_filename(modpath)
265  if stat then
266    local e_hash, e_chunk = read_cachefile(cname)
267    if hash_eq(e_hash, stat) and e_chunk then
268      -- found in cache and up to date
269      local chunk, err = load(e_chunk, '@' .. modpath, mode, env)
270      if not (err and err:find('cannot load incompatible bytecode', 1, true)) then
271        return chunk, err
272      end
273    end
274  end
275
276  local chunk, err = _loadfile(modpath, mode, env)
277  if chunk and stat then
278    write_cachefile(cname, stat, chunk)
279  end
280  return chunk, err
281end
282
283--- Return the top-level \`/lua/*` modules for this path
284--- @param path string path to check for top-level Lua modules
285local function lsmod(path)
286  if not indexed[path] then
287    indexed[path] = {}
288    for name, t in fs.dir(path .. '/lua') do
289      local modpath = path .. '/lua/' .. name
290      -- HACK: type is not always returned due to a bug in luv
291      t = t or assert(fs_stat_cached(modpath)).type
292      --- @type string
293      local topname
294      local ext = name:sub(-4)
295      if ext == '.lua' or ext == '.dll' then
296        topname = name:sub(1, -5)
297      elseif name:sub(-3) == '.so' then
298        topname = name:sub(1, -4)
299      elseif t == 'link' or t == 'directory' then
300        topname = name
301      end
302      if topname then
303        indexed[path][topname] = { modpath = modpath, modname = topname }
304      end
305    end
306  end
307  return indexed[path]
308end
309
310--- Finds Lua modules for the given module name.
311---
312--- @since 0
313---
314--- @param modname string Module name, or `"*"` to find the top-level modules instead
315--- @param opts? vim.loader.find.Opts Options for finding a module:
316--- @return vim.loader.ModuleInfo[]
317function M.find(modname, opts)
318  opts = opts or {}
319
320  modname = modname:gsub('/', '.')
321  local basename = modname:gsub('%.', '/')
322  local idx = modname:find('.', 1, true)
323
324  -- HACK: fix incorrect require statements. Really not a fan of keeping this,
325  -- but apparently the regular Lua loader also allows this
326  if idx == 1 then
327    modname = modname:gsub('^%.+', '')
328    basename = modname:gsub('%.', '/')
329    idx = modname:find('.', 1, true)
330  end
331
332  -- get the top-level module name
333  local topmod = idx and modname:sub(1, idx - 1) or modname
334
335  -- OPTIM: search for a directory first when topmod == modname
336  local patterns = opts.patterns
337    or (topmod == modname and { '/init.lua', '.lua' } or { '.lua', '/init.lua' })
338  for p, pattern in ipairs(patterns) do
339    patterns[p] = '/lua/' .. basename .. pattern
340  end
341
342  --- @type vim.loader.ModuleInfo[]
343  local results = {}
344
345  -- Only continue if we haven't found anything yet or we want to find all
346  local function continue()
347    return #results == 0 or opts.all
348  end
349
350  -- Checks if the given paths contain the top-level module.
351  -- If so, it tries to find the module path for the given module name.
352  --- @param paths string[]
353  local function _find(paths)
354    for _, path in ipairs(paths) do
355      if topmod == '*' then
356        for _, r in pairs(lsmod(path)) do
357          results[#results + 1] = r
358          if not continue() then
359            return
360          end
361        end
362      elseif lsmod(path)[topmod] then
363        for _, pattern in ipairs(patterns) do
364          local modpath = path .. pattern
365          stats.find.stat = (stats.find.stat or 0) + 1
366          local stat = fs_stat_cached(modpath)
367          if stat then
368            results[#results + 1] = { modpath = modpath, stat = stat, modname = modname }
369            if not continue() then
370              return
371            end
372          end
373        end
374      end
375    end
376  end
377
378  -- always check the rtp first
379  if opts.rtp ~= false then
380    _find(rtp_cached or {})
381    if continue() then
382      local rtp, updated = get_rtp()
383      if updated then
384        _find(rtp)
385      end
386    end
387  end
388
389  -- check any additional paths
390  if continue() and opts.paths then
391    _find(opts.paths)
392  end
393
394  if #results == 0 then
395    -- module not found
396    stats.find.not_found = stats.find.not_found + 1
397  end
398
399  return results
400end
401
402--- Resets the cache for the path, or all the paths if path is nil.
403---
404--- @since 0
405---
406--- @param path string? path to reset
407function M.reset(path)
408  if path then
409    indexed[normalize(path)] = nil
410  else
411    indexed = {}
412  end
413
414  -- Path could be a directory so just clear all the hashes.
415  if fs_stat_cache then
416    fs_stat_cache = {}
417  end
418end
419
420--- Enables or disables the experimental Lua module loader:
421---
422--- Enable (`enable=true`):
423--- * overrides |loadfile()|
424--- * adds the Lua loader using the byte-compilation cache
425--- * adds the libs loader
426--- * removes the default Nvim loader
427---
428--- Disable (`enable=false`):
429--- * removes the loaders
430--- * adds the default Nvim loader
431---
432--- @since 0
433---
434--- @param enable? (boolean) true/nil to enable, false to disable
435function M.enable(enable)
436  enable = enable == nil and true or enable
437  if enable == M.enabled then
438    return
439  end
440  M.enabled = enable
441
442  if enable then
443    vim.fn.mkdir(fs.abspath(M.path), 'p')
444    ---@diagnostic disable-next-line: global-in-non-module
445    _G.loadfile = loadfile_cached
446    -- add Lua loader
447    table.insert(loaders, 2, loader_cached)
448    -- add libs loader
449    table.insert(loaders, 3, loader_lib_cached)
450    -- remove Nvim loader
451    for l, loader in ipairs(loaders) do
452      if loader == vim._load_package then
453        table.remove(loaders, l)
454        break
455      end
456    end
457  else
458    ---@diagnostic disable-next-line: global-in-non-module
459    _G.loadfile = _loadfile
460    for l = #loaders, 1, -1 do
461      local loader = loaders[l]
462      if loader == loader_cached or loader == loader_lib_cached then
463        table.remove(loaders, l)
464      end
465    end
466    table.insert(loaders, 2, vim._load_package)
467  end
468end
469
470--- Tracks the time spent in a function
471--- @generic F: function
472--- @param stat string
473--- @param f F
474--- @return F
475local function track(stat, f)
476  return function(...)
477    local start = uv.hrtime()
478    local r = { f(...) }
479    stats[stat] = stats[stat] or { total = 0, time = 0 }
480    stats[stat].total = stats[stat].total + 1
481    stats[stat].time = stats[stat].time + uv.hrtime() - start
482    return unpack(r, 1, table.maxn(r))
483  end
484end
485
486--- @class (private) vim.loader._profile.Opts
487--- @field loaders? boolean Add profiling to the loaders
488
489--- Debug function that wraps all loaders and tracks stats
490--- Must be called before vim.loader.enable()
491--- @private
492--- @param opts vim.loader._profile.Opts?
493function M._profile(opts)
494  get_rtp = track('get_rtp', get_rtp)
495  read_cachefile = track('read', read_cachefile)
496  loader_cached = track('loader', loader_cached)
497  loader_lib_cached = track('loader_lib', loader_lib_cached)
498  loadfile_cached = track('loadfile', loadfile_cached)
499  M.find = track('find', M.find)
500  lsmod = track('lsmod', lsmod)
501
502  if opts and opts.loaders then
503    for l, loader in pairs(loaders) do
504      local loc = assert(debug.getinfo(loader, 'Sn')).source:gsub('^@', '')
505      loaders[l] = track('loader ' .. l .. ': ' .. loc, loader)
506    end
507  end
508end
509
510--- Prints all cache stats
511--- @param opts? {print?:boolean}
512--- @return vim.loader.Stats
513--- @private
514function M._inspect(opts)
515  if opts and opts.print then
516    --- @param nsec number
517    local function ms(nsec)
518      return math.floor(nsec / 1e6 * 1000 + 0.5) / 1000 .. 'ms'
519    end
520    local chunks = {} --- @type [string, string?][]
521    for name, stat in vim.spairs(stats) do
522      vim.list_extend(chunks, {
523        { '\n' .. name .. '\n', 'Title' },
524        { '* total:    ' },
525        { tostring(stat.total) .. '\n', 'Number' },
526        { '* time:     ' },
527        { ms(stat.time) .. '\n', 'Bold' },
528        { '* avg time: ' },
529        { ms(stat.time / stat.total) .. '\n', 'Bold' },
530      })
531      for k, v in pairs(stat) do
532        if not vim.list_contains({ 'time', 'total' }, k) then
533          chunks[#chunks + 1] = { '* ' .. k .. ':' .. string.rep(' ', 9 - #k) }
534          chunks[#chunks + 1] = { tostring(v) .. '\n', 'Number' }
535        end
536      end
537    end
538    vim.api.nvim_echo(chunks, true)
539  end
540  return stats
541end
542
543return M