robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
40.3 KiB1418 linesraw
1#!/usr/bin/env -S nvim -l
2--- Generates Nvim :help docs from Lua/C docstrings.
3---
4--- Usage:
5---     make doc
6---
7--- The generated :help text for each function is formatted as follows:
8--- - Max width of 78 columns (`TEXT_WIDTH`).
9--- - Indent with spaces (not tabs).
10--- - Indent of 4 columns for body text (`INDENTATION`).
11--- - Function signature and helptag (right-aligned) on the same line.
12---   - Signature and helptag must have a minimum of 8 spaces between them.
13---   - If the signature is too long, it is placed on the line after the helptag.
14---     Signature wraps with subsequent lines indented to the open parenthesis.
15---   - Subsection bodies are indented an additional 4 spaces.
16--- - Body consists of function description, parameters, return description, and
17---   C declaration (`INCLUDE_C_DECL`).
18--- - Parameters are omitted for the `void` and `Error *` types, or if the
19---   parameter is marked as [out].
20--- - Each function documentation is separated by a single line.
21
22local luacats_parser = require('gen.luacats_parser')
23local cdoc_parser = require('gen.cdoc_parser')
24local util = require('gen.util')
25local lint = require('gen.lint')
26
27local fmt = string.format
28
29local wrap = util.wrap
30local md_to_vimdoc = util.md_to_vimdoc
31local align_tags = util.align_tags
32
33local TEXT_WIDTH = 78
34local INDENTATION = 4
35
36--- @class (exact) nvim.gen_vimdoc.Config
37---
38--- Generated documentation target, e.g. api.txt
39--- @field filename string
40---
41--- Ordered filenames or groups of filenames to merge into one section.
42--- For a group, the first filename determines the section name and help tag.
43--- @field section_order (string|string[])[]
44---
45--- List of files/directories for doxygen to read, relative to `base_dir`.
46--- @field files string[]
47---
48--- Section name overrides. Key: filename (e.g., vim.c)
49--- @field section_name? table<string,string>
50---
51--- @field fn_name_pat? string
52---
53--- @field fn_xform? fun(fun: nvim.luacats.parser.fun)
54---
55--- @field brief_xform? fun(brief: string): string
56---
57--- For generated section names.
58--- @field section_fmt fun(name: string): string
59---
60--- @field helptag_fmt fun(name: string): string|string[]
61---
62--- Per-function helptag.
63--- @field fn_helptag_fmt? fun(fun: nvim.gen_vimdoc.HelptagTarget): string
64
65---@alias nvim.gen_vimdoc.HelptagTarget
66---| nvim.luacats.parser.fun
67---| nvim.luacats.parser.field
68---| nvim.luacats.parser.param
69
70local function contains(t, xs)
71  return vim.tbl_contains(xs, t)
72end
73
74--- True if the `.` class member should render like a module function.
75--- @param fun nvim.gen_vimdoc.HelptagTarget
76--- @return boolean
77local function is_module_fun(fun)
78  return fun.classvar ~= nil
79    and fun.member_sep == '.'
80    and fun.modvar ~= nil
81    and fun.module ~= nil
82    and fun.classvar == fun.modvar
83end
84
85--- @type {level:integer, prerelease:boolean}?
86local nvim_api_info_
87
88--- @return {level: integer, prerelease:boolean}
89local function nvim_api_info()
90  if not nvim_api_info_ then
91    --- @type integer?, boolean?
92    local level, prerelease
93    for l in io.lines('CMakeLists.txt') do
94      --- @cast l string
95      if level and prerelease then
96        break
97      end
98      local m1 = l:match('^set%(NVIM_API_LEVEL%s+(%d+)%)')
99      if m1 then
100        level = tonumber(m1) --[[@as integer]]
101      end
102      local m2 = l:match('^set%(NVIM_API_PRERELEASE%s+(%w+)%)')
103      if m2 then
104        prerelease = m2 == 'true'
105      end
106    end
107    nvim_api_info_ = { level = assert(level), prerelease = assert(prerelease) }
108  end
109
110  return nvim_api_info_
111end
112
113--- @param fun nvim.gen_vimdoc.HelptagTarget
114--- @return string
115local function fn_helptag_fmt_common(fun)
116  local fn_sfx = fun.table and '' or '()'
117  if is_module_fun(fun) then
118    return fmt('%s.%s%s', fun.module, fun.name, fn_sfx)
119  end
120  if fun.classvar then
121    return fmt('%s:%s%s', fun.classvar, fun.name, fn_sfx)
122  end
123  if fun.module then
124    return fmt('%s.%s%s', fun.module, fun.name, fn_sfx)
125  end
126  return fun.name .. fn_sfx
127end
128
129--- @type table<string,nvim.gen_vimdoc.Config>
130local config = {
131  api = {
132    filename = 'api.txt',
133    section_order = {
134      -- Sections at the top, in a specific order:
135      'events.c',
136      'vim.c',
137      'vimscript.c',
138
139      -- Sections in alphanumeric order:
140      'autocmd.c',
141      'buffer.c',
142      'command.c',
143      'extmark.c',
144      'options.c',
145      'tabpage.c',
146      'ui.c',
147      'win_config.c',
148      'window.c',
149    },
150    fn_name_pat = 'nvim_.*',
151    files = { 'src/nvim/api' },
152    section_name = {
153      ['vim.c'] = 'Global',
154    },
155    section_fmt = function(name)
156      if name == 'Events' then
157        return 'Global Events'
158      end
159
160      return name .. ' Functions'
161    end,
162    helptag_fmt = function(name)
163      return fmt('api-%s', name:lower())
164    end,
165    fn_helptag_fmt = function(fun)
166      local name = fun.name
167      if vim.endswith(name, '_event') then
168        return name
169      end
170      return fn_helptag_fmt_common(fun)
171    end,
172  },
173  lua = {
174    filename = 'lua.txt',
175    section_order = {
176      -- Sections at the top, in a specific order:
177      'builtin.lua',
178      'options.lua',
179      { 'editor.lua', 'inspect.lua', 'shared.lua' },
180      '_inspector.lua',
181
182      -- Sections in alphanumeric order:
183      'base64.lua',
184      'filetype.lua',
185      'fs.lua',
186      'glob.lua',
187      'hl.lua',
188      'iter.lua',
189      'json.lua',
190      'keymap.lua',
191      'loader.lua',
192      'log.lua',
193      'lpeg.lua',
194      'mpack.lua',
195      'net.lua',
196      'pos.lua',
197      'range.lua',
198      're.lua',
199      'regex.lua',
200      'secure.lua',
201      'snippet.lua',
202      'spell.lua',
203      'system.lua',
204      'text.lua',
205      'ui.lua',
206      'img.lua', -- ui/img.lua
207      'uri.lua',
208      'version.lua',
209
210      -- Sections at the end, in a specific order:
211      'ui2.lua',
212    },
213    files = {
214      'runtime/lua/vim/_core/editor.lua',
215      'runtime/lua/vim/_core/options.lua',
216      'runtime/lua/vim/_core/shared.lua',
217      'runtime/lua/vim/_core/system.lua',
218      'runtime/lua/vim/_core/ui2.lua',
219      'runtime/lua/vim/_inspector.lua',
220      'runtime/lua/vim/_meta/base64.lua',
221      'runtime/lua/vim/_meta/builtin.lua',
222      'runtime/lua/vim/_meta/json.lua',
223      'runtime/lua/vim/_meta/lpeg.lua',
224      'runtime/lua/vim/_meta/mpack.lua',
225      'runtime/lua/vim/_meta/re.lua',
226      'runtime/lua/vim/_meta/regex.lua',
227      'runtime/lua/vim/_meta/spell.lua',
228      'runtime/lua/vim/filetype.lua',
229      'runtime/lua/vim/fs.lua',
230      'runtime/lua/vim/glob.lua',
231      'runtime/lua/vim/hl.lua',
232      'runtime/lua/vim/inspect.lua',
233      'runtime/lua/vim/iter.lua',
234      'runtime/lua/vim/keymap.lua',
235      'runtime/lua/vim/loader.lua',
236      'runtime/lua/vim/log.lua',
237      'runtime/lua/vim/net.lua',
238      'runtime/lua/vim/pos.lua',
239      'runtime/lua/vim/range.lua',
240      'runtime/lua/vim/secure.lua',
241      'runtime/lua/vim/snippet.lua',
242      'runtime/lua/vim/text.lua',
243      'runtime/lua/vim/ui.lua',
244      'runtime/lua/vim/ui/img.lua',
245      'runtime/lua/vim/uri.lua',
246      'runtime/lua/vim/version.lua',
247    },
248    fn_xform = function(fun)
249      if contains(fun.module, { 'vim.uri', 'vim._core.shared', 'vim._core.editor' }) then
250        fun.module = 'vim'
251      end
252
253      if fun.module == 'vim' and fun.name == 'cmd' then
254        fun.table = nil
255      end
256
257      -- Render the callable version module as ordinary module functions.
258      if fun.class == 'vim.VersionModule' then
259        fun.classvar = nil
260      end
261
262      if fun.classvar or vim.startswith(fun.name, 'vim.') or fun.module == 'vim.iter' then
263        return
264      end
265
266      fun.name = fmt('%s.%s', fun.module, fun.name)
267    end,
268    section_name = {
269      ['_inspector.lua'] = 'inspector',
270      ['img.lua'] = 'ui.img',
271      ['ui2.lua'] = 'ui2',
272    },
273    section_fmt = function(name)
274      name = name:lower()
275      if name == 'editor' then
276        return 'Lua module: vim'
277      elseif name == 'system' then
278        return 'Lua module: vim.system'
279      elseif name == 'options' then
280        return 'LUA-VIMSCRIPT BRIDGE'
281      elseif name == 'builtin' then
282        return 'VIM'
283      elseif name == 'ui2' then
284        return 'UI2'
285      end
286      return 'Lua module: vim.' .. name
287    end,
288    helptag_fmt = function(name)
289      if name == 'Editor' then
290        return 'lua-vim'
291      elseif name == 'System' then
292        return 'lua-vim-system'
293      elseif name == 'Options' then
294        return 'lua-vimscript'
295      elseif name == 'ui2' then
296        return 'ui2'
297      end
298      return 'vim.' .. name:lower()
299    end,
300    fn_helptag_fmt = function(fun)
301      local name = fun.name
302
303      if vim.startswith(name, 'vim.') then
304        local fn_sfx = fun.table and '' or '()'
305        return name .. fn_sfx
306      elseif fun.classvar == 'Option' then
307        return fmt('vim.opt:%s()', name)
308      end
309
310      return fn_helptag_fmt_common(fun)
311    end,
312  },
313  lsp = {
314    filename = 'lsp.txt',
315    section_order = {
316      -- Sections at the top, in a specific order:
317      { 'lsp.lua', 'tagfunc.lua' },
318
319      -- Sections in alphanumeric order:
320      'buf.lua',
321      'client.lua',
322      'codelens.lua',
323      'completion.lua',
324      'diagnostic.lua',
325      'document_color.lua',
326      'folding_range.lua',
327      'handlers.lua',
328      'inlay_hint.lua',
329      'inline_completion.lua',
330      'linked_editing_range.lua',
331      'log.lua',
332      'on_type_formatting.lua',
333      'rpc.lua',
334      'semantic_tokens.lua',
335
336      -- Sections at the end, in a specific order:
337      'util.lua',
338      'protocol.lua',
339    },
340    files = {
341      'runtime/lua/vim/lsp',
342      'runtime/lua/vim/lsp.lua',
343    },
344    fn_xform = function(fun)
345      fun.name = fun.name:gsub('result%.', '')
346      if fun.module == 'vim.lsp' and fun.name == 'config' then
347        fun.table = nil
348      end
349      if fun.module == 'vim.lsp.protocol' then
350        fun.classvar = nil
351      end
352    end,
353    section_fmt = function(name)
354      if name:lower() == 'lsp' then
355        return 'Lua module: vim.lsp'
356      end
357      return 'Lua module: vim.lsp.' .. name:lower()
358    end,
359    helptag_fmt = function(name)
360      if name:lower() == 'lsp' then
361        return 'lsp-core'
362      end
363      return fmt('lsp-%s', name:lower())
364    end,
365  },
366  async = {
367    filename = 'lua-async.txt',
368    section_order = {
369      { 'async.lua', '_core.lua', '_semaphore.lua' },
370    },
371    files = {
372      'runtime/lua/vim/async.lua',
373      'runtime/lua/vim/async/_core.lua',
374      'runtime/lua/vim/async/_semaphore.lua',
375    },
376    section_fmt = function()
377      return 'Lua module: vim.async'
378    end,
379    helptag_fmt = function()
380      return { 'lua-async', 'vim.async' }
381    end,
382    fn_xform = function(fun)
383      if fun.classvar == 'M' then
384        fun.classvar = nil
385      end
386    end,
387  },
388  diagnostic = {
389    filename = 'diagnostic.txt',
390    section_order = {
391      'diagnostic.lua',
392    },
393    files = { 'runtime/lua/vim/diagnostic.lua' },
394    section_fmt = function()
395      return 'Lua module: vim.diagnostic'
396    end,
397    helptag_fmt = function()
398      return 'diagnostic-api'
399    end,
400  },
401  treesitter = {
402    filename = 'treesitter.txt',
403    section_order = {
404      -- Sections at the top, in a specific order:
405      'tstree.lua',
406      'tsnode.lua',
407      'treesitter.lua',
408
409      -- Sections in alphanumeric order:
410      'dev.lua',
411      'highlighter.lua',
412      'language.lua',
413      'languagetree.lua',
414      { 'query.lua', 'tsquery.lua' },
415    },
416    files = {
417      'runtime/lua/vim/treesitter/_meta/',
418      'runtime/lua/vim/treesitter.lua',
419      'runtime/lua/vim/treesitter/',
420    },
421    section_fmt = function(name)
422      if name:lower() == 'treesitter' then
423        return 'Lua module: vim.treesitter'
424      elseif name:lower() == 'tstree' then
425        return 'TREESITTER TREES'
426      elseif name:lower() == 'tsnode' then
427        return 'TREESITTER NODES'
428      end
429      return 'Lua module: vim.treesitter.' .. name:lower()
430    end,
431    helptag_fmt = function(name)
432      if name:lower() == 'treesitter' then
433        return 'lua-treesitter-core'
434      elseif name:lower() == 'query' then
435        return 'lua-treesitter-query'
436      elseif name:lower() == 'tstree' then
437        return { 'treesitter-tree', 'TSTree' }
438      elseif name:lower() == 'tsnode' then
439        return { 'treesitter-node', 'TSNode' }
440      end
441      return 'treesitter-' .. name:lower()
442    end,
443  },
444  health = {
445    filename = 'health.txt',
446    files = {
447      'runtime/lua/vim/health.lua',
448    },
449    section_order = {
450      'health.lua',
451    },
452    section_fmt = function(_name)
453      return 'Checkhealth'
454    end,
455    helptag_fmt = function()
456      return { 'vim.health', 'health' }
457    end,
458  },
459  pack = {
460    filename = 'pack.txt',
461    files = { 'runtime/lua/vim/pack.lua' },
462    section_order = { 'pack.lua' },
463    section_fmt = function(_name)
464      return 'Plugin manager'
465    end,
466    helptag_fmt = function()
467      return { 'vim.pack' }
468    end,
469  },
470  plugins = {
471    filename = 'plugins.txt',
472    section_order = {
473      'difftool.lua',
474      'editorconfig.lua',
475      'spellfile.lua',
476      'tohtml.lua',
477      'undotree.lua',
478    },
479    files = {
480      'runtime/lua/editorconfig.lua',
481      'runtime/lua/nvim/spellfile.lua',
482      'runtime/pack/dist/opt/nvim.tohtml/lua/tohtml.lua',
483      'runtime/pack/dist/opt/nvim.undotree/lua/undotree.lua',
484      'runtime/pack/dist/opt/nvim.difftool/lua/difftool.lua',
485    },
486    fn_xform = function(fun)
487      if fun.module == 'editorconfig' then
488        -- Example: "editorconfig.properties.root()" => "editorconfig.root"
489        fun.table = true
490        fun.name = vim.split(fun.name, '.', { plain = true })[2] or fun.name
491      end
492      if vim.startswith(fun.module, 'nvim.') then
493        fun.module = fun.module:sub(#'nvim.' + 1)
494      end
495    end,
496    section_fmt = function(name)
497      return 'Builtin plugin: ' .. name:lower()
498    end,
499    helptag_fmt = function(name)
500      name = name:lower()
501      if vim.tbl_contains({ 'spellfile', 'tohtml', 'undotree' }, name) then
502        name = ('package-%s'):format(name)
503      end
504      return name
505    end,
506  },
507  tui = {
508    filename = 'tui.txt',
509    section_order = { 'tui.lua' },
510    files = { 'runtime/lua/vim/_meta/tui.lua' },
511    section_fmt = function(_name)
512      return 'Terminfo override'
513    end,
514    helptag_fmt = function()
515      return { 'tui-termdefs' }
516    end,
517    brief_xform = function(brief)
518      local terminfo = require('src.gen.terminfo').fields
519      local booleans = terminfo.bools
520      local numbers = terminfo.ints
521      local strings = terminfo.strings
522
523      local strings_ext = vim.tbl_map(function(v)
524        return v[1]
525      end, terminfo.strings_ext)
526
527      local unshifted_keys = vim.tbl_map(function(v)
528        return 'key_' .. v[1]
529      end, (vim.tbl_filter(function(v)
530        return not v[2]
531      end, terminfo.termkeys)))
532
533      local shifted_keys = vim.tbl_map(function(v)
534        return 'key_' .. v[1]
535      end, (vim.tbl_filter(function(v)
536        return v[2]
537      end, terminfo.termkeys)))
538
539      local f_keys = { 'key_f1', '...', 'key_f' .. terminfo.func_key_max }
540
541      local table_rows = { { 'Field', 'Type' } }
542      local col1_max_width = 0
543      --- @param defs string[]
544      --- @param type string
545      --- @param omit_padding_row nil | boolean
546      --- @param skip_sort nil | boolean
547      local function add_defs(defs, type, omit_padding_row, skip_sort)
548        if not skip_sort then
549          table.sort(defs)
550        end
551        for _, def in ipairs(defs) do
552          table.insert(table_rows, { def, type })
553          col1_max_width = math.max(col1_max_width, #def)
554        end
555        if not omit_padding_row then
556          table.insert(table_rows, { '', '' })
557        end
558      end
559
560      add_defs(booleans, 'bool')
561      add_defs(numbers, 'int')
562      add_defs(strings, 'string')
563      add_defs(strings_ext, 'string')
564      add_defs(unshifted_keys, 'string')
565      add_defs(shifted_keys, 'string[]')
566      add_defs(f_keys, 'string', true, true)
567
568      -- Convert all the table rows into strings by calculating the padding
569      -- needed between them
570      local table_str_rows = {}
571      local min_padding = 3 -- padding between table columns
572      local max_width = 0 -- max width of col1 + padding + col2
573      local indent = '    '
574      for _, row in ipairs(table_rows) do
575        if #row[1] == 0 then
576          table.insert(table_str_rows, '')
577        else
578          local padding = string.rep(' ', col1_max_width + min_padding - #row[1])
579          local val = table.concat(row, padding)
580          max_width = math.max(max_width, #val)
581          table.insert(table_str_rows, indent .. val)
582        end
583      end
584
585      -- Add table header
586      table.insert(table_str_rows, 2, indent .. string.rep('-', max_width))
587      return (brief:gsub('NVIM_TERMDEFS_TABLE', table.concat(table_str_rows, '\n')))
588    end,
589  },
590}
591
592--- @param ty string
593--- @param generics table<string,string>
594--- @return string
595local function replace_generics(ty, generics)
596  if ty:sub(-2) == '[]' then
597    local ty0 = ty:sub(1, -3)
598    if generics[ty0] then
599      return generics[ty0] .. '[]'
600    end
601  elseif ty:sub(-1) == '?' then
602    local ty0 = ty:sub(1, -2)
603    if generics[ty0] then
604      return generics[ty0] .. '?'
605    end
606  end
607
608  return generics[ty] or ty
609end
610
611--- @param name string
612local function fmt_field_name(name)
613  local name0, opt = name:match('^([^?]*)(%??)$')
614  return fmt('{%s}%s', name0, opt)
615end
616
617--- @param ty string
618--- @param generics? table<string,string>
619--- @param default? string
620local function render_type(ty, generics, default)
621  ty = ty:gsub('vim%.lsp%.protocol%.Method.[%w.]+', 'string')
622
623  if generics then
624    ty = replace_generics(ty, generics)
625  end
626  ty = ty:gsub('%s*|%s*nil', '?')
627  ty = ty:gsub('nil%s*|%s*(.*)', '%1?')
628  ty = ty:gsub('%s*|%s*', '|')
629  if default then
630    return fmt('(`%s`, default: %s)', ty, default)
631  end
632  return fmt('(`%s`)', ty)
633end
634
635--- @param p nvim.luacats.parser.param|nvim.luacats.parser.field
636local function should_render_field_or_param(p)
637  return not p.nodoc
638    and not p.access
639    and not contains(p.name, { '_', 'self' })
640    and not vim.startswith(p.name, '_')
641end
642
643--- Gets a field's description and its "(default: …)" value, if any (see `lsp/client.lua` for
644--- examples).
645---
646--- @param desc? string
647--- @return string?, string?
648local function get_default(desc)
649  if not desc then
650    return
651  end
652
653  local default = desc:match('\n%s*%([dD]efault: ([^)]+)%)')
654  if default then
655    desc = desc:gsub('\n%s*%([dD]efault: [^)]+%)', '')
656  end
657
658  return desc, default
659end
660
661--- @param ty string
662--- @param classes? table<string,nvim.luacats.parser.class>
663--- @return nvim.luacats.parser.class?
664local function get_class(ty, classes)
665  if not classes then
666    return
667  end
668
669  local cty = ty:gsub('%s*|%s*nil', '?'):gsub('?$', ''):gsub('%[%]$', ''):gsub('%b<>$', '')
670
671  return classes[cty]
672end
673
674--- Recursively resolves `@inlinedoc` classes: replaces the type with "table" and expands class
675--- fields into the object's description.
676---
677--- @param obj nvim.luacats.parser.param|nvim.luacats.parser.return|nvim.luacats.parser.field
678--- @param classes? table<string,nvim.luacats.parser.class>
679local function inline_type(obj, classes)
680  local ty = obj.type
681  if not ty then
682    return
683  end
684
685  local cls = get_class(ty, classes)
686
687  if not cls or cls.nodoc or not cls.inlinedoc then
688    return
689  end
690
691  local ty_isopt = (ty:match('%?$') or ty:match('%s*|%s*nil')) ~= nil
692  local ty_islist = (ty:match('%[%]$')) ~= nil
693  ty = ty_isopt and 'table?' or ty_islist and 'table[]' or 'table'
694
695  local desc = obj.desc or ''
696  if cls.desc then
697    desc = desc .. cls.desc
698  elseif desc == '' then
699    if ty_islist then
700      desc = desc .. 'A list of objects with the following fields:'
701    elseif cls.parent then
702      desc = desc .. fmt('Extends |%s| with the additional fields:', cls.parent)
703    else
704      desc = desc .. 'A table with the following fields:'
705    end
706  end
707
708  util.sort_by_key(cls.fields, 'name')
709
710  local desc_append = {}
711  for _, f in ipairs(cls.fields) do
712    if not f.access then
713      inline_type(f, classes)
714      local fdesc, default = get_default(f.desc)
715      if fdesc then
716        -- Indent nested list items from recursive inlining.
717        fdesc = fdesc:gsub('\n(%- {)', '\n  %1')
718      end
719      local fty = render_type(f.type, nil, default)
720      local fnm = fmt_field_name(f.name)
721      table.insert(desc_append, table.concat({ '-', fnm, fty, fdesc }, ' '))
722    end
723  end
724
725  desc = desc .. '\n' .. table.concat(desc_append, '\n')
726  obj.type = ty
727  obj.desc = desc
728end
729
730--- @param xs (nvim.luacats.parser.param|nvim.luacats.parser.field)[]
731--- @param generics? table<string,string>
732--- @param classes? table<string,nvim.luacats.parser.class>
733--- @param cfg nvim.gen_vimdoc.Config
734local function render_fields_or_params(xs, generics, classes, cfg)
735  local ret = {} --- @type string[]
736
737  xs = vim.tbl_filter(should_render_field_or_param, xs)
738
739  local indent = 0
740  for _, p in ipairs(xs) do
741    if p.type or p.desc then
742      indent = math.max(indent, #p.name + 3)
743    end
744  end
745
746  for _, p in ipairs(xs) do
747    local pdesc, default = get_default(p.desc)
748    p.desc = pdesc
749
750    inline_type(p, classes)
751    local nm, ty = p.name, p.type
752
753    local desc = p.classvar and fmt('See |%s|.', cfg.fn_helptag_fmt(p)) or p.desc
754
755    local fnm = p.kind == 'operator' and fmt('op(%s)', nm) or fmt_field_name(nm)
756    local pnm = fmt('      • %-' .. indent .. 's', fnm)
757
758    if ty then
759      local pty = render_type(ty, generics, default)
760
761      if desc then
762        table.insert(ret, pnm)
763        if #pty > TEXT_WIDTH - indent then
764          vim.list_extend(ret, { ' ', pty, '\n' })
765          table.insert(ret, md_to_vimdoc(desc, 9 + indent, 9 + indent, TEXT_WIDTH, true))
766        else
767          desc = fmt('%s %s', pty, desc)
768          table.insert(ret, md_to_vimdoc(desc, 1, 9 + indent, TEXT_WIDTH, true))
769        end
770      else
771        table.insert(ret, fmt('%s %s\n', pnm, pty))
772      end
773    else
774      if desc then
775        table.insert(ret, pnm)
776        table.insert(ret, md_to_vimdoc(desc, 1, 9 + indent, TEXT_WIDTH, true))
777      end
778    end
779  end
780
781  return table.concat(ret)
782end
783
784--- @param class nvim.luacats.parser.class
785--- @param classes table<string,nvim.luacats.parser.class>
786--- @param hidden_fields? table<string,table<string,true>>
787--- @param cfg nvim.gen_vimdoc.Config
788local function render_class(class, classes, hidden_fields, cfg)
789  if class.access or class.nodoc or class.inlinedoc then
790    return
791  end
792
793  local ret = {} --- @type string[]
794
795  table.insert(ret, fmt('*%s*\n', class.name))
796
797  if class.parent then
798    local txt = fmt('Extends: |%s|', class.parent)
799    table.insert(ret, md_to_vimdoc(txt, INDENTATION, INDENTATION, TEXT_WIDTH))
800    table.insert(ret, '\n')
801  end
802
803  if class.desc then
804    table.insert(ret, md_to_vimdoc(class.desc, INDENTATION, INDENTATION, TEXT_WIDTH))
805  end
806
807  local class_hidden = hidden_fields and hidden_fields[class.name]
808  local fields = class.fields
809  if class_hidden then
810    fields = vim.tbl_filter(function(field)
811      return not class_hidden[field.name]
812    end, fields)
813  end
814
815  util.sort_by_key(fields, 'name')
816
817  local fields_txt = render_fields_or_params(fields, nil, classes, cfg)
818  if not fields_txt:match('^%s*$') then
819    table.insert(ret, '\n    Fields: ~\n')
820    table.insert(ret, fields_txt)
821  end
822  table.insert(ret, '\n')
823
824  return table.concat(ret)
825end
826
827--- @param classes table<string,nvim.luacats.parser.class>
828--- @param funs nvim.luacats.parser.fun[]
829--- @param cfg nvim.gen_vimdoc.Config
830local function render_classes(classes, funs, cfg)
831  local ret = {} --- @type string[]
832  -- Hide `.` members of returned class-modules from class Fields;
833  -- they render as module functions.
834  local hidden_fields = {} --- @type table<string,table<string,true>>
835  for _, fun in ipairs(funs) do
836    if is_module_fun(fun) and fun.class then
837      hidden_fields[fun.class] = hidden_fields[fun.class] or {}
838      hidden_fields[fun.class][fun.name] = true
839    end
840  end
841
842  for _, class in vim.spairs(classes) do
843    ret[#ret + 1] = render_class(class, classes, hidden_fields, cfg)
844  end
845
846  return table.concat(ret)
847end
848
849--- @param fun nvim.luacats.parser.fun
850--- @param cfg nvim.gen_vimdoc.Config
851local function render_fun_header(fun, cfg)
852  local ret = {} --- @type string[]
853
854  local args = {} --- @type string[]
855  for _, p in ipairs(fun.params or {}) do
856    if p.name ~= 'self' then
857      args[#args + 1] = fmt_field_name(p.name)
858    end
859  end
860
861  local nm = fun.name
862  if fun.classvar and not is_module_fun(fun) then
863    nm = fmt('%s:%s', fun.classvar, nm)
864  end
865  if nm == 'vim.bo' then
866    nm = 'vim.bo[{bufnr}]'
867  end
868  if nm == 'vim.wo' then
869    nm = 'vim.wo[{winid}][{bufnr}]'
870  end
871
872  local proto = fun.table and nm or nm .. '(' .. table.concat(args, ', ') .. ')'
873
874  local tag = '*' .. cfg.fn_helptag_fmt(fun) .. '*'
875
876  if #proto + #tag > TEXT_WIDTH - 8 then
877    table.insert(ret, fmt('%78s\n', tag))
878    local name, pargs = proto:match('([^(]+%()(.*)')
879    if name then
880      table.insert(ret, name)
881      table.insert(ret, wrap(pargs, 0, #name, TEXT_WIDTH))
882    else
883      table.insert(ret, proto)
884    end
885  else
886    local pad = TEXT_WIDTH - #proto - #tag
887    table.insert(ret, proto .. string.rep(' ', pad) .. tag)
888  end
889
890  return table.concat(ret)
891end
892
893--- @param returns nvim.luacats.parser.return[]
894--- @param generics? table<string,string>
895--- @param classes? table<string,nvim.luacats.parser.class>
896--- @return string?
897local function render_returns(returns, generics, classes)
898  local ret = {} --- @type string[]
899
900  if #returns == 1 and returns[1].type == 'nil' then
901    return
902  end
903
904  if #returns > 1 then
905    table.insert(ret, '    Return (multiple): ~\n')
906  elseif #returns == 1 and next(returns[1]) then
907    table.insert(ret, '    Return: ~\n')
908  end
909
910  for _, p in ipairs(returns) do
911    inline_type(p, classes)
912    local rnm, ty, desc = p.name, p.type, p.desc
913
914    local blk = {} --- @type string[]
915    if ty then
916      blk[#blk + 1] = render_type(ty, generics)
917    end
918    blk[#blk + 1] = rnm
919    blk[#blk + 1] = desc
920
921    ret[#ret + 1] = md_to_vimdoc(table.concat(blk, ' '), 8, 8, TEXT_WIDTH, true)
922  end
923
924  return table.concat(ret)
925end
926
927--- @param fun nvim.luacats.parser.fun
928--- @param classes table<string,nvim.luacats.parser.class>
929--- @param cfg nvim.gen_vimdoc.Config
930local function render_fun(fun, classes, cfg)
931  if fun.access or fun.deprecated or fun.nodoc then
932    return
933  end
934
935  if cfg.fn_name_pat and not fun.name:match(cfg.fn_name_pat) then
936    return
937  end
938
939  if not fun.name then
940    error(('fun.name is nil, check fn_xform(). fun: %s'):format(vim.inspect(fun)))
941  end
942
943  if vim.startswith(fun.name, '_') or fun.name:find('[:.]_') then
944    return
945  end
946
947  local internal = vim.startswith(fun.name, 'nvim__')
948  local ret = {} --- @type string[]
949
950  table.insert(ret, render_fun_header(fun, cfg))
951  table.insert(ret, '\n')
952
953  if internal or fun.since then
954    local since = assert(tonumber(fun.since or (internal and 0)), 'invalid @since on ' .. fun.name)
955    local nvim_api = false and nvim_api_info()
956    _ = nvim_api -- Disable prerelease "WARNING" doc, in preparation for for upcoming release.
957
958    if
959      internal or since == 0 --[[or (nvim_api.prerelease and since == nvim_api.level)]]
960    then
961      -- Experimental = (since==0 or current prerelease)
962      local s = 'WARNING: This feature is experimental/unstable.'
963      table.insert(ret, md_to_vimdoc(s, INDENTATION, INDENTATION, TEXT_WIDTH))
964      table.insert(ret, '\n')
965    end
966    if since > 0 then
967      local v = assert(util.version_level[since], 'invalid @since on ' .. fun.name)
968      fun.attrs = fun.attrs or {}
969      table.insert(fun.attrs, fmt('Since: %s', v))
970    end
971  end
972
973  if fun.desc then
974    table.insert(ret, md_to_vimdoc(fun.desc, INDENTATION, INDENTATION, TEXT_WIDTH))
975  end
976
977  if fun.notes then
978    table.insert(ret, '\n    Note: ~\n')
979    for _, p in ipairs(fun.notes) do
980      table.insert(ret, '      • ' .. md_to_vimdoc(p.desc, 0, 8, TEXT_WIDTH, true))
981    end
982  end
983
984  if fun.attrs then
985    table.insert(ret, '\n    Attributes: ~\n')
986    for _, attr in ipairs(fun.attrs) do
987      local attr_str = ({
988        textlock = 'not allowed when |textlock| is active',
989        fast = '|api-fast|',
990        remote_only = '|RPC| only',
991        lua_only = 'Lua |vim.api| only',
992      })[attr] or attr
993      table.insert(ret, fmt('        %s\n', attr_str))
994    end
995  end
996
997  if fun.params and #fun.params > 0 then
998    local param_txt = render_fields_or_params(fun.params, fun.generics, classes, cfg)
999    if not param_txt:match('^%s*$') then
1000      table.insert(ret, '\n    Parameters: ~\n')
1001      ret[#ret + 1] = param_txt
1002    end
1003  end
1004
1005  if fun.overloads then
1006    table.insert(ret, '\n    Overloads: ~\n')
1007    for _, p in ipairs(fun.overloads) do
1008      table.insert(ret, fmt('      • `%s`\n', p))
1009    end
1010  end
1011
1012  if fun.returns then
1013    local txt = render_returns(fun.returns, fun.generics, classes)
1014    if txt and not txt:match('^%s*$') then
1015      table.insert(ret, '\n')
1016      ret[#ret + 1] = txt
1017    end
1018  end
1019
1020  if fun.see then
1021    table.insert(ret, '\n    See also: ~\n')
1022    for _, p in ipairs(fun.see) do
1023      table.insert(ret, '      • ' .. md_to_vimdoc(p.desc, 0, 8, TEXT_WIDTH, true))
1024    end
1025  end
1026
1027  table.insert(ret, '\n')
1028  return table.concat(ret)
1029end
1030
1031--- @param briefs string[]
1032--- @param cfg nvim.gen_vimdoc.Config
1033local function render_briefs(briefs, cfg)
1034  local ret = {} --- @type string[]
1035
1036  for _, b in ipairs(briefs) do
1037    if cfg.brief_xform then
1038      b = cfg.brief_xform(b)
1039    end
1040    ret[#ret + 1] = b
1041  end
1042
1043  return ret
1044end
1045
1046--- @param funs nvim.luacats.parser.fun[]
1047--- @param classes table<string,nvim.luacats.parser.class>
1048--- @param cfg nvim.gen_vimdoc.Config
1049local function render_funs(funs, classes, cfg)
1050  local ret = {} --- @type string[]
1051
1052  for _, f in ipairs(funs) do
1053    if cfg.fn_xform then
1054      cfg.fn_xform(f)
1055    end
1056    ret[#ret + 1] = render_fun(f, classes, cfg)
1057  end
1058
1059  -- Sort via prototype. Experimental API functions ("nvim__") sort last.
1060  table.sort(ret, function(a, b)
1061    local a1 = ('\n' .. a):match('\n[a-zA-Z_][^\n]+\n')
1062    local b1 = ('\n' .. b):match('\n[a-zA-Z_][^\n]+\n')
1063
1064    local a1__ = a1:find('^%s*nvim__') and 1 or 0
1065    local b1__ = b1:find('^%s*nvim__') and 1 or 0
1066    if a1__ ~= b1__ then
1067      return a1__ < b1__
1068    end
1069
1070    return a1:lower() < b1:lower()
1071  end)
1072
1073  return table.concat(ret)
1074end
1075
1076--- @return string
1077local function get_script_path()
1078  local str = debug.getinfo(2, 'S').source:gsub('^@', '')
1079  return str:match('(.*[/\\])') or './'
1080end
1081
1082local script_path = get_script_path()
1083local base_dir = vim.fs.dirname(vim.fs.dirname(vim.fs.dirname(script_path)))
1084
1085local function delete_lines_below(doc_file, tokenstr)
1086  local lines = {} --- @type string[]
1087  local found = false
1088  for line in io.lines(doc_file) do
1089    if line:find(vim.pesc(tokenstr)) then
1090      found = true
1091      break
1092    end
1093    lines[#lines + 1] = line
1094  end
1095  if not found then
1096    error(fmt('not found: %s in %s', tokenstr, doc_file))
1097  end
1098  lines[#lines] = nil
1099  local fp = assert(io.open(doc_file, 'w'))
1100  fp:write(table.concat(lines, '\n'))
1101  fp:write('\n')
1102  fp:close()
1103end
1104
1105--- @param x string
1106local function mktitle(x)
1107  if x == 'ui' then
1108    return 'UI'
1109  end
1110  return x:sub(1, 1):upper() .. x:sub(2)
1111end
1112
1113--- @class nvim.gen_vimdoc.Section
1114--- @field name string
1115--- @field title string
1116--- @field help_tag string
1117--- @field funs_txt string
1118--- @field classes_txt string
1119--- @field briefs string[]
1120
1121--- @param filename string
1122--- @param cfg nvim.gen_vimdoc.Config
1123--- @param briefs string[]
1124--- @param funs_txt string
1125--- @param classes_txt string
1126--- @return nvim.gen_vimdoc.Section?
1127local function make_section(filename, cfg, briefs, funs_txt, classes_txt)
1128  -- filename: e.g., 'autocmd.c'
1129  -- name: e.g. 'autocmd'
1130  local name = filename:match('(.*)%.[a-z]+')
1131
1132  -- Formatted (this is what's going to be written in the vimdoc)
1133  -- e.g., "Autocmd Functions"
1134  local sectname = cfg.section_name and cfg.section_name[filename] or mktitle(name)
1135
1136  -- section tag: e.g., "*api-autocmd*"
1137  local help_labels = cfg.helptag_fmt(sectname)
1138  if type(help_labels) == 'table' then
1139    help_labels = table.concat(help_labels, '* *')
1140  end
1141  local help_tags = '*' .. help_labels .. '*'
1142
1143  if funs_txt == '' and classes_txt == '' and #briefs == 0 then
1144    return
1145  end
1146
1147  return {
1148    name = sectname,
1149    title = cfg.section_fmt(sectname),
1150    help_tag = help_tags,
1151    funs_txt = funs_txt,
1152    classes_txt = classes_txt,
1153    briefs = briefs,
1154  }
1155end
1156
1157--- @param section nvim.gen_vimdoc.Section
1158local function render_section(section)
1159  local doc = {} --- @type string[]
1160
1161  if not section.title then
1162    error(('section.title is nil, check section_fmt(). section: %s'):format(vim.inspect(section)))
1163  end
1164
1165  doc[#doc + 1] = string.rep('=', TEXT_WIDTH)
1166    .. '\n'
1167    .. align_tags(TEXT_WIDTH)(section.title .. ' ' .. section.help_tag)
1168
1169  if next(section.briefs) then
1170    local briefs_txt = {} --- @type string[]
1171    for _, b in ipairs(section.briefs) do
1172      briefs_txt[#briefs_txt + 1] = md_to_vimdoc(b, 0, 0, TEXT_WIDTH)
1173    end
1174
1175    local sdoc = table.concat(briefs_txt, '\n')
1176    if sdoc:find('[^%s]') then
1177      doc[#doc + 1] = sdoc
1178    end
1179  end
1180
1181  if section.classes_txt ~= '' then
1182    table.insert(doc, (section.classes_txt:gsub('\n+$', '\n')))
1183  end
1184
1185  if section.funs_txt ~= '' then
1186    table.insert(doc, section.funs_txt)
1187  end
1188
1189  return table.concat(doc, '\n\n')
1190end
1191
1192local parsers = {
1193  lua = luacats_parser.parse,
1194  c = cdoc_parser.parse,
1195  h = cdoc_parser.parse,
1196}
1197
1198--- @param files string[]
1199local function expand_files(files)
1200  for k, f in pairs(files) do
1201    if vim.fn.isdirectory(f) == 1 then
1202      table.remove(files, k)
1203      for path, ty in vim.fs.dir(f) do
1204        if ty == 'file' then
1205          table.insert(files, vim.fs.joinpath(f, path))
1206        end
1207      end
1208    end
1209  end
1210end
1211
1212--- @param classes table<string,nvim.luacats.parser.class>
1213--- @return string?
1214local function find_module_class(classes, modvar)
1215  for nm, cls in pairs(classes) do
1216    local _, field = next(cls.fields or {})
1217    if cls.desc and field and field.classvar == modvar then
1218      return nm
1219    end
1220  end
1221end
1222
1223--- Add callable exports and inherited module functions under their public names.
1224--- E.g. `M.semaphore = require('vim.async._semaphore')` in vim.async exposes
1225--- that module's returned `new_semaphore` function as `vim.async.semaphore()`.
1226--- A callable table uses its module name: vim.inspect's `__call` => `vim.inspect()`.
1227--- @param modules table<string,nvim.luacats.parser.module>
1228local function expand_module_docs(modules)
1229  local exports = {} --- @type table<nvim.luacats.parser.module,string[]>
1230  for _, module in pairs(modules) do
1231    local documented = {} --- @type table<string,true>
1232    for _, fun in ipairs(module.funs) do
1233      if fun.modvar == module.modvar and (not fun.classvar or fun.classvar == module.modvar) then
1234        documented[fun.name] = true
1235      end
1236    end
1237    for name, imported in pairs(module.imports) do
1238      local public_name = module.name .. '.' .. name
1239      if not documented[name] and not ('.' .. public_name):find('%._') then
1240        exports[imported] = exports[imported] or {}
1241        table.insert(exports[imported], public_name)
1242      end
1243    end
1244  end
1245
1246  for name, module in pairs(modules) do
1247    -- E.g. new_semaphore becomes vim.async.semaphore through a require() binding.
1248    -- Otherwise, use the public module path (vim.inspect for its __call).
1249    if module.callable and (exports[module] or not ('.' .. name):find('%._')) then
1250      for _, public_name in ipairs(exports[module] or { name }) do
1251        local fun = vim.deepcopy(module.callable)
1252        fun.module, fun.name = public_name:match('^(.*)%.([^.]+)$')
1253        fun.name = fun.name or public_name
1254        module.funs[#module.funs + 1] = fun
1255      end
1256    end
1257  end
1258
1259  -- `@class vim.async: vim.async._core` makes `vim.async._core.run()` => `vim.async.run()`.
1260  -- Copy inherited functions under the public module name, keeping nearer declarations.
1261  local hidden = {} --- @type table<nvim.luacats.parser.fun,true>
1262  for _, module in pairs(modules) do
1263    if module.class and not ('.' .. module.name):find('%._') then
1264      local names = {} --- @type table<string,true>
1265      local seen = {} --- @type table<nvim.luacats.parser.module,true>
1266      local source = module
1267      while source and not seen[source] do
1268        seen[source] = true
1269        for _, fun in ipairs(source.funs) do
1270          if fun.class == source.class.name and fun.member_sep == '.' then
1271            if
1272              source ~= module
1273              and not names[fun.name]
1274              and not fun.nodoc
1275              and not fun.access
1276              and fun.name:sub(1, 1) ~= '_'
1277            then
1278              local inherited = vim.deepcopy(fun)
1279              inherited.module, inherited.class = module.name, module.class.name
1280              inherited.modvar, inherited.classvar = module.modvar, module.modvar
1281              module.funs[#module.funs + 1] = inherited
1282            end
1283            if source ~= module and ('.' .. source.name):find('%._') then
1284              hidden[fun] = true
1285            end
1286            -- Include functions already inherited by the source module.
1287            names[fun.name] = true
1288          end
1289        end
1290        -- A nearer declaration shadows ancestors, including non-function fields.
1291        for _, field in ipairs(source.class.fields) do
1292          names[field.name] = true
1293        end
1294        for name in pairs(source.assignments) do
1295          names[name] = true
1296        end
1297        source = source.parent
1298      end
1299    end
1300  end
1301  -- Delay hiding until all modules have inherited the original documentation.
1302  for fun in pairs(hidden) do
1303    fun.nodoc = true
1304  end
1305end
1306
1307--- @param cfg nvim.gen_vimdoc.Config
1308local function gen_target(cfg)
1309  cfg.fn_helptag_fmt = cfg.fn_helptag_fmt or fn_helptag_fmt_common
1310  print('Target:', cfg.filename)
1311  local sections = {} --- @type nvim.gen_vimdoc.Section[]
1312
1313  expand_files(cfg.files)
1314
1315  --- @type table<string,[table<string,nvim.luacats.parser.class>, nvim.luacats.parser.fun[], string[]]>
1316  local file_results = {}
1317
1318  --- @type table<string,nvim.luacats.parser.class>
1319  local all_classes = {}
1320
1321  --- @type table<string,nvim.luacats.parser.module>
1322  local modules = {}
1323
1324  --- First pass so we can collect all classes and module exports.
1325  for _, f in vim.spairs(cfg.files) do
1326    local ext = f:match('%.([^.]+)$')
1327    local parser = parsers[ext]
1328    if parser then
1329      local classes, funs, briefs, _, module = parser(f)
1330      file_results[f] = { classes, funs, briefs }
1331      all_classes = vim.tbl_extend('error', all_classes, classes)
1332      if module then
1333        modules[module.name] = module
1334      end
1335    end
1336  end
1337
1338  luacats_parser.resolve_modules(modules)
1339  expand_module_docs(modules)
1340
1341  --- @type table<string,[table<string,nvim.luacats.parser.class>, nvim.luacats.parser.fun[], string[]]>
1342  local files_by_name = {}
1343
1344  for f, r in vim.spairs(file_results) do
1345    local classes, funs, briefs = r[1], r[2], r[3]
1346
1347    if not f:find('ui_events%.in%.h$') then -- TODO(justinmk): also lint UI events.
1348      lint.lint_names(f, funs, nil, classes)
1349      lint.lint_quasi_keysets(f, funs)
1350    end
1351
1352    local mod_cls_nm = find_module_class(classes, 'M')
1353    if mod_cls_nm then
1354      local mod_cls = classes[mod_cls_nm]
1355      classes[mod_cls_nm] = nil
1356      -- If the module documentation is present, add it to the briefs
1357      -- so it appears at the top of the section.
1358      briefs[#briefs + 1] = mod_cls.desc
1359    end
1360
1361    print('    Processing file:', f)
1362
1363    -- FIXME: Using basenames will confuse `_meta/protocol.lua` with `protocol.lua`
1364    files_by_name[vim.fs.basename(f)] = r
1365  end
1366
1367  for _, entry in ipairs(cfg.section_order) do
1368    local files = type(entry) == 'table' and entry or { entry }
1369    local classes = {} --- @type table<string,nvim.luacats.parser.class>
1370    local funs = {} --- @type nvim.luacats.parser.fun[]
1371    local briefs = {} --- @type string[]
1372    for _, f in ipairs(files) do
1373      local r = files_by_name[f]
1374      if r then
1375        classes = vim.tbl_extend('error', classes, r[1])
1376        vim.list_extend(funs, r[2])
1377        vim.list_extend(briefs, r[3])
1378      end
1379    end
1380    sections[#sections + 1] = make_section(
1381      files[1],
1382      cfg,
1383      render_briefs(briefs, cfg),
1384      render_funs(funs, all_classes, cfg),
1385      render_classes(classes, funs, cfg)
1386    )
1387  end
1388
1389  local first_section_tag = sections[1].help_tag
1390  local docs = {} --- @type string[]
1391  for _, section in ipairs(sections) do
1392    print(fmt("    Rendering section: '%s'", section.title))
1393    docs[#docs + 1] = render_section(section)
1394  end
1395
1396  table.insert(
1397    docs,
1398    fmt(' vim:tw=78:ts=8:sw=%d:sts=%d:et:ft=help:norl:\n', INDENTATION, INDENTATION)
1399  )
1400
1401  local doc_file = vim.fs.joinpath(base_dir, 'runtime', 'doc', cfg.filename)
1402
1403  if vim.uv.fs_stat(doc_file) then
1404    delete_lines_below(doc_file, first_section_tag)
1405  end
1406
1407  local fp = assert(io.open(doc_file, 'a'))
1408  fp:write(table.concat(docs, '\n'))
1409  fp:close()
1410end
1411
1412local function run()
1413  for _, cfg in vim.spairs(config) do
1414    gen_target(cfg)
1415  end
1416end
1417
1418run()