robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
16.8 KiB541 linesraw
1---@brief This module provides functionality for requesting LSP diagnostics for a document/workspace
2---and populating them using |vim.Diagnostic|s. `DiagnosticRelatedInformation` is supported: it is
3---included in the window shown by |vim.diagnostic.open_float()|. When the cursor is on a line with
4---related information, |gf| jumps to the problem location.
5
6local lsp = vim.lsp
7local protocol = lsp.protocol
8local util = lsp.util
9local Capability = require('vim.lsp._capability')
10
11local api = vim.api
12
13local M = {}
14
15---@class (private) vim.lsp.diagnostic.ClientState
16---@field pull_kind 'document'|'workspace' Whether diagnostics are being updated via document or workspace pull
17---@field result_id table<string, string?>  Latest responded `resultId`, keyed by `identifier`
18
19---@class (private) Diagnostics : vim.lsp.Capability
20---@field active table<integer, Diagnostics>
21---@field client_state table<integer, vim.lsp.diagnostic.ClientState>
22local Diagnostics = {
23  name = 'diagnostics',
24  method = 'textDocument/diagnostic',
25  active = {},
26}
27Diagnostics.__index = Diagnostics
28setmetatable(Diagnostics, Capability)
29Capability.all[Diagnostics.name] = Diagnostics
30
31--- Diagnostics are enabled by default
32Capability.enable('diagnostics', true)
33
34local DEFAULT_CLIENT_ID = -1
35
36---@param severity lsp.DiagnosticSeverity?
37---@return vim.diagnostic.Severity?
38local function severity_lsp_to_vim(severity)
39  if type(severity) == 'string' then
40    return protocol.DiagnosticSeverity[severity] --[[@as vim.diagnostic.Severity]]
41  end
42  return severity
43end
44
45---@param severity vim.diagnostic.Severity|vim.diagnostic.SeverityName
46---@return lsp.DiagnosticSeverity
47local function severity_vim_to_lsp(severity)
48  if type(severity) == 'string' then
49    return vim.diagnostic.severity[severity]
50  end
51  return severity --[[@as lsp.DiagnosticSeverity]]
52end
53
54---@param bufnr integer
55---@return string[]?
56local function get_buf_lines(bufnr)
57  if api.nvim_buf_is_loaded(bufnr) then
58    return api.nvim_buf_get_lines(bufnr, 0, -1, false)
59  end
60
61  local filename = api.nvim_buf_get_name(bufnr)
62  local f = io.open(filename)
63  if not f then
64    return
65  end
66
67  local content = f:read('*a')
68  if not content then
69    -- Some LSP servers report diagnostics at a directory level, in which case
70    -- io.read() returns nil
71    f:close()
72    return
73  end
74
75  local lines = vim.split(content, '\n')
76  f:close()
77  return lines
78end
79
80--- @param diagnostic lsp.Diagnostic
81--- @param client_id integer
82--- @return table?
83local function tags_lsp_to_vim(diagnostic, client_id)
84  local tags ---@type table?
85  assert(diagnostic.tags ~= vim.NIL, 'server response has invalid (null) tags')
86  for _, tag in ipairs(diagnostic.tags or {}) do
87    if tag == protocol.DiagnosticTag.Unnecessary then
88      tags = tags or {}
89      tags.unnecessary = true
90    elseif tag == protocol.DiagnosticTag.Deprecated then
91      tags = tags or {}
92      tags.deprecated = true
93    else
94      lsp.log.info(string.format('Unknown DiagnosticTag %d from LSP client %d', tag, client_id))
95    end
96  end
97  return tags
98end
99
100---@param diagnostics lsp.Diagnostic[]
101---@param bufnr integer
102---@param client_id integer
103---@return vim.Diagnostic.Set[]
104local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id)
105  local buf_lines = get_buf_lines(bufnr)
106  local client = lsp.get_client_by_id(client_id)
107  local position_encoding = client and client.offset_encoding or 'utf-16'
108  --- @param diagnostic lsp.Diagnostic
109  --- @return vim.Diagnostic.Set
110  return vim.tbl_map(function(diagnostic)
111    local start = diagnostic.range.start
112    local _end = diagnostic.range['end']
113    local message = diagnostic.message
114    if type(message) ~= 'string' then
115      vim.notify_once(
116        string.format('Unsupported Markup message from LSP client %d', client_id),
117        lsp.log_levels.ERROR
118      )
119      message = message.value
120    end
121    local line = buf_lines and buf_lines[start.line + 1] or ''
122    local end_line = line
123    if _end.line > start.line then
124      end_line = buf_lines and buf_lines[_end.line + 1] or ''
125    end
126    --- @type vim.Diagnostic.Set
127    return {
128      lnum = start.line,
129      col = vim.str_byteindex(line, position_encoding, start.character, false),
130      end_lnum = _end.line,
131      end_col = vim.str_byteindex(end_line, position_encoding, _end.character, false),
132      severity = severity_lsp_to_vim(diagnostic.severity),
133      message = message,
134      source = diagnostic.source,
135      code = diagnostic.code,
136      _tags = tags_lsp_to_vim(diagnostic, client_id),
137      user_data = {
138        lsp = diagnostic,
139      },
140    }
141  end, diagnostics)
142end
143
144--- @param diagnostic vim.Diagnostic
145--- @return lsp.DiagnosticTag[]?
146local function tags_vim_to_lsp(diagnostic)
147  if not diagnostic._tags then
148    return
149  end
150
151  local tags = {} --- @type lsp.DiagnosticTag[]
152  if diagnostic._tags.unnecessary then
153    tags[#tags + 1] = protocol.DiagnosticTag.Unnecessary
154  end
155  if diagnostic._tags.deprecated then
156    tags[#tags + 1] = protocol.DiagnosticTag.Deprecated
157  end
158  return tags
159end
160
161---@param identifier string?
162---@return string
163local function result_id_key(identifier)
164  return identifier or 'nil'
165end
166
167--- Converts the input `vim.Diagnostic`s to LSP diagnostics.
168--- @param diagnostics vim.Diagnostic[]
169--- @return lsp.Diagnostic[]
170function M.from(diagnostics)
171  ---@param diagnostic vim.Diagnostic
172  ---@return lsp.Diagnostic
173  return vim.tbl_map(function(diagnostic)
174    local user_data = diagnostic.user_data or {}
175    if user_data.lsp then
176      return user_data.lsp
177    end
178    return {
179      range = {
180        start = {
181          line = diagnostic.lnum,
182          character = diagnostic.col,
183        },
184        ['end'] = {
185          line = diagnostic.end_lnum,
186          character = diagnostic.end_col,
187        },
188      },
189      severity = severity_vim_to_lsp(diagnostic.severity),
190      message = diagnostic.message,
191      source = diagnostic.source,
192      code = diagnostic.code,
193      tags = tags_vim_to_lsp(diagnostic),
194    }
195  end, diagnostics)
196end
197
198---@type table<integer, integer>
199local client_push_namespaces = {}
200
201---@type table<string, integer>
202local client_pull_namespaces = {}
203
204--- Get the diagnostic namespace associated with an LSP client |vim.diagnostic| for diagnostics
205---
206---@param client_id integer The id of the LSP client
207---@param is_pull boolean? Whether the namespace is for a pull or push client. Defaults to
208---                        `false` (push).
209---@param pull_id string? (default: nil) Optional identifier for pull diagnostic providers.
210---                       Only used if `is_pull` is `true`.
211function M.get_namespace(client_id, is_pull, pull_id)
212  vim.validate('client_id', client_id, 'number')
213  vim.validate('is_pull', is_pull, 'boolean', true)
214  vim.validate('pull_id', pull_id, 'string', true)
215
216  local client = lsp.get_client_by_id(client_id)
217  if is_pull then
218    pull_id = pull_id or 'nil'
219    local key = ('%d:%s'):format(client_id, pull_id)
220    local name = ('nvim.lsp.%s.%d.%s'):format(
221      client and client.name or 'unknown',
222      client_id,
223      pull_id
224    )
225    local ns = client_pull_namespaces[key]
226    if not ns then
227      ns = api.nvim_create_namespace(name)
228      client_pull_namespaces[key] = ns
229    end
230    return ns
231  end
232
233  local ns = client_push_namespaces[client_id]
234  if not ns then
235    local name = ('nvim.lsp.%s.%d'):format(client and client.name or 'unknown', client_id)
236    ns = api.nvim_create_namespace(name)
237    client_push_namespaces[client_id] = ns
238  end
239  return ns
240end
241
242--- @param uri string
243--- @param client_id? integer
244--- @param diagnostics lsp.Diagnostic[]
245--- @param is_pull? boolean
246--- @param pull_id? string
247local function handle_diagnostics(uri, client_id, diagnostics, is_pull, pull_id)
248  local fname = vim.uri_to_fname(uri)
249
250  if #diagnostics == 0 and vim.fn.bufexists(fname) == 0 then
251    return
252  end
253
254  local bufnr = vim.fn.bufadd(fname)
255  if not bufnr then
256    return
257  end
258
259  client_id = client_id or DEFAULT_CLIENT_ID
260
261  local namespace = M.get_namespace(client_id, is_pull, pull_id)
262
263  vim.diagnostic.set(namespace, bufnr, diagnostic_lsp_to_vim(diagnostics, bufnr, client_id))
264end
265
266--- |lsp-handler| for the method "textDocument/publishDiagnostics"
267---
268--- See |vim.diagnostic.config()| for configuration options.
269---
270---@param _ lsp.ResponseError?
271---@param params lsp.PublishDiagnosticsParams
272---@param ctx lsp.HandlerContext
273function M.on_publish_diagnostics(_, params, ctx)
274  -- TODO(tris203): if empty array then clear diags
275  -- https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_publishDiagnostics
276  handle_diagnostics(params.uri, ctx.client_id, params.diagnostics)
277end
278
279--- |lsp-handler| for the method "textDocument/diagnostic"
280---
281--- See |vim.diagnostic.config()| for configuration options.
282---
283---@param error lsp.ResponseError?
284---@param result lsp.DocumentDiagnosticReport
285---@param ctx lsp.HandlerContext
286function M.on_diagnostic(error, result, ctx)
287  local client_id = ctx.client_id
288  local bufnr = assert(ctx.bufnr)
289  local state = Diagnostics.active[bufnr] and Diagnostics.active[bufnr].client_state[client_id]
290  if not state then
291    return
292  end
293
294  if error ~= nil then
295    if error.code == protocol.ErrorCodes.ServerCancelled then
296      if error.data == nil or error.data.retriggerRequest ~= false then
297        local client = assert(lsp.get_client_by_id(client_id))
298        ---@diagnostic disable-next-line: param-type-mismatch
299        client:request(ctx.method, ctx.params, nil, ctx.bufnr)
300      end
301    else
302      lsp.log.error('diagnostics', error)
303    end
304    return
305  end
306
307  if result == nil then
308    return
309  end
310
311  ---@type lsp.DocumentDiagnosticParams
312  local params = ctx.params
313  local key = result_id_key(params.identifier)
314  state.result_id[key] = result.resultId
315
316  if result.kind == 'unchanged' then
317    return
318  end
319
320  handle_diagnostics(params.textDocument.uri, client_id, result.items, true, params.identifier)
321
322  for uri, related_result in pairs(result.relatedDocuments or {}) do
323    if related_result.kind == 'full' then
324      handle_diagnostics(uri, client_id, related_result.items, true, params.identifier)
325    end
326
327    -- Create a new client state if it doesn't exist for the related document. This will not enable
328    -- diagnostic pulling by itself, but will allow previous result IDs to be passed correctly the
329    -- next time this buffer's diagnostics are pulled.
330    local related_bufnr = vim.uri_to_bufnr(uri)
331    local related_diagnostics = Diagnostics.active[related_bufnr] or Diagnostics:new(related_bufnr)
332    local related_state = related_diagnostics.client_state[client_id]
333    if not related_state then
334      related_state = { pull_kind = 'document', result_id = {} }
335      related_diagnostics.client_state[client_id] = related_state
336    end
337    related_state.result_id[key] = related_result.resultId
338  end
339end
340
341--- Clear diagnostics from pull based clients
342---@package
343---@param client_id integer?
344function Diagnostics:clear(client_id)
345  for key, namespace in pairs(client_pull_namespaces) do
346    if not client_id or vim.startswith(key, ('%d:'):format(client_id)) then
347      vim.diagnostic.reset(namespace, self.bufnr)
348    end
349  end
350end
351
352--- Refresh diagnostics, only if we have attached clients that support it
353---@package
354---@param client_id integer Client ID to refresh
355function Diagnostics:refresh(client_id)
356  local client = lsp.get_client_by_id(client_id)
357
358  local method = 'textDocument/diagnostic'
359  local clients = { client }
360
361  util._cancel_requests({
362    bufnr = self.bufnr,
363    clients = clients,
364    method = method,
365    type = 'pending',
366  })
367
368  local state = self.client_state[client_id]
369  if client and state then
370    client:_provider_foreach(method, function(cap)
371      --- @cast cap lsp.DiagnosticRegistrationOptions
372      local key = result_id_key(cap.identifier)
373      ---@type lsp.DocumentDiagnosticParams
374      local params = {
375        identifier = cap.identifier,
376        textDocument = util.make_text_document_params(self.bufnr),
377        previousResultId = state.result_id[key],
378      }
379      client:request(method, params, nil, self.bufnr)
380    end)
381  end
382end
383
384--- |lsp-handler| for the method `workspace/diagnostic/refresh`
385---@internal
386---@param err lsp.ResponseError?
387---@param ctx lsp.HandlerContext
388function M.on_refresh(err, _, ctx)
389  if err then
390    return vim.NIL
391  end
392  local client = lsp.get_client_by_id(ctx.client_id)
393  if client == nil then
394    return vim.NIL
395  end
396  if client:supports_method('workspace/diagnostic') then
397    M._workspace_diagnostics({ client_id = ctx.client_id })
398  end
399
400  -- Always refresh document-pull buffers. Workspace diagnostics only cover
401  -- buffers with pull_kind == 'workspace', so open buffers must be refreshed
402  -- individually or their diagnostics go stale until the next didChange.
403  for bufnr in pairs(client.attached_buffers or {}) do
404    local provider = Diagnostics.active[bufnr]
405    local state = provider and provider.client_state[ctx.client_id]
406    if state and state.pull_kind == 'document' then
407      provider:refresh(ctx.client_id)
408    end
409  end
410
411  return vim.NIL
412end
413
414--- Enable pull diagnostics for a buffer from a client
415---@package
416---@param client_id integer
417function Diagnostics:on_attach(client_id)
418  local state = self.client_state[client_id]
419
420  if state then
421    state.pull_kind = 'document'
422  else
423    state = { pull_kind = 'document', result_id = {} }
424    self.client_state[client_id] = state
425  end
426
427  self:refresh(client_id)
428end
429
430--- Disable pull diagnostics for a buffer from a client
431---@package
432---@param client_id integer
433function Diagnostics:on_detach(client_id)
434  local state = self.client_state[client_id]
435  if state then
436    self:clear(client_id)
437    self.client_state[client_id] = nil
438  end
439end
440
441---@private
442---@param client_id integer
443function Diagnostics:on_close(client_id)
444  local state = self.client_state[client_id]
445  if state and state.pull_kind == 'document' then
446    self:clear(client_id)
447  end
448end
449
450---@private
451---@param client_id integer
452function Diagnostics:on_change(client_id)
453  local state = self.client_state[client_id]
454  if state and state.pull_kind == 'document' then
455    self:refresh(client_id)
456  end
457end
458
459--- Returns the result IDs from the reports provided by the given client.
460--- @return lsp.PreviousResultId[]
461--- @param client_id integer
462--- @param identifier string?
463local function previous_result_ids(client_id, identifier)
464  local results = {} ---@type lsp.PreviousResultId[]
465  local key = result_id_key(identifier)
466
467  for bufnr, provider in pairs(Diagnostics.active) do
468    local state = provider.client_state[client_id]
469    if state then
470      local result_id = state.result_id[key]
471      if result_id then
472        results[#results + 1] = {
473          uri = vim.uri_from_bufnr(bufnr),
474          value = result_id,
475        }
476      end
477    end
478  end
479
480  return results
481end
482
483--- Request workspace-wide diagnostics.
484--- @param opts vim.lsp.WorkspaceDiagnosticsOpts
485function M._workspace_diagnostics(opts)
486  local clients = lsp.get_clients({ method = 'workspace/diagnostic', id = opts.client_id })
487
488  --- @param error lsp.ResponseError?
489  --- @param result lsp.WorkspaceDiagnosticReport
490  --- @param ctx lsp.HandlerContext
491  local function handler(error, result, ctx)
492    -- Check for retrigger requests on cancellation errors.
493    -- Unless `retriggerRequest` is explicitly disabled, try again.
494    if error ~= nil and error.code == protocol.ErrorCodes.ServerCancelled then
495      if error.data == nil or error.data.retriggerRequest ~= false then
496        local client = assert(lsp.get_client_by_id(ctx.client_id))
497        client:request('workspace/diagnostic', ctx.params, handler)
498      end
499      return
500    end
501
502    if error == nil and result ~= nil then
503      ---@type lsp.WorkspaceDiagnosticParams
504      local params = ctx.params
505      for _, report in ipairs(result.items) do
506        local bufnr = vim.uri_to_bufnr(report.uri)
507
508        -- Start tracking the buffer (but don't send "textDocument/diagnostic" requests for it).
509        local provider = Diagnostics.active[bufnr] or Diagnostics:new(bufnr)
510        local state = provider.client_state[ctx.client_id]
511        if not state then
512          state = { pull_kind = 'workspace', result_id = {} }
513          provider.client_state[ctx.client_id] = state
514        end
515
516        -- We favor document pull requests over workspace results, so only update the buffer
517        -- state if we're not pulling document diagnostics for this buffer.
518        if state.pull_kind == 'workspace' and report.kind == 'full' then
519          handle_diagnostics(report.uri, ctx.client_id, report.items, true, params.identifier)
520          local key = result_id_key(params.identifier)
521          state.result_id[key] = report.resultId
522        end
523      end
524    end
525  end
526
527  for _, client in ipairs(clients) do
528    client:_provider_foreach('workspace/diagnostic', function(cap)
529      --- @cast cap lsp.DiagnosticRegistrationOptions
530      --- @type lsp.WorkspaceDiagnosticParams
531      local params = {
532        identifier = cap.identifier,
533        previousResultIds = previous_result_ids(client.id, cap.identifier),
534      }
535
536      client:request('workspace/diagnostic', params, handler)
537    end)
538  end
539end
540
541return M