robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 ={ 23name ='diagnostics' , 24method ='textDocument/diagnostic' , 25active ={} , 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 ) 39if type ( severity ) == 'string' then 40return protocol . DiagnosticSeverity [ severity ] --[[@as vim.diagnostic.Severity]] 41end 42return severity 43end 44 45---@param severity vim.diagnostic.Severity|vim.diagnostic.SeverityName 46---@return lsp.DiagnosticSeverity 47local function severity_vim_to_lsp ( severity ) 48if type ( severity ) == 'string' then 49return vim . diagnostic . severity [ severity ] 50end 51return severity --[[@as lsp.DiagnosticSeverity]] 52end 53 54---@param bufnr integer 55---@return string[]? 56local function get_buf_lines ( bufnr ) 57if api . nvim_buf_is_loaded ( bufnr ) then 58return api . nvim_buf_get_lines ( bufnr , 0 , - 1 , false ) 59end 60 61local filename =api . nvim_buf_get_name ( bufnr ) 62local f =io . open ( filename ) 63if not f then 64return 65end 66 67local content =f : read ( '*a' ) 68if not content then 69-- Some LSP servers report diagnostics at a directory level, in which case 70-- io.read() returns nil 71f : close () 72return 73end 74 75local lines =vim . split ( content , '\n' ) 76f : close () 77return 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 ) 84local tags ---@type table? 85assert ( diagnostic . tags ~= vim . NIL , 'server response has invalid (null) tags' ) 86for _ , tag in ipairs ( diagnostic . tags or {} ) do 87if tag == protocol . DiagnosticTag . Unnecessary then 88tags =tags or {} 89tags . unnecessary =true 90elseif tag == protocol . DiagnosticTag . Deprecated then 91tags =tags or {} 92tags . deprecated =true 93else 94lsp . log . info ( string . format ( 'Unknown DiagnosticTag %d from LSP client %d' , tag , client_id )) 95end 96end 97return 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 ) 105local buf_lines =get_buf_lines ( bufnr ) 106local client =lsp . get_client_by_id ( client_id ) 107local position_encoding =client and client . offset_encoding or 'utf-16' 108--- @param diagnostic lsp.Diagnostic 109--- @return vim.Diagnostic.Set 110return vim . tbl_map ( function ( diagnostic ) 111local start =diagnostic . range . start 112local _end =diagnostic . range [ 'end' ] 113local message =diagnostic . message 114if type ( message ) ~= 'string' then 115vim . notify_once ( 116string . format ( 'Unsupported Markup message from LSP client %d' , client_id ), 117lsp . log_levels . ERROR 118) 119message =message . value 120end 121local line =buf_lines and buf_lines [ start . line + 1 ] or '' 122local end_line =line 123if _end . line > start . line then 124end_line =buf_lines and buf_lines [ _end . line + 1 ] or '' 125end 126--- @type vim.Diagnostic.Set 127return { 128lnum =start . line , 129col =vim . str_byteindex ( line , position_encoding , start . character , false ), 130end_lnum =_end . line , 131end_col =vim . str_byteindex ( end_line , position_encoding , _end . character , false ), 132severity =severity_lsp_to_vim ( diagnostic . severity ), 133message =message , 134source =diagnostic . source , 135code =diagnostic . code , 136_tags =tags_lsp_to_vim ( diagnostic , client_id ), 137user_data ={ 138lsp =diagnostic , 139} , 140} 141end , diagnostics ) 142end 143 144--- @param diagnostic vim.Diagnostic 145--- @return lsp.DiagnosticTag[]? 146local function tags_vim_to_lsp ( diagnostic ) 147if not diagnostic . _tags then 148return 149end 150 151local tags ={} --- @type lsp.DiagnosticTag[] 152if diagnostic . _tags . unnecessary then 153tags [ # tags + 1 ] =protocol . DiagnosticTag . Unnecessary 154end 155if diagnostic . _tags . deprecated then 156tags [ # tags + 1 ] =protocol . DiagnosticTag . Deprecated 157end 158return tags 159end 160 161---@param identifier string? 162---@return string 163local function result_id_key ( identifier ) 164return 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 173return vim . tbl_map ( function ( diagnostic ) 174local user_data =diagnostic . user_data or {} 175if user_data . lsp then 176return user_data . lsp 177end 178return { 179range ={ 180start ={ 181line =diagnostic . lnum , 182character =diagnostic . col , 183} , 184[ 'end' ] ={ 185line =diagnostic . end_lnum , 186character =diagnostic . end_col , 187} , 188} , 189severity =severity_vim_to_lsp ( diagnostic . severity ), 190message =diagnostic . message , 191source =diagnostic . source , 192code =diagnostic . code , 193tags =tags_vim_to_lsp ( diagnostic ), 194} 195end , 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 ) 212vim . validate ( 'client_id' , client_id , 'number' ) 213vim . validate ( 'is_pull' , is_pull , 'boolean' , true ) 214vim . validate ( 'pull_id' , pull_id , 'string' , true ) 215 216local client =lsp . get_client_by_id ( client_id ) 217if is_pull then 218pull_id =pull_id or 'nil' 219local key =( '%d:%s' ): format ( client_id , pull_id ) 220local name =( 'nvim.lsp.%s.%d.%s' ): format ( 221client and client . name or 'unknown' , 222client_id , 223pull_id 224) 225local ns =client_pull_namespaces [ key ] 226if not ns then 227ns =api . nvim_create_namespace ( name ) 228client_pull_namespaces [ key ] =ns 229end 230return ns 231end 232 233local ns =client_push_namespaces [ client_id ] 234if not ns then 235local name =( 'nvim.lsp.%s.%d' ): format ( client and client . name or 'unknown' , client_id ) 236ns =api . nvim_create_namespace ( name ) 237client_push_namespaces [ client_id ] =ns 238end 239return 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 ) 248local fname =vim . uri_to_fname ( uri ) 249 250if # diagnostics == 0 and vim . fn . bufexists ( fname ) == 0 then 251return 252end 253 254local bufnr =vim . fn . bufadd ( fname ) 255if not bufnr then 256return 257end 258 259client_id =client_id or DEFAULT_CLIENT_ID 260 261local namespace =M . get_namespace ( client_id , is_pull , pull_id ) 262 263vim . 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 276handle_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 ) 287local client_id =ctx . client_id 288local bufnr =assert ( ctx . bufnr ) 289local state =Diagnostics . active [ bufnr ] and Diagnostics . active [ bufnr ]. client_state [ client_id ] 290if not state then 291return 292end 293 294if error ~= nil then 295if error . code == protocol . ErrorCodes . ServerCancelled then 296if error . data == nil or error . data . retriggerRequest ~= false then 297local client =assert ( lsp . get_client_by_id ( client_id )) 298---@diagnostic disable-next-line: param-type-mismatch 299client : request ( ctx . method , ctx . params , nil , ctx . bufnr ) 300end 301else 302lsp . log . error ( 'diagnostics' , error ) 303end 304return 305end 306 307if result == nil then 308return 309end 310 311---@type lsp.DocumentDiagnosticParams 312local params =ctx . params 313local key =result_id_key ( params . identifier ) 314state . result_id [ key ] =result . resultId 315 316if result . kind == 'unchanged' then 317return 318end 319 320handle_diagnostics ( params . textDocument . uri , client_id , result . items , true , params . identifier ) 321 322for uri , related_result in pairs ( result . relatedDocuments or {} ) do 323if related_result . kind == 'full' then 324handle_diagnostics ( uri , client_id , related_result . items , true , params . identifier ) 325end 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. 330local related_bufnr =vim . uri_to_bufnr ( uri ) 331local related_diagnostics =Diagnostics . active [ related_bufnr ] or Diagnostics : new ( related_bufnr ) 332local related_state =related_diagnostics . client_state [ client_id ] 333if not related_state then 334related_state ={ pull_kind ='document' , result_id ={} } 335related_diagnostics . client_state [ client_id ] =related_state 336end 337related_state . result_id [ key ] =related_result . resultId 338end 339end 340 341--- Clear diagnostics from pull based clients 342---@package 343---@param client_id integer? 344function Diagnostics : clear ( client_id ) 345for key , namespace in pairs ( client_pull_namespaces ) do 346if not client_id or vim . startswith ( key , ( '%d:' ): format ( client_id )) then 347vim . diagnostic . reset ( namespace , self . bufnr ) 348end 349end 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 ) 356local client =lsp . get_client_by_id ( client_id ) 357 358local method ='textDocument/diagnostic' 359local clients ={ client } 360 361util . _cancel_requests ( { 362bufnr =self . bufnr , 363clients =clients , 364method =method , 365type ='pending' , 366} ) 367 368local state =self . client_state [ client_id ] 369if client and state then 370client : _provider_foreach ( method , function ( cap ) 371--- @cast cap lsp.DiagnosticRegistrationOptions 372local key =result_id_key ( cap . identifier ) 373---@type lsp.DocumentDiagnosticParams 374local params ={ 375identifier =cap . identifier , 376textDocument =util . make_text_document_params ( self . bufnr ), 377previousResultId =state . result_id [ key ], 378} 379client : request ( method , params , nil , self . bufnr ) 380end ) 381end 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 ) 389if err then 390return vim . NIL 391end 392local client =lsp . get_client_by_id ( ctx . client_id ) 393if client == nil then 394return vim . NIL 395end 396if client : supports_method ( 'workspace/diagnostic' ) then 397M . _workspace_diagnostics ( { client_id =ctx . client_id } ) 398end 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. 403for bufnr in pairs ( client . attached_buffers or {} ) do 404local provider =Diagnostics . active [ bufnr ] 405local state =provider and provider . client_state [ ctx . client_id ] 406if state and state . pull_kind == 'document' then 407provider : refresh ( ctx . client_id ) 408end 409end 410 411return 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 ) 418local state =self . client_state [ client_id ] 419 420if state then 421state . pull_kind ='document' 422else 423state ={ pull_kind ='document' , result_id ={} } 424self . client_state [ client_id ] =state 425end 426 427self : 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 ) 434local state =self . client_state [ client_id ] 435if state then 436self : clear ( client_id ) 437self . client_state [ client_id ] =nil 438end 439end 440 441---@private 442---@param client_id integer 443function Diagnostics : on_close ( client_id ) 444local state =self . client_state [ client_id ] 445if state and state . pull_kind == 'document' then 446self : clear ( client_id ) 447end 448end 449 450---@private 451---@param client_id integer 452function Diagnostics : on_change ( client_id ) 453local state =self . client_state [ client_id ] 454if state and state . pull_kind == 'document' then 455self : refresh ( client_id ) 456end 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 ) 464local results ={} ---@type lsp.PreviousResultId[] 465local key =result_id_key ( identifier ) 466 467for bufnr , provider in pairs ( Diagnostics . active ) do 468local state =provider . client_state [ client_id ] 469if state then 470local result_id =state . result_id [ key ] 471if result_id then 472results [ # results + 1 ] ={ 473uri =vim . uri_from_bufnr ( bufnr ), 474value =result_id , 475} 476end 477end 478end 479 480return results 481end 482 483--- Request workspace-wide diagnostics. 484--- @param opts vim.lsp.WorkspaceDiagnosticsOpts 485function M . _workspace_diagnostics ( opts ) 486local 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 491local function handler ( error , result , ctx ) 492-- Check for retrigger requests on cancellation errors. 493-- Unless `retriggerRequest` is explicitly disabled, try again. 494if error ~= nil and error . code == protocol . ErrorCodes . ServerCancelled then 495if error . data == nil or error . data . retriggerRequest ~= false then 496local client =assert ( lsp . get_client_by_id ( ctx . client_id )) 497client : request ( 'workspace/diagnostic' , ctx . params , handler ) 498end 499return 500end 501 502if error == nil and result ~= nil then 503---@type lsp.WorkspaceDiagnosticParams 504local params =ctx . params 505for _ , report in ipairs ( result . items ) do 506local bufnr =vim . uri_to_bufnr ( report . uri ) 507 508-- Start tracking the buffer (but don't send "textDocument/diagnostic" requests for it). 509local provider =Diagnostics . active [ bufnr ] or Diagnostics : new ( bufnr ) 510local state =provider . client_state [ ctx . client_id ] 511if not state then 512state ={ pull_kind ='workspace' , result_id ={} } 513provider . client_state [ ctx . client_id ] =state 514end 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. 518if state . pull_kind == 'workspace' and report . kind == 'full' then 519handle_diagnostics ( report . uri , ctx . client_id , report . items , true , params . identifier ) 520local key =result_id_key ( params . identifier ) 521state . result_id [ key ] =report . resultId 522end 523end 524end 525end 526 527for _ , client in ipairs ( clients ) do 528client : _provider_foreach ( 'workspace/diagnostic' , function ( cap ) 529--- @cast cap lsp.DiagnosticRegistrationOptions 530--- @type lsp.WorkspaceDiagnosticParams 531local params ={ 532identifier =cap . identifier , 533previousResultIds =previous_result_ids ( client . id , cap . identifier ), 534} 535 536client : request ( 'workspace/diagnostic' , params , handler ) 537end ) 538end 539end 540 541return M