robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
19.8 KiB644 linesraw
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)
85  for _, type in ipairs({ 'table', 'function' }) do
86    line = line:gsub('@param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. ')%)', '@param %1 %2')
87    line = line:gsub('@param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. '|nil)%)', '@param %1 %2')
88    line = line:gsub('@param%s+([a-zA-Z_?]+)%s+.*%((' .. type .. '%?)%)', '@param %1 %2')
89
90    line = line:gsub('@return%s+.*%((' .. type .. ')%)', '@return %1')
91    line = line:gsub('@return%s+.*%((' .. type .. '|nil)%)', '@return %1')
92    line = line:gsub('@return%s+.*%((' .. type .. '%?)%)', '@return %1')
93  end
94  return 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)
101  if state.doc_lines then
102    state.cur_obj = state.cur_obj or {}
103    local cur_obj = assert(state.cur_obj)
104    local txt = table.concat(state.doc_lines, '\n')
105    if cur_obj.desc then
106      cur_obj.desc = cur_obj.desc .. '\n' .. txt
107    else
108      cur_obj.desc = txt
109    end
110    state.doc_lines = nil
111  end
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)
118  if not parsed then
119    if line:match('^ ') then
120      line = line:sub(2)
121    end
122
123    if state.last_doc_item then
124      if not state.last_doc_item_indent then
125        state.last_doc_item_indent = #line:match('^%s*') + 1
126      end
127      state.last_doc_item.desc = (state.last_doc_item.desc or '')
128        .. '\n'
129        .. line:sub(state.last_doc_item_indent or 1)
130    else
131      state.doc_lines = state.doc_lines or {}
132      table.insert(state.doc_lines, line)
133    end
134    return
135  end
136
137  state.last_doc_item_indent = nil
138  state.last_doc_item = nil
139  state.cur_obj = state.cur_obj or {}
140  local cur_obj = assert(state.cur_obj)
141
142  local kind = parsed.kind
143
144  if kind == 'brief' then
145    state.cur_obj = {
146      kind = 'brief',
147      desc = parsed.desc,
148    }
149  elseif kind == 'class' then
150    --- @cast parsed nvim.luacats.Class
151    cur_obj.kind = 'class'
152    cur_obj.name = parsed.name
153    cur_obj.generics = parsed.generics
154    cur_obj.parent = parsed.parent
155    cur_obj.parent_generics = parsed.parent_generics
156    cur_obj.access = parsed.access
157    cur_obj.desc = state.doc_lines and table.concat(state.doc_lines, '\n') or nil
158    state.doc_lines = nil
159    cur_obj.fields = {}
160  elseif kind == 'field' then
161    --- @cast parsed nvim.luacats.Field
162    if parsed.desc == '' then
163      parsed.desc = nil
164    end
165    parsed.desc = parsed.desc or state.doc_lines and table.concat(state.doc_lines, '\n') or nil
166    if parsed.desc then
167      parsed.desc = vim.trim(parsed.desc)
168    end
169    table.insert(cur_obj.fields, parsed)
170    state.doc_lines = nil
171  elseif kind == 'operator' then
172    parsed.desc = parsed.desc or state.doc_lines and table.concat(state.doc_lines, '\n') or nil
173    if parsed.desc then
174      parsed.desc = vim.trim(parsed.desc)
175    end
176    table.insert(cur_obj.fields, parsed)
177    state.doc_lines = nil
178  elseif kind == 'param' then
179    state.last_doc_item_indent = nil
180    cur_obj.params = cur_obj.params or {}
181    if vim.endswith(parsed.name, '?') then
182      parsed.name = parsed.name:sub(1, -2)
183      parsed.type = parsed.type .. '?'
184    end
185    state.last_doc_item = {
186      name = parsed.name,
187      type = parsed.type,
188      desc = parsed.desc,
189    }
190    table.insert(cur_obj.params, state.last_doc_item)
191  elseif kind == 'return' then
192    cur_obj.returns = cur_obj.returns or {}
193    for _, t in ipairs(parsed) do
194      table.insert(cur_obj.returns, {
195        name = t.name,
196        type = t.type,
197        desc = parsed.desc,
198      })
199    end
200    state.last_doc_item_indent = nil
201    state.last_doc_item = cur_obj.returns[#cur_obj.returns]
202  elseif kind == 'private' then
203    cur_obj.access = 'private'
204  elseif kind == 'package' then
205    cur_obj.access = 'package'
206  elseif kind == 'protected' then
207    cur_obj.access = 'protected'
208  elseif kind == 'internal' then
209    cur_obj.access = 'internal'
210  elseif kind == 'deprecated' then
211    cur_obj.deprecated = true
212  elseif kind == 'inlinedoc' then
213    cur_obj.inlinedoc = true
214  elseif kind == 'nodoc' then
215    cur_obj.nodoc = true
216  elseif kind == 'since' then
217    cur_obj.since = parsed.desc
218  elseif kind == 'see' then
219    cur_obj.see = cur_obj.see or {}
220    table.insert(cur_obj.see, { desc = parsed.desc })
221  elseif kind == 'note' then
222    state.last_doc_item_indent = nil
223    state.last_doc_item = {
224      desc = parsed.desc,
225    }
226    cur_obj.notes = cur_obj.notes or {}
227    table.insert(cur_obj.notes, state.last_doc_item)
228  elseif kind == 'type' then
229    cur_obj.desc = parsed.desc
230    parsed.desc = nil
231    parsed.kind = nil
232    cur_obj.type = parsed
233  elseif kind == 'alias' then
234    state.cur_obj = {
235      kind = 'alias',
236      desc = parsed.desc,
237    }
238  elseif kind == 'enum' then
239    -- TODO
240    state.doc_lines = nil
241  elseif kind == 'async' then
242    cur_obj.async = true
243  elseif kind == 'overload' then
244    cur_obj.overloads = cur_obj.overloads or {}
245    table.insert(cur_obj.overloads, parsed.type)
246  elseif
247    vim.tbl_contains({
248      'diagnostic',
249      'cast',
250      'return_cast',
251      'overload',
252      'meta',
253    }, kind)
254  then
255    -- Ignore
256    return
257  elseif kind == 'generic' then
258    cur_obj.generics = cur_obj.generics or {}
259    cur_obj.generics[parsed.name] = parsed.type or 'any'
260  else
261    error('Unhandled' .. vim.inspect(parsed))
262  end
263end
264
265--- @param fun nvim.luacats.parser.fun
266--- @return nvim.luacats.parser.field
267local function fun2field(fun)
268  local parts = { 'fun(' }
269
270  local params = {} ---@type string[]
271  for _, p in ipairs(fun.params or {}) do
272    params[#params + 1] = string.format('%s: %s', p.name, p.type)
273  end
274  parts[#parts + 1] = table.concat(params, ', ')
275  parts[#parts + 1] = ')'
276  if fun.returns then
277    parts[#parts + 1] = ': '
278    local tys = {} --- @type string[]
279    for _, p in ipairs(fun.returns) do
280      tys[#tys + 1] = p.type
281    end
282    parts[#parts + 1] = table.concat(tys, ', ')
283  end
284
285  return {
286    kind = 'field',
287    name = fun.name,
288    type = table.concat(parts, ''),
289    access = fun.access,
290    desc = fun.desc,
291    nodoc = fun.nodoc,
292    classvar = 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(...)
304  line = line:gsub('^local (.+) = memoize%([^,]+, function%((.*)%)$', 'local function %1(%2)')
305  line = line:gsub('^(.+) = memoize%([^,]+, function%((.*)%)$', 'function %1(%2)')
306  return 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)
315  line = filter_decl(line)
316
317  if state.cur_obj and state.cur_obj.kind == 'class' then
318    local nm = line:match('^local%s+([a-zA-Z0-9_]+)%s*=')
319    if nm then
320      classvars[nm] = state.cur_obj.name
321    end
322    return
323  end
324
325  do
326    local parent_tbl, sep, fun_or_meth_nm =
327      line:match('^function%s+([a-zA-Z0-9_]+)([.:])([a-zA-Z0-9_]+)%s*%(')
328    if parent_tbl then
329      -- Have a decl. Ensure cur_obj
330      state.cur_obj = state.cur_obj or {}
331      local cur_obj = assert(state.cur_obj)
332
333      -- Match `Class:foo` methods for defined classes
334      local class = classvars[parent_tbl]
335      if class then
336        --- @cast cur_obj nvim.luacats.parser.fun
337        cur_obj.name = fun_or_meth_nm
338        cur_obj.class = class
339        cur_obj.classvar = parent_tbl
340        cur_obj.member_sep = sep
341        -- Add self param to methods
342        if sep == ':' then
343          cur_obj.params = cur_obj.params or {}
344          table.insert(cur_obj.params, 1, {
345            name = 'self',
346            type = class,
347          })
348        end
349
350        table.insert(classes[class].fields, fun2field(cur_obj))
351        return
352      end
353
354      -- Match `M.foo`
355      if cur_obj and parent_tbl == cur_obj.modvar then
356        cur_obj.name = fun_or_meth_nm
357        return
358      end
359    end
360  end
361
362  do
363    -- Handle: `function A.B.C.foo(...)`
364    local fn_nm = line:match('^function%s+([.a-zA-Z0-9_]+)%s*%(')
365    if fn_nm then
366      state.cur_obj = state.cur_obj or {}
367      state.cur_obj.name = fn_nm
368      return
369    end
370  end
371
372  do
373    -- Handle: `M.foo = {...}` where `M` is the modvar
374    local parent_tbl, tbl_nm = line:match('([a-zA-Z_]+)%.([a-zA-Z0-9_]+)%s*=')
375    if state.cur_obj and parent_tbl and parent_tbl == state.cur_obj.modvar then
376      state.cur_obj.name = tbl_nm
377      state.cur_obj.table = true
378      return
379    end
380  end
381
382  do
383    -- Handle: `foo = {...}`
384    local tbl_nm = line:match('^([a-zA-Z0-9_]+)%s*=')
385    if tbl_nm and not has_indent then
386      state.cur_obj = state.cur_obj or {}
387      state.cur_obj.name = tbl_nm
388      state.cur_obj.table = true
389      return
390    end
391  end
392
393  do
394    -- Handle: `vim.foo = {...}`
395    local tbl_nm = line:match('^(vim%.[a-zA-Z0-9_]+)%s*=')
396    if state.cur_obj and tbl_nm and not has_indent then
397      state.cur_obj.name = tbl_nm
398      state.cur_obj.table = true
399      return
400    end
401  end
402
403  if state.cur_obj then
404    if line:find('^%s*%-%- luacheck:') then
405      state.cur_obj = nil
406    elseif line:find('^%s*local%s+') then
407      state.cur_obj = nil
408    elseif line:find('^%s*return%s+') then
409      state.cur_obj = nil
410    elseif line:find('^%s*[a-zA-Z_.]+%(%s+') then
411      state.cur_obj = nil
412    end
413  end
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)
421  local modvar --- @type string?
422  for line in vim.gsplit(str, '\n') do
423    modvar = line:match('^return%s+setmetatable%s*%(%s*([%w_]+)%s*,')
424      or line:match('^return%s+([%w_]+)')
425      or modvar
426  end
427  return 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)
436  local commit = false
437  if obj.kind == 'class' then
438    --- @cast obj nvim.luacats.parser.class
439    if not classes[obj.name] then
440      classes[obj.name] = obj
441      commit = true
442    end
443  elseif obj.kind == 'alias' then
444    -- Just pretend
445    commit = true
446  elseif obj.kind == 'brief' then
447    --- @cast obj nvim.luacats.parser.brief`
448    briefs[#briefs + 1] = obj.desc
449    commit = true
450  else
451    --- @cast obj nvim.luacats.parser.fun`
452    if obj.name then
453      funs[#funs + 1] = obj
454      commit = true
455    end
456  end
457  if not commit then
458    table.insert(uncommitted, obj)
459  end
460  return 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)
468  local out_path = 'luacats-uncommited/' .. filename:gsub('/', '%%') .. '.txt'
469  if #uncommitted > 0 then
470    print(string.format('Could not commit %d objects in %s', #uncommitted, filename))
471    vim.fn.mkdir(vim.fs.dirname(out_path), 'p')
472    local f = assert(io.open(out_path, 'w'))
473    for i, x in ipairs(uncommitted) do
474      f:write(i)
475      f:write(': ')
476      f:write(vim.inspect(x))
477      f:write('\n')
478    end
479    f:close()
480  else
481    vim.fn.delete(out_path)
482  end
483end
484
485local M = {}
486
487function M.parse_str(str, filename)
488  local funs = {} --- @type nvim.luacats.parser.fun[]
489  local classes = {} --- @type table<string,nvim.luacats.parser.class>
490  local briefs = {} --- @type string[]
491
492  local mod_return = determine_modvar(str)
493
494  --- @type string
495  local module = filename:match('.*/lua/([a-z_][a-z0-9_/]+)%.lua') or filename
496  module = module:gsub('/', '.')
497
498  --- @type nvim.luacats.parser.module
499  local module_info = {
500    name = module,
501    modvar = mod_return,
502    requires = {},
503    imports = {},
504    assignments = {},
505    funs = funs,
506  }
507
508  local classvars = {} --- @type table<string,string>
509
510  local state = {} --- @type nvim.luacats.parser.State
511
512  -- Keep track of any partial objects we don't commit
513  local uncommitted = {} --- @type nvim.luacats.parser.obj[]
514
515  local comments = {}
516  local in_module_metatable = false
517  for line in vim.gsplit(str, '\n') do
518    local has_indent = line:match('^%s+') ~= nil
519    line = vim.trim(line)
520    if vim.startswith(line, '---') then
521      comments[#comments + 1] = use_type_alt(line:sub(4):gsub('^%s+@', '@'))
522    else
523      -- Recognize the returned module's inline metatable at file scope.
524      if not has_indent and line ~= '' and not vim.startswith(line, '--') then
525        local target = line:match('^setmetatable%s*%(%s*([%w_]+)%s*,%s*{')
526          or line:match('^return%s+setmetatable%s*%(%s*([%w_]+)%s*,%s*{')
527        in_module_metatable = target ~= nil and target == mod_return
528      end
529
530      if #comments > 0 then
531        local comment = table.concat(comments, '\n') .. '\n'
532        local pos = 1
533        while pos <= #comment do
534          -- LPeg consumes a complete annotation, which may span several lines.
535          local parsed, next_pos = luacats_grammar:match(comment, pos)
536          local eol = assert(comment:find('\n', next_pos or pos, true))
537          process_doc_line(comment:sub(pos, eol - 1), parsed, state)
538          pos = eol + 1
539        end
540        comments = {}
541      end
542      add_doc_lines_to_obj(state)
543
544      if not has_indent then
545        local parent, name, value = line:match('^([%w_]+)%.([%w_]+)%s*=%s*(.*)$')
546        if parent == mod_return and name then
547          module_info.assignments[name] = true
548          local _, required, tail = value:match([[^require%s*%(%s*(['"])([^'"]+)%1%s*%)%s*(.*)$]])
549          module_info.requires[name] = required and (tail == '' or tail:match('^%-%-')) and required
550            or nil
551        end
552      end
553
554      if state.cur_obj then
555        state.cur_obj.modvar = mod_return
556        state.cur_obj.module = module
557      end
558
559      -- Keep the callable declaration separate from the table's member functions.
560      local returned = line:match('^local%s+function%s+([%w_]+)%s*%(')
561      local callable_name = returned
562      if in_module_metatable and line:match('^__call%s*=%s*function%s*%(') then
563        in_module_metatable = false
564        returned = mod_return
565        callable_name = '__call'
566      end
567      if returned and returned == mod_return and state.cur_obj then
568        state.cur_obj.name = callable_name
569        module_info.callable = state.cur_obj
570        state.cur_obj = nil
571      else
572        process_lua_line(line, state, classes, classvars, has_indent)
573      end
574
575      -- Commit the object
576      local cur_obj = state.cur_obj
577      if cur_obj then
578        if not commit_obj(cur_obj, classes, funs, briefs, uncommitted) then
579          --- @diagnostic disable-next-line:inject-field
580          cur_obj.line = line
581        end
582      end
583
584      state = {}
585    end
586  end
587
588  if mod_return then
589    module_info.class = classes[classvars[mod_return]]
590  end
591
592  -- dump_uncommitted(filename, uncommitted)
593
594  return 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)
619  local by_class = {} --- @type table<string,nvim.luacats.parser.module>
620  for _, module in pairs(modules) do
621    if module.class then
622      by_class[module.class.name] = module
623    end
624  end
625
626  for _, module in pairs(modules) do
627    module.imports = {}
628    for name, required in pairs(module.requires) do
629      module.imports[name] = modules[required]
630    end
631    module.parent = module.class and by_class[module.class.parent] or nil
632  end
633end
634
635--- @param filename string
636function M.parse(filename)
637  local f = assert(io.open(filename, 'r'))
638  local txt = f:read('*all')
639  f:close()
640
641  return M.parse_str(txt, filename)
642end
643
644return M