impatient.lua 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. -- modified version from https://github.com/lewis6991/impatient.nvim
  2. local vim = vim
  3. local uv = vim.loop
  4. local impatient_start = uv.hrtime()
  5. local api = vim.api
  6. local ffi = require "ffi"
  7. local get_option, set_option = api.nvim_get_option, api.nvim_set_option
  8. local get_runtime_file = api.nvim_get_runtime_file
  9. local home_dir = uv.os_homedir()
  10. local impatient_dur
  11. local M = {
  12. cache = {},
  13. profile = nil,
  14. dirty = false,
  15. path = home_dir .. "/.local/share/lunarvim/cache",
  16. log = {},
  17. }
  18. _G.__luacache = M
  19. --{{{
  20. local cachepack = {}
  21. -- using double for packing/unpacking numbers has no conversion overhead
  22. local c_double = ffi.typeof "double[1]"
  23. local sizeof_c_double = ffi.sizeof "double"
  24. local out_buf = {}
  25. function out_buf.write_number(buf, num)
  26. buf[#buf + 1] = ffi.string(c_double(num), sizeof_c_double)
  27. end
  28. function out_buf.write_string(buf, str)
  29. out_buf.write_number(buf, #str)
  30. buf[#buf + 1] = str
  31. end
  32. function out_buf.to_string(buf)
  33. return table.concat(buf)
  34. end
  35. local in_buf = {}
  36. function in_buf.read_number(buf)
  37. if buf.size < buf.pos then
  38. error "buffer access violation"
  39. end
  40. local res = ffi.cast("double*", buf.ptr + buf.pos)[0]
  41. buf.pos = buf.pos + sizeof_c_double
  42. return res
  43. end
  44. function in_buf.read_string(buf)
  45. local len = in_buf.read_number(buf)
  46. local res = ffi.string(buf.ptr + buf.pos, len)
  47. buf.pos = buf.pos + len
  48. return res
  49. end
  50. function cachepack.pack(cache)
  51. local total_keys = vim.tbl_count(cache)
  52. local buf = {}
  53. out_buf.write_number(buf, total_keys)
  54. for k, v in pairs(cache) do
  55. out_buf.write_string(buf, k)
  56. out_buf.write_string(buf, v[1] or "")
  57. out_buf.write_number(buf, v[2] or 0)
  58. out_buf.write_string(buf, v[3] or "")
  59. end
  60. return out_buf.to_string(buf)
  61. end
  62. function cachepack.unpack(str, raw_buf_size)
  63. if raw_buf_size == 0 or str == nil or (raw_buf_size == nil and #str == 0) then
  64. return {}
  65. end
  66. local buf = {
  67. ptr = raw_buf_size and str or ffi.new("const char[?]", #str, str),
  68. pos = 0,
  69. size = raw_buf_size or #str,
  70. }
  71. local cache = {}
  72. local total_keys = in_buf.read_number(buf)
  73. for _ = 1, total_keys do
  74. local k = in_buf.read_string(buf)
  75. local v = {
  76. in_buf.read_string(buf),
  77. in_buf.read_number(buf),
  78. in_buf.read_string(buf),
  79. }
  80. cache[k] = v
  81. end
  82. return cache
  83. end
  84. --}}}
  85. local function log(...)
  86. M.log[#M.log + 1] = table.concat({ string.format(...) }, " ")
  87. end
  88. function M.print_log()
  89. for _, l in ipairs(M.log) do
  90. print(l)
  91. end
  92. end
  93. function M.enable_profile()
  94. M.profile = {}
  95. M.print_profile = function()
  96. M.profile["impatient"] = {
  97. resolve = 0,
  98. load = impatient_dur,
  99. loader = "standard",
  100. }
  101. require("impatient.profile").print_profile(M.profile)
  102. end
  103. vim.cmd [[command! LuaCacheProfile lua _G.__luacache.print_profile()]]
  104. end
  105. local function is_cacheable(path)
  106. -- Don't cache files in /tmp since they are not likely to persist.
  107. -- Note: Appimage versions of Neovim mount $VIMRUNTIME in /tmp in a unique
  108. -- directory on each launch.
  109. return not vim.startswith(path, "/tmp/")
  110. end
  111. local function hash(modpath)
  112. local stat = uv.fs_stat(modpath)
  113. if stat then
  114. return stat.mtime.sec
  115. end
  116. end
  117. local function hrtime()
  118. if M.profile then
  119. return uv.hrtime()
  120. end
  121. end
  122. local function load_package_with_cache(name, loader)
  123. local resolve_start = hrtime()
  124. local basename = name:gsub("%.", "/")
  125. local paths = { "lua/" .. basename .. ".lua", "lua/" .. basename .. "/init.lua" }
  126. for _, path in ipairs(paths) do
  127. local modpath = get_runtime_file(path, false)[1]
  128. if modpath then
  129. local load_start = hrtime()
  130. local chunk, err = loadfile(modpath)
  131. if M.profile then
  132. M.profile[name] = {
  133. resolve = load_start - resolve_start,
  134. load = hrtime() - load_start,
  135. loader = loader or "standard",
  136. }
  137. end
  138. if chunk == nil then
  139. return err
  140. end
  141. if is_cacheable(modpath) then
  142. log("Creating cache for module %s", name)
  143. M.cache[name] = { modpath, hash(modpath), string.dump(chunk) }
  144. M.dirty = true
  145. else
  146. log("Unable to cache module %s", name)
  147. end
  148. return chunk
  149. end
  150. end
  151. return nil
  152. end
  153. local reduced_rtp
  154. -- Speed up non-cached loads by reducing the rtp path during requires
  155. function M.update_reduced_rtp()
  156. local luadirs = get_runtime_file("lua/", true)
  157. for i = 1, #luadirs do
  158. luadirs[i] = luadirs[i]:sub(1, -6)
  159. end
  160. reduced_rtp = table.concat(luadirs, ",")
  161. end
  162. local function load_package_with_cache_reduced_rtp(name)
  163. local orig_rtp = get_option "runtimepath"
  164. local orig_ei = get_option "eventignore"
  165. if not reduced_rtp then
  166. M.update_reduced_rtp()
  167. end
  168. set_option("eventignore", "all")
  169. set_option("rtp", reduced_rtp)
  170. local found = load_package_with_cache(name, "reduced")
  171. set_option("rtp", orig_rtp)
  172. set_option("eventignore", orig_ei)
  173. return found
  174. end
  175. local function load_from_cache(name)
  176. local resolve_start = hrtime()
  177. if M.cache[name] == nil then
  178. log("No cache for module %s", name)
  179. return "No cache entry"
  180. end
  181. local modpath, mhash, codes = unpack(M.cache[name])
  182. if mhash ~= hash(modpath) then
  183. log("Stale cache for module %s", name)
  184. M.cache[name] = nil
  185. M.dirty = true
  186. return "Stale cache"
  187. end
  188. local load_start = hrtime()
  189. local chunk = loadstring(codes)
  190. if M.profile then
  191. M.profile[name] = {
  192. resolve = load_start - resolve_start,
  193. load = hrtime() - load_start,
  194. loader = "cache",
  195. }
  196. end
  197. if not chunk then
  198. M.cache[name] = nil
  199. M.dirty = true
  200. log("Error loading cache for module. Invalidating", name)
  201. return "Cache error"
  202. end
  203. return chunk
  204. end
  205. function M.save_cache()
  206. if M.dirty then
  207. log("Updating cache file: %s", M.path)
  208. local f = io.open(M.path, "w+b")
  209. f:write(cachepack.pack(M.cache))
  210. f:flush()
  211. M.dirty = false
  212. end
  213. end
  214. function M.clear_cache()
  215. M.cache = {}
  216. os.remove(M.path)
  217. end
  218. local function setup()
  219. local stat = uv.fs_stat(M.path)
  220. if stat then
  221. log("Loading cache file %s", M.path)
  222. local ok
  223. -- Linux/macOS lets us easily mmap the cache file for faster reads without passing to Lua
  224. if jit.os == "Linux" or jit.os == "OSX" then
  225. local size = stat.size
  226. local C = ffi.C
  227. local O_RDONLY = 0x00
  228. local PROT_READ = 0x01
  229. local MAP_PRIVATE = 0x02
  230. ffi.cdef [[
  231. int open(const char *pathname, int flags);
  232. int close(int fd);
  233. void *mmap(void *addr, size_t length, int prot, int flags, int fd, long int offset);
  234. int munmap(void *addr, size_t length);
  235. ]]
  236. local f = C.open(M.path, O_RDONLY)
  237. local addr = C.mmap(nil, size, PROT_READ, MAP_PRIVATE, f, 0)
  238. ok = ffi.cast("intptr_t", addr) ~= -1
  239. if ok then
  240. M.cache = cachepack.unpack(ffi.cast("char *", addr), size)
  241. C.munmap(addr, size)
  242. end
  243. C.close(f)
  244. else
  245. local f = io.open(M.path, "rb")
  246. ok, M.cache = pcall(function()
  247. return cachepack.unpack(f:read "*a")
  248. end)
  249. end
  250. if not ok then
  251. log("Corrupted cache file, %s. Invalidating...", M.path)
  252. os.remove(M.path)
  253. M.cache = {}
  254. end
  255. M.dirty = not ok
  256. end
  257. local insert = table.insert
  258. local package = package
  259. -- Fix the position of the preloader. This also makes loading modules like 'ffi'
  260. -- and 'bit' quicker
  261. if package.loaders[1] == vim._load_package then
  262. -- Move vim._load_package to the second position
  263. local vim_load = table.remove(package.loaders, 1)
  264. insert(package.loaders, 2, vim_load)
  265. end
  266. insert(package.loaders, 2, load_from_cache)
  267. insert(package.loaders, 3, load_package_with_cache_reduced_rtp)
  268. insert(package.loaders, 4, load_package_with_cache)
  269. vim.cmd [[
  270. augroup impatient
  271. autocmd VimEnter,VimLeave * lua _G.__luacache.save_cache()
  272. autocmd OptionSet runtimepath lua _G.__luacache.update_reduced_rtp(true)
  273. augroup END
  274. command! LuaCacheClear lua _G.__luacache.clear_cache()
  275. command! LuaCacheLog lua _G.__luacache.print_log()
  276. ]]
  277. end
  278. setup()
  279. impatient_dur = uv.hrtime() - impatient_start
  280. return M