robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
22.7 KiB670 linesraw
1local log = require('vim.lsp.log')
2local protocol = require('vim.lsp.protocol')
3local net_transport = require('vim.net._transport')
4local strbuffer = require('vim._core.stringbuffer')
5local validate = vim.validate
6
7--- Embeds the given string into a table and correctly computes `Content-Length`.
8---
9--- @param message string
10--- @return string message with `Content-Length` attribute
11local function format_message_with_content_length(message)
12  return table.concat({
13    'Content-Length: ',
14    tostring(#message),
15    '\r\n\r\n',
16    message,
17  })
18end
19
20--- Extract `content-length` from the header.
21---
22--- The structure of header fields conforms to [HTTP semantics](https://tools.ietf.org/html/rfc7230#section-3.2),
23--- i.e., `header-field = field-name : OWS field-value OWS`. OWS means optional whitespace (space/horizontal tabs).
24---
25--- We ignore lines ending with `\n` that don't contain `content-length`, since some servers
26--- write log to standard output and there's no way to avoid it.
27--- See https://github.com/neovim/neovim/pull/35743#pullrequestreview-3379705828
28--- @param ptr vim._core.stringbuffer.ptr The ptr to buffer to parse
29--- @param start integer The starting index of the buffer to parse, 0-based
30--- @param len integer The length of the header to parse
31--- @return integer
32local function get_content_length(ptr, start, len)
33  local state = 'name'
34  local i, end_ = start, start + len
35  local j, name = 1, 'content-length'
36  local buf = strbuffer.new()
37  local digit = true
38  while i < end_ do
39    local c = ptr[i]
40    if state == 'name' then
41      if c >= 65 and c <= 90 then -- lower case
42        c = c + 32
43      end
44      if c == 10 then -- a blank line or a line with a prefix of header
45        j = 1
46      elseif (c == 32 or c == 9) and j == 1 then -- luacheck: ignore 542
47        -- skip OWS for compatibility only
48      elseif c == name:byte(j) then
49        j = j + 1
50      elseif c == 58 and j == 15 then
51        state = 'colon'
52      else
53        state = 'invalid'
54      end
55    elseif state == 'colon' then
56      if c ~= 32 and c ~= 9 then -- skip OWS normally
57        state = 'value'
58        i = i - 1
59      end
60    elseif state == 'value' then
61      if c == 13 and ptr[i + 1] == 10 then -- must end with \r\n
62        local value = buf:get()
63        if digit then
64          return vim._assert_integer(value)
65        end
66        error('value of Content-Length is not number: ' .. value)
67      else
68        buf:put(string.char(c))
69      end
70      if c < 48 and c ~= 32 and c ~= 9 or c > 57 then
71        digit = false
72      end
73    elseif state == 'invalid' then
74      if c == 10 then -- reset for next line
75        state, j = 'name', 1
76      end
77    end
78    i = i + 1
79  end
80  local header = strbuffer.new()
81  for k = start, end_ - 1 do
82    header:put(string.char(ptr[k]))
83  end
84  error('Content-Length not found in header: ' .. header:tostring())
85end
86
87local M = {}
88
89--- Mapping of error codes used by the client
90--- @enum vim.lsp.rpc.ClientErrors
91local client_errors = {
92  INVALID_SERVER_MESSAGE = 1,
93  INVALID_SERVER_JSON = 2,
94  NO_RESULT_CALLBACK_FOUND = 3,
95  READ_ERROR = 4,
96  NOTIFICATION_HANDLER_ERROR = 5,
97  SERVER_REQUEST_HANDLER_ERROR = 6,
98  SERVER_RESULT_CALLBACK_ERROR = 7,
99}
100
101--- @type table<string,integer> | table<integer,string>
102--- @nodoc
103M.client_errors = vim.deepcopy(client_errors)
104for k, v in pairs(client_errors) do
105  M.client_errors[v] = k
106end
107
108--- Constructs an error message from an LSP error object.
109---
110---@param err table The error object
111---@return string error_message The formatted error message
112function M.format_rpc_error(err)
113  validate('err', err, 'table')
114
115  -- There is ErrorCodes in the LSP specification,
116  -- but in ResponseError.code it is not used and the actual type is number.
117  local code --- @type string
118  if protocol.ErrorCodes[err.code] then
119    code = string.format('code_name = %s,', protocol.ErrorCodes[err.code])
120  else
121    code = string.format('code_name = unknown, code = %s,', err.code)
122  end
123
124  local message_parts = { 'RPC[Error]', code }
125  if err.message then
126    table.insert(message_parts, 'message =')
127    table.insert(message_parts, string.format('%q', err.message))
128  end
129  if err.data then
130    table.insert(message_parts, 'data =')
131    table.insert(message_parts, vim.inspect(err.data))
132  end
133  return table.concat(message_parts, ' ')
134end
135
136--- Creates an RPC response table `error` to be sent to the LSP response.
137---
138---@param code integer RPC error code defined, see `vim.lsp.protocol.ErrorCodes`
139---@param message? string arbitrary message to send to server
140---@param data? any arbitrary data to send to server
141---
142---@see lsp.ErrorCodes See `vim.lsp.protocol.ErrorCodes`
143---@return lsp.ResponseError
144function M.rpc_response_error(code, message, data)
145  -- TODO should this error or just pick a sane error (like InternalError)?
146  ---@type string
147  local code_name = assert(protocol.ErrorCodes[code], 'Invalid RPC error code')
148  return {
149    code = code,
150    message = message or code_name,
151    data = data,
152  }
153end
154
155--- Dispatchers for LSP message types.
156--- @class vim.lsp.rpc.Dispatchers
157--- @inlinedoc
158--- @field notification fun(method: string, params: table)
159--- @field server_request fun(method: string, params: table): any?, lsp.ResponseError?
160--- @field on_exit fun(code: integer, signal: integer)
161--- @field on_error fun(code: integer, err: any)
162
163--- @type vim.lsp.rpc.Dispatchers
164local default_dispatchers = {
165  --- Default dispatcher for notifications sent to an LSP server.
166  ---
167  ---@param method string The invoked LSP method
168  ---@param params table Parameters for the invoked LSP method
169  notification = function(method, params)
170    log.debug('notification', method, params)
171  end,
172
173  --- Default dispatcher for requests sent to an LSP server.
174  ---
175  ---@param method string The invoked LSP method
176  ---@param params table Parameters for the invoked LSP method
177  ---@return any result (always nil for the default dispatchers)
178  ---@return lsp.ResponseError error `vim.lsp.protocol.ErrorCodes.MethodNotFound`
179  server_request = function(method, params)
180    log.debug('server_request', method, params)
181    return nil, M.rpc_response_error(protocol.ErrorCodes.MethodNotFound)
182  end,
183
184  --- Default dispatcher for when a client exits.
185  ---
186  ---@param code integer Exit code
187  ---@param signal integer Number describing the signal used to terminate (if any)
188  on_exit = function(code, signal)
189    log.info('client_exit', { code = code, signal = signal })
190  end,
191
192  --- Default dispatcher for client errors.
193  ---
194  ---@param code integer Error code
195  ---@param err any Details about the error
196  on_error = function(code, err)
197    log.error('client_error:', M.client_errors[code], err)
198  end,
199}
200
201--- Parse one `Content-Length` framed message from `strbuf`.
202---
203--- Returns a body after consuming one full frame, returns nil if more bytes are needed.
204--- Raises an error if the buffered data is not a valid frame.
205---
206---@param strbuf vim._core.stringbuffer
207---@return string?
208local function message_decoder(strbuf)
209  local header_len ---@type integer?
210  local ptr, len = strbuf:ref()
211  for i = 0, len - 4 do
212    -- Find the header boundary "\r\n\r\n"
213    -- (compare bytes instead of string.find(), to avoid a string alloc).
214    if ptr[i] == 13 and ptr[i + 1] == 10 and ptr[i + 2] == 13 and ptr[i + 3] == 10 then
215      header_len = i + 2
216      break
217    end
218  end
219
220  if not header_len then
221    return nil
222  end
223
224  local content_length = get_content_length(ptr, 0, header_len)
225  if strbuffer.len(strbuf) < header_len + 2 + content_length then
226    return nil
227  end
228
229  strbuf:skip(header_len + 2) -- skip past header boundary
230  return strbuf:get(content_length)
231end
232
233--- @private
234--- @param handle_body fun(body: string)
235--- @param on_exit? fun()
236--- @param on_error? fun(err: any, errkind: vim.lsp.rpc.ClientErrors)
237function M.create_read_loop(handle_body, on_exit, on_error)
238  on_exit = on_exit or function() end
239  on_error = on_error or function() end
240  local message_stream = net_transport.MessageStream.new(
241    message_decoder,
242    format_message_with_content_length,
243    function(err, chunk)
244      if err then
245        on_error(err, client_errors.READ_ERROR)
246      elseif chunk then
247        handle_body(chunk)
248      else
249        on_exit()
250      end
251    end,
252    function(err)
253      on_error(err, client_errors.INVALID_SERVER_MESSAGE)
254    end
255  )
256
257  return function(err, chunk)
258    message_stream:feed(err, chunk)
259  end
260end
261
262--- Client RPC object
263--- @class vim.lsp.rpc.Client
264--- @field private message_index integer
265--- @field private message_callbacks table<integer, function> dict of message_id to callback
266--- @field private notify_reply_callbacks table<integer, function> dict of message_id to callback
267--- @field private transport vim.net.Transport
268--- @field private message_stream vim.net.MessageStream
269--- @field private dispatchers vim.lsp.rpc.Dispatchers
270---
271--- Sends a request to the LSP server.
272--- @field request fun(method: vim.lsp.protocol.Method.ClientToServer.Request, params: table?, callback: fun(err?: lsp.ResponseError, result: any, request_id: integer), notify_reply_callback?: fun(message_id: integer)):boolean,integer?
273---
274--- Sends a notification to the LSP server.
275--- @field notify fun(method: vim.lsp.protocol.Method.ClientToServer.Notification, params: any): boolean
276---
277--- Indicates if the RPC is closing.
278--- @field is_closing fun(): boolean
279---
280--- Terminates the RPC client.
281--- @field terminate fun()
282local Client = {}
283
284---@package
285---@param dispatchers vim.lsp.rpc.Dispatchers
286---@param transport vim.net.Transport
287---@param decode fun(buf: vim._core.stringbuffer): string?
288---@param format fun(msg: string): string
289---@return vim.lsp.rpc.Client
290function Client.new(dispatchers, transport, decode, format)
291  local result = {
292    message_index = 0,
293    message_callbacks = {},
294    notify_reply_callbacks = {},
295    transport = transport,
296    dispatchers = dispatchers,
297  }
298
299  ---@private
300  function result.is_closing()
301    return result.transport:is_closing()
302  end
303
304  ---@private
305  function result.terminate()
306    result.transport:terminate()
307  end
308
309  ---@private
310  ---@param method (vim.lsp.protocol.Method.ClientToServer.Request) The invoked LSP method
311  ---@param params (table?) Parameters for the invoked LSP method
312  ---@param callback fun(err: lsp.ResponseError?, result: any) Callback to invoke
313  ---@param notify_reply_callback? fun(message_id: integer) Callback to invoke as soon as a request is no longer pending
314  ---@return boolean success `true` if request could be sent, `false` if not
315  ---@return integer? message_id if request could be sent, `nil` if not
316  function result.request(method, params, callback, notify_reply_callback)
317    return result:_request(method, params, callback, notify_reply_callback)
318  end
319
320  ---@private
321  ---@param method (vim.lsp.protocol.Method.ClientToServer.Notification) The invoked LSP method
322  ---@param params (table?) Parameters for the invoked LSP method
323  ---@return boolean `true` if notification could be sent, `false` if not
324  function result.notify(method, params)
325    return result:_notify(method, params)
326  end
327
328  ---@cast result vim.lsp.rpc.Client
329  local self = setmetatable(result, { __index = Client })
330
331  self.message_stream = net_transport.MessageStream.new(decode, format, function(err, data)
332    if err then
333      self:on_error(client_errors.READ_ERROR, err)
334    elseif data then
335      self:handle_body(data)
336    else
337      ---@diagnostic disable-next-line: invisible
338      self.transport:terminate()
339    end
340  end, function(err)
341    self:on_error(client_errors.INVALID_SERVER_MESSAGE, err)
342    ---@diagnostic disable-next-line: invisible
343    self.transport:terminate()
344  end)
345
346  transport:listen(function(err, data)
347    ---@diagnostic disable-next-line: invisible
348    self.message_stream:feed(err, data)
349  end, dispatchers.on_exit)
350  return self
351end
352
353---@private
354---@param payload {
355---  jsonrpc: '2.0',
356---  id?: number|string|vim.NIL,
357---  method?: string,
358---  params?: table,
359---  error?: lsp.ResponseError,
360---  result?: any
361---}
362function Client:encode_and_send(payload)
363  log.debug('rpc.send', payload)
364  if self.transport:is_closing() then
365    return false
366  end
367  local jsonstr = vim.json.encode(payload)
368
369  self.transport:write(self.message_stream.encode(jsonstr))
370  return true
371end
372
373---@package
374--- Sends a notification to the LSP server.
375---@param method vim.lsp.protocol.Method.ClientToServer.Notification The invoked LSP method
376---@param params any Parameters for the invoked LSP method
377---@return boolean `true` if notification could be sent, `false` if not
378function Client:_notify(method, params)
379  return self:encode_and_send({
380    jsonrpc = '2.0',
381    method = method,
382    params = params,
383  })
384end
385
386---@private
387--- sends an error object to the remote LSP process.
388---@param request_id number|string|vim.NIL
389---@param err lsp.ResponseError?
390---@param result any
391function Client:send_response(request_id, err, result)
392  return self:encode_and_send({
393    id = request_id,
394    jsonrpc = '2.0',
395    error = err,
396    result = result,
397  })
398end
399
400---@package
401--- Sends a request to the LSP server and runs {callback} upon response.
402---
403---@param method vim.lsp.protocol.Method.ClientToServer.Request The invoked LSP method
404---@param params table? Parameters for the invoked LSP method
405---@param callback fun(err?: lsp.ResponseError, result: any, message_id: integer) Callback to invoke
406---@param notify_reply_callback? fun(message_id: integer) Callback to invoke as soon as a request is no longer pending
407---@return boolean success `true` if request could be sent, `false` if not
408---@return integer? message_id if request could be sent, `nil` if not
409function Client:_request(method, params, callback, notify_reply_callback)
410  validate('callback', callback, 'function')
411  validate('notify_reply_callback', notify_reply_callback, 'function', true)
412  self.message_index = self.message_index + 1
413  local message_id = self.message_index
414  local result = self:encode_and_send({
415    id = message_id,
416    jsonrpc = '2.0',
417    method = method,
418    params = params,
419  })
420
421  if not result then
422    return false
423  end
424
425  self.message_callbacks[message_id] = vim.schedule_wrap(callback)
426  if notify_reply_callback then
427    self.notify_reply_callbacks[message_id] = vim.schedule_wrap(notify_reply_callback)
428  end
429  return result, message_id
430end
431
432---@package
433---@param errkind vim.lsp.rpc.ClientErrors
434---@param err any
435function Client:on_error(errkind, err)
436  assert(M.client_errors[errkind])
437  -- TODO what to do if this fails?
438  pcall(self.dispatchers.on_error, errkind, err)
439end
440
441-- TODO periodically check message_callbacks for old requests past a certain
442-- time and log them. This would require storing the timestamp. I could call
443-- them with an error then, perhaps.
444
445--- @package
446--- @param body string
447function Client:handle_body(body)
448  local ok, decoded = pcall(vim.json.decode, body)
449  if not ok then
450    self:on_error(client_errors.INVALID_SERVER_JSON, decoded)
451    return
452  elseif type(decoded) ~= 'table' then
453    self:on_error(client_errors.INVALID_SERVER_MESSAGE, decoded)
454    return
455  end
456
457  log.debug('rpc.receive', decoded)
458
459  if
460    -- Received a request.
461    type(decoded.method) == 'string' and decoded.id
462  then
463    if type(decoded.id) ~= 'number' and type(decoded.id) ~= 'string' and decoded.id ~= vim.NIL then
464      log.error(
465        'Server request id must be a number or string, got ' .. type(decoded.id),
466        decoded.method,
467        decoded.id
468      )
469      self:on_error(client_errors.INVALID_SERVER_MESSAGE, decoded)
470      return
471    end
472
473    -- Schedule here so that the users functions don't trigger an error and
474    -- we can still use the result.
475    vim.schedule(coroutine.wrap(function()
476      xpcall(function()
477        local result, err = self.dispatchers.server_request(decoded.method, decoded.params)
478        log.debug('server_request: callback result', { result = result, err = err })
479        if result == nil and err == nil then
480          error(
481            string.format(
482              'method %q: either a result or an error must be sent to the server in response',
483              decoded.method
484            )
485          )
486        end
487        if err then
488          assert(
489            type(err) == 'table',
490            'err must be a table. Use rpc_response_error to help format errors.'
491          )
492          assert(
493            protocol.ErrorCodes[err.code],
494            'Errors must use protocol.ErrorCodes. Use rpc_response_error to help format errors.'
495          )
496        end
497        self:send_response(decoded.id, err, result)
498      end, function(err)
499        self:on_error(client_errors.SERVER_REQUEST_HANDLER_ERROR, err)
500        self:send_response(
501          decoded.id,
502          M.rpc_response_error(protocol.ErrorCodes.InternalError, err),
503          nil
504        )
505      end)
506    end))
507  elseif
508    -- Received a response to a request we sent.
509    decoded.id
510  then
511    -- If there was an error in detecting the id in the Request object
512    -- (e.g. Parse error/Invalid Request), it must be Null.
513    if decoded.id == vim.NIL then
514      log.warn('Server sent response with null id', decoded)
515      self:on_error(client_errors.INVALID_SERVER_MESSAGE, decoded)
516      return
517    end
518    -- Proceed only if exactly one of 'result' or 'error' is present,
519    -- as required by the JSON-RPC spec:
520    -- * If 'error' is nil, then 'result' must be present.
521    -- * If 'result' is nil, then 'error' must be present (and not vim.NIL).
522    if (decoded.error == nil or decoded.error == vim.NIL) and decoded.result == nil then
523      log.error('Server respond empty result and error', decoded)
524      self:on_error(client_errors.INVALID_SERVER_MESSAGE, decoded)
525      return
526    end
527
528    -- We sent a number, so we expect a number.
529    local result_id = vim._assert_integer(decoded.id)
530
531    -- Notify the user that a response was received for the request
532    local notify_reply_callback = self.notify_reply_callbacks[result_id]
533    if notify_reply_callback then
534      validate('notify_reply_callback', notify_reply_callback, 'function')
535      notify_reply_callback(result_id)
536      self.notify_reply_callbacks[result_id] = nil
537    end
538
539    -- Do not surface RequestCancelled to users, it is RPC-internal.
540    if decoded.error then
541      assert(type(decoded.error) == 'table')
542      if decoded.error.code == protocol.ErrorCodes.RequestCancelled then
543        log.debug('Received cancellation ack', decoded)
544        -- Clear any callback since this is cancelled now.
545        -- This is safe to do assuming that these conditions hold:
546        -- - The server will not send a result callback after this cancellation.
547        -- - If the server sent this cancellation ACK after sending the result, the user of this RPC
548        -- client will ignore the result themselves.
549        if result_id then
550          self.message_callbacks[result_id] = nil
551        end
552        return
553      end
554    end
555
556    local callback = self.message_callbacks[result_id]
557    if callback then
558      self.message_callbacks[result_id] = nil
559      validate('callback', callback, 'function')
560      xpcall(function()
561        callback(decoded.error, decoded.result ~= vim.NIL and decoded.result or nil, result_id)
562      end, function(err)
563        self:on_error(client_errors.SERVER_RESULT_CALLBACK_ERROR, err)
564      end)
565    else
566      self:on_error(client_errors.NO_RESULT_CALLBACK_FOUND, decoded)
567      log.error('No callback found for server response id ' .. result_id)
568    end
569  elseif
570    -- Received a notification.
571    type(decoded.method) == 'string'
572  then
573    xpcall(function()
574      assert(
575        self.dispatchers.notification(decoded.method, decoded.params) == nil,
576        'notification handlers should not return a value'
577      )
578    end, function(err)
579      self:on_error(client_errors.NOTIFICATION_HANDLER_ERROR, err)
580    end)
581  else
582    -- Invalid server message
583    self:on_error(client_errors.INVALID_SERVER_MESSAGE, decoded)
584  end
585end
586
587---@param dispatchers vim.lsp.rpc.Dispatchers?
588---@return vim.lsp.rpc.Dispatchers
589local function merge_dispatchers(dispatchers)
590  if not dispatchers then
591    return default_dispatchers
592  end
593  ---@diagnostic disable-next-line: no-unknown
594  for name, fn in pairs(dispatchers) do
595    if type(fn) ~= 'function' then
596      error(string.format('dispatcher.%s must be a function', name))
597    end
598  end
599  ---@type vim.lsp.rpc.Dispatchers
600  local merged = {
601    notification = (
602      dispatchers.notification and vim.schedule_wrap(dispatchers.notification)
603      or default_dispatchers.notification
604    ),
605    on_error = (
606      dispatchers.on_error and vim.schedule_wrap(dispatchers.on_error)
607      or default_dispatchers.on_error
608    ),
609    on_exit = dispatchers.on_exit or default_dispatchers.on_exit,
610    server_request = dispatchers.server_request or default_dispatchers.server_request,
611  }
612  return merged
613end
614
615--- Create a LSP RPC client factory that connects to either:
616---
617---  - a named pipe (windows)
618---  - a domain socket (unix)
619---  - a host and port via TCP
620---
621--- Return a function that can be passed to the `cmd` field for
622--- |vim.lsp.start()|.
623---
624---@param host_or_path string host to connect to or path to a pipe/domain socket
625---@param port integer? TCP port to connect to. If absent the first argument must be a pipe
626---@return fun(dispatchers: vim.lsp.rpc.Dispatchers): vim.lsp.rpc.Client
627function M.connect(host_or_path, port)
628  log.info('Connecting RPC client', { host_or_path = host_or_path, port = port })
629
630  validate('host_or_path', host_or_path, 'string')
631  validate('port', port, 'number', true)
632
633  return function(dispatchers)
634    validate('dispatchers', dispatchers, 'table', true)
635
636    dispatchers = merge_dispatchers(dispatchers)
637
638    local transport = net_transport.TransportConnect.new(host_or_path, port, vim.lsp.log._self)
639    return Client.new(dispatchers, transport, message_decoder, format_message_with_content_length)
640  end
641end
642
643--- Additional context for the LSP server process.
644--- @class vim.net.transport.ExtraSpawnParams
645--- @inlinedoc
646--- @field cwd? string Working directory for the LSP server process
647--- @field detached? boolean Detach the LSP server process from the current process
648--- @field env? table<string,string> Additional environment variables for LSP server process. See |vim.system()|
649
650--- Starts an LSP server process and create an LSP RPC client object to
651--- interact with it. Communication with the spawned process happens via stdio. For
652--- communication via TCP, spawn a process manually and use |vim.lsp.rpc.connect()|
653---
654--- @param cmd string[] Command to start the LSP server.
655--- @param dispatchers? vim.lsp.rpc.Dispatchers
656--- @param extra_spawn_params? vim.net.transport.ExtraSpawnParams
657--- @return vim.lsp.rpc.Client
658function M.start(cmd, dispatchers, extra_spawn_params)
659  log.info('Starting RPC client', { cmd = cmd, extra = extra_spawn_params })
660
661  validate('cmd', cmd, 'table')
662  validate('dispatchers', dispatchers, 'table', true)
663
664  dispatchers = merge_dispatchers(dispatchers)
665
666  local transport = net_transport.TransportRun.new(cmd, extra_spawn_params, vim.lsp.log._self)
667  return Client.new(dispatchers, transport, message_decoder, format_message_with_content_length)
668end
669
670return M