robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local luacats_grammar =require ( 'gen.luacats_grammar' ) * vim . lpeg . Cp () 2 3--- @class nvim.luacats.parser.param : nvim.luacats.Param 4 5--- @class nvim.luacats.parser.return 6--- @field name string 7--- @field type string 8--- @field desc string 9 10--- @class nvim.luacats.parser.note 11--- @field desc string 12 13--- @class nvim.luacats.parser.brief 14--- @field kind 'brief' 15--- @field desc string 16 17--- @class nvim.luacats.parser.alias 18--- @field kind 'alias' 19--- @field type string[] 20--- @field desc string 21 22--- @class nvim.luacats.parser.fun 23--- @field name string 24--- @field params nvim.luacats.parser.param[] 25--- @field overloads string[] 26--- @field returns nvim.luacats.parser.return[] 27--- @field desc string 28--- @field access? 'private'|'package'|'protected'|'internal' 29--- @field class? string 30--- @field module? string 31--- @field modvar? string 32--- @field classvar? string 33--- @field member_sep? '.'|':' 34--- @field deprecated? true 35--- @field async? true 36--- @field since? string 37--- @field attrs? string[] 38--- @field nodoc? true 39--- @field generics? table<string,string> 40--- @field table? true 41--- @field notes? nvim.luacats.parser.note[] 42--- @field see? nvim.luacats.parser.note[] 43 44--- @class nvim.luacats.parser.field : nvim.luacats.Field 45--- @field classvar? string 46--- @field nodoc? true 47 48--- @class nvim.luacats.parser.class : nvim.luacats.Class 49--- @field desc? string 50--- @field nodoc? true 51--- @field inlinedoc? true 52--- @field fields nvim.luacats.parser.field[] 53--- @field notes? string[] 54 55--- @class nvim.luacats.parser.State 56--- @field doc_lines? string[] 57--- @field cur_obj? nvim.luacats.parser.obj 58--- @field last_doc_item? nvim.luacats.parser.param|nvim.luacats.parser.return|nvim.luacats.parser.note 59--- @field last_doc_item_indent? integer 60 61--- @class nvim.luacats.parser.module 62--- @field name string Module name inferred from the path, used to resolve require(). 63--- @field modvar? string 64--- @field class? nvim.luacats.parser.class Class of the returned module table. 65--- @field requires table<string,string> Module fields assigned directly from require(), keyed by field name. 66--- @field imports table<string,nvim.luacats.parser.module> Bindings linked by resolve_modules(). 67--- @field parent? nvim.luacats.parser.module Module whose returned class is this module class's parent. 68--- @field callable? nvim.luacats.parser.fun Returned function or the returned table's __call. 69--- @field assignments table<string,true> Field assignments (`M.name = ...`), including unannotated ones. 70--- @field funs nvim.luacats.parser.fun[] 71 72--- @alias nvim.luacats.parser.obj 73--- | nvim.luacats.parser.class 74--- | nvim.luacats.parser.fun 75--- | nvim.luacats.parser.brief 76--- | nvim.luacats.parser.alias 77 78-- Remove this when we document classes properly 79--- Some doc lines have the form: 80--- param name some.complex.type (table) description 81--- if so then transform the line to remove the complex type: 82--- param name (table) description 83--- @param line string 84local function use_type_alt ( line ) 85for _ , type in ipairs ( { 'table' , 'function' } ) do 86line =line : gsub ( '@param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. ')%)' , '@param %1 %2' ) 87line =line : gsub ( '@param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. '|nil)%)' , '@param %1 %2' ) 88line =line : gsub ( '@param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. '%?)%)' , '@param %1 %2' ) 89 90line =line : gsub ( '@return%s+.*%((' .. type .. ')%)' , '@return %1' ) 91line =line : gsub ( '@return%s+.*%((' .. type .. '|nil)%)' , '@return %1' ) 92line =line : gsub ( '@return%s+.*%((' .. type .. '%?)%)' , '@return %1' ) 93end 94return line 95end 96 97--- If we collected any `---` lines. Add them to the existing (or new) object 98--- Used for function/class descriptions and multiline param descriptions. 99--- @param state nvim.luacats.parser.State 100local function add_doc_lines_to_obj ( state ) 101if state . doc_lines then 102state . cur_obj =state . cur_obj or {} 103local cur_obj =assert ( state . cur_obj ) 104local txt =table . concat ( state . doc_lines , '\n' ) 105if cur_obj . desc then 106cur_obj . desc =cur_obj . desc .. '\n' .. txt 107else 108cur_obj . desc =txt 109end 110state . doc_lines =nil 111end 112end 113 114--- @param line string 115--- @param parsed nvim.luacats.grammar.result? 116--- @param state nvim.luacats.parser.State 117local function process_doc_line ( line , parsed , state ) 118if not parsed then 119if line : match ( '^ ' ) then 120line =line : sub ( 2 ) 121end 122 123if state . last_doc_item then 124if not state . last_doc_item_indent then 125state . last_doc_item_indent =# line : match ( '^%s*' ) + 1 126end 127state . last_doc_item . desc =( state . last_doc_item . desc or '' ) 128.. '\n' 129.. line : sub ( state . last_doc_item_indent or 1 ) 130else 131state . doc_lines =state . doc_lines or {} 132table . insert ( state . doc_lines , line ) 133end 134return 135end 136 137state . last_doc_item_indent =nil 138state . last_doc_item =nil 139state . cur_obj =state . cur_obj or {} 140local cur_obj =assert ( state . cur_obj ) 141 142local kind =parsed . kind 143 144if kind == 'brief' then 145state . cur_obj ={ 146kind ='brief' , 147desc =parsed . desc , 148} 149elseif kind == 'class' then 150--- @cast parsed nvim.luacats.Class 151cur_obj . kind ='class' 152cur_obj . name =parsed . name 153cur_obj . generics =parsed . generics 154cur_obj . parent =parsed . parent 155cur_obj . parent_generics =parsed . parent_generics 156cur_obj . access =parsed . access 157cur_obj . desc =state . doc_lines and table . concat ( state . doc_lines , '\n' ) or nil 158state . doc_lines =nil 159cur_obj . fields ={} 160elseif kind == 'field' then 161--- @cast parsed nvim.luacats.Field 162if parsed . desc == '' then 163parsed . desc =nil 164end 165parsed . desc =parsed . desc or state . doc_lines and table . concat ( state . doc_lines , '\n' ) or nil 166if parsed . desc then 167parsed . desc =vim . trim ( parsed . desc ) 168end 169table . insert ( cur_obj . fields , parsed ) 170state . doc_lines =nil 171elseif kind == 'operator' then 172parsed . desc =parsed . desc or state . doc_lines and table . concat ( state . doc_lines , '\n' ) or nil 173if parsed . desc then 174parsed . desc =vim . trim ( parsed . desc ) 175end 176table . insert ( cur_obj . fields , parsed ) 177state . doc_lines =nil 178elseif kind == 'param' then 179state . last_doc_item_indent =nil 180cur_obj . params =cur_obj . params or {} 181if vim . endswith ( parsed . name , '?' ) then 182parsed . name =parsed . name : sub ( 1 , - 2 ) 183parsed . type =parsed . type .. '?' 184end 185state . last_doc_item ={ 186name =parsed . name , 187type =parsed . type , 188desc =parsed . desc , 189} 190table . insert ( cur_obj . params , state . last_doc_item ) 191elseif kind == 'return' then 192cur_obj . returns =cur_obj . returns or {} 193for _ , t in ipairs ( parsed ) do 194table . insert ( cur_obj . returns , { 195name =t . name , 196type =t . type , 197desc =parsed . desc , 198} ) 199end 200state . last_doc_item_indent =nil 201state . last_doc_item =cur_obj . returns [ # cur_obj . returns ] 202elseif kind == 'private' then 203cur_obj . access ='private' 204elseif kind == 'package' then 205cur_obj . access ='package' 206elseif kind == 'protected' then 207cur_obj . access ='protected' 208elseif kind == 'internal' then 209cur_obj . access ='internal' 210elseif kind == 'deprecated' then 211cur_obj . deprecated =true 212elseif kind == 'inlinedoc' then 213cur_obj . inlinedoc =true 214elseif kind == 'nodoc' then 215cur_obj . nodoc =true 216elseif kind == 'since' then 217cur_obj . since =parsed . desc 218elseif kind == 'see' then 219cur_obj . see =cur_obj . see or {} 220table . insert ( cur_obj . see , { desc =parsed . desc } ) 221elseif kind == 'note' then 222state . last_doc_item_indent =nil 223state . last_doc_item ={ 224desc =parsed . desc , 225} 226cur_obj . notes =cur_obj . notes or {} 227table . insert ( cur_obj . notes , state . last_doc_item ) 228elseif kind == 'type' then 229cur_obj . desc =parsed . desc 230parsed . desc =nil 231parsed . kind =nil 232cur_obj . type =parsed 233elseif kind == 'alias' then 234state . cur_obj ={ 235kind ='alias' , 236desc =parsed . desc , 237} 238elseif kind == 'enum' then 239-- TODO 240state . doc_lines =nil 241elseif kind == 'async' then 242cur_obj . async =true 243elseif kind == 'overload' then 244cur_obj . overloads =cur_obj . overloads or {} 245table . insert ( cur_obj . overloads , parsed . type ) 246elseif 247vim . tbl_contains ( { 248'diagnostic' , 249'cast' , 250'return_cast' , 251'overload' , 252'meta' , 253} , kind ) 254then 255-- Ignore 256return 257elseif kind == 'generic' then 258cur_obj . generics =cur_obj . generics or {} 259cur_obj . generics [ parsed . name ] =parsed . type or 'any' 260else 261error ( 'Unhandled' .. vim . inspect ( parsed )) 262end 263end 264 265--- @param fun nvim.luacats.parser.fun 266--- @return nvim.luacats.parser.field 267local function fun2field ( fun ) 268local parts ={ 'fun(' } 269 270local params ={} ---@type string[] 271for _ , p in ipairs ( fun . params or {} ) do 272params [ # params + 1 ] =string . format ( '%s: %s' , p . name , p . type ) 273end 274parts [ # parts + 1 ] =table . concat ( params , ', ' ) 275parts [ # parts + 1 ] =')' 276if fun . returns then 277parts [ # parts + 1 ] =': ' 278local tys ={} --- @type string[] 279for _ , p in ipairs ( fun . returns ) do 280tys [ # tys + 1 ] =p . type 281end 282parts [ # parts + 1 ] =table . concat ( tys , ', ' ) 283end 284 285return { 286kind ='field' , 287name =fun . name , 288type =table . concat ( parts , '' ), 289access =fun . access , 290desc =fun . desc , 291nodoc =fun . nodoc , 292classvar =fun . classvar , 293} 294end 295 296--- Function to normalize known form for declaring functions and normalize into a more standard 297--- form. 298--- @param line string 299--- @return string 300local function filter_decl ( line ) 301-- M.fun = vim._memoize(function(...) 302-- -> 303-- function M.fun(...) 304line =line : gsub ( '^local (.+) = memoize%([^,]+, function%((.*)%)$' , 'local function %1(%2)' ) 305line =line : gsub ( '^(.+) = memoize%([^,]+, function%((.*)%)$' , 'function %1(%2)' ) 306return line 307end 308 309--- @param line string 310--- @param state nvim.luacats.parser.State 311--- @param classes table<string,nvim.luacats.parser.class> 312--- @param classvars table<string,string> 313--- @param has_indent boolean 314local function process_lua_line ( line , state , classes , classvars , has_indent ) 315line =filter_decl ( line ) 316 317if state . cur_obj and state . cur_obj . kind == 'class' then 318local nm =line : match ( '^local%s+([a-zA-Z0-9_]+)%s*=' ) 319if nm then 320classvars [ nm ] =state . cur_obj . name 321end 322return 323end 324 325do 326local parent_tbl , sep , fun_or_meth_nm = 327line : match ( '^function%s+([a-zA-Z0-9_]+)([.:])([a-zA-Z0-9_]+)%s*%(' ) 328if parent_tbl then 329-- Have a decl. Ensure cur_obj 330state . cur_obj =state . cur_obj or {} 331local cur_obj =assert ( state . cur_obj ) 332 333-- Match `Class:foo` methods for defined classes 334local class =classvars [ parent_tbl ] 335if class then 336--- @cast cur_obj nvim.luacats.parser.fun 337cur_obj . name =fun_or_meth_nm 338cur_obj . class =class 339cur_obj . classvar =parent_tbl 340cur_obj . member_sep =sep 341-- Add self param to methods 342if sep == ':' then 343cur_obj . params =cur_obj . params or {} 344table . insert ( cur_obj . params , 1 , { 345name ='self' , 346type =class , 347} ) 348end 349 350table . insert ( classes [ class ]. fields , fun2field ( cur_obj )) 351return 352end 353 354-- Match `M.foo` 355if cur_obj and parent_tbl == cur_obj . modvar then 356cur_obj . name =fun_or_meth_nm 357return 358end 359end 360end 361 362do 363-- Handle: `function A.B.C.foo(...)` 364local fn_nm =line : match ( '^function%s+([.a-zA-Z0-9_]+)%s*%(' ) 365if fn_nm then 366state . cur_obj =state . cur_obj or {} 367state . cur_obj . name =fn_nm 368return 369end 370end 371 372do 373-- Handle: `M.foo = {...}` where `M` is the modvar 374local parent_tbl , tbl_nm =line : match ( '([a-zA-Z_]+)%.([a-zA-Z0-9_]+)%s*=' ) 375if state . cur_obj and parent_tbl and parent_tbl == state . cur_obj . modvar then 376state . cur_obj . name =tbl_nm 377state . cur_obj . table =true 378return 379end 380end 381 382do 383-- Handle: `foo = {...}` 384local tbl_nm =line : match ( '^([a-zA-Z0-9_]+)%s*=' ) 385if tbl_nm and not has_indent then 386state . cur_obj =state . cur_obj or {} 387state . cur_obj . name =tbl_nm 388state . cur_obj . table =true 389return 390end 391end 392 393do 394-- Handle: `vim.foo = {...}` 395local tbl_nm =line : match ( '^(vim%.[a-zA-Z0-9_]+)%s*=' ) 396if state . cur_obj and tbl_nm and not has_indent then 397state . cur_obj . name =tbl_nm 398state . cur_obj . table =true 399return 400end 401end 402 403if state . cur_obj then 404if line : find ( '^%s*%-%- luacheck:' ) then 405state . cur_obj =nil 406elseif line : find ( '^%s*local%s+' ) then 407state . cur_obj =nil 408elseif line : find ( '^%s*return%s+' ) then 409state . cur_obj =nil 410elseif line : find ( '^%s*[a-zA-Z_.]+%(%s+' ) then 411state . cur_obj =nil 412end 413end 414end 415 416--- Determine the table name used to export functions of a module 417--- Usually this is `M`. 418--- @param str string 419--- @return string? 420local function determine_modvar ( str ) 421local modvar --- @type string? 422for line in vim . gsplit ( str , '\n' ) do 423modvar =line : match ( '^return%s+setmetatable%s*%(%s*([%w_]+)%s*,' ) 424or line : match ( '^return%s+([%w_]+)' ) 425or modvar 426end 427return modvar 428end 429 430--- @param obj nvim.luacats.parser.obj 431--- @param funs nvim.luacats.parser.fun[] 432--- @param classes table<string,nvim.luacats.parser.class> 433--- @param briefs string[] 434--- @param uncommitted nvim.luacats.parser.obj[] 435local function commit_obj ( obj , classes , funs , briefs , uncommitted ) 436local commit =false 437if obj . kind == 'class' then 438--- @cast obj nvim.luacats.parser.class 439if not classes [ obj . name ] then 440classes [ obj . name ] =obj 441commit =true 442end 443elseif obj . kind == 'alias' then 444-- Just pretend 445commit =true 446elseif obj . kind == 'brief' then 447--- @cast obj nvim.luacats.parser.brief` 448briefs [ # briefs + 1 ] =obj . desc 449commit =true 450else 451--- @cast obj nvim.luacats.parser.fun` 452if obj . name then 453funs [ # funs + 1 ] =obj 454commit =true 455end 456end 457if not commit then 458table . insert ( uncommitted , obj ) 459end 460return commit 461end 462 463--- @param filename string 464--- @param uncommitted nvim.luacats.parser.obj[] 465-- luacheck: no unused 466---@diagnostic disable-next-line: unused-function, unused-local 467local function dump_uncommitted ( filename , uncommitted ) 468local out_path ='luacats-uncommited/' .. filename : gsub ( '/' , '%%' ) .. '.txt' 469if # uncommitted > 0 then 470( string . format ( 'Could not commit %d objects in %s' , # uncommitted , filename )) 471vim . fn . mkdir ( vim . fs . dirname ( out_path ), 'p' ) 472local f =assert ( io . open ( out_path , 'w' )) 473for i , x in ipairs ( uncommitted ) do 474f : write ( i ) 475f : write ( ': ' ) 476f : write ( vim . inspect ( x )) 477f : write ( '\n' ) 478end 479f : close () 480else 481vim . fn . delete ( out_path ) 482end 483end 484 485local M ={} 486 487function M . parse_str ( str , filename ) 488local funs ={} --- @type nvim.luacats.parser.fun[] 489local classes ={} --- @type table<string,nvim.luacats.parser.class> 490local briefs ={} --- @type string[] 491 492local mod_return =determine_modvar ( str ) 493 494--- @type string 495local module =filename : match ( '.*/lua/([a-z_][a-z0-9_/]+)%.lua' ) or filename 496module =module : gsub ( '/' , '.' ) 497 498--- @type nvim.luacats.parser.module 499local module_info ={ 500name =module , 501modvar =mod_return , 502requires ={} , 503imports ={} , 504assignments ={} , 505funs =funs , 506} 507 508local classvars ={} --- @type table<string,string> 509 510local state ={} --- @type nvim.luacats.parser.State 511 512-- Keep track of any partial objects we don't commit 513local uncommitted ={} --- @type nvim.luacats.parser.obj[] 514 515local comments ={} 516local in_module_metatable =false 517for line in vim . gsplit ( str , '\n' ) do 518local has_indent =line : match ( '^%s+' ) ~= nil 519line =vim . trim ( line ) 520if vim . startswith ( line , '---' ) then 521comments [ # comments + 1 ] =use_type_alt ( line : sub ( 4 ): gsub ( '^%s+@' , '@' )) 522else 523-- Recognize the returned module's inline metatable at file scope. 524if not has_indent and line ~= '' and not vim . startswith ( line , '--' ) then 525local target =line : match ( '^setmetatable%s*%(%s*([%w_]+)%s*,%s*{' ) 526or line : match ( '^return%s+setmetatable%s*%(%s*([%w_]+)%s*,%s*{' ) 527in_module_metatable =target ~= nil and target == mod_return 528end 529 530if # comments > 0 then 531local comment =table . concat ( comments , '\n' ) .. '\n' 532local pos =1 533while pos <= # comment do 534-- LPeg consumes a complete annotation, which may span several lines. 535local parsed , next_pos =luacats_grammar : match ( comment , pos ) 536local eol =assert ( comment : find ( '\n' , next_pos or pos , true )) 537process_doc_line ( comment : sub ( pos , eol - 1 ), parsed , state ) 538pos =eol + 1 539end 540comments ={} 541end 542add_doc_lines_to_obj ( state ) 543 544if not has_indent then 545local parent , name , value =line : match ( '^([%w_]+)%.([%w_]+)%s*=%s*(.*)$' ) 546if parent == mod_return and name then 547module_info . assignments [ name ] =true 548local _ , required , tail =value : match ( [[^require%s*%(%s*(['"])([^'"]+)%1%s*%)%s*(.*)$]] ) 549module_info . requires [ name ] =required and ( tail == '' or tail : match ( '^%-%-' )) and required 550or nil 551end 552end 553 554if state . cur_obj then 555state . cur_obj . modvar =mod_return 556state . cur_obj . module =module 557end 558 559-- Keep the callable declaration separate from the table's member functions. 560local returned =line : match ( '^local%s+function%s+([%w_]+)%s*%(' ) 561local callable_name =returned 562if in_module_metatable and line : match ( '^__call%s*=%s*function%s*%(' ) then 563in_module_metatable =false 564returned =mod_return 565callable_name ='__call' 566end 567if returned and returned == mod_return and state . cur_obj then 568state . cur_obj . name =callable_name 569module_info . callable =state . cur_obj 570state . cur_obj =nil 571else 572process_lua_line ( line , state , classes , classvars , has_indent ) 573end 574 575-- Commit the object 576local cur_obj =state . cur_obj 577if cur_obj then 578if not commit_obj ( cur_obj , classes , funs , briefs , uncommitted ) then 579--- @diagnostic disable-next-line:inject-field 580cur_obj . line =line 581end 582end 583 584state ={} 585end 586end 587 588if mod_return then 589module_info . class =classes [ classvars [ mod_return ]] 590end 591 592-- dump_uncommitted(filename, uncommitted) 593 594return classes , funs , briefs , uncommitted , module_info 595end 596 597--- Connect separately parsed modules by filling their `imports` and `parent` fields. 598--- Call after parsing all input files, passing their module records keyed by module name. 599--- 600--- For example, the Lua source file pkg/child.lua contains: 601--- ```lua 602--- --- @class Child: Base 603--- local M = {} 604--- M.factory = require('pkg.factory') 605--- return M 606--- ``` 607--- The caller stores the parsed record for this file in `modules['pkg.child']`. 608--- That record describes M, the table returned by the source file: 609--- - `requires.factory` contains the string 'pkg.factory'. This function fills 610--- `imports.factory` with `modules['pkg.factory']`, the parsed record for that file. 611--- - `class.parent` contains the string 'Base'. This function fills `parent` with 612--- the parsed record of the module whose returned table is annotated `@class Base`. 613--- 614--- Each link points to the original parsed module; a missing target leaves it nil. 615--- The string names in `requires` and `class.parent` are retained. No declarations 616--- are copied, renamed or hidden. 617--- @param modules table<string,nvim.luacats.parser.module> Parsed modules keyed by require path. 618function M . resolve_modules ( modules ) 619local by_class ={} --- @type table<string,nvim.luacats.parser.module> 620for _ , module in pairs ( modules ) do 621if module . class then 622by_class [ module . class . name ] =module 623end 624end 625 626for _ , module in pairs ( modules ) do 627module . imports ={} 628for name , required in pairs ( module . requires ) do 629module . imports [ name ] =modules [ required ] 630end 631module . parent =module . class and by_class [ module . class . parent ] or nil 632end 633end 634 635--- @param filename string 636function M . parse ( filename ) 637local f =assert ( io . open ( filename , 'r' )) 638local txt =f : read ( '*all' ) 639f : close () 640 641return M . parse_str ( txt , filename ) 642end 643 644return M