robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
13.3 KiB430 linesraw
1local protocol = require('vim.lsp.protocol')
2local sync = require('vim.lsp.sync')
3local util = require('vim.lsp.util')
4
5local api = vim.api
6local uv = vim.uv
7
8local M = {}
9
10--- LSP has 3 different sync modes:
11---   - None (Servers will read the files themselves when needed)
12---   - Full (Client sends the full buffer content on updates)
13---   - Incremental (Client sends only the changed parts)
14---
15--- Changes are tracked per buffer.
16--- A buffer can have multiple clients attached and each client needs to send the changes
17--- To minimize the amount of changesets to compute, computation is grouped:
18---
19---   None: One group for all clients
20---   Full: One group for all clients
21---   Incremental: One group per `position_encoding`
22---
23--- Sending changes can be debounced per buffer. To simplify the implementation the
24--- smallest debounce interval is used and we don't group clients by different intervals.
25---
26--- @class vim.lsp.CTGroup
27--- @field sync_kind integer TextDocumentSyncKind, considers config.flags.allow_incremental_sync
28--- @field position_encoding "utf-8"|"utf-16"|"utf-32"
29---
30--- @class vim.lsp.CTBufferState
31--- @field name string name of the buffer
32--- @field lines string[] snapshot of buffer lines from last didChange
33--- @field lines_tmp string[]
34--- @field pending_changes table[] List of debounced changes in incremental sync mode
35--- @field timer? uv.uv_timer_t uv_timer
36--- @field last_flush? number uv.hrtime of the last flush/didChange-notification
37--- @field needs_flush boolean true if buffer updates haven't been sent to clients/servers yet
38--- @field refs integer how many clients are using this group
39---
40--- @class vim.lsp.CTGroupState
41--- @field buffers table<integer,vim.lsp.CTBufferState>
42--- @field debounce integer debounce duration in ms
43--- @field clients table<integer, vim.lsp.Client> clients using this state. {client_id, client}
44
45---@param group vim.lsp.CTGroup
46---@return string
47local function group_key(group)
48  if group.sync_kind == protocol.TextDocumentSyncKind.Incremental then
49    return tostring(group.sync_kind) .. '\0' .. group.position_encoding
50  end
51  return tostring(group.sync_kind)
52end
53
54---@type table<vim.lsp.CTGroup,vim.lsp.CTGroupState>
55local state_by_group = setmetatable({}, {
56  __index = function(tbl, k)
57    return rawget(tbl, group_key(k))
58  end,
59  __newindex = function(tbl, k, v)
60    rawset(tbl, group_key(k), v)
61  end,
62})
63
64---@param client vim.lsp.Client
65---@return vim.lsp.CTGroup
66local function get_group(client)
67  local allow_inc_sync = vim.nonnil(client.flags.allow_incremental_sync, true)
68  local change_capability = vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'change')
69  local sync_kind = change_capability or protocol.TextDocumentSyncKind.None
70  if not allow_inc_sync and change_capability == protocol.TextDocumentSyncKind.Incremental then
71    sync_kind = protocol.TextDocumentSyncKind.Full
72  end
73  return {
74    sync_kind = sync_kind,
75    position_encoding = client.offset_encoding,
76  }
77end
78
79---@param state vim.lsp.CTBufferState
80---@param encoding 'utf-8'|'utf-16'|'utf-32'
81---@param bufnr integer
82---@param firstline integer
83---@param lastline integer
84---@param new_lastline integer
85---@return lsp.TextDocumentContentChangeEvent
86local function incremental_changes(state, encoding, bufnr, firstline, lastline, new_lastline)
87  local prev_lines = state.lines
88  local curr_lines = state.lines_tmp
89
90  local changed_lines = api.nvim_buf_get_lines(bufnr, firstline, new_lastline, true)
91  for i = 1, firstline do
92    curr_lines[i] = prev_lines[i]
93  end
94  for i = firstline + 1, new_lastline do
95    curr_lines[i] = changed_lines[i - firstline]
96  end
97  for i = lastline + 1, #prev_lines do
98    curr_lines[i - lastline + new_lastline] = prev_lines[i]
99  end
100  if vim.tbl_isempty(curr_lines) then
101    -- Can happen when deleting the entire contents of a buffer, see https://github.com/neovim/neovim/issues/16259.
102    curr_lines[1] = ''
103  end
104
105  local line_ending = vim.lsp._buf_get_line_ending(bufnr)
106  local incremental_change = sync.compute_diff(
107    prev_lines,
108    curr_lines,
109    firstline,
110    lastline,
111    new_lastline,
112    encoding,
113    line_ending
114  )
115
116  -- Double-buffering of lines tables is used to reduce the load on the garbage collector.
117  -- At this point the prev_lines table is useless, but its internal storage has already been allocated,
118  -- so let's keep it around for the next didChange event, in which it will become the next
119  -- curr_lines table. Note that setting elements to nil doesn't actually deallocate slots in the
120  -- internal storage - it merely marks them as free, for the GC to deallocate them.
121  for i in ipairs(prev_lines) do
122    prev_lines[i] = nil
123  end
124  state.lines = curr_lines
125  state.lines_tmp = prev_lines
126
127  return incremental_change
128end
129
130---@param client vim.lsp.Client
131---@param bufnr integer
132function M.init(client, bufnr)
133  local group = get_group(client)
134  local state = state_by_group[group]
135  if state then
136    state.debounce = math.min(state.debounce, client.flags.debounce_text_changes or 150)
137    state.clients[client.id] = client
138  else
139    state = {
140      buffers = {},
141      debounce = client.flags.debounce_text_changes or 150,
142      clients = {
143        [client.id] = client,
144      },
145    }
146    state_by_group[group] = state
147  end
148  local buf_state = state.buffers[bufnr]
149  if buf_state then
150    buf_state.refs = buf_state.refs + 1
151  else
152    buf_state = {
153      name = api.nvim_buf_get_name(bufnr),
154      lines = {},
155      lines_tmp = {},
156      pending_changes = {},
157      needs_flush = false,
158      refs = 1,
159    }
160    state.buffers[bufnr] = buf_state
161    if group.sync_kind == protocol.TextDocumentSyncKind.Incremental then
162      buf_state.lines = api.nvim_buf_get_lines(bufnr, 0, -1, true)
163    end
164  end
165end
166
167--- Sends didOpen/didClose/didSave to all client groups.
168---
169--- @param bufnr integer
170function M._send_did_save(bufnr)
171  --- Groups of the clients attached to `bufnr`, along with those clients.
172  --- Only clients attached to the buffer must be notified.
173  local groups = {} ---@type table<string,{group: vim.lsp.CTGroup, clients: vim.lsp.Client[]}>
174  for _, client in pairs(vim.lsp.get_clients({ bufnr = bufnr })) do
175    local group = get_group(client)
176    local key = group_key(group)
177    local entry = groups[key]
178    if not entry then
179      entry = { group = group, clients = {} }
180      groups[key] = entry
181    end
182    table.insert(entry.clients, client)
183  end
184
185  local uri = vim.uri_from_bufnr(bufnr)
186  local text = vim.func._memoize('concat', vim.lsp._buf_get_full_text)
187
188  -- Send didOpen/didClose/didSave to all client groups.
189  for _, entry in pairs(groups) do
190    local name = api.nvim_buf_get_name(bufnr)
191    local state = state_by_group[entry.group]
192    local buf_state = state.buffers[bufnr] or {}
193    local old_name = buf_state.name
194    buf_state.name = name
195
196    for _, client in ipairs(entry.clients) do
197      if old_name and name ~= old_name then
198        client:notify('textDocument/didClose', {
199          textDocument = {
200            uri = vim.uri_from_fname(old_name),
201          },
202        }, bufnr)
203        client:notify('textDocument/didOpen', {
204          textDocument = {
205            version = 0,
206            uri = uri,
207            languageId = client.get_language_id(bufnr, vim.bo[bufnr].filetype),
208            text = vim.lsp._buf_get_full_text(bufnr),
209          },
210        }, bufnr)
211        util.buf_versions[bufnr] = 0
212      end
213      local save_capability = vim.tbl_get(client.server_capabilities, 'textDocumentSync', 'save')
214      if save_capability then
215        local included_text --- @type string?
216        if type(save_capability) == 'table' and save_capability.includeText then
217          included_text = text(bufnr)
218        end
219        client:notify('textDocument/didSave', {
220          textDocument = {
221            uri = uri,
222          },
223          text = included_text,
224        }, bufnr)
225      else
226        M.flush(client, bufnr)
227      end
228    end
229  end
230end
231
232---@param buf_state vim.lsp.CTBufferState
233local function reset_timer(buf_state)
234  local timer = buf_state.timer
235  if timer then
236    buf_state.timer = nil
237    if not timer:is_closing() then
238      timer:stop()
239      timer:close()
240    end
241  end
242end
243
244--- @param client vim.lsp.Client
245--- @param bufnr integer
246function M.reset_buf(client, bufnr)
247  M.flush(client, bufnr)
248  local state = state_by_group[get_group(client)]
249  if not state then
250    return
251  end
252  local buf_state = state.buffers[bufnr]
253  if not buf_state then
254    return
255  end
256  buf_state.refs = buf_state.refs - 1
257  assert(buf_state.refs >= 0, 'refcount on buffer state must not get negative')
258  if buf_state.refs == 0 then
259    state.buffers[bufnr] = nil
260    reset_timer(buf_state)
261  end
262end
263
264--- @param client vim.lsp.Client
265function M.reset(client)
266  local state = state_by_group[get_group(client)]
267  if not state then
268    return
269  end
270  state.clients[client.id] = nil
271  if vim.tbl_count(state.clients) == 0 then
272    for _, buf_state in pairs(state.buffers) do
273      reset_timer(buf_state)
274    end
275    state.buffers = {}
276  end
277end
278
279-- Adjust debounce time by taking time of last didChange notification into
280-- consideration. If the last didChange happened more than `debounce` time ago,
281-- debounce can be skipped and otherwise maybe reduced.
282--
283-- This turns the debounce into a kind of client rate limiting
284--
285---@param debounce integer
286---@param buf_state vim.lsp.CTBufferState
287---@return number
288local function next_debounce(debounce, buf_state)
289  if debounce == 0 then
290    return 0
291  end
292  local ns_to_ms = 0.000001
293  if not buf_state.last_flush then
294    return debounce
295  end
296  local now = uv.hrtime()
297  local ms_since_last_flush = (now - buf_state.last_flush) * ns_to_ms
298  return math.max(debounce - ms_since_last_flush, 0)
299end
300
301---@param bufnr integer
302---@param sync_kind integer protocol.TextDocumentSyncKind
303---@param state vim.lsp.CTGroupState
304---@param buf_state vim.lsp.CTBufferState
305local function send_changes(bufnr, sync_kind, state, buf_state)
306  if not buf_state.needs_flush then
307    return
308  end
309  buf_state.last_flush = uv.hrtime()
310  buf_state.needs_flush = false
311
312  if not api.nvim_buf_is_valid(bufnr) then
313    buf_state.pending_changes = {}
314    return
315  end
316
317  local changes --- @type lsp.TextDocumentContentChangeEvent[]
318  if sync_kind == protocol.TextDocumentSyncKind.None then
319    return
320  elseif sync_kind == protocol.TextDocumentSyncKind.Incremental then
321    changes = buf_state.pending_changes
322    buf_state.pending_changes = {}
323  else
324    changes = {
325      { text = vim.lsp._buf_get_full_text(bufnr) },
326    }
327  end
328  local uri = vim.uri_from_bufnr(bufnr)
329  for _, client in pairs(state.clients) do
330    if not client:is_stopped() and vim.lsp.buf_is_attached(bufnr, client.id) then
331      client:notify('textDocument/didChange', {
332        textDocument = {
333          uri = uri,
334          version = util.buf_versions[bufnr],
335        },
336        contentChanges = changes,
337      }, bufnr)
338    end
339  end
340end
341
342--- @param bufnr integer
343--- @param firstline integer
344--- @param lastline integer
345--- @param new_lastline integer
346--- @param group vim.lsp.CTGroup
347local function send_changes_for_group(bufnr, firstline, lastline, new_lastline, group)
348  local state = state_by_group[group]
349  if not state then
350    error(
351      string.format(
352        'changetracking.init must have been called for all LSP clients. group=%s states=%s',
353        vim.inspect(group),
354        vim.inspect(vim.tbl_keys(state_by_group))
355      )
356    )
357  end
358  local buf_state = state.buffers[bufnr]
359  if not buf_state then
360    return
361  end
362  buf_state.needs_flush = true
363  reset_timer(buf_state)
364  local debounce = next_debounce(state.debounce, buf_state)
365  if group.sync_kind == protocol.TextDocumentSyncKind.Incremental then
366    -- This must be done immediately and cannot be delayed
367    -- The contents would further change and startline/endline may no longer fit
368    local changes = incremental_changes(
369      buf_state,
370      group.position_encoding,
371      bufnr,
372      firstline,
373      lastline,
374      new_lastline
375    )
376    table.insert(buf_state.pending_changes, changes)
377  end
378  if debounce == 0 then
379    send_changes(bufnr, group.sync_kind, state, buf_state)
380  else
381    local timer = assert(uv.new_timer(), 'Must be able to create timer')
382    buf_state.timer = timer
383    timer:start(
384      math.floor(debounce),
385      0,
386      vim.schedule_wrap(function()
387        reset_timer(buf_state)
388        send_changes(bufnr, group.sync_kind, state, buf_state)
389      end)
390    )
391  end
392end
393
394--- @param bufnr integer
395--- @param firstline integer
396--- @param lastline integer
397--- @param new_lastline integer
398function M.send_changes(bufnr, firstline, lastline, new_lastline)
399  local groups = {} ---@type table<string,vim.lsp.CTGroup>
400  for _, client in pairs(vim.lsp.get_clients({ bufnr = bufnr })) do
401    local group = get_group(client)
402    groups[group_key(group)] = group
403  end
404  for _, group in pairs(groups) do
405    send_changes_for_group(bufnr, firstline, lastline, new_lastline, group)
406  end
407end
408
409--- Flushes any outstanding change notification.
410---@param client vim.lsp.Client
411---@param bufnr? integer
412function M.flush(client, bufnr)
413  local group = get_group(client)
414  local state = state_by_group[group]
415  if not state then
416    return
417  end
418  if bufnr then
419    local buf_state = state.buffers[bufnr] or {}
420    reset_timer(buf_state)
421    send_changes(bufnr, group.sync_kind, state, buf_state)
422  else
423    for buf, buf_state in pairs(state.buffers) do
424      reset_timer(buf_state)
425      send_changes(buf, group.sync_kind, state, buf_state)
426    end
427  end
428end
429
430return M