robin/laufey

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

Justin M. Keyesbuild(docs): lint more quasi-keysets #39654b351024daf

master
9.7 KiB306 linesraw
1local fmt = string.format
2
3local M = {}
4
5--- Banned nouns. See `:help dev-name-common`.
6--- Apply to parameter names, keyset keys, and function name parts.
7local banned_nouns = {
8  buffer = 'buf',
9  bufnr = 'buf',
10  -- channel = 'chan',
11  command = 'cmd',
12  directory = 'dir',
13  highlight = 'hl',
14  position = 'pos',
15  process = 'proc',
16  window = 'win',
17  winnr = 'win',
18}
19
20--- Banned verbs. See `:help dev-name-common`.
21--- Apply to function name parts.
22local banned_verbs = {
23  contains = 'has',
24  delete = 'del',
25  disable = 'enable',
26  exit = 'cancel', -- or "stop"
27  -- format = 'fmt',
28  -- hide = '?',
29  -- show = '?',
30  list = 'get',
31  notify = 'print', -- or "echo"
32  pretty = 'fmt',
33  remove = 'del',
34  toggle = 'enable',
35}
36
37--- Whitelist of legacy function names that violate the naming conventions.
38--- Do not add new entries here. New functions must follow `:help dev-naming`.
39---
40--- @type table<string, table<string, true>>
41local legacy_names = {
42  ['src/nvim/api/buffer.c'] = {
43    nvim_buf_delete = true,
44  },
45  ['src/nvim/api/window.c'] = {
46    nvim_win_get_position = true,
47  },
48  ['src/nvim/api/tabpage.c'] = {
49    nvim_tabpage_list_wins = true,
50  },
51  ['src/nvim/api/ui.c'] = {
52    remote_ui_highlight_set = true,
53  },
54  ['src/nvim/api/vim.c'] = {
55    nvim_list_bufs = true,
56    nvim_list_chans = true,
57    nvim_list_runtime_paths = true,
58    nvim_list_tabpages = true,
59    nvim_list_uis = true,
60    nvim_list_wins = true,
61  },
62  ['runtime/lua/vim/uri.lua'] = {
63    uri_from_bufnr = true,
64    uri_to_bufnr = true,
65  },
66  ['runtime/lua/vim/_core/shared.lua'] = {
67    _ensure_list = true,
68    _list_insert = true,
69    _list_remove = true,
70    _resolve_bufnr = true,
71    list_contains = true,
72    tbl_contains = true,
73  },
74  ['runtime/lua/vim/lsp.lua'] = {
75    buf_notify = true,
76  },
77  ['runtime/lua/vim/lsp/client.lua'] = {
78    _on_exit = true,
79    _process_request = true,
80    _process_static_registrations = true,
81    _remove_workspace_folder = true,
82  },
83  ['runtime/lua/vim/lsp/util.lua'] = {
84    buf_highlight_references = true,
85    make_position_params = true,
86  },
87  ['runtime/lua/vim/lsp/rpc.lua'] = {
88    _notify = true,
89  },
90  ['runtime/lua/vim/treesitter.lua'] = {
91    node_contains = true,
92  },
93  ['runtime/lua/vim/treesitter/highlighter.lua'] = {
94    for_each_highlight_state = true,
95    prepare_highlight_states = true,
96  },
97  ['runtime/lua/vim/treesitter/query.lua'] = {
98    _process_patterns = true,
99  },
100  ['src/nvim/api/command.c'] = {
101    create_user_command = true,
102    nvim_buf_create_user_command = true,
103    nvim_buf_del_user_command = true,
104    nvim_create_user_command = true,
105    nvim_del_user_command = true,
106  },
107  ['src/nvim/api/vimscript.c'] = {
108    nvim_command = true,
109  },
110}
111
112--- Whitelist of legacy Lua class fields that violate the naming conventions.
113--- Do not add new entries here. New classes must follow `:help dev-naming`.
114---
115--- @type table<string, table<string, true>>
116local legacy_fields = {
117  ['vim.Diagnostic'] = {
118    bufnr = true,
119  },
120  ['vim.lsp.Capability'] = {
121    bufnr = true,
122  },
123  ['vim.lsp.inlay_hint.enable.Filter'] = {
124    bufnr = true,
125  },
126  ['vim.lsp.inlay_hint.get.Filter'] = {
127    bufnr = true,
128  },
129  ['vim.lsp.inlay_hint.get.ret'] = {
130    bufnr = true,
131  },
132  ['TS.Heading'] = {
133    bufnr = true, -- Passed to setloclist().
134  },
135  ['vim.treesitter.get_node.Opts'] = {
136    bufnr = true,
137  },
138  ['vim.treesitter.dev.inspect_tree.Opts'] = {
139    bufnr = true,
140    command = true,
141  },
142  ['vim.undotree.opts'] = {
143    bufnr = true,
144    command = true,
145  },
146}
147
148--- Whitelist of legacy keyset keys that violate the naming conventions.
149--- Do not add new entries here. New keysets must follow `:help dev-naming`.
150---
151--- @type table<string, table<string, true>>
152local legacy_keys = {
153  create_autocmd = {
154    command = true,
155  },
156}
157
158--- Enforces naming conventions (`:help dev-naming`).
159---
160--- - For API functions:
161---   - Checks positional parameter names of non-deprecated functions.
162---     The `legacy_names` whitelist does NOT apply to params: misnamed positional
163---     parameters are never allowed.
164---   - Checks function name parts (split by `_`) for banned nouns/verbs.
165--- - For `keysets_defs.h` keys:
166---   - Checks key names. Because we don't (currently) have a way to mark keyset names as
167---     "deprecated", a banned key is allowed (only) if its replacement also exists.
168--- - For Lua classes (opts dicts, etc.):
169---   - Checks field names. A banned field is allowed only if its replacement also exists
170---     (same compat rule as keysets).
171---
172--- @param source string Source filename or module name.
173--- @param api_funs {name:string, params:{name:string}[], deprecated?:true, deprecated_since?:integer}[]? Parsed API functions.
174--- @param keysets {name: string, keys: string[], types: table<string,string>}[]? API keyset metadata.
175--- @param classes table<string, {name:string, fields:{name:string, access?:string}[], nodoc?:true, access?:string}>? Parsed Lua classes.
176function M.lint_names(source, api_funs, keysets, classes)
177  local errors = {} --- @type string[]
178
179  if api_funs then
180    local src_legacy = legacy_names[source] or {}
181    for _, fun in ipairs(api_funs) do
182      if fun.name and fun.params and not fun.deprecated and not fun.deprecated_since then
183        -- Positional parameter names: always checked (no legacy allowed).
184        -- Exception: "bufnr" is allowed as a param name.
185        for _, p in ipairs(fun.params) do
186          local want_name = banned_nouns[p.name]
187          if want_name and p.name ~= 'bufnr' then
188            local msg = '%s: %s(): param "%s" should be renamed to "%s"'
189            errors[#errors + 1] = fmt(msg, source, fun.name, p.name, want_name)
190          end
191        end
192
193        -- Function name parts: check for banned nouns/verbs.
194        -- Skip the `nvim_` prefix; start from the second part.
195        -- Legacy-whitelisted names are skipped.
196        if not src_legacy[fun.name] then
197          local parts = vim.split(fun.name, '_', { plain = true })
198          for i = 2, #parts do
199            local part = parts[i]
200            local want_noun = banned_nouns[part]
201            if want_noun then
202              local msg = '%s: %s(): name contains banned noun "%s", use "%s"'
203              errors[#errors + 1] = fmt(msg, source, fun.name, part, want_noun)
204            end
205            local want_verb = banned_verbs[part]
206            if want_verb then
207              local msg = '%s: %s(): name contains banned verb "%s", use "%s"'
208              errors[#errors + 1] = fmt(msg, source, fun.name, part, want_verb)
209            end
210          end
211        end
212      end
213    end
214  end
215
216  if keysets then
217    for _, k in ipairs(keysets) do
218      local keyset = {} --- @type table<string, true>
219      for _, key in ipairs(k.keys) do
220        keyset[key] = true
221      end
222      local ks_legacy = legacy_keys[k.name] or {}
223      for _, key in ipairs(k.keys) do
224        local want_name = banned_nouns[key]
225        if want_name and not keyset[want_name] and not ks_legacy[key] then
226          -- Banned key without its replacement: not a compat key, just stale.
227          local msg = '%s: keyset "%s": key "%s" should be renamed to "%s"'
228          errors[#errors + 1] = fmt(msg, source, k.name, key, want_name)
229        end
230      end
231    end
232  end
233
234  if classes then
235    for cls_name, cls in pairs(classes) do
236      if cls.fields and not cls.nodoc and not cls.access then
237        local field_set = {} --- @type table<string, true>
238        for _, f in ipairs(cls.fields) do
239          field_set[f.name] = true
240        end
241        local cls_legacy = legacy_fields[cls_name] or {}
242        for _, f in ipairs(cls.fields) do
243          if not f.access then
244            local want_name = banned_nouns[f.name]
245            if want_name and not field_set[want_name] and not cls_legacy[f.name] then
246              -- Banned field without its replacement: not a compat field, just stale.
247              local msg = '%s: class "%s": field "%s" should be renamed to "%s"'
248              errors[#errors + 1] = fmt(msg, source, cls_name, f.name, want_name)
249            end
250          end
251        end
252      end
253    end
254  end
255
256  if #errors > 0 then
257    table.sort(errors)
258    error('lint_names(): found banned parameter/key names:\n  ' .. table.concat(errors, '\n  '))
259  end
260end
261
262--- Checks that markdown list items (`- name :` or `- {name}`) in parameter/field
263--- descriptions are in sorted order.
264---
265--- This is for "quasi-keysets" defined as markdown lists in docstrings. Ideally they would be
266--- defined as a luals `@class` or a API keyset, but sometimes that isn't possible.
267---
268--- @param source string Source filename.
269--- @param funs {name:string, params:{name:string, desc?:string}[]}[]
270function M.lint_quasi_keysets(source, funs)
271  local errors = {} --- @type string[]
272
273  for _, fun in ipairs(funs) do
274    for _, p in ipairs(fun.params or {}) do
275      if p.desc then
276        local prev = nil --- @type string?
277        -- Capture the keyname with optional punctuation (`, "), so the sort includes surrounding
278        -- chars: backtick items group together, double-quote group together, etc. (Example: |Client:stop()|)
279        for name in p.desc:gmatch('\n%- (["`]?[%w_]+["`]?)') do
280          -- Sort underscore-prefixed keys (e.g. "_cmdline_offset") at the end.
281          local prev_key = prev and prev:gsub('^([`"]?)_', '%1~') or nil
282          local name_key = name:gsub('^([`"]?)_', '%1~')
283          if prev_key and name_key < prev_key then
284            errors[#errors + 1] = fmt(
285              '%s: %s(): param "%s": key "%s" should come before "%s" (sort alphabetically)',
286              source,
287              fun.name,
288              p.name,
289              name,
290              prev
291            )
292          end
293          prev = name
294        end
295      end
296    end
297  end
298
299  if #errors > 0 then
300    error(
301      'lint_quasi_keysets(): unsorted keys in doc comments:\n  ' .. table.concat(errors, '\n  ')
302    )
303  end
304end
305
306return M