robin/laufey

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

Tristan Knightfix(lsp): support nested workspace registrations #39574ed194b99ac

master
22.8 KiB705 linesraw
1#!/usr/bin/env -S nvim -l
2-- Generates lua-ls annotations for lsp.
3
4local USAGE = [[
5Generates lua-ls annotations for lsp.
6
7Also updates types in runtime/lua/vim/lsp/protocol.lua
8
9Usage:
10  src/gen/gen_lsp.lua [options]
11
12Options:
13  --version <version>  LSP version to use (default: 3.18)
14  --out <out>          Output file (default: runtime/lua/vim/lsp/_meta/protocol.lua)
15  --help               Print this help message
16]]
17
18--- The LSP protocol JSON data (it's partial, non-exhaustive).
19--- https://raw.githubusercontent.com/microsoft/language-server-protocol/gh-pages/_specifications/lsp/3.18/metaModel/metaModel.schema.json
20--- @class vim._gen_lsp.Protocol
21--- @field requests vim._gen_lsp.Request[]
22--- @field notifications vim._gen_lsp.Notification[]
23--- @field structures vim._gen_lsp.Structure[]
24--- @field enumerations vim._gen_lsp.Enumeration[]
25--- @field typeAliases vim._gen_lsp.TypeAlias[]
26
27--- @class vim._gen_lsp.Notification
28--- @field deprecated? string
29--- @field documentation? string
30--- @field messageDirection string
31--- @field clientCapability? string
32--- @field serverCapability? string
33--- @field method vim.lsp.protocol.Method
34--- @field params? any
35--- @field proposed? boolean
36--- @field registrationMethod? string
37--- @field registrationOptions? any
38--- @field since? string
39
40--- @class vim._gen_lsp.Request : vim._gen_lsp.Notification
41--- @field errorData? any
42--- @field partialResult? any
43--- @field result any
44
45--- @class vim._gen_lsp.Structure translated to @class
46--- @field deprecated? string
47--- @field documentation? string
48--- @field extends? { kind: string, name: string }[]
49--- @field mixins? { kind: string, name: string }[]
50--- @field name string
51--- @field properties? vim._gen_lsp.Property[]  members, translated to @field
52--- @field proposed? boolean
53--- @field since? string
54
55--- @class vim._gen_lsp.StructureLiteral translated to anonymous @class.
56--- @field deprecated? string
57--- @field description? string
58--- @field properties vim._gen_lsp.Property[]
59--- @field proposed? boolean
60--- @field since? string
61
62--- @class vim._gen_lsp.Property translated to @field
63--- @field deprecated? string
64--- @field documentation? string
65--- @field name string
66--- @field optional? boolean
67--- @field proposed? boolean
68--- @field since? string
69--- @field type { kind: string, name: string }
70
71--- @class vim._gen_lsp.Enumeration translated to @enum
72--- @field deprecated string?
73--- @field documentation string?
74--- @field name string?
75--- @field proposed boolean?
76--- @field since string?
77--- @field suportsCustomValues boolean?
78--- @field values { name: string, value: string, documentation?: string, since?: string }[]
79
80--- @class vim._gen_lsp.TypeAlias translated to @alias
81--- @field deprecated? string?
82--- @field documentation? string
83--- @field name string
84--- @field proposed? boolean
85--- @field since? string
86--- @field type vim._gen_lsp.Type
87
88--- @class vim._gen_lsp.Type
89--- @field kind string a common field for all Types.
90--- @field name? string for ReferenceType, BaseType
91--- @field element? any for ArrayType
92--- @field items? vim._gen_lsp.Type[] for OrType, AndType
93--- @field key? vim._gen_lsp.Type for MapType
94--- @field value? string|vim._gen_lsp.Type for StringLiteralType, MapType, StructureLiteralType
95
96--- @param fname string
97--- @param text string
98local function tofile(fname, text)
99  local f = assert(io.open(fname, 'w'), ('failed to open: %s'):format(fname))
100  f:write(text)
101  f:close()
102  print('Written to:', fname)
103end
104
105---@param opt vim._gen_lsp.opt
106---@return vim._gen_lsp.Protocol
107local function read_json(opt)
108  local uri = 'https://raw.githubusercontent.com/microsoft/language-server-protocol/gh-pages/_specifications/lsp/'
109    .. opt.version
110    .. '/metaModel/metaModel.json'
111  print('Reading ' .. uri)
112
113  local res = vim.system({ 'curl', '--no-progress-meter', uri, '-o', '-' }):wait()
114  if res.code ~= 0 or (res.stdout or ''):len() < 999 then
115    print(('URL failed: %s'):format(uri))
116    vim.print(res)
117    error(res.stdout)
118  end
119  return vim.json.decode(res.stdout)
120end
121
122--- Gets the Lua symbol for a given fully-qualified LSP method name.
123--- @param s string
124--- @return string
125local function to_luaname(s)
126  -- "$/" prefix is special: https://microsoft.github.io/language-server-protocol/specification/#dollarRequests
127  return (s:gsub('^%$', 'dollar'):gsub('/', '_'))
128end
129
130--- @param a vim._gen_lsp.Notification
131--- @param b vim._gen_lsp.Notification
132--- @return boolean
133local function compare_method(a, b)
134  return to_luaname(a.method) < to_luaname(b.method)
135end
136
137--- @param item vim._gen_lsp.Request|vim._gen_lsp.Notification
138--- @return string?
139local function registration_provider(item)
140  local server_capability = item.serverCapability
141  if not server_capability then
142    return nil
143  end
144  if vim.startswith(server_capability, 'workspace.') then
145    return server_capability
146  end
147  return server_capability:match('^[^%.]+')
148end
149
150---@param structures table<string,vim._gen_lsp.Structure>
151---@param type vim._gen_lsp.Type
152---@param seen? table<string,true>
153---@return boolean
154local function supports_static_registration(structures, type, seen)
155  if type.kind == 'reference' then
156    if type.name == 'StaticRegistrationOptions' then
157      return true
158    end
159
160    seen = seen or {}
161    if seen[type.name] then
162      return false
163    end
164    seen[type.name] = true
165
166    local structure = structures[type.name]
167    if not structure then
168      return false
169    end
170    local bases = {}
171    vim.list_extend(bases, structure.extends or {})
172    vim.list_extend(bases, structure.mixins or {})
173    for _, base in ipairs(bases) do
174      if supports_static_registration(structures, base, seen) then
175        return true
176      end
177    end
178  elseif type.kind == 'and' or type.kind == 'or' then
179    for _, item in ipairs(type.items) do
180      if supports_static_registration(structures, item, seen) then
181        return true
182      end
183    end
184  end
185
186  return false
187end
188
189---@param protocol vim._gen_lsp.Protocol
190local function write_to_vim_protocol(protocol)
191  local all = {} --- @type (vim._gen_lsp.Request|vim._gen_lsp.Notification)[]
192  vim.list_extend(all, protocol.notifications)
193  vim.list_extend(all, protocol.requests)
194
195  local structures = {} --- @type table<string,vim._gen_lsp.Structure>
196  for _, structure in ipairs(protocol.structures) do
197    structures[structure.name] = structure
198  end
199
200  table.sort(all, compare_method)
201  table.sort(protocol.requests, compare_method)
202  table.sort(protocol.notifications, compare_method)
203
204  local output = { '-- Generated by gen_lsp.lua, keep at end of file.' }
205
206  do -- methods
207    for _, dir in ipairs({ 'clientToServer', 'serverToClient' }) do
208      local dir1 = dir:sub(1, 1):upper() .. dir:sub(2)
209      local alias = ('vim.lsp.protocol.Method.%s'):format(dir1)
210      for _, b in ipairs({
211        { title = 'Request', methods = protocol.requests },
212        { title = 'Notification', methods = protocol.notifications },
213      }) do
214        output[#output + 1] = ('--- LSP %s (direction: %s)'):format(b.title, dir)
215        output[#output + 1] = ('--- @alias %s.%s'):format(alias, b.title)
216        for _, item in ipairs(b.methods) do
217          if item.messageDirection == dir or item.messageDirection == 'both' then
218            output[#output + 1] = ("--- | '%s',"):format(item.method)
219          end
220        end
221        output[#output + 1] = ''
222      end
223
224      vim.list_extend(output, {
225        ('--- LSP Message (direction: %s).'):format(dir),
226        ('--- @alias %s'):format(alias),
227        ('--- | %s.Request'):format(alias),
228        ('--- | %s.Notification'):format(alias),
229        '',
230      })
231    end
232
233    vim.list_extend(output, {
234      '--- @alias vim.lsp.protocol.Method',
235      '--- | vim.lsp.protocol.Method.ClientToServer',
236      '--- | vim.lsp.protocol.Method.ServerToClient',
237      '',
238      '-- Generated by gen_lsp.lua, keep at end of file.',
239      '--- @deprecated Use `vim.lsp.protocol.Method` instead.',
240      '--- @enum vim.lsp.protocol.Methods',
241      '--- @see https://microsoft.github.io/language-server-protocol/specification/#metaModel',
242      '--- LSP method names.',
243      'protocol.Methods = {',
244    })
245
246    for _, item in ipairs(all) do
247      if item.method then
248        if item.documentation then
249          local document = vim.split(item.documentation, '\n?\n', { trimempty = true })
250          for _, docstring in ipairs(document) do
251            output[#output + 1] = '  --- ' .. docstring
252          end
253        end
254        output[#output + 1] = ("  %s = '%s',"):format(to_luaname(item.method), item.method)
255      end
256    end
257    output[#output + 1] = '}'
258  end
259
260  do -- registrationMethods
261    local found = {} --- @type table<string, boolean>
262    vim.list_extend(output, {
263      '',
264      '-- Generated by gen_lsp.lua, keep at end of file.',
265      '--- LSP registration methods',
266      '---@alias vim.lsp.protocol.Method.Registration',
267    })
268    for _, item in ipairs(all) do
269      if item.registrationMethod and not found[item.registrationMethod] then
270        vim.list_extend(output, {
271          ("--- | '%s'"):format(item.registrationMethod or item.method),
272        })
273        found[item.registrationMethod or item.method] = true
274      end
275    end
276  end
277
278  do -- capabilities
279    vim.list_extend(output, {
280      '',
281      '-- stylua: ignore start',
282      '-- Generated by gen_lsp.lua, keep at end of file.',
283      '--- Maps method names to the required client capability',
284      'protocol._provider_to_client_registration = {',
285    })
286
287    local providers = {} --- @type table<string, string>
288    for _, item in ipairs(all) do
289      local provider = registration_provider(item)
290      if item.registrationOptions and not providers[provider] and item.clientCapability then
291        if
292          item.clientCapability == item.serverCapability
293          and not (item.serverCapability and vim.startswith(item.serverCapability, 'workspace.'))
294        then
295          provider = nil
296        end
297        local key = provider or item.method
298        providers[key] = item.clientCapability
299      end
300    end
301
302    ---@type { provider: string, path : string }[]
303    local found_entries = {}
304    for key, value in pairs(providers) do
305      found_entries[#found_entries + 1] = { provider = key, path = value }
306    end
307    table.sort(found_entries, function(a, b)
308      return a.provider < b.provider
309    end)
310    for _, entry in ipairs(found_entries) do
311      output[#output + 1] = ("  ['%s'] = { %s },"):format(
312        entry.provider,
313        "'" .. entry.path:gsub('%.', "', '") .. "'"
314      )
315    end
316
317    output[#output + 1] = '}'
318    output[#output + 1] = '-- stylua: ignore end'
319
320    vim.list_extend(output, {
321      '',
322      '-- stylua: ignore start',
323      '-- Generated by gen_lsp.lua, keep at end of file.',
324      '--- Maps method names to dynamic/static registration providers',
325      'protocol._request_name_to_registration_provider = {',
326    })
327
328    for _, item in ipairs(all) do
329      local provider = registration_provider(item) or item.method
330      output[#output + 1] = ("  ['%s'] = '%s',"):format(item.method, provider)
331    end
332
333    output[#output + 1] = '}'
334    output[#output + 1] = '-- stylua: ignore end'
335
336    vim.list_extend(output, {
337      '',
338      '-- stylua: ignore start',
339      '-- Generated by gen_lsp.lua, keep at end of file.',
340      '--- Maps method names to the required server capability',
341      '-- A server capability equal to the method means there is no related server capability',
342      'protocol._request_name_to_server_capability = {',
343    })
344
345    for _, item in ipairs(all) do
346      output[#output + 1] = ("  ['%s'] = { %s },"):format(
347        item.method,
348        "'" .. (item.serverCapability or item.method):gsub('%.', "', '") .. "'"
349      )
350    end
351
352    ---@type table<string, string[]>
353    local registration_capability = {}
354    for _, item in ipairs(all) do
355      if item.serverCapability then
356        if item.registrationMethod and item.registrationMethod ~= item.method then
357          local registrationMethod = item.registrationMethod
358          assert(registrationMethod, 'registrationMethod is nil')
359          if not registration_capability[item.registrationMethod] then
360            registration_capability[registrationMethod] = {}
361          end
362          table.insert(registration_capability[registrationMethod], item.serverCapability)
363        end
364      end
365    end
366
367    for registrationMethod, capabilities in pairs(registration_capability) do
368      output[#output + 1] = ("  ['%s'] = { '%s' },"):format(
369        registrationMethod,
370        vim.iter(capabilities):fold(capabilities[1], function(acc, v)
371          return #v < #acc and v or acc
372        end)
373      )
374    end
375
376    output[#output + 1] = '}'
377    output[#output + 1] = '-- stylua: ignore end'
378
379    vim.list_extend(output, {
380      '',
381      '-- stylua: ignore start',
382      '-- Generated by gen_lsp.lua, keep at end of file.',
383      'protocol._method_supports_dynamic_registration = {',
384    })
385
386    --- These methods have no registrationOptions but can still be registered
387    --- TODO: remove if resolved upstream: https://github.com/microsoft/language-server-protocol/issues/2218
388    local methods_with_no_registration_options = {
389      ['workspace/didChangeWorkspaceFolders'] = true,
390    }
391
392    for _, item in ipairs(all) do
393      if
394        item.registrationMethod
395        or item.registrationOptions
396        or methods_with_no_registration_options[item.method]
397      then
398        output[#output + 1] = ("  ['%s'] = %s,"):format(item.method, true)
399      end
400    end
401
402    output[#output + 1] = '}'
403    output[#output + 1] = '-- stylua: ignore end'
404
405    vim.list_extend(output, {
406      '',
407      '-- stylua: ignore start',
408      '-- Generated by gen_lsp.lua, keep at end of file.',
409      'protocol._method_supports_static_registration = {',
410    })
411
412    local static_registration_providers = {} --- @type table<string,true>
413    for _, item in ipairs(all) do
414      if
415        item.registrationOptions
416        and item.serverCapability
417        and supports_static_registration(structures, item.registrationOptions)
418      then
419        static_registration_providers[registration_provider(item)] = true
420      end
421    end
422
423    for _, item in ipairs(all) do
424      local provider = registration_provider(item)
425      local has_static_registration = item.registrationOptions
426        and supports_static_registration(structures, item.registrationOptions)
427      if
428        item.serverCapability
429        and static_registration_providers[provider]
430        and (has_static_registration or item.serverCapability == provider)
431      then
432        output[#output + 1] = ("  ['%s'] = %s,"):format(item.method, true)
433      end
434    end
435
436    output[#output + 1] = '}'
437    output[#output + 1] = '-- stylua: ignore end'
438
439    vim.list_extend(output, {
440      '',
441      '-- stylua: ignore start',
442      '-- Generated by gen_lsp.lua, keep at end of file.',
443      '-- These methods have no registration options but can still be registered dynamically.',
444      'protocol._methods_with_no_registration_options = {',
445    })
446    for key, v in pairs(methods_with_no_registration_options) do
447      output[#output + 1] = ("  ['%s'] = %s ,"):format(key, v)
448    end
449    output[#output + 1] = '}'
450    output[#output + 1] = '-- stylua: ignore end'
451  end
452
453  output[#output + 1] = ''
454  output[#output + 1] = 'return protocol'
455
456  local fname = './runtime/lua/vim/lsp/protocol.lua'
457  local bufnr = vim.fn.bufadd(fname)
458  vim.fn.bufload(bufnr)
459  vim.api.nvim_set_current_buf(bufnr)
460  local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
461  local index = vim.iter(ipairs(lines)):find(function(key, item)
462    return vim.startswith(item, '-- Generated by') and key or nil
463  end)
464  index = index and index - 1 or vim.api.nvim_buf_line_count(bufnr) - 1
465  vim.api.nvim_buf_set_lines(bufnr, index, -1, true, output)
466  vim.cmd.write()
467end
468
469--- @param doc string
470local function process_documentation(doc)
471  doc = doc:gsub('\n', '\n---')
472  -- Remove <200b> (zero-width space) unicode characters: e.g., `**/<200b>*`
473  doc = doc:gsub('\226\128\139', '')
474  -- Escape annotations that are not recognized by lua-ls
475  doc = doc:gsub('%^---@sample', '---\\@sample')
476  return '---' .. doc
477end
478
479local simple_types = {
480  string = true,
481  boolean = true,
482  integer = true,
483  uinteger = true,
484  decimal = true,
485}
486
487local anonymous_num = 0
488
489--- @type string[]
490local anonym_classes = {}
491
492--- @param type vim._gen_lsp.Type
493--- @param prefix? string Optional prefix associated with the this type, made of (nested) field name.
494---              Used to generate class name for structure literal types.
495--- @return string
496local function parse_type(type, prefix)
497  if type.kind == 'reference' or type.kind == 'base' then
498    if type.kind == 'base' and type.name == 'string' and prefix == 'method' then
499      return 'vim.lsp.protocol.Method'
500    end
501    if simple_types[type.name] then
502      return type.name
503    end
504    return 'lsp.' .. type.name
505  elseif type.kind == 'array' then
506    local parsed_items = parse_type(type.element, prefix)
507    if type.element.items and #type.element.items > 1 then
508      parsed_items = '(' .. parsed_items .. ')'
509    end
510    return parsed_items .. '[]'
511  elseif type.kind == 'or' then
512    local types = {} --- @type string[]
513    for _, item in ipairs(type.items) do
514      types[#types + 1] = parse_type(item, prefix)
515    end
516    return table.concat(types, '|')
517  elseif type.kind == 'stringLiteral' then
518    return '"' .. type.value .. '"'
519  elseif type.kind == 'map' then
520    local key = assert(type.key)
521    local value = type.value --[[ @as vim._gen_lsp.Type ]]
522    return ('table<%s, %s>'):format(parse_type(key, prefix), parse_type(value, prefix))
523  elseif type.kind == 'literal' then
524    -- can I use ---@param disabled? {reason: string}
525    -- use | to continue the inline class to be able to add docs
526    -- https://github.com/LuaLS/lua-language-server/issues/2128
527    anonymous_num = anonymous_num + 1
528    local anonymous_classname = 'lsp._anonym' .. anonymous_num
529    if prefix then
530      anonymous_classname = anonymous_classname .. '.' .. prefix
531    end
532
533    local anonym = { '---@class ' .. anonymous_classname }
534    if anonymous_num > 1 then
535      table.insert(anonym, 1, '')
536    end
537
538    ---@type vim._gen_lsp.StructureLiteral
539    local structural_literal = assert(type.value) --[[ @as vim._gen_lsp.StructureLiteral ]]
540    for _, field in ipairs(structural_literal.properties) do
541      anonym[#anonym + 1] = '---'
542      if field.documentation then
543        anonym[#anonym + 1] = process_documentation(field.documentation)
544      end
545      anonym[#anonym + 1] = ('---@field %s%s %s'):format(
546        field.name,
547        (field.optional and '?' or ''),
548        parse_type(field.type, prefix .. '.' .. field.name)
549      )
550    end
551    for _, line in ipairs(anonym) do
552      if line then
553        anonym_classes[#anonym_classes + 1] = line
554      end
555    end
556    return anonymous_classname
557  elseif type.kind == 'tuple' then
558    local types = {} --- @type string[]
559    for _, value in ipairs(type.items) do
560      types[#types + 1] = parse_type(value, prefix)
561    end
562    return '[' .. table.concat(types, ', ') .. ']'
563  end
564
565  vim.print('WARNING: Unknown type ', type)
566  return ''
567end
568
569--- @param protocol vim._gen_lsp.Protocol
570--- @param version string
571--- @param output_file string
572local function write_to_meta_protocol(protocol, version, output_file)
573  local output = {
574    '--' .. '[[',
575    'THIS FILE IS GENERATED by src/gen/gen_lsp.lua',
576    'DO NOT EDIT MANUALLY',
577    '',
578    'Based on LSP protocol ' .. version,
579    '',
580    'Regenerate:',
581    ([=[nvim -l src/gen/gen_lsp.lua --version %s]=]):format(version),
582    '--' .. ']]',
583    '',
584    '---@meta',
585    "error('Cannot require a meta file')",
586    '',
587    '---@alias lsp.null vim.NIL',
588    '---@alias uinteger integer',
589    '---@alias decimal number',
590    '---@alias lsp.DocumentUri string',
591    '---@alias lsp.URI string',
592    '',
593  }
594
595  for _, structure in ipairs(protocol.structures) do
596    if structure.documentation then
597      output[#output + 1] = process_documentation(structure.documentation)
598    end
599    local class_string = ('---@class lsp.%s'):format(structure.name)
600    if structure.extends or structure.mixins then
601      local inherits_from = table.concat(
602        vim.list_extend(
603          vim.tbl_map(parse_type, structure.extends or {}),
604          vim.tbl_map(parse_type, structure.mixins or {})
605        ),
606        ', '
607      )
608      class_string = class_string .. ': ' .. inherits_from
609    end
610    output[#output + 1] = class_string
611
612    for _, field in ipairs(structure.properties or {}) do
613      output[#output + 1] = '---' -- Insert a single newline between @fields (and after @class)
614      if field.documentation then
615        output[#output + 1] = process_documentation(field.documentation)
616      end
617      output[#output + 1] = ('---@field %s%s %s'):format(
618        field.name,
619        (field.optional and '?' or ''),
620        parse_type(field.type, field.name)
621      )
622    end
623    output[#output + 1] = ''
624  end
625
626  for _, enum in ipairs(protocol.enumerations) do
627    if enum.documentation then
628      output[#output + 1] = process_documentation(enum.documentation)
629    end
630    output[#output + 1] = '---@alias lsp.' .. enum.name
631    for _, value in ipairs(enum.values) do
632      local value1 = (type(value.value) == 'string' and ('"%s"'):format(value.value) or value.value)
633      output[#output + 1] = ('---| %s # %s'):format(value1, value.name)
634    end
635    output[#output + 1] = ''
636  end
637
638  for _, alias in ipairs(protocol.typeAliases) do
639    if alias.documentation then
640      output[#output + 1] = process_documentation(alias.documentation)
641    end
642
643    local alias_type --- @type string
644
645    if alias.type.kind == 'or' then
646      local alias_types = {} --- @type string[]
647      for _, item in ipairs(alias.type.items) do
648        alias_types[#alias_types + 1] = parse_type(item, alias.name)
649      end
650      alias_type = table.concat(alias_types, '|')
651    else
652      alias_type = parse_type(alias.type, alias.name)
653    end
654    output[#output + 1] = ('---@alias lsp.%s %s'):format(alias.name, alias_type)
655    output[#output + 1] = ''
656  end
657
658  -- anonymous classes
659  vim.list_extend(output, anonym_classes)
660
661  tofile(output_file, table.concat(output, '\n') .. '\n')
662end
663
664---@class vim._gen_lsp.opt
665---@field output_file string
666---@field version string
667
668--- @return vim._gen_lsp.opt
669local function parse_args()
670  ---@type vim._gen_lsp.opt
671  local opt = {
672    output_file = 'runtime/lua/vim/lsp/_meta/protocol.lua',
673    version = '3.18',
674  }
675
676  local i = 1
677  while i <= #_G.arg do
678    local cur_arg = _G.arg[i]
679    if cur_arg == '--out' then
680      opt.output_file = assert(_G.arg[i + 1], '--out <outfile> needed')
681      i = i + 1
682    elseif cur_arg == '--version' then
683      opt.version = assert(_G.arg[i + 1], '--version <version> needed')
684      i = i + 1
685    elseif cur_arg == '--help' or cur_arg == '-h' then
686      print(USAGE)
687      os.exit(0)
688    elseif vim.startswith(cur_arg, '-') then
689      print('Unrecognized option:', cur_arg, '\n')
690      os.exit(1)
691    end
692    i = i + 1
693  end
694
695  return opt
696end
697
698local function main()
699  local opt = parse_args()
700  local protocol = read_json(opt)
701  write_to_vim_protocol(protocol)
702  write_to_meta_protocol(protocol, opt.version, opt.output_file)
703end
704
705main()