robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 ) 71if not fs_stat_cache then 72return ( uv . fs_stat ( path )) 73end 74 75if 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. 78fs_stat_cache [ path ] =uv . fs_stat ( path ) 79end 80return fs_stat_cache [ path ] 81end 82 83--- @param path string 84local function normalize ( path ) 85return 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 () 96if vim . in_fast_event () then 97return ( rtp_cached or {} ), false 98end 99local updated =false 100local key =vim . go . rtp 101if key ~= rtp_cache_key then 102rtp_cached ={} 103for _ , path in ipairs ( vim . api . nvim_get_runtime_file ( '' , true )) do 104path =normalize ( path ) 105-- skip after directories 106if 107path : sub ( - 6 , - 1 ) ~= '/after' 108and not ( indexed [ path ] and vim . tbl_isempty ( indexed [ path ])) 109then 110rtp_cached [ # rtp_cached + 1 ] =path 111end 112end 113updated =true 114rtp_cache_key =key 115end 116return 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 ) 123if 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" 126name =name : match ( '(/usr/.*)' ) or name 127end 128 129local ret =( '%s/%s' ): format ( M . path , uri_encode ( name , 'rfc2396' )) 130return 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 ) 138local f =assert ( uv . fs_open ( cname , 'w' , 438 )) 139local header ={ 140VERSION , 141hash . size , 142hash . mtime . sec , 143hash . mtime . nsec , 144} 145uv . fs_write ( f , table . concat ( header , ',' ) .. '\0' ) 146uv . fs_write ( f , string . dump ( chunk )) 147uv . fs_close ( f ) 148end 149 150--- @param path string 151--- @param mode integer 152--- @return string? data 153local function readfile ( path , mode ) 154local f =uv . fs_open ( path , 'r' , mode ) 155if f then 156local size =assert ( uv . fs_fstat ( f )). size 157local data =uv . fs_read ( f , size , 0 ) 158uv . fs_close ( f ) 159return data 160end 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 ) 168local data =readfile ( cname , 438 ) 169if not data then 170return 171end 172 173local zero =data : find ( '\0' , 1 , true ) 174if not zero then 175return 176end 177 178local header =vim . split ( data : sub ( 1 , zero - 1 ), ',' ) 179local version =vim . _tointeger ( header [ 1 ]) 180if version ~= VERSION then 181return 182end 183 184local size =vim . _tointeger ( header [ 2 ]) 185local sec =vim . _tointeger ( header [ 3 ]) 186local nsec =vim . _tointeger ( header [ 4 ]) 187if not ( size and sec and nsec ) then 188return 189end 190 191local hash ={ 192size =size , 193mtime ={ sec =sec , nsec =nsec } , 194} 195 196local chunk =data : sub ( zero + 1 ) 197 198return 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 ) 205fs_stat_cache ={} 206local ret =M . find ( modname )[ 1 ] 207if ret then 208-- Make sure to call the global loadfile so we respect any augmentations done elsewhere. 209-- E.g. profiling 210local chunk , err =loadfile ( ret . modpath ) 211fs_stat_cache =nil 212return chunk or error ( err ) 213end 214fs_stat_cache =nil 215return ( "\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 ) 224local ret =M . find ( modname , { patterns ={ is_win and '.dll' or '.so' } } )[ 1 ] 225if not ret then 226return ( "\n\tcache_loader_lib: module '%s' not found" ): format ( modname ) 227end 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" 234local dash =modname : find ( '-' , 1 , true ) 235local funcname =dash and modname : sub ( dash + 1 ) or modname 236local chunk , err =package . loadlib ( ret . modpath , 'luaopen_' .. funcname : gsub ( '%.' , '_' )) 237return 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 ) 247return a 248and b 249and a . size == b . size 250and a . mtime . sec == b . mtime . sec 251and 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 ) 262local modpath =normalize ( assert ( filename )) 263local stat =fs_stat_cached ( modpath ) 264local cname =cache_filename ( modpath ) 265if stat then 266local e_hash , e_chunk =read_cachefile ( cname ) 267if hash_eq ( e_hash , stat ) and e_chunk then 268-- found in cache and up to date 269local chunk , err =load ( e_chunk , '@' .. modpath , mode , env ) 270if not ( err and err : find ( 'cannot load incompatible bytecode' , 1 , true )) then 271return chunk , err 272end 273end 274end 275 276local chunk , err =_loadfile ( modpath , mode , env ) 277if chunk and stat then 278write_cachefile ( cname , stat , chunk ) 279end 280return 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 ) 286if not indexed [ path ] then 287indexed [ path ] ={} 288for name , t in fs . dir ( path .. '/lua' ) do 289local modpath =path .. '/lua/' .. name 290-- HACK: type is not always returned due to a bug in luv 291t =t or assert ( fs_stat_cached ( modpath )). type 292--- @type string 293local topname 294local ext =name : sub ( - 4 ) 295if ext == '.lua' or ext == '.dll' then 296topname =name : sub ( 1 , - 5 ) 297elseif name : sub ( - 3 ) == '.so' then 298topname =name : sub ( 1 , - 4 ) 299elseif t == 'link' or t == 'directory' then 300topname =name 301end 302if topname then 303indexed [ path ][ topname ] ={ modpath =modpath , modname =topname } 304end 305end 306end 307return 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 ) 318opts =opts or {} 319 320modname =modname : gsub ( '/' , '.' ) 321local basename =modname : gsub ( '%.' , '/' ) 322local 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 326if idx == 1 then 327modname =modname : gsub ( '^%.+' , '' ) 328basename =modname : gsub ( '%.' , '/' ) 329idx =modname : find ( '.' , 1 , true ) 330end 331 332-- get the top-level module name 333local topmod =idx and modname : sub ( 1 , idx - 1 ) or modname 334 335-- OPTIM: search for a directory first when topmod == modname 336local patterns =opts . patterns 337or ( topmod == modname and { '/init.lua' , '.lua' } or { '.lua' , '/init.lua' } ) 338for p , pattern in ipairs ( patterns ) do 339patterns [ p ] ='/lua/' .. basename .. pattern 340end 341 342--- @type vim.loader.ModuleInfo[] 343local results ={} 344 345-- Only continue if we haven't found anything yet or we want to find all 346local function continue () 347return # results == 0 or opts . all 348end 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[] 353local function _find ( paths ) 354for _ , path in ipairs ( paths ) do 355if topmod == '*' then 356for _ , r in pairs ( lsmod ( path )) do 357results [ # results + 1 ] =r 358if not continue () then 359return 360end 361end 362elseif lsmod ( path )[ topmod ] then 363for _ , pattern in ipairs ( patterns ) do 364local modpath =path .. pattern 365stats . find . stat =( stats . find . stat or 0 ) + 1 366local stat =fs_stat_cached ( modpath ) 367if stat then 368results [ # results + 1 ] ={ modpath =modpath , stat =stat , modname =modname } 369if not continue () then 370return 371end 372end 373end 374end 375end 376end 377 378-- always check the rtp first 379if opts . rtp ~= false then 380_find ( rtp_cached or {} ) 381if continue () then 382local rtp , updated =get_rtp () 383if updated then 384_find ( rtp ) 385end 386end 387end 388 389-- check any additional paths 390if continue () and opts . paths then 391_find ( opts . paths ) 392end 393 394if # results == 0 then 395-- module not found 396stats . find . not_found =stats . find . not_found + 1 397end 398 399return 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 ) 408if path then 409indexed [ normalize ( path )] =nil 410else 411indexed ={} 412end 413 414-- Path could be a directory so just clear all the hashes. 415if fs_stat_cache then 416fs_stat_cache ={} 417end 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 ) 436enable =enable == nil and true or enable 437if enable == M . enabled then 438return 439end 440M . enabled =enable 441 442if enable then 443vim . 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 447table . insert ( loaders , 2 , loader_cached ) 448-- add libs loader 449table . insert ( loaders , 3 , loader_lib_cached ) 450-- remove Nvim loader 451for l , loader in ipairs ( loaders ) do 452if loader == vim . _load_package then 453table . remove ( loaders , l ) 454break 455end 456end 457else 458---@diagnostic disable-next-line: global-in-non-module 459_G . loadfile =_loadfile 460for l =# loaders , 1 , - 1 do 461local loader =loaders [ l ] 462if loader == loader_cached or loader == loader_lib_cached then 463table . remove ( loaders , l ) 464end 465end 466table . insert ( loaders , 2 , vim . _load_package ) 467end 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 ) 476return function ( ... ) 477local start =uv . hrtime () 478local r ={ f ( ... ) } 479stats [ stat ] =stats [ stat ] or { total =0 , time =0 } 480stats [ stat ]. total =stats [ stat ]. total + 1 481stats [ stat ]. time =stats [ stat ]. time + uv . hrtime () - start 482return unpack ( r , 1 , table . maxn ( r )) 483end 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 ) 494get_rtp =track ( 'get_rtp' , get_rtp ) 495read_cachefile =track ( 'read' , read_cachefile ) 496loader_cached =track ( 'loader' , loader_cached ) 497loader_lib_cached =track ( 'loader_lib' , loader_lib_cached ) 498loadfile_cached =track ( 'loadfile' , loadfile_cached ) 499M . find =track ( 'find' , M . find ) 500lsmod =track ( 'lsmod' , lsmod ) 501 502if opts and opts . loaders then 503for l , loader in pairs ( loaders ) do 504local loc =assert ( debug . getinfo ( loader , 'Sn' )). source : gsub ( '^@' , '' ) 505loaders [ l ] =track ( 'loader ' .. l .. ': ' .. loc , loader ) 506end 507end 508end 509 510--- Prints all cache stats 511--- @param opts? {print?:boolean} 512--- @return vim.loader.Stats 513--- @private 514function M . _inspect ( opts ) 515if opts and opts . then 516--- @param nsec number 517local function ms ( nsec ) 518return math . floor ( nsec / 1e6 * 1000 + 0.5 ) / 1000 .. 'ms' 519end 520local chunks ={} --- @type [string, string?][] 521for name , stat in vim . spairs ( stats ) do 522vim . 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} ) 531for k , v in pairs ( stat ) do 532if not vim . list_contains ( { 'time' , 'total' } , k ) then 533chunks [ # chunks + 1 ] ={ '* ' .. k .. ':' .. string . rep ( ' ' , 9 - # k ) } 534chunks [ # chunks + 1 ] ={ tostring ( v ) .. '\n' , 'Number' } 535end 536end 537end 538vim . api . nvim_echo ( chunks , true ) 539end 540return stats 541end 542 543return M