loader.lua 14 KB

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