aboutsummaryrefslogtreecommitdiff
path: root/src/gen/gen_lsp.lua
blob: f958e89fb87ce90392cfe1913eb81949bff75d95 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
#!/usr/bin/env -S nvim -l
-- Generates lua-ls annotations for lsp.

local USAGE = [[
Generates lua-ls annotations for lsp.

Also updates types in runtime/lua/vim/lsp/protocol.lua

Usage:
  src/gen/gen_lsp.lua [options]

Options:
  --version <version>  LSP version to use (default: 3.18)
  --out <out>          Output file (default: runtime/lua/vim/lsp/_meta/protocol.lua)
  --help               Print this help message
]]

--- The LSP protocol JSON data (it's partial, non-exhaustive).
--- https://raw.githubusercontent.com/microsoft/language-server-protocol/gh-pages/_specifications/lsp/3.18/metaModel/metaModel.schema.json
--- @class vim._gen_lsp.Protocol
--- @field requests vim._gen_lsp.Request[]
--- @field notifications vim._gen_lsp.Notification[]
--- @field structures vim._gen_lsp.Structure[]
--- @field enumerations vim._gen_lsp.Enumeration[]
--- @field typeAliases vim._gen_lsp.TypeAlias[]

--- @class vim._gen_lsp.Notification
--- @field deprecated? string
--- @field documentation? string
--- @field messageDirection string
--- @field clientCapability? string
--- @field serverCapability? string
--- @field method vim.lsp.protocol.Method
--- @field params? any
--- @field proposed? boolean
--- @field registrationMethod? string
--- @field registrationOptions? any
--- @field since? string

--- @class vim._gen_lsp.Request : vim._gen_lsp.Notification
--- @field errorData? any
--- @field partialResult? any
--- @field result any

--- @class vim._gen_lsp.Structure translated to @class
--- @field deprecated? string
--- @field documentation? string
--- @field extends? { kind: string, name: string }[]
--- @field mixins? { kind: string, name: string }[]
--- @field name string
--- @field properties? vim._gen_lsp.Property[]  members, translated to @field
--- @field proposed? boolean
--- @field since? string

--- @class vim._gen_lsp.StructureLiteral translated to anonymous @class.
--- @field deprecated? string
--- @field description? string
--- @field properties vim._gen_lsp.Property[]
--- @field proposed? boolean
--- @field since? string

--- @class vim._gen_lsp.Property translated to @field
--- @field deprecated? string
--- @field documentation? string
--- @field name string
--- @field optional? boolean
--- @field proposed? boolean
--- @field since? string
--- @field type { kind: string, name: string }

--- @class vim._gen_lsp.Enumeration translated to @enum
--- @field deprecated string?
--- @field documentation string?
--- @field name string?
--- @field proposed boolean?
--- @field since string?
--- @field suportsCustomValues boolean?
--- @field values { name: string, value: string, documentation?: string, since?: string }[]

--- @class vim._gen_lsp.TypeAlias translated to @alias
--- @field deprecated? string?
--- @field documentation? string
--- @field name string
--- @field proposed? boolean
--- @field since? string
--- @field type vim._gen_lsp.Type

--- @class vim._gen_lsp.Type
--- @field kind string a common field for all Types.
--- @field name? string for ReferenceType, BaseType
--- @field element? any for ArrayType
--- @field items? vim._gen_lsp.Type[] for OrType, AndType
--- @field key? vim._gen_lsp.Type for MapType
--- @field value? string|vim._gen_lsp.Type for StringLiteralType, MapType, StructureLiteralType

--- @param fname string
--- @param text string
local function tofile(fname, text)
  local f = assert(io.open(fname, 'w'), ('failed to open: %s'):format(fname))
  f:write(text)
  f:close()
  print('Written to:', fname)
end

---@param opt vim._gen_lsp.opt
---@return vim._gen_lsp.Protocol
local function read_json(opt)
  local uri = 'https://raw.githubusercontent.com/microsoft/language-server-protocol/gh-pages/_specifications/lsp/'
    .. opt.version
    .. '/metaModel/metaModel.json'
  print('Reading ' .. uri)

  local res = vim.system({ 'curl', '--no-progress-meter', uri, '-o', '-' }):wait()
  if res.code ~= 0 or (res.stdout or ''):len() < 999 then
    print(('URL failed: %s'):format(uri))
    vim.print(res)
    error(res.stdout)
  end
  return vim.json.decode(res.stdout)
end

--- Gets the Lua symbol for a given fully-qualified LSP method name.
--- @param s string
--- @return string
local function to_luaname(s)
  -- "$/" prefix is special: https://microsoft.github.io/language-server-protocol/specification/#dollarRequests
  return (s:gsub('^%$', 'dollar'):gsub('/', '_'))
end

--- @param a vim._gen_lsp.Notification
--- @param b vim._gen_lsp.Notification
--- @return boolean
local function compare_method(a, b)
  return to_luaname(a.method) < to_luaname(b.method)
end

--- @param item vim._gen_lsp.Request|vim._gen_lsp.Notification
--- @return string?
local function registration_provider(item)
  local server_capability = item.serverCapability
  if not server_capability then
    return nil
  end
  if vim.startswith(server_capability, 'workspace.') then
    return server_capability
  end
  return server_capability:match('^[^%.]+')
end

---@param structures table<string,vim._gen_lsp.Structure>
---@param type vim._gen_lsp.Type
---@param seen? table<string,true>
---@return boolean
local function supports_static_registration(structures, type, seen)
  if type.kind == 'reference' then
    if type.name == 'StaticRegistrationOptions' then
      return true
    end

    seen = seen or {}
    if seen[type.name] then
      return false
    end
    seen[type.name] = true

    local structure = structures[type.name]
    if not structure then
      return false
    end
    local bases = {}
    vim.list_extend(bases, structure.extends or {})
    vim.list_extend(bases, structure.mixins or {})
    for _, base in ipairs(bases) do
      if supports_static_registration(structures, base, seen) then
        return true
      end
    end
  elseif type.kind == 'and' or type.kind == 'or' then
    for _, item in ipairs(type.items) do
      if supports_static_registration(structures, item, seen) then
        return true
      end
    end
  end

  return false
end

---@param protocol vim._gen_lsp.Protocol
local function write_to_vim_protocol(protocol)
  local all = {} --- @type (vim._gen_lsp.Request|vim._gen_lsp.Notification)[]
  vim.list_extend(all, protocol.notifications)
  vim.list_extend(all, protocol.requests)

  local structures = {} --- @type table<string,vim._gen_lsp.Structure>
  for _, structure in ipairs(protocol.structures) do
    structures[structure.name] = structure
  end

  table.sort(all, compare_method)
  table.sort(protocol.requests, compare_method)
  table.sort(protocol.notifications, compare_method)

  local output = { '-- Generated by gen_lsp.lua, keep at end of file.' }

  do -- methods
    for _, dir in ipairs({ 'clientToServer', 'serverToClient' }) do
      local dir1 = dir:sub(1, 1):upper() .. dir:sub(2)
      local alias = ('vim.lsp.protocol.Method.%s'):format(dir1)
      for _, b in ipairs({
        { title = 'Request', methods = protocol.requests },
        { title = 'Notification', methods = protocol.notifications },
      }) do
        output[#output + 1] = ('--- LSP %s (direction: %s)'):format(b.title, dir)
        output[#output + 1] = ('--- @alias %s.%s'):format(alias, b.title)
        for _, item in ipairs(b.methods) do
          if item.messageDirection == dir or item.messageDirection == 'both' then
            output[#output + 1] = ("--- | '%s',"):format(item.method)
          end
        end
        output[#output + 1] = ''
      end

      vim.list_extend(output, {
        ('--- LSP Message (direction: %s).'):format(dir),
        ('--- @alias %s'):format(alias),
        ('--- | %s.Request'):format(alias),
        ('--- | %s.Notification'):format(alias),
        '',
      })
    end

    vim.list_extend(output, {
      '--- @alias vim.lsp.protocol.Method',
      '--- | vim.lsp.protocol.Method.ClientToServer',
      '--- | vim.lsp.protocol.Method.ServerToClient',
      '',
      '-- Generated by gen_lsp.lua, keep at end of file.',
      '--- @deprecated Use `vim.lsp.protocol.Method` instead.',
      '--- @enum vim.lsp.protocol.Methods',
      '--- @see https://microsoft.github.io/language-server-protocol/specification/#metaModel',
      '--- LSP method names.',
      'protocol.Methods = {',
    })

    for _, item in ipairs(all) do
      if item.method then
        if item.documentation then
          local document = vim.split(item.documentation, '\n?\n', { trimempty = true })
          for _, docstring in ipairs(document) do
            output[#output + 1] = '  --- ' .. docstring
          end
        end
        output[#output + 1] = ("  %s = '%s',"):format(to_luaname(item.method), item.method)
      end
    end
    output[#output + 1] = '}'
  end

  do -- registrationMethods
    local found = {} --- @type table<string, boolean>
    vim.list_extend(output, {
      '',
      '-- Generated by gen_lsp.lua, keep at end of file.',
      '--- LSP registration methods',
      '---@alias vim.lsp.protocol.Method.Registration',
    })
    for _, item in ipairs(all) do
      if item.registrationMethod and not found[item.registrationMethod] then
        vim.list_extend(output, {
          ("--- | '%s'"):format(item.registrationMethod or item.method),
        })
        found[item.registrationMethod or item.method] = true
      end
    end
  end

  do -- capabilities
    vim.list_extend(output, {
      '',
      '-- stylua: ignore start',
      '-- Generated by gen_lsp.lua, keep at end of file.',
      '--- Maps method names to the required client capability',
      'protocol._provider_to_client_registration = {',
    })

    local providers = {} --- @type table<string, string>
    for _, item in ipairs(all) do
      local provider = registration_provider(item)
      if item.registrationOptions and not providers[provider] and item.clientCapability then
        if
          item.clientCapability == item.serverCapability
          and not (item.serverCapability and vim.startswith(item.serverCapability, 'workspace.'))
        then
          provider = nil
        end
        local key = provider or item.method
        providers[key] = item.clientCapability
      end
    end

    ---@type { provider: string, path : string }[]
    local found_entries = {}
    for key, value in pairs(providers) do
      found_entries[#found_entries + 1] = { provider = key, path = value }
    end
    table.sort(found_entries, function(a, b)
      return a.provider < b.provider
    end)
    for _, entry in ipairs(found_entries) do
      output[#output + 1] = ("  ['%s'] = { %s },"):format(
        entry.provider,
        "'" .. entry.path:gsub('%.', "', '") .. "'"
      )
    end

    output[#output + 1] = '}'
    output[#output + 1] = '-- stylua: ignore end'

    vim.list_extend(output, {
      '',
      '-- stylua: ignore start',
      '-- Generated by gen_lsp.lua, keep at end of file.',
      '--- Maps method names to dynamic/static registration providers',
      'protocol._request_name_to_registration_provider = {',
    })

    for _, item in ipairs(all) do
      local provider = registration_provider(item) or item.method
      output[#output + 1] = ("  ['%s'] = '%s',"):format(item.method, provider)
    end

    output[#output +