@codua/codeoutline-win32-x64 0.1.9 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +38 -6
  2. package/README.zh-CN.md +36 -6
  3. package/THIRD_PARTY.md +3 -3
  4. package/bin/xnet.exe +0 -0
  5. package/build-info.json +1 -1
  6. package/package.json +1 -1
  7. package/scripts/codeoutline/cli.lua +2 -2
  8. package/scripts/codeoutline/command.lua +9 -1
  9. package/scripts/codeoutline/common.lua +45 -5
  10. package/scripts/codeoutline/completion.lua +936 -0
  11. package/scripts/codeoutline/control.lua +5 -1
  12. package/scripts/codeoutline/documents.lua +154 -0
  13. package/scripts/codeoutline/explore.lua +35 -8
  14. package/scripts/codeoutline/graph.lua +321 -102
  15. package/scripts/codeoutline/index.lua +170 -50
  16. package/scripts/codeoutline/index_worker.lua +108 -17
  17. package/scripts/codeoutline/indirect.lua +201 -0
  18. package/scripts/codeoutline/js_evidence.lua +175 -0
  19. package/scripts/codeoutline/js_resolution.lua +201 -0
  20. package/scripts/codeoutline/lang/c.lua +22 -12
  21. package/scripts/codeoutline/lang/cpp.lua +13 -12
  22. package/scripts/codeoutline/lang/csharp.lua +21 -21
  23. package/scripts/codeoutline/lang/go.lua +10 -10
  24. package/scripts/codeoutline/lang/java.lua +9 -9
  25. package/scripts/codeoutline/lang/js.lua +15 -14
  26. package/scripts/codeoutline/lang/kotlin.lua +384 -0
  27. package/scripts/codeoutline/lang/lua.lua +11 -6
  28. package/scripts/codeoutline/lang/python.lua +6 -6
  29. package/scripts/codeoutline/lang/rust.lua +23 -15
  30. package/scripts/codeoutline/lsp.lua +574 -0
  31. package/scripts/codeoutline/lua_bindings.lua +222 -0
  32. package/scripts/codeoutline/main.lua +28 -5
  33. package/scripts/codeoutline/navigation.lua +1046 -0
  34. package/scripts/codeoutline/parse.lua +9 -2
  35. package/scripts/codeoutline/parse_pool.lua +189 -0
  36. package/scripts/codeoutline/parse_worker.lua +24 -0
  37. package/scripts/codeoutline/service.lua +82 -31
  38. package/scripts/codeoutline/update_sequence.lua +1 -1
  39. package/scripts/codeoutline/version.lua +1 -1
  40. package/licenses/rpmalloc.txt +0 -12
@@ -0,0 +1,574 @@
1
+ local documents = require('codeoutline.documents')
2
+ local paths = require('codeoutline.path')
3
+ local text = require('codeoutline.text')
4
+ local M = { MAX_HEADER = 16384, MAX_MESSAGE = 4194304, MAX_ROOTS = 16,
5
+ MAX_DOCUMENTS = 128, MAX_DRAFT_BYTES = 33554432, MAX_PENDING = 64,
6
+ MAX_QUERY = 4096, MAX_SYMBOLS = 200, POLL_MS = 1000 }
7
+ local null = xutils.json_null
8
+ local function array(t) return setmetatable(t or {}, xutils.json_array_mt) end
9
+ local function object(t) return type(t) == 'table' and getmetatable(t) ~= xutils.json_array_mt end
10
+ local function valid_id(id) return type(id) == 'string' or (type(id) == 'number' and id % 1 == 0) end
11
+ local kinds = { namespace = 3, impl = 3, class = 5, method = 6, property = 7, field = 8,
12
+ constructor = 9, destructor = 9, enum = 10, interface = 11, ['function'] = 12, prototype = 12,
13
+ variable = 13, constant = 14, enum_member = 22, struct = 23, union = 23, record = 23,
14
+ typedef = 13, macro = 12, annotation_type = 11 }
15
+
16
+ function M.frame(message)
17
+ local body = xutils.json_pack(message)
18
+ return 'Content-Length: ' .. #body .. '\r\n\r\n' .. body
19
+ end
20
+
21
+ function M.reader()
22
+ local self = { buffer = '', length = nil }
23
+ function self:feed(data, accept)
24
+ self.buffer = self.buffer .. data
25
+ while true do
26
+ if not self.length then
27
+ local stop = self.buffer:find('\r\n\r\n', 1, true)
28
+ assert((stop or #self.buffer) <= M.MAX_HEADER, 'LSP header too large')
29
+ if not stop then return end
30
+ local header = self.buffer:sub(1, stop - 1)
31
+ local length
32
+ for line in (header .. '\r\n'):gmatch('(.-)\r\n') do
33
+ local name, value = line:match('^([%w%-]+):%s*(.-)%s*$')
34
+ assert(name, 'invalid LSP header')
35
+ if name:lower() == 'content-length' then
36
+ assert(not length and value:match('^%d+$'), 'invalid Content-Length')
37
+ length = tonumber(value)
38
+ elseif name:lower() == 'content-type' then
39
+ local charset = value:lower():match('charset%s*=%s*([^;%s]+)')
40
+ assert(not charset or charset == 'utf-8' or charset == 'utf8', 'unsupported LSP charset')
41
+ end
42
+ end
43
+ assert(length and length <= M.MAX_MESSAGE, 'missing or excessive Content-Length')
44
+ self.length, self.buffer = length, self.buffer:sub(stop + 4)
45
+ end
46
+ if #self.buffer < self.length then return end
47
+ local body = self.buffer:sub(1, self.length)
48
+ self.buffer, self.length = self.buffer:sub(self.length + 1), nil
49
+ accept(body)
50
+ end
51
+ end
52
+ function self:complete() return self.length == nil and self.buffer == '' end
53
+ return self
54
+ end
55
+
56
+ local function kind(node) return kinds[node.kind] or 13 end
57
+ M.symbol_kind = kind
58
+ local function location(doc, node) return { uri = doc.uri, range = doc:range(node.name_start, node.name_end) } end
59
+
60
+ function M.document_symbols(doc, hierarchical)
61
+ local rec, result, entries = doc:parse(), array(), {}
62
+ for i, node in ipairs(rec.nodes) do
63
+ local item
64
+ if hierarchical then
65
+ item = { name = node.name, detail = node.sig, kind = kind(node),
66
+ range = doc:range(node.start_byte, node.end_byte), selectionRange = doc:range(node.name_start, node.name_end) }
67
+ else item = { name = node.name, kind = kind(node), location = location(doc, node),
68
+ containerName = node.parent and rec.nodes[node.parent].qualified or nil } end
69
+ entries[i] = item
70
+ local pn = node.parent and rec.nodes[node.parent]
71
+ if hierarchical and pn and entries[node.parent]
72
+ and pn.start_byte <= node.start_byte and node.end_byte <= pn.end_byte then
73
+ local parent = entries[node.parent]
74
+ parent.children = parent.children or array()
75
+ parent.children[#parent.children + 1] = item
76
+ -- Logical parents of out-of-line methods are not lexical containers.
77
+ else result[#result + 1] = item end
78
+ end
79
+ return result
80
+ end
81
+
82
+ -- initializationOptions.features may disable any of these, e.g. in assistant mode
83
+ -- next to another language server; disabled features are not advertised.
84
+ M.FEATURES = { 'documentSymbol', 'workspaceSymbol', 'definition', 'hover', 'references', 'callHierarchy', 'completion', 'signatureHelp' }
85
+ local feature_of = { ['textDocument/documentSymbol'] = 'documentSymbol', ['workspace/symbol'] = 'workspaceSymbol',
86
+ ['textDocument/definition'] = 'definition', ['textDocument/hover'] = 'hover',
87
+ ['textDocument/references'] = 'references', ['textDocument/prepareCallHierarchy'] = 'callHierarchy',
88
+ ['callHierarchy/incomingCalls'] = 'callHierarchy', ['callHierarchy/outgoingCalls'] = 'callHierarchy',
89
+ ['textDocument/completion'] = 'completion', ['textDocument/signatureHelp'] = 'signatureHelp' }
90
+ local sessions = 0
91
+
92
+ function M.new(config, emit, submit, cancel, stop)
93
+ config = config or {}
94
+ sessions = sessions + 1
95
+ local self = { state = 'new', documents = {}, roots = {}, pending = {}, scans = {}, ready = {},
96
+ document_bytes = 0, document_count = 0, session = config.session or ('lsp-' .. sessions),
97
+ synced = {}, features = {} }
98
+ local progress, server_pending, next_id, next_poll = {}, {}, 0, 0
99
+ local handlers = {}
100
+ local function error_response(id, code, message)
101
+ emit({ jsonrpc = '2.0', id = id == nil and null or id, error = { code = code, message = message } })
102
+ end
103
+ local function reply(id, value) emit({ jsonrpc = '2.0', id = id, result = value == nil and null or value }) end
104
+ local function progress_value(job, value)
105
+ emit({ jsonrpc = '2.0', method = '$/progress', params = { token = job.token, value = value } })
106
+ end
107
+ function self:begin_index(root)
108
+ if not self.work_done or self.state ~= 'ready' or progress[root] then return end
109
+ next_id = next_id + 1
110
+ local id = 'codeoutline-progress-' .. next_id
111
+ local job = { token = id, root = root }
112
+ progress[root], server_pending[id] = job, job
113
+ emit({ jsonrpc = '2.0', id = id, method = 'window/workDoneProgress/create', params = { token = id } })
114
+ end
115
+ function self:end_index(root, message)
116
+ local job = progress[root]
117
+ if not job then return end
118
+ job.done, job.message = true, message
119
+ if job.started then
120
+ progress_value(job, { kind = 'end', message = message })
121
+ progress[root] = nil
122
+ end
123
+ end
124
+ local function root_for(path)
125
+ for _, root in ipairs(self.roots) do if paths.contains(root, path) then return root end end
126
+ end
127
+ -- Clients may name a workspace through a symlink, junction or short name
128
+ -- (/var for /private/var, RUNNER~1), while roots and the index use the
129
+ -- canonical spelling. Paths are mapped at this boundary: the worker sees
130
+ -- canonical paths and URIs, and results return in the client's spelling.
131
+ local aliases = {}
132
+ local function rebase(path, from, to)
133
+ if not paths.contains(from, path) then return nil end
134
+ local rest = path:sub(#from + 1):gsub('^/', '')
135
+ if rest == '' then return to end
136
+ return (to:sub(-1) == '/' and to or to .. '/') .. rest
137
+ end
138
+ local function server_path(path)
139
+ for _, alias in ipairs(aliases) do
140
+ local mapped = rebase(path, alias.client, alias.root)
141
+ if mapped then return mapped end
142
+ end
143
+ return path
144
+ end
145
+ local function server_uri(uri)
146
+ local path = #aliases > 0 and documents.path(uri)
147
+ local mapped = path and server_path(path)
148
+ return mapped and mapped ~= path and documents.uri(mapped) or uri
149
+ end
150
+ local function client_uri(uri)
151
+ local path = documents.path(uri)
152
+ for _, alias in ipairs(aliases) do
153
+ local mapped = path and rebase(path, alias.root, alias.client)
154
+ if mapped then return documents.uri(mapped) end
155
+ end
156
+ return uri
157
+ end
158
+ -- Rewrites result URIs in place; call hierarchy data stays canonical.
159
+ local function to_client(value)
160
+ if #aliases == 0 or type(value) ~= 'table' then return value end
161
+ for key, item in pairs(value) do
162
+ if key == 'uri' and type(item) == 'string' then value[key] = client_uri(item)
163
+ elseif key ~= 'data' then to_client(item) end
164
+ end
165
+ return value
166
+ end
167
+ local function document_path(uri)
168
+ local path = documents.path(uri)
169
+ return path and server_path(path)
170
+ end
171
+ local function scan(root, hints)
172
+ local existing = self.scans[root]
173
+ if existing then
174
+ for _, path in ipairs(hints or {}) do existing.hints[path] = true end
175
+ return
176
+ end
177
+ local job = { hints = {} }
178
+ self.scans[root] = job
179
+ if not self.ready[root] then self:begin_index(root) end
180
+ local id, err = submit({ method = 'lsp_refresh', projectPath = root, allowedRoots = self.roots,
181
+ paths = hints }, function(ok, result)
182
+ if self.scans[root] ~= job then return end
183
+ self.scans[root] = nil
184
+ self.ready[root] = ok or nil
185
+ self:end_index(root, ok and 'Ready' or tostring(result))
186
+ if not ok then
187
+ emit({ jsonrpc = '2.0', method = 'window/logMessage', params = { type = 1, message = tostring(result) } })
188
+ end
189
+ local pending = {}
190
+ for path in pairs(job.hints) do pending[#pending + 1] = path end
191
+ if #pending > 0 and self.state == 'ready' then scan(root, pending) end
192
+ end)
193
+ job.id = id
194
+ if not id then self.scans[root] = nil; self:end_index(root, err) end
195
+ end
196
+ function self:poll()
197
+ if self.state ~= 'ready' or xtimer.now_ms() < next_poll then return end
198
+ next_poll = xtimer.now_ms() + M.POLL_MS
199
+ for _, root in ipairs(self.roots) do scan(root) end
200
+ end
201
+ local function set_roots(folders)
202
+ local roots, spelled = {}, {}
203
+ assert(type(folders) == 'table' and #folders <= M.MAX_ROOTS, 'too many workspace folders')
204
+ for _, folder in ipairs(folders) do
205
+ local path = documents.path(folder.uri)
206
+ local root = path and paths.canonical(path)
207
+ assert(root, 'workspace folder must be an existing local directory')
208
+ roots[#roots + 1] = root
209
+ if paths.key(path) ~= paths.key(root) then spelled[#spelled + 1] = { client = path, root = root } end
210
+ end
211
+ table.sort(roots, function(a, b) return #a < #b or (#a == #b and a < b) end)
212
+ -- The longest client spelling wins when aliases nest.
213
+ table.sort(spelled, function(a, b) return #a.client > #b.client end)
214
+ aliases = spelled
215
+ self.roots = {}
216
+ for _, root in ipairs(roots) do
217
+ if not root_for(root) then self.roots[#self.roots + 1] = root end
218
+ end
219
+ self.folders = folders
220
+ local retained = {}
221
+ for _, root in ipairs(self.roots) do retained[root] = true end
222
+ for root, job in pairs(self.scans) do
223
+ if not retained[root] then cancel(job.id); self.scans[root] = nil; self:end_index(root, 'Workspace removed') end
224
+ end
225
+ for root in pairs(self.ready) do if not retained[root] then self.ready[root] = nil end end
226
+ if self.state == 'ready' then next_poll = 0; self:poll() end
227
+ end
228
+ local function document(params)
229
+ assert(object(params.textDocument) and type(params.textDocument.uri) == 'string', 'document URI required')
230
+ local uri = params.textDocument.uri
231
+ local doc = self.documents[uri]
232
+ if doc then return doc end
233
+ local path = document_path(uri)
234
+ assert(path and root_for(path), 'document is outside the workspace')
235
+ local canonical = xutils.realpath(path)
236
+ assert(canonical and root_for(paths.normalize(canonical)), 'document is outside the workspace')
237
+ doc = documents.read(canonical)
238
+ if doc then doc.uri = uri end
239
+ return doc
240
+ end
241
+ local function cancel_pending(id)
242
+ local job = self.pending[id]
243
+ if job then
244
+ self.pending[id] = nil
245
+ cancel(job.id)
246
+ error_response(id, -32800, 'Request cancelled')
247
+ end
248
+ end
249
+ function self:close()
250
+ if self.state == 'closed' then return end
251
+ self.state = 'closed'
252
+ for id in pairs(self.pending) do cancel_pending(id) end
253
+ for _, job in pairs(self.scans) do cancel(job.id) end
254
+ if next(self.synced) then submit({ method = 'lsp_close', session = self.session }, function() end) end
255
+ self.scans, self.documents, self.ready = {}, {}, {}
256
+ progress, server_pending = {}, {}
257
+ end
258
+ handlers.initialize = function(id, params)
259
+ assert(self.state == 'new', 'server already initialized')
260
+ local folders = params.workspaceFolders
261
+ if folders == null or folders == nil then
262
+ local uri = params.rootUri
263
+ if uri == null or uri == nil then
264
+ local root = params.rootPath ~= null and params.rootPath or config.project
265
+ uri = root and documents.uri(assert(paths.canonical(root)))
266
+ end
267
+ folders = uri and { { uri = uri } } or {}
268
+ end
269
+ set_roots(folders)
270
+ local td = (params.capabilities or {}).textDocument or {}
271
+ local window = (params.capabilities or {}).window or {}
272
+ self.work_done = window.workDoneProgress == true
273
+ self.hierarchical = td.documentSymbol and td.documentSymbol.hierarchicalDocumentSymbolSupport == true
274
+ local options = object(params.initializationOptions) and params.initializationOptions.features
275
+ assert(options == nil or options == false or object(options), 'initializationOptions.features must be an object')
276
+ for _, name in ipairs(M.FEATURES) do self.features[name] = not options or options[name] ~= false end
277
+ -- Extra C/C++ include directories searched before the detected system ones.
278
+ local includes = object(params.initializationOptions) and params.initializationOptions.includePaths or nil
279
+ assert(includes == nil or (type(includes) == 'table' and #includes <= M.MAX_ROOTS * 4),
280
+ 'initializationOptions.includePaths must be an array')
281
+ self.include_paths = {}
282
+ for _, dir in ipairs(includes or {}) do
283
+ assert(type(dir) == 'string' and dir ~= '' and not dir:find('%z'), 'include paths must be strings')
284
+ self.include_paths[#self.include_paths + 1] = dir
285
+ end
286
+ self.state = 'initialized'
287
+ local f = self.features
288
+ reply(id, { capabilities = { positionEncoding = 'utf-16',
289
+ textDocumentSync = { openClose = true, change = 1, save = { includeText = false } },
290
+ documentSymbolProvider = f.documentSymbol or nil, workspaceSymbolProvider = f.workspaceSymbol or nil,
291
+ definitionProvider = f.definition or nil, hoverProvider = f.hover or nil,
292
+ referencesProvider = f.references or nil, callHierarchyProvider = f.callHierarchy or nil,
293
+ completionProvider = f.completion and { triggerCharacters = { '.', ':', '>' }, resolveProvider = false } or nil,
294
+ signatureHelpProvider = f.signatureHelp and { triggerCharacters = { '(', ',' }, retriggerCharacters = { ')' } } or nil,
295
+ workspace = { workspaceFolders = { supported = true, changeNotifications = true } } },
296
+ serverInfo = { name = 'codeoutline', version = require('codeoutline.version') } })
297
+ end
298
+ handlers.initialized = function()
299
+ if self.state == 'initialized' then self.state = 'ready'; self:poll() end
300
+ end
301
+ handlers.shutdown = function(id)
302
+ self.state = 'shutdown'
303
+ for request_id in pairs(self.pending) do cancel_pending(request_id) end
304
+ for _, job in pairs(self.scans) do cancel(job.id) end
305
+ self.scans = {}
306
+ reply(id, nil)
307
+ end
308
+ handlers['textDocument/didOpen'] = function(_, params)
309
+ local td = assert(params.textDocument, 'textDocument required')
310
+ assert(type(td.version) == 'number' and td.version % 1 == 0, 'invalid document version')
311
+ assert(not self.documents[td.uri], 'document already open')
312
+ local doc = documents.new(td.uri, td.text, td.version, td.languageId)
313
+ assert(self.document_count < M.MAX_DOCUMENTS and self.document_bytes + #doc.source <= M.MAX_DRAFT_BYTES, 'open document limit reached')
314
+ self.documents[td.uri] = doc
315
+ self.document_count, self.document_bytes = self.document_count + 1, self.document_bytes + #doc.source
316
+ end
317
+ handlers['textDocument/didChange'] = function(_, params)
318
+ local td = assert(params.textDocument, 'textDocument required')
319
+ local doc = assert(self.documents[td.uri], 'document is not open')
320
+ assert(type(td.version) == 'number' and td.version % 1 == 0 and td.version > doc.version, 'stale document version')
321
+ local source = doc.source
322
+ assert(type(params.contentChanges) == 'table' and #params.contentChanges > 0, 'contentChanges required')
323
+ for _, change in ipairs(params.contentChanges) do
324
+ assert(change.range == nil and type(change.text) == 'string', 'server requires full document synchronization')
325
+ source = change.text
326
+ end
327
+ local updated = documents.new(td.uri, source, td.version, doc.language)
328
+ assert(self.document_bytes - #doc.source + #updated.source <= M.MAX_DRAFT_BYTES, 'open document limit reached')
329
+ self.documents[td.uri] = updated
330
+ self.document_bytes = self.document_bytes - #doc.source + #updated.source
331
+ end
332
+ handlers['textDocument/didClose'] = function(_, params)
333
+ local uri = params.textDocument.uri
334
+ local doc = self.documents[uri]
335
+ if doc then
336
+ self.document_count, self.document_bytes = self.document_count - 1, self.document_bytes - #doc.source
337
+ self.documents[uri] = nil
338
+ self.synced[uri] = nil
339
+ end
340
+ end
341
+ local function hint(uri)
342
+ local path = document_path(uri)
343
+ local root = path and root_for(path)
344
+ if root then scan(root, { path }) end
345
+ end
346
+ handlers['textDocument/didSave'] = function(_, params) hint(params.textDocument.uri) end
347
+ handlers['workspace/didChangeWatchedFiles'] = function(_, params)
348
+ assert(type(params.changes) == 'table', 'changes required')
349
+ for _, change in ipairs(params.changes) do hint(change.uri) end
350
+ end
351
+ handlers['workspace/didChangeWorkspaceFolders'] = function(_, params)
352
+ local folders, removed = {}, {}
353
+ for _, folder in ipairs(params.event.removed) do removed[folder.uri] = true end
354
+ for _, folder in ipairs(self.folders) do if not removed[folder.uri] then folders[#folders + 1] = folder end end
355
+ for _, folder in ipairs(params.event.added) do folders[#folders + 1] = folder end
356
+ set_roots(folders)
357
+ end
358
+ handlers['textDocument/documentSymbol'] = function(id, params)
359
+ assert(id ~= nil, 'symbol query must be a request')
360
+ local doc = document(params)
361
+ reply(id, doc and M.document_symbols(doc, self.hierarchical) or array())
362
+ end
363
+ -- One worker job per request; late results of cancelled requests are dropped.
364
+ local function request(id, req, finish)
365
+ local count = 0
366
+ for _ in pairs(self.pending) do count = count + 1 end
367
+ assert(count < M.MAX_PENDING, 'too many pending requests')
368
+ local job = {}
369
+ self.pending[id] = job
370
+ local job_id, err = submit(req, function(ok, result)
371
+ if self.pending[id] ~= job then return end
372
+ self.pending[id] = nil
373
+ if not ok then
374
+ if req.changed then self.synced = {} end -- resend drafts with the next request
375
+ error_response(id, -32603, tostring(result)); return
376
+ end
377
+ finish(result)
378
+ end)
379
+ job.id = job_id
380
+ if not job_id and self.pending[id] == job then
381
+ self.pending[id] = nil; error_response(id, -32603, err)
382
+ end
383
+ return job_id ~= nil
384
+ end
385
+ handlers['workspace/symbol'] = function(id, params)
386
+ assert(id ~= nil, 'symbol query must be a request')
387
+ assert(type(params.query) == 'string' and #params.query <= M.MAX_QUERY, 'invalid symbol query')
388
+ local drafts, exclude, result = {}, {}, array()
389
+ for _, doc in pairs(self.documents) do
390
+ local path = doc.path and server_path(doc.path)
391
+ if path and root_for(path) then
392
+ drafts[#drafts + 1] = doc
393
+ exclude[paths.key(path)] = true
394
+ end
395
+ end
396
+ table.sort(drafts, function(a, b) return a.uri < b.uri end)
397
+ local needle = params.query:lower()
398
+ for _, doc in ipairs(drafts) do
399
+ for _, node in ipairs(doc:parse().nodes) do
400
+ if #result < M.MAX_SYMBOLS and node.qualified:lower():find(needle, 1, true) then
401
+ result[#result + 1] = { name = node.name, kind = kind(node), location = location(doc, node),
402
+ containerName = node.qualified ~= node.name and node.qualified or nil }
403
+ end
404
+ end
405
+ end
406
+ for _, root in ipairs(self.roots) do
407
+ if not self.ready[root] then reply(id, result); return end
408
+ end
409
+ request(id, { method = 'lsp_symbols', roots = self.roots, exclude = exclude,
410
+ query = params.query, limit = M.MAX_SYMBOLS - #result }, function(symbols)
411
+ for _, symbol in ipairs(to_client(symbols)) do result[#result + 1] = symbol end
412
+ reply(id, result)
413
+ end)
414
+ end
415
+ -- Navigation runs in the worker against the session's drafts: every request
416
+ -- carries the open set and the text of versions the worker has not seen.
417
+ local function navigate(id, req, finish)
418
+ assert(id ~= nil, 'navigation must be a request')
419
+ local open, changed, sent = {}, {}, {}
420
+ for uri, doc in pairs(self.documents) do
421
+ if doc.path and root_for(server_path(doc.path)) then
422
+ local key = server_uri(uri)
423
+ open[key] = doc.version
424
+ if self.synced[uri] ~= doc.version then
425
+ changed[key] = { source = doc.source, version = doc.version, language = doc.language }
426
+ sent[uri] = doc.version
427
+ end
428
+ end
429
+ end
430
+ req.session, req.open, req.changed = self.session, open, changed
431
+ req.includePaths = self.include_paths
432
+ local submitted = request(id, req, function(value)
433
+ if value.error then error_response(id, -32803, value.error); return end
434
+ if value.incomplete then
435
+ emit({ jsonrpc = '2.0', method = 'window/showMessage', params = { type = 2,
436
+ message = 'CodeOutline: results were truncated; too many matching references' } })
437
+ end
438
+ reply(id, to_client(finish(value.result)))
439
+ end)
440
+ if submitted then
441
+ for uri, version in pairs(sent) do self.synced[uri] = version end
442
+ end
443
+ end
444
+ -- Worker results lose array metatables in transit; empty lists must stay JSON arrays.
445
+ local function list(value) return array(value or nil) end
446
+ local function calls(value)
447
+ local result = array(value or nil)
448
+ for _, call in ipairs(result) do call.fromRanges = array(call.fromRanges) end
449
+ return result
450
+ end
451
+ -- Position requests outside every workspace root answer empty without a job.
452
+ local function at(id, params, method, empty, finish, extra)
453
+ assert(object(params.textDocument) and type(params.textDocument.uri) == 'string', 'document URI required')
454
+ assert(object(params.position), 'position required')
455
+ local path = document_path(params.textDocument.uri)
456
+ local root = path and root_for(path)
457
+ if not root then reply(id, empty); return end
458
+ local req = { method = method, root = root, uri = server_uri(params.textDocument.uri), position = params.position }
459
+ for key, value in pairs(extra or {}) do req[key] = value end
460
+ navigate(id, req, finish)
461
+ end
462
+ handlers['textDocument/definition'] = function(id, params)
463
+ at(id, params, 'lsp_definition', array(), list)
464
+ end
465
+ handlers['textDocument/hover'] = function(id, params)
466
+ at(id, params, 'lsp_hover', nil, function(value) return value or nil end)
467
+ end
468
+ handlers['textDocument/signatureHelp'] = function(id, params)
469
+ at(id, params, 'lsp_signature', nil, function(value)
470
+ if not value then return nil end
471
+ value.signatures = array(value.signatures)
472
+ for _, signature in ipairs(value.signatures) do signature.parameters = array(signature.parameters) end
473
+ return value
474
+ end)
475
+ end
476
+ handlers['textDocument/references'] = function(id, params)
477
+ local context = object(params.context) and params.context or {}
478
+ at(id, params, 'lsp_references', array(), list, { includeDeclaration = context.includeDeclaration == true })
479
+ end
480
+ handlers['textDocument/completion'] = function(id, params)
481
+ local context = object(params.context) and params.context or {}
482
+ -- Trigger characters complete only after member operators (`a.`, `a->`, `A::`).
483
+ local trigger = context.triggerKind == 2 and type(context.triggerCharacter) == 'string' or nil
484
+ at(id, params, 'lsp_completion', { isIncomplete = false, items = array() }, function(value)
485
+ value = value or {}
486
+ return { isIncomplete = value.isIncomplete == true, items = array(value.items or nil) }
487
+ end, { trigger = trigger })
488
+ end
489
+ handlers['textDocument/prepareCallHierarchy'] = function(id, params)
490
+ at(id, params, 'lsp_prepare_calls', nil, function(value) return value and array(value) or nil end)
491
+ end
492
+ -- Items carry their root; only this session's roots are accepted.
493
+ local function hierarchy(method)
494
+ return function(id, params)
495
+ local data = object(params.item) and params.item.data
496
+ local root
497
+ for _, candidate in ipairs(self.roots) do
498
+ if object(data) and type(data.root) == 'string' and paths.key(data.root) == paths.key(candidate) then
499
+ root = candidate
500
+ end
501
+ end
502
+ if not root then reply(id, array()); return end
503
+ navigate(id, { method = method, root = root, data = data }, calls)
504
+ end
505
+ end
506
+ handlers['callHierarchy/incomingCalls'] = hierarchy('lsp_incoming')
507
+ handlers['callHierarchy/outgoingCalls'] = hierarchy('lsp_outgoing')
508
+ local navigation = { ['textDocument/definition'] = true, ['textDocument/hover'] = true, ['textDocument/signatureHelp'] = true,
509
+ ['textDocument/references'] = true, ['textDocument/prepareCallHierarchy'] = true,
510
+ ['callHierarchy/incomingCalls'] = true, ['callHierarchy/outgoingCalls'] = true }
511
+ local function dispatch(msg)
512
+ local id, method, params = msg.id, msg.method, msg.params or {}
513
+ if method == 'exit' then
514
+ local code = self.state == 'shutdown' and 0 or 1
515
+ self:close(); stop(code); return
516
+ end
517
+ if self.state == 'closed' then return end
518
+ if method == '$/cancelRequest' then cancel_pending(params.id); return end
519
+ if self.pending[id] then error_response(id, -32600, 'Request ID is already pending'); return end
520
+ if method == 'initialize' then handlers.initialize(id, params); return end
521
+ if self.state == 'new' then if id ~= nil then error_response(id, -32002, 'Server not initialized') end; return end
522
+ if method == 'initialized' then handlers.initialized(); return end
523
+ if self.state == 'shutdown' then if id ~= nil then error_response(id, -32600, 'Server is shutting down') end; return end
524
+ if method == 'shutdown' then handlers.shutdown(id); return end
525
+ if self.state ~= 'ready' then if id ~= nil then error_response(id, -32002, 'Initialization is incomplete') end; return end
526
+ if navigation[method] or method == 'textDocument/completion' then
527
+ for _, root in ipairs(self.roots) do
528
+ if not self.ready[root] then
529
+ if id ~= nil then
530
+ if method == 'textDocument/completion' then reply(id, { isIncomplete = true, items = array() })
531
+ else error_response(id, -32803, 'Project is indexing; retry when indexing completes') end
532
+ end
533
+ return
534
+ end
535
+ end
536
+ end
537
+ local handler = handlers[method]
538
+ if handler and feature_of[method] and not self.features[feature_of[method]] then handler = nil end
539
+ if handler then handler(id, params)
540
+ elseif id ~= nil then error_response(id, -32601, 'Method not found: ' .. method) end
541
+ end
542
+ function self:accept(body)
543
+ local ok, msg = pcall(xutils.json_unpack, body)
544
+ if not ok or text.valid(body) ~= body then error_response(nil, -32700, 'Invalid JSON'); return end
545
+ if object(msg) and msg.jsonrpc == '2.0' and msg.method == nil and valid_id(msg.id)
546
+ and ((msg.result ~= nil and msg.error == nil) or (msg.result == nil and object(msg.error))) then
547
+ local job = server_pending[msg.id]
548
+ if not job then return end
549
+ server_pending[msg.id] = nil
550
+ if msg.error or self.state ~= 'ready' then progress[job.root] = nil; return end
551
+ job.started = true
552
+ progress_value(job, { kind = 'begin', title = 'CodeOutline indexing', message = job.root, cancellable = false })
553
+ if job.done then self:end_index(job.root, job.message) end
554
+ return
555
+ end
556
+ -- Some clients send `"params": null` for parameterless requests such as
557
+ -- shutdown; treat it as omitted.
558
+ if object(msg) and msg.params == null then msg.params = nil end
559
+ if not object(msg) or msg.jsonrpc ~= '2.0' or type(msg.method) ~= 'string'
560
+ or (msg.id ~= nil and not valid_id(msg.id)) or (msg.params ~= nil and not object(msg.params)) then
561
+ -- Echo a readable id so the client can fail that request instead of waiting.
562
+ error_response(object(msg) and valid_id(msg.id) and msg.id or nil, -32600, 'Invalid JSON-RPC request'); return
563
+ end
564
+ if (msg.method == 'initialize' or msg.method == 'shutdown') and msg.id == nil then return end
565
+ local dispatched, err = pcall(dispatch, msg)
566
+ if not dispatched then
567
+ if msg.id ~= nil then error_response(msg.id, -32602, tostring(err))
568
+ else io.stderr:write('[codeoutline lsp] ', tostring(err), '\n') end
569
+ end
570
+ end
571
+ return self
572
+ end
573
+
574
+ return M