rpc.lua 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. local log = require('vim.lsp.log')
  2. local protocol = require('vim.lsp.protocol')
  3. local lsp_transport = require('vim.lsp._transport')
  4. local validate, schedule_wrap = vim.validate, vim.schedule_wrap
  5. --- Embeds the given string into a table and correctly computes `Content-Length`.
  6. ---
  7. ---@param message string
  8. ---@return string message with `Content-Length` attribute
  9. local function format_message_with_content_length(message)
  10. return table.concat({
  11. 'Content-Length: ',
  12. tostring(#message),
  13. '\r\n\r\n',
  14. message,
  15. })
  16. end
  17. ---@class (private) vim.lsp.rpc.Headers: {string: any}
  18. ---@field content_length integer
  19. --- Parses an LSP Message's header
  20. ---
  21. ---@param header string The header to parse.
  22. ---@return vim.lsp.rpc.Headers#parsed headers
  23. local function parse_headers(header)
  24. assert(type(header) == 'string', 'header must be a string')
  25. --- @type vim.lsp.rpc.Headers
  26. local headers = {}
  27. for line in vim.gsplit(header, '\r\n', { plain = true }) do
  28. if line == '' then
  29. break
  30. end
  31. --- @type string?, string?
  32. local key, value = line:match('^%s*(%S+)%s*:%s*(.+)%s*$')
  33. if key then
  34. key = key:lower():gsub('%-', '_') --- @type string
  35. headers[key] = value
  36. else
  37. log.error('invalid header line %q', line)
  38. error(string.format('invalid header line %q', line))
  39. end
  40. end
  41. headers.content_length = tonumber(headers.content_length)
  42. or error(string.format('Content-Length not found in headers. %q', header))
  43. return headers
  44. end
  45. -- This is the start of any possible header patterns. The gsub converts it to a
  46. -- case insensitive pattern.
  47. local header_start_pattern = ('content'):gsub('%w', function(c)
  48. return '[' .. c .. c:upper() .. ']'
  49. end)
  50. --- The actual workhorse.
  51. local function request_parser_loop()
  52. local buffer = '' -- only for header part
  53. while true do
  54. -- A message can only be complete if it has a double CRLF and also the full
  55. -- payload, so first let's check for the CRLFs
  56. local start, finish = buffer:find('\r\n\r\n', 1, true)
  57. -- Start parsing the headers
  58. if start then
  59. -- This is a workaround for servers sending initial garbage before
  60. -- sending headers, such as if a bash script sends stdout. It assumes
  61. -- that we know all of the headers ahead of time. At this moment, the
  62. -- only valid headers start with "Content-*", so that's the thing we will
  63. -- be searching for.
  64. -- TODO(ashkan) I'd like to remove this, but it seems permanent :(
  65. local buffer_start = buffer:find(header_start_pattern)
  66. if not buffer_start then
  67. error(
  68. string.format(
  69. "Headers were expected, a different response was received. The server response was '%s'.",
  70. buffer
  71. )
  72. )
  73. end
  74. local headers = parse_headers(buffer:sub(buffer_start, start - 1))
  75. local content_length = headers.content_length
  76. -- Use table instead of just string to buffer the message. It prevents
  77. -- a ton of strings allocating.
  78. -- ref. http://www.lua.org/pil/11.6.html
  79. ---@type string[]
  80. local body_chunks = { buffer:sub(finish + 1) }
  81. local body_length = #body_chunks[1]
  82. -- Keep waiting for data until we have enough.
  83. while body_length < content_length do
  84. ---@type string
  85. local chunk = coroutine.yield()
  86. or error('Expected more data for the body. The server may have died.') -- TODO hmm.
  87. table.insert(body_chunks, chunk)
  88. body_length = body_length + #chunk
  89. end
  90. local last_chunk = body_chunks[#body_chunks]
  91. body_chunks[#body_chunks] = last_chunk:sub(1, content_length - body_length - 1)
  92. local rest = ''
  93. if body_length > content_length then
  94. rest = last_chunk:sub(content_length - body_length)
  95. end
  96. local body = table.concat(body_chunks)
  97. -- Yield our data.
  98. --- @type string
  99. local data = coroutine.yield(headers, body)
  100. or error('Expected more data for the body. The server may have died.')
  101. buffer = rest .. data
  102. else
  103. -- Get more data since we don't have enough.
  104. --- @type string
  105. local data = coroutine.yield()
  106. or error('Expected more data for the header. The server may have died.')
  107. buffer = buffer .. data
  108. end
  109. end
  110. end
  111. local M = {}
  112. --- Mapping of error codes used by the client
  113. --- @nodoc
  114. local client_errors = {
  115. INVALID_SERVER_MESSAGE = 1,
  116. INVALID_SERVER_JSON = 2,
  117. NO_RESULT_CALLBACK_FOUND = 3,
  118. READ_ERROR = 4,
  119. NOTIFICATION_HANDLER_ERROR = 5,
  120. SERVER_REQUEST_HANDLER_ERROR = 6,
  121. SERVER_RESULT_CALLBACK_ERROR = 7,
  122. }
  123. --- @type table<string,integer> | table<integer,string>
  124. --- @nodoc
  125. M.client_errors = vim.deepcopy(client_errors)
  126. for k, v in pairs(client_errors) do
  127. M.client_errors[v] = k
  128. end
  129. --- Constructs an error message from an LSP error object.
  130. ---
  131. ---@param err table The error object
  132. ---@return string error_message The formatted error message
  133. function M.format_rpc_error(err)
  134. validate('err', err, 'table')
  135. -- There is ErrorCodes in the LSP specification,
  136. -- but in ResponseError.code it is not used and the actual type is number.
  137. local code --- @type string
  138. if protocol.ErrorCodes[err.code] then
  139. code = string.format('code_name = %s,', protocol.ErrorCodes[err.code])
  140. else
  141. code = string.format('code_name = unknown, code = %s,', err.code)
  142. end
  143. local message_parts = { 'RPC[Error]', code }
  144. if err.message then
  145. table.insert(message_parts, 'message =')
  146. table.insert(message_parts, string.format('%q', err.message))
  147. end
  148. if err.data then
  149. table.insert(message_parts, 'data =')
  150. table.insert(message_parts, vim.inspect(err.data))
  151. end
  152. return table.concat(message_parts, ' ')
  153. end
  154. --- Creates an RPC response table `error` to be sent to the LSP response.
  155. ---
  156. ---@param code integer RPC error code defined, see `vim.lsp.protocol.ErrorCodes`
  157. ---@param message? string arbitrary message to send to server
  158. ---@param data? any arbitrary data to send to server
  159. ---
  160. ---@see lsp.ErrorCodes See `vim.lsp.protocol.ErrorCodes`
  161. ---@return lsp.ResponseError
  162. function M.rpc_response_error(code, message, data)
  163. -- TODO should this error or just pick a sane error (like InternalError)?
  164. ---@type string
  165. local code_name = assert(protocol.ErrorCodes[code], 'Invalid RPC error code')
  166. return setmetatable({
  167. code = code,
  168. message = message or code_name,
  169. data = data,
  170. }, {
  171. __tostring = M.format_rpc_error,
  172. })
  173. end
  174. --- Dispatchers for LSP message types.
  175. --- @class vim.lsp.rpc.Dispatchers
  176. --- @inlinedoc
  177. --- @field notification fun(method: string, params: table)
  178. --- @field server_request fun(method: string, params: table): any?, lsp.ResponseError?
  179. --- @field on_exit fun(code: integer, signal: integer)
  180. --- @field on_error fun(code: integer, err: any)
  181. --- @type vim.lsp.rpc.Dispatchers
  182. local default_dispatchers = {
  183. --- Default dispatcher for notifications sent to an LSP server.
  184. ---
  185. ---@param method string The invoked LSP method
  186. ---@param params table Parameters for the invoked LSP method
  187. notification = function(method, params)
  188. log.debug('notification', method, params)
  189. end,
  190. --- Default dispatcher for requests sent to an LSP server.
  191. ---
  192. ---@param method string The invoked LSP method
  193. ---@param params table Parameters for the invoked LSP method
  194. ---@return any result (always nil for the default dispatchers)
  195. ---@return lsp.ResponseError error `vim.lsp.protocol.ErrorCodes.MethodNotFound`
  196. server_request = function(method, params)
  197. log.debug('server_request', method, params)
  198. return nil, M.rpc_response_error(protocol.ErrorCodes.MethodNotFound)
  199. end,
  200. --- Default dispatcher for when a client exits.
  201. ---
  202. ---@param code integer Exit code
  203. ---@param signal integer Number describing the signal used to terminate (if any)
  204. on_exit = function(code, signal)
  205. log.info('client_exit', { code = code, signal = signal })
  206. end,
  207. --- Default dispatcher for client errors.
  208. ---
  209. ---@param code integer Error code
  210. ---@param err any Details about the error
  211. on_error = function(code, err)
  212. log.error('client_error:', M.client_errors[code], err)
  213. end,
  214. }
  215. --- @private
  216. --- @param handle_body fun(body: string)
  217. --- @param on_exit? fun()
  218. --- @param on_error fun(err: any)
  219. function M.create_read_loop(handle_body, on_exit, on_error)
  220. local parse_chunk = coroutine.wrap(request_parser_loop) --[[@as fun(chunk: string?): vim.lsp.rpc.Headers?, string?]]
  221. parse_chunk()
  222. return function(err, chunk)
  223. if err then
  224. on_error(err)
  225. return
  226. end
  227. if not chunk then
  228. if on_exit then
  229. on_exit()
  230. end
  231. return
  232. end
  233. while true do
  234. local headers, body = parse_chunk(chunk)
  235. if headers then
  236. handle_body(assert(body))
  237. chunk = ''
  238. else
  239. break
  240. end
  241. end
  242. end
  243. end
  244. ---@class (private) vim.lsp.rpc.Client
  245. ---@field message_index integer
  246. ---@field message_callbacks table<integer, function> dict of message_id to callback
  247. ---@field notify_reply_callbacks table<integer, function> dict of message_id to callback
  248. ---@field transport vim.lsp.rpc.Transport
  249. ---@field dispatchers vim.lsp.rpc.Dispatchers
  250. local Client = {}
  251. ---@private
  252. function Client:encode_and_send(payload)
  253. log.debug('rpc.send', payload)
  254. if self.transport:is_closing() then
  255. return false
  256. end
  257. local jsonstr = assert(
  258. vim.json.encode(payload),
  259. string.format("Couldn't encode payload '%s'", vim.inspect(payload))
  260. )
  261. self.transport:write(format_message_with_content_length(jsonstr))
  262. return true
  263. end
  264. ---@package
  265. --- Sends a notification to the LSP server.
  266. ---@param method string The invoked LSP method
  267. ---@param params any Parameters for the invoked LSP method
  268. ---@return boolean `true` if notification could be sent, `false` if not
  269. function Client:notify(method, params)
  270. return self:encode_and_send({
  271. jsonrpc = '2.0',
  272. method = method,
  273. params = params,
  274. })
  275. end
  276. ---@private
  277. --- sends an error object to the remote LSP process.
  278. function Client:send_response(request_id, err, result)
  279. return self:encode_and_send({
  280. id = request_id,
  281. jsonrpc = '2.0',
  282. error = err,
  283. result = result,
  284. })
  285. end
  286. ---@package
  287. --- Sends a request to the LSP server and runs {callback} upon response. |vim.lsp.rpc.request()|
  288. ---
  289. ---@param method string The invoked LSP method
  290. ---@param params table? Parameters for the invoked LSP method
  291. ---@param callback fun(err?: lsp.ResponseError, result: any) Callback to invoke
  292. ---@param notify_reply_callback? fun(message_id: integer) Callback to invoke as soon as a request is no longer pending
  293. ---@return boolean success `true` if request could be sent, `false` if not
  294. ---@return integer? message_id if request could be sent, `nil` if not
  295. function Client:request(method, params, callback, notify_reply_callback)
  296. validate('callback', callback, 'function')
  297. validate('notify_reply_callback', notify_reply_callback, 'function', true)
  298. self.message_index = self.message_index + 1
  299. local message_id = self.message_index
  300. local result = self:encode_and_send({
  301. id = message_id,
  302. jsonrpc = '2.0',
  303. method = method,
  304. params = params,
  305. })
  306. if not result then
  307. return false
  308. end
  309. self.message_callbacks[message_id] = schedule_wrap(callback)
  310. if notify_reply_callback then
  311. self.notify_reply_callbacks[message_id] = schedule_wrap(notify_reply_callback)
  312. end
  313. return result, message_id
  314. end
  315. ---@package
  316. ---@param errkind integer
  317. ---@param ... any
  318. function Client:on_error(errkind, ...)
  319. assert(M.client_errors[errkind])
  320. -- TODO what to do if this fails?
  321. pcall(self.dispatchers.on_error, errkind, ...)
  322. end
  323. ---@private
  324. ---@param errkind integer
  325. ---@param status boolean
  326. ---@param head any
  327. ---@param ... any
  328. ---@return boolean status
  329. ---@return any head
  330. ---@return any? ...
  331. function Client:pcall_handler(errkind, status, head, ...)
  332. if not status then
  333. self:on_error(errkind, head, ...)
  334. return status, head
  335. end
  336. return status, head, ...
  337. end
  338. ---@private
  339. ---@param errkind integer
  340. ---@param fn function
  341. ---@param ... any
  342. ---@return boolean status
  343. ---@return any head
  344. ---@return any? ...
  345. function Client:try_call(errkind, fn, ...)
  346. return self:pcall_handler(errkind, pcall(fn, ...))
  347. end
  348. -- TODO periodically check message_callbacks for old requests past a certain
  349. -- time and log them. This would require storing the timestamp. I could call
  350. -- them with an error then, perhaps.
  351. --- @package
  352. --- @param body string
  353. function Client:handle_body(body)
  354. local ok, decoded = pcall(vim.json.decode, body, { luanil = { object = true } })
  355. if not ok then
  356. self:on_error(M.client_errors.INVALID_SERVER_JSON, decoded)
  357. return
  358. end
  359. log.debug('rpc.receive', decoded)
  360. if type(decoded) ~= 'table' then
  361. self:on_error(M.client_errors.INVALID_SERVER_MESSAGE, decoded)
  362. elseif type(decoded.method) == 'string' and decoded.id then
  363. local err --- @type lsp.ResponseError?
  364. -- Schedule here so that the users functions don't trigger an error and
  365. -- we can still use the result.
  366. vim.schedule(coroutine.wrap(function()
  367. local status, result
  368. status, result, err = self:try_call(
  369. M.client_errors.SERVER_REQUEST_HANDLER_ERROR,
  370. self.dispatchers.server_request,
  371. decoded.method,
  372. decoded.params
  373. )
  374. log.debug('server_request: callback result', { status = status, result = result, err = err })
  375. if status then
  376. if result == nil and err == nil then
  377. error(
  378. string.format(
  379. 'method %q: either a result or an error must be sent to the server in response',
  380. decoded.method
  381. )
  382. )
  383. end
  384. if err then
  385. ---@cast err lsp.ResponseError
  386. assert(
  387. type(err) == 'table',
  388. 'err must be a table. Use rpc_response_error to help format errors.'
  389. )
  390. ---@type string
  391. local code_name = assert(
  392. protocol.ErrorCodes[err.code],
  393. 'Errors must use protocol.ErrorCodes. Use rpc_response_error to help format errors.'
  394. )
  395. err.message = err.message or code_name
  396. end
  397. else
  398. -- On an exception, result will contain the error message.
  399. err = M.rpc_response_error(protocol.ErrorCodes.InternalError, result)
  400. result = nil
  401. end
  402. self:send_response(decoded.id, err, result)
  403. end))
  404. -- This works because we are expecting vim.NIL here
  405. elseif decoded.id and (decoded.result ~= vim.NIL or decoded.error ~= vim.NIL) then
  406. -- We sent a number, so we expect a number.
  407. local result_id = assert(tonumber(decoded.id), 'response id must be a number')
  408. -- Notify the user that a response was received for the request
  409. local notify_reply_callback = self.notify_reply_callbacks[result_id]
  410. if notify_reply_callback then
  411. validate('notify_reply_callback', notify_reply_callback, 'function')
  412. notify_reply_callback(result_id)
  413. self.notify_reply_callbacks[result_id] = nil
  414. end
  415. -- Do not surface RequestCancelled to users, it is RPC-internal.
  416. if decoded.error then
  417. assert(type(decoded.error) == 'table')
  418. if decoded.error.code == protocol.ErrorCodes.RequestCancelled then
  419. log.debug('Received cancellation ack', decoded)
  420. -- Clear any callback since this is cancelled now.
  421. -- This is safe to do assuming that these conditions hold:
  422. -- - The server will not send a result callback after this cancellation.
  423. -- - If the server sent this cancellation ACK after sending the result, the user of this RPC
  424. -- client will ignore the result themselves.
  425. if result_id then
  426. self.message_callbacks[result_id] = nil
  427. end
  428. return
  429. end
  430. end
  431. local callback = self.message_callbacks[result_id]
  432. if callback then
  433. self.message_callbacks[result_id] = nil
  434. validate('callback', callback, 'function')
  435. if decoded.error then
  436. setmetatable(decoded.error, { __tostring = M.format_rpc_error })
  437. end
  438. self:try_call(
  439. M.client_errors.SERVER_RESULT_CALLBACK_ERROR,
  440. callback,
  441. decoded.error,
  442. decoded.result
  443. )
  444. else
  445. self:on_error(M.client_errors.NO_RESULT_CALLBACK_FOUND, decoded)
  446. log.error('No callback found for server response id ' .. result_id)
  447. end
  448. elseif type(decoded.method) == 'string' then
  449. -- Notification
  450. self:try_call(
  451. M.client_errors.NOTIFICATION_HANDLER_ERROR,
  452. self.dispatchers.notification,
  453. decoded.method,
  454. decoded.params
  455. )
  456. else
  457. -- Invalid server message
  458. self:on_error(M.client_errors.INVALID_SERVER_MESSAGE, decoded)
  459. end
  460. end
  461. ---@param dispatchers vim.lsp.rpc.Dispatchers
  462. ---@param transport vim.lsp.rpc.Transport
  463. ---@return vim.lsp.rpc.Client
  464. local function new_client(dispatchers, transport)
  465. local state = {
  466. message_index = 0,
  467. message_callbacks = {},
  468. notify_reply_callbacks = {},
  469. transport = transport,
  470. dispatchers = dispatchers,
  471. }
  472. return setmetatable(state, { __index = Client })
  473. end
  474. --- Client RPC object
  475. --- @class vim.lsp.rpc.PublicClient
  476. ---
  477. --- See [vim.lsp.rpc.request()]
  478. --- @field request fun(method: string, params: table?, callback: fun(err?: lsp.ResponseError, result: any), notify_reply_callback?: fun(message_id: integer)):boolean,integer?
  479. ---
  480. --- See [vim.lsp.rpc.notify()]
  481. --- @field notify fun(method: string, params: any): boolean
  482. ---
  483. --- Indicates if the RPC is closing.
  484. --- @field is_closing fun(): boolean
  485. ---
  486. --- Terminates the RPC client.
  487. --- @field terminate fun()
  488. ---@param client vim.lsp.rpc.Client
  489. ---@return vim.lsp.rpc.PublicClient
  490. local function public_client(client)
  491. ---@type vim.lsp.rpc.PublicClient
  492. ---@diagnostic disable-next-line: missing-fields
  493. local result = {}
  494. ---@private
  495. function result.is_closing()
  496. return client.transport:is_closing()
  497. end
  498. ---@private
  499. function result.terminate()
  500. client.transport:terminate()
  501. end
  502. --- Sends a request to the LSP server and runs {callback} upon response.
  503. ---
  504. ---@param method (string) The invoked LSP method
  505. ---@param params (table?) Parameters for the invoked LSP method
  506. ---@param callback fun(err: lsp.ResponseError?, result: any) Callback to invoke
  507. ---@param notify_reply_callback? fun(message_id: integer) Callback to invoke as soon as a request is no longer pending
  508. ---@return boolean success `true` if request could be sent, `false` if not
  509. ---@return integer? message_id if request could be sent, `nil` if not
  510. function result.request(method, params, callback, notify_reply_callback)
  511. return client:request(method, params, callback, notify_reply_callback)
  512. end
  513. --- Sends a notification to the LSP server.
  514. ---@param method (string) The invoked LSP method
  515. ---@param params (table?) Parameters for the invoked LSP method
  516. ---@return boolean `true` if notification could be sent, `false` if not
  517. function result.notify(method, params)
  518. return client:notify(method, params)
  519. end
  520. return result
  521. end
  522. ---@param dispatchers vim.lsp.rpc.Dispatchers?
  523. ---@return vim.lsp.rpc.Dispatchers
  524. local function merge_dispatchers(dispatchers)
  525. if not dispatchers then
  526. return default_dispatchers
  527. end
  528. ---@diagnostic disable-next-line: no-unknown
  529. for name, fn in pairs(dispatchers) do
  530. if type(fn) ~= 'function' then
  531. error(string.format('dispatcher.%s must be a function', name))
  532. end
  533. end
  534. ---@type vim.lsp.rpc.Dispatchers
  535. local merged = {
  536. notification = (
  537. dispatchers.notification and vim.schedule_wrap(dispatchers.notification)
  538. or default_dispatchers.notification
  539. ),
  540. on_error = (
  541. dispatchers.on_error and vim.schedule_wrap(dispatchers.on_error)
  542. or default_dispatchers.on_error
  543. ),
  544. on_exit = dispatchers.on_exit or default_dispatchers.on_exit,
  545. server_request = dispatchers.server_request or default_dispatchers.server_request,
  546. }
  547. return merged
  548. end
  549. --- @param client vim.lsp.rpc.Client
  550. --- @param on_exit? fun()
  551. local function create_client_read_loop(client, on_exit)
  552. --- @param body string
  553. local function handle_body(body)
  554. client:handle_body(body)
  555. end
  556. local function on_error(err)
  557. client:on_error(M.client_errors.READ_ERROR, err)
  558. end
  559. return M.create_read_loop(handle_body, on_exit, on_error)
  560. end
  561. --- Create a LSP RPC client factory that connects to either:
  562. ---
  563. --- - a named pipe (windows)
  564. --- - a domain socket (unix)
  565. --- - a host and port via TCP
  566. ---
  567. --- Return a function that can be passed to the `cmd` field for
  568. --- |vim.lsp.start()|.
  569. ---
  570. ---@param host_or_path string host to connect to or path to a pipe/domain socket
  571. ---@param port integer? TCP port to connect to. If absent the first argument must be a pipe
  572. ---@return fun(dispatchers: vim.lsp.rpc.Dispatchers): vim.lsp.rpc.PublicClient
  573. function M.connect(host_or_path, port)
  574. validate('host_or_path', host_or_path, 'string')
  575. validate('port', port, 'number', true)
  576. return function(dispatchers)
  577. validate('dispatchers', dispatchers, 'table', true)
  578. dispatchers = merge_dispatchers(dispatchers)
  579. local transport = lsp_transport.TransportConnect.new()
  580. local client = new_client(dispatchers, transport)
  581. local on_read = create_client_read_loop(client, function()
  582. transport:terminate()
  583. end)
  584. transport:connect(host_or_path, port, on_read, dispatchers.on_exit)
  585. return public_client(client)
  586. end
  587. end
  588. --- Additional context for the LSP server process.
  589. --- @class vim.lsp.rpc.ExtraSpawnParams
  590. --- @inlinedoc
  591. --- @field cwd? string Working directory for the LSP server process
  592. --- @field detached? boolean Detach the LSP server process from the current process
  593. --- @field env? table<string,string> Additional environment variables for LSP server process. See |vim.system()|
  594. --- Starts an LSP server process and create an LSP RPC client object to
  595. --- interact with it. Communication with the spawned process happens via stdio. For
  596. --- communication via TCP, spawn a process manually and use |vim.lsp.rpc.connect()|
  597. ---
  598. --- @param cmd string[] Command to start the LSP server.
  599. --- @param dispatchers? vim.lsp.rpc.Dispatchers
  600. --- @param extra_spawn_params? vim.lsp.rpc.ExtraSpawnParams
  601. --- @return vim.lsp.rpc.PublicClient
  602. function M.start(cmd, dispatchers, extra_spawn_params)
  603. log.info('Starting RPC client', { cmd = cmd, extra = extra_spawn_params })
  604. validate('cmd', cmd, 'table')
  605. validate('dispatchers', dispatchers, 'table', true)
  606. dispatchers = merge_dispatchers(dispatchers)
  607. local transport = lsp_transport.TransportRun.new()
  608. local client = new_client(dispatchers, transport)
  609. local on_read = create_client_read_loop(client)
  610. transport:run(cmd, extra_spawn_params, on_read, dispatchers.on_exit)
  611. return public_client(client)
  612. end
  613. return M