impatient.lua 8.2 KB

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