robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 ) 12return table . concat ( { 13'Content-Length: ' , 14tostring ( # message ), 15'\r\n\r\n' , 16message , 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 ) 33local state ='name' 34local i , end_ =start , start + len 35local j , name =1 , 'content-length' 36local buf =strbuffer . new () 37local digit =true 38while i < end_ do 39local c =ptr [ i ] 40if state == 'name' then 41if c >= 65 and c <= 90 then -- lower case 42c =c + 32 43end 44if c == 10 then -- a blank line or a line with a prefix of header 45j =1 46elseif ( c == 32 or c == 9 ) and j == 1 then -- luacheck: ignore 542 47-- skip OWS for compatibility only 48elseif c == name : byte ( j ) then 49j =j + 1 50elseif c == 58 and j == 15 then 51state ='colon' 52else 53state ='invalid' 54end 55elseif state == 'colon' then 56if c ~= 32 and c ~= 9 then -- skip OWS normally 57state ='value' 58i =i - 1 59end 60elseif state == 'value' then 61if c == 13 and ptr [ i + 1 ] == 10 then -- must end with \r\n 62local value =buf : get () 63if digit then 64return vim . _assert_integer ( value ) 65end 66error ( 'value of Content-Length is not number: ' .. value ) 67else 68buf : put ( string . char ( c )) 69end 70if c < 48 and c ~= 32 and c ~= 9 or c > 57 then 71digit =false 72end 73elseif state == 'invalid' then 74if c == 10 then -- reset for next line 75state , j ='name' , 1 76end 77end 78i =i + 1 79end 80local header =strbuffer . new () 81for k =start , end_ - 1 do 82header : put ( string . char ( ptr [ k ])) 83end 84error ( '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 ={ 92INVALID_SERVER_MESSAGE =1 , 93INVALID_SERVER_JSON =2 , 94NO_RESULT_CALLBACK_FOUND =3 , 95READ_ERROR =4 , 96NOTIFICATION_HANDLER_ERROR =5 , 97SERVER_REQUEST_HANDLER_ERROR =6 , 98SERVER_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 105M . 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 ) 113validate ( '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. 117local code --- @type string 118if protocol . ErrorCodes [ err . code ] then 119code =string . format ( 'code_name = %s,' , protocol . ErrorCodes [ err . code ]) 120else 121code =string . format ( 'code_name = unknown, code = %s,' , err . code ) 122end 123 124local message_parts ={ 'RPC[Error]' , code } 125if err . message then 126table . insert ( message_parts , 'message =' ) 127table . insert ( message_parts , string . format ( '%q' , err . message )) 128end 129if err . data then 130table . insert ( message_parts , 'data =' ) 131table . insert ( message_parts , vim . inspect ( err . data )) 132end 133return 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 147local code_name =assert ( protocol . ErrorCodes [ code ], 'Invalid RPC error code' ) 148return { 149code =code , 150message =message or code_name , 151data =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 169notification =function ( method , params ) 170log . debug ( 'notification' , method , params ) 171end , 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` 179server_request =function ( method , params ) 180log . debug ( 'server_request' , method , params ) 181return nil , M . rpc_response_error ( protocol . ErrorCodes . MethodNotFound ) 182end , 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) 188on_exit =function ( code , signal ) 189log . info ( 'client_exit' , { code =code , signal =signal } ) 190end , 191 192--- Default dispatcher for client errors. 193--- 194---@param code integer Error code 195---@param err any Details about the error 196on_error =function ( code , err ) 197log . error ( 'client_error:' , M . client_errors [ code ], err ) 198end , 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 ) 209local header_len ---@type integer? 210local ptr , len =strbuf : ref () 211for 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). 214if ptr [ i ] == 13 and ptr [ i + 1 ] == 10 and ptr [ i + 2 ] == 13 and ptr [ i + 3 ] == 10 then 215header_len =i + 2 216break 217end 218end 219 220if not header_len then 221return nil 222end 223 224local content_length =get_content_length ( ptr , 0 , header_len ) 225if strbuffer . len ( strbuf ) < header_len + 2 + content_length then 226return nil 227end 228 229strbuf : skip ( header_len + 2 ) -- skip past header boundary 230return 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 ) 238on_exit =on_exit or function () end 239on_error =on_error or function () end 240local message_stream =net_transport . MessageStream . new ( 241message_decoder , 242format_message_with_content_length , 243function ( err , chunk ) 244if err then 245on_error ( err , client_errors . READ_ERROR ) 246elseif chunk then 247handle_body ( chunk ) 248else 249on_exit () 250end 251end , 252function ( err ) 253on_error ( err , client_errors . INVALID_SERVER_MESSAGE ) 254end 255) 256 257return function ( err , chunk ) 258message_stream : feed ( err , chunk ) 259end 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 ) 291local result ={ 292message_index =0 , 293message_callbacks ={} , 294notify_reply_callbacks ={} , 295transport =transport , 296dispatchers =dispatchers , 297} 298 299---@private 300function result . is_closing () 301return result . transport : is_closing () 302end 303 304---@private 305function result . terminate () 306result . transport : terminate () 307end 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 316function result . request ( method , params , callback , notify_reply_callback ) 317return result : _request ( method , params , callback , notify_reply_callback ) 318end 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 324function result . notify ( method , params ) 325return result : _notify ( method , params ) 326end 327 328---@cast result vim.lsp.rpc.Client 329local self =setmetatable ( result , { __index =Client } ) 330 331self . message_stream =net_transport . MessageStream . new ( decode , format , function ( err , data ) 332if err then 333self : on_error ( client_errors . READ_ERROR , err ) 334elseif data then 335self : handle_body ( data ) 336else 337---@diagnostic disable-next-line: invisible 338self . transport : terminate () 339end 340end , function ( err ) 341self : on_error ( client_errors . INVALID_SERVER_MESSAGE , err ) 342---@diagnostic disable-next-line: invisible 343self . transport : terminate () 344end ) 345 346transport : listen ( function ( err , data ) 347---@diagnostic disable-next-line: invisible 348self . message_stream : feed ( err , data ) 349end , dispatchers . on_exit ) 350return 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 ) 363log . debug ( 'rpc.send' , payload ) 364if self . transport : is_closing () then 365return false 366end 367local jsonstr =vim . json . encode ( payload ) 368 369self . transport : write ( self . message_stream . encode ( jsonstr )) 370return 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 ) 379return self : encode_and_send ( { 380jsonrpc ='2.0' , 381method =method , 382params =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 ) 392return self : encode_and_send ( { 393id =request_id , 394jsonrpc ='2.0' , 395error =err , 396result =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 ) 410validate ( 'callback' , callback , 'function' ) 411validate ( 'notify_reply_callback' , notify_reply_callback , 'function' , true ) 412self . message_index =self . message_index + 1 413local message_id =self . message_index 414local result =self : encode_and_send ( { 415id =message_id , 416jsonrpc ='2.0' , 417method =method , 418params =params , 419} ) 420 421if not result then 422return false 423end 424 425self . message_callbacks [ message_id ] =vim . schedule_wrap ( callback ) 426if notify_reply_callback then 427self . notify_reply_callbacks [ message_id ] =vim . schedule_wrap ( notify_reply_callback ) 428end 429return result , message_id 430end 431 432---@package 433---@param errkind vim.lsp.rpc.ClientErrors 434---@param err any 435function Client : on_error ( errkind , err ) 436assert ( M . client_errors [ errkind ]) 437-- TODO what to do if this fails? 438pcall ( 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 ) 448local ok , decoded =pcall ( vim . json . decode , body ) 449if not ok then 450self : on_error ( client_errors . INVALID_SERVER_JSON , decoded ) 451return 452elseif type ( decoded ) ~= 'table' then 453self : on_error ( client_errors . INVALID_SERVER_MESSAGE , decoded ) 454return 455end 456 457log . debug ( 'rpc.receive' , decoded ) 458 459if 460-- Received a request. 461type ( decoded . method ) == 'string' and decoded . id 462then 463if type ( decoded . id ) ~= 'number' and type ( decoded . id ) ~= 'string' and decoded . id ~= vim . NIL then 464log . error ( 465'Server request id must be a number or string, got ' .. type ( decoded . id ), 466decoded . method , 467decoded . id 468) 469self : on_error ( client_errors . INVALID_SERVER_MESSAGE , decoded ) 470return 471end 472 473-- Schedule here so that the users functions don't trigger an error and 474-- we can still use the result. 475vim . schedule ( coroutine . wrap ( function () 476xpcall ( function () 477local result , err =self . dispatchers . server_request ( decoded . method , decoded . params ) 478log . debug ( 'server_request: callback result' , { result =result , err =err } ) 479if result == nil and err == nil then 480error ( 481string . format ( 482'method %q: either a result or an error must be sent to the server in response' , 483decoded . method 484) 485) 486end 487if err then 488assert ( 489type ( err ) == 'table' , 490'err must be a table. Use rpc_response_error to help format errors.' 491) 492assert ( 493protocol . ErrorCodes [ err . code ], 494'Errors must use protocol.ErrorCodes. Use rpc_response_error to help format errors.' 495) 496end 497self : send_response ( decoded . id , err , result ) 498end , function ( err ) 499self : on_error ( client_errors . SERVER_REQUEST_HANDLER_ERROR , err ) 500self : send_response ( 501decoded . id , 502M . rpc_response_error ( protocol . ErrorCodes . InternalError , err ), 503nil 504) 505end ) 506end )) 507elseif 508-- Received a response to a request we sent. 509decoded . id 510then 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. 513if decoded . id == vim . NIL then 514log . warn ( 'Server sent response with null id' , decoded ) 515self : on_error ( client_errors . INVALID_SERVER_MESSAGE , decoded ) 516return 517end 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). 522if ( decoded . error == nil or decoded . error == vim . NIL ) and decoded . result == nil then 523log . error ( 'Server respond empty result and error' , decoded ) 524self : on_error ( client_errors . INVALID_SERVER_MESSAGE , decoded ) 525return 526end 527 528-- We sent a number, so we expect a number. 529local result_id =vim . _assert_integer ( decoded . id ) 530 531-- Notify the user that a response was received for the request 532local notify_reply_callback =self . notify_reply_callbacks [ result_id ] 533if notify_reply_callback then 534validate ( 'notify_reply_callback' , notify_reply_callback , 'function' ) 535notify_reply_callback ( result_id ) 536self . notify_reply_callbacks [ result_id ] =nil 537end 538 539-- Do not surface RequestCancelled to users, it is RPC-internal. 540if decoded . error then 541assert ( type ( decoded . error ) == 'table' ) 542if decoded . error . code == protocol . ErrorCodes . RequestCancelled then 543log . 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. 549if result_id then 550self . message_callbacks [ result_id ] =nil 551end 552return 553end 554end 555 556local callback =self . message_callbacks [ result_id ] 557if callback then 558self . message_callbacks [ result_id ] =nil 559validate ( 'callback' , callback , 'function' ) 560xpcall ( function () 561callback ( decoded . error , decoded . result ~= vim . NIL and decoded . result or nil , result_id ) 562end , function ( err ) 563self : on_error ( client_errors . SERVER_RESULT_CALLBACK_ERROR , err ) 564end ) 565else 566self : on_error ( client_errors . NO_RESULT_CALLBACK_FOUND , decoded ) 567log . error ( 'No callback found for server response id ' .. result_id ) 568end 569elseif 570-- Received a notification. 571type ( decoded . method ) == 'string' 572then 573xpcall ( function () 574assert ( 575self . dispatchers . notification ( decoded . method , decoded . params ) == nil , 576'notification handlers should not return a value' 577) 578end , function ( err ) 579self : on_error ( client_errors . NOTIFICATION_HANDLER_ERROR , err ) 580end ) 581else 582-- Invalid server message 583self : on_error ( client_errors . INVALID_SERVER_MESSAGE , decoded ) 584end 585end 586 587---@param dispatchers vim.lsp.rpc.Dispatchers? 588---@return vim.lsp.rpc.Dispatchers 589local function merge_dispatchers ( dispatchers ) 590if not dispatchers then 591return default_dispatchers 592end 593---@diagnostic disable-next-line: no-unknown 594for name , fn in pairs ( dispatchers ) do 595if type ( fn ) ~= 'function' then 596error ( string . format ( 'dispatcher.%s must be a function' , name )) 597end 598end 599---@type vim.lsp.rpc.Dispatchers 600local merged ={ 601notification =( 602dispatchers . notification and vim . schedule_wrap ( dispatchers . notification ) 603or default_dispatchers . notification 604), 605on_error =( 606dispatchers . on_error and vim . schedule_wrap ( dispatchers . on_error ) 607or default_dispatchers . on_error 608), 609on_exit =dispatchers . on_exit or default_dispatchers . on_exit , 610server_request =dispatchers . server_request or default_dispatchers . server_request , 611} 612return 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 ) 628log . info ( 'Connecting RPC client' , { host_or_path =host_or_path , port =port } ) 629 630validate ( 'host_or_path' , host_or_path , 'string' ) 631validate ( 'port' , port , 'number' , true ) 632 633return function ( dispatchers ) 634validate ( 'dispatchers' , dispatchers , 'table' , true ) 635 636dispatchers =merge_dispatchers ( dispatchers ) 637 638local transport =net_transport . TransportConnect . new ( host_or_path , port , vim . lsp . log . _self ) 639return Client . new ( dispatchers , transport , message_decoder , format_message_with_content_length ) 640end 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 ) 659log . info ( 'Starting RPC client' , { cmd =cmd , extra =extra_spawn_params } ) 660 661validate ( 'cmd' , cmd , 'table' ) 662validate ( 'dispatchers' , dispatchers , 'table' , true ) 663 664dispatchers =merge_dispatchers ( dispatchers ) 665 666local transport =net_transport . TransportRun . new ( cmd , extra_spawn_params , vim . lsp . log . _self ) 667return Client . new ( dispatchers , transport , message_decoder , format_message_with_content_length ) 668end 669 670return M