@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,1046 @@
1
+ -- navigation.lua — LSP navigation inside the INDEX worker.
2
+ --
3
+ -- Resolution reuses the graph resolver over the resident symbol tables of one
4
+ -- workspace root, overlaid with the session's open documents (and the queried
5
+ -- file itself), so drafts hide the disk records of their files. Nothing here
6
+ -- is persisted: exact positions come from reparsing only the files a result
7
+ -- names, and callers are found by one scan of reference names per request.
8
+ local graph = require('codeoutline.graph')
9
+ local service = require('codeoutline.service')
10
+ local documents = require('codeoutline.documents')
11
+ local paths = require('codeoutline.path')
12
+ local control = require('codeoutline.control')
13
+ local lsp = require('codeoutline.lsp')
14
+ -- Reference scans stop at a result count or time budget and report truncation.
15
+ local M = { MAX_RESULTS = 1000, MAX_HOVER = 3, SCAN_SECONDS = 3, POSITION_SECONDS = 2, MAX_INCLUDES = 2000 }
16
+
17
+ local sessions = {}
18
+ local ANY = setmetatable({}, { __index = function() return true end })
19
+ -- Bare identifiers bind only nearby, except type names used across files.
20
+ local TYPES = { class = true, struct = true, union = true, interface = true, enum = true, record = true,
21
+ typedef = true, namespace = true, annotation_type = true }
22
+ -- references and call hierarchy cover callables; types need complete reference semantics.
23
+ local REFERENCE = { ['function'] = true, method = true, macro = true, constructor = true,
24
+ prototype = true, destructor = true }
25
+ local CALLS = { ['function'] = true, method = true, macro = true, constructor = true,
26
+ prototype = true, destructor = true, class = true, record = true }
27
+ local MEMBER = { ['.'] = true, ['->'] = true, ['::'] = true, ['?.'] = true }
28
+ local LUA_MEMBER = { ['.'] = true, [':'] = true }
29
+ local SELF = { self = true, this = true, cls = true }
30
+ local PROTOTYPE = { prototype = true }
31
+ local C_FAMILY = { c = true, cpp = true }
32
+
33
+ -- Session drafts arrive with each navigation request: the open set always,
34
+ -- text only for versions this worker has not seen.
35
+ function M.sync(req)
36
+ local store = sessions[req.session] or {}
37
+ sessions[req.session] = store
38
+ for uri in pairs(store) do
39
+ if not req.open[uri] then store[uri] = nil end
40
+ end
41
+ for uri, draft in pairs(req.changed or {}) do
42
+ store[uri] = documents.new(uri, draft.source, draft.version, draft.language)
43
+ end
44
+ end
45
+
46
+ function M.close(session) sessions[session] = nil end
47
+
48
+ local function relative(root, path)
49
+ local real = xutils.realpath(path)
50
+ local full = real and paths.normalize(real) or path
51
+ if not paths.contains(root, full) or paths.key(full) == paths.key(root) then return nil end
52
+ return full:sub(#root + 2)
53
+ end
54
+
55
+ -- The request's document: the session draft, else the file on disk.
56
+ local function request_doc(req)
57
+ local doc = (sessions[req.session] or {})[req.uri]
58
+ if doc then return doc end
59
+ local path = documents.path(req.uri)
60
+ local real = path and xutils.realpath(path)
61
+ if not real or not paths.contains(req.root, paths.normalize(real)) then return nil end
62
+ doc = documents.read(paths.normalize(real))
63
+ if doc then doc.uri = req.uri end
64
+ return doc
65
+ end
66
+
67
+ -- The index's maintained symbol tables with documents layered over their
68
+ -- files. Overlay files and nodes take ids after every resident one; masked
69
+ -- resident nodes drop out of name lists, which keep path and node order.
70
+ -- Nothing is written to the resident tables.
71
+ local function view(session, root)
72
+ local idx = service.resident(root)
73
+ local G = idx:symbols()
74
+ local V = setmetatable({ root = root, idx = idx, drafts = {}, disk = {}, dep_cache = {}, new_files = {},
75
+ next_file = G.next_file, next_node = G.next_node, next_dir = G.next_dir }, { __index = G })
76
+ V.js_context = require('codeoutline.js_resolution').context(V)
77
+ V.js_context.lua = require('codeoutline.lua_bindings').context(V)
78
+ for _, name in ipairs({ 'files', 'nodes', 'node_file', 'id_of', 'file_index', 'file_dir' }) do
79
+ V[name] = setmetatable({}, { __index = G[name] })
80
+ end
81
+ local masked, added = {}, {}
82
+ function V.add(doc)
83
+ local rel = doc.path and relative(root, doc.path)
84
+ local f = rel and V.file_index[rel]
85
+ if not rel or (f and V.drafts[f]) then return f end
86
+ local rec = doc:parse()
87
+ if not rec.language then return nil end
88
+ if f then masked[f] = true
89
+ else
90
+ -- An unsaved file resolves against others; no resident file depends on it.
91
+ V.next_file = V.next_file + 1
92
+ f = V.next_file
93
+ V.file_index[rel] = f
94
+ V.new_files[#V.new_files + 1] = f
95
+ local same = G.dir_ids[rel:match('^(.*)/[^/]*$') or '']
96
+ if not same then V.next_dir = V.next_dir + 1; same = V.next_dir end
97
+ V.file_dir[f] = same
98
+ end
99
+ local copy = {}
100
+ for key, value in pairs(rec) do copy[key] = value end
101
+ copy.path = rel
102
+ V.files[f], V.drafts[f] = copy, doc
103
+ local ids = {}
104
+ V.id_of[f] = ids
105
+ for n, node in ipairs(rec.nodes) do
106
+ V.next_node = V.next_node + 1
107
+ local id = V.next_node
108
+ V.nodes[id], V.node_file[id], ids[n] = node, f, id
109
+ local list = added[node.name]
110
+ if not list then list = {}; added[node.name] = list end
111
+ list[#list + 1] = id
112
+ end
113
+ return f
114
+ end
115
+ V.by_name = setmetatable({}, { __index = function(cache, name)
116
+ local list, extra = G.by_name[name] or {}, added[name]
117
+ if next(masked) then
118
+ local kept = {}
119
+ for _, id in ipairs(list) do
120
+ if not masked[G.node_file[id]] then kept[#kept + 1] = id end
121
+ end
122
+ list = kept
123
+ end
124
+ if extra then
125
+ local merged = {}
126
+ for _, id in ipairs(list) do merged[#merged + 1] = id end
127
+ for _, id in ipairs(extra) do merged[#merged + 1] = id end
128
+ table.sort(merged, function(a, b) return graph.before(V, a, b) end)
129
+ list = merged
130
+ end
131
+ rawset(cache, name, list)
132
+ return list
133
+ end })
134
+ local drafts = {}
135
+ for _, doc in pairs(sessions[session] or {}) do drafts[#drafts + 1] = doc end
136
+ table.sort(drafts, function(a, b) return a.uri < b.uri end)
137
+ for _, doc in ipairs(drafts) do V.add(doc) end
138
+ return V
139
+ end
140
+
141
+ -- Dependencies of file f. C and C++ see everything their includes include,
142
+ -- so headers are followed transitively (bounded), with the sources paired to
143
+ -- any of them.
144
+ local function deps(V, f)
145
+ local entry = V.dep_cache[f]
146
+ if not entry then
147
+ local direct, paired = graph.dependencies(V, f, V.js_context)
148
+ if C_FAMILY[V.files[f].language] then
149
+ local queue = {}
150
+ for g in pairs(direct) do queue[#queue + 1] = g end
151
+ local i = 1
152
+ while i <= #queue and #queue < M.MAX_INCLUDES do
153
+ local more, sources = graph.dependencies(V, queue[i])
154
+ for h in pairs(sources) do paired[h] = true end
155
+ for h in pairs(more) do
156
+ if not direct[h] and h ~= f then direct[h] = true; queue[#queue + 1] = h end
157
+ end
158
+ i = i + 1
159
+ end
160
+ end
161
+ entry = { direct, paired }
162
+ V.dep_cache[f] = entry
163
+ end
164
+ return entry[1], entry[2]
165
+ end
166
+
167
+ local function index_of(V, id)
168
+ local f = V.node_file[id]
169
+ return id - V.id_of[f][1] + 1, f
170
+ end
171
+
172
+ -- self.f() inside f, or M.f() inside M.f / Box::f() inside Box::f.
173
+ local function recursive(node, recv)
174
+ if not recv then return false end
175
+ if SELF[recv] then return true end
176
+ local q = node.qualified
177
+ for _, sep in ipairs({ '.', ':', '::' }) do
178
+ local tail = recv .. sep .. node.name
179
+ if q == tail or q:sub(-(#tail + 1)) == '.' .. tail then return true end
180
+ end
181
+ return false
182
+ end
183
+
184
+ -- Targets of one occurrence of name in file f, enclosed by node index from.
185
+ local function resolve_site(V, f, from, name, kind, recv, evidence)
186
+ local src = from > 0 and V.id_of[f][from] or nil
187
+ local direct, paired = deps(V, f)
188
+ local rkind, accept = kind, nil
189
+ if kind == 'symbol' then rkind, accept = 'call', ANY
190
+ elseif kind == 'member_symbol' then rkind, accept = 'member_call', ANY end
191
+ local targets = graph.resolve(V, f, src, name, rkind, recv or nil, direct, paired, accept, evidence, V.js_context) or {}
192
+ if kind == 'symbol' then
193
+ local kept = {}
194
+ for _, id in ipairs(targets) do
195
+ local node = V.nodes[id]
196
+ if TYPES[node.kind] or (graph.placement(V, f, V.node_file[id], node, direct, paired) or 0) > 0 then
197
+ kept[#kept + 1] = id
198
+ end
199
+ end
200
+ targets = kept
201
+ end
202
+ -- The resolver never binds a ref to its enclosing node, which hides recursion.
203
+ if #targets == 0 and src and V.nodes[src].name == name and (kind == 'call' or recursive(V.nodes[src], recv)) then
204
+ targets = { src }
205
+ end
206
+ -- Definitions too far apart to choose between: a visible prototype still
207
+ -- names the function, and going to its definition lists them all.
208
+ if #targets == 0 and (kind == 'call' or kind == 'ref') then
209
+ targets = graph.resolve(V, f, src, name, kind, recv or nil, direct, paired, PROTOTYPE, evidence, V.js_context) or {}
210
+ end
211
+ if C_FAMILY[V.files[f].language] then
212
+ -- C binds only what its includes make visible; a lone far definition
213
+ -- (another library's macro) is not the one a system header declares.
214
+ local kept = {}
215
+ for _, id in ipairs(targets) do
216
+ if id == src or (graph.placement(V, f, V.node_file[id], V.nodes[id], direct, paired) or 0) > 0 then
217
+ kept[#kept + 1] = id
218
+ end
219
+ end
220
+ targets = kept
221
+ end
222
+ return targets
223
+ end
224
+
225
+ -- What the cursor names: a declaration, an indexed reference, or another identifier.
226
+ local function find_cursor(doc, offset, strict)
227
+ local rec = doc:parse()
228
+ local function inside(a, b) return a <= offset and (offset < b or (not strict and offset == b)) end
229
+ for n, node in ipairs(rec.nodes) do
230
+ if node.name_start and inside(node.name_start, node.name_end) then
231
+ return { decl = n, name = node.name, first = node.name_start, last = node.name_end }
232
+ end
233
+ end
234
+ local refs = rec.refs
235
+ if refs and refs.start then
236
+ for i = 1, #refs.name do
237
+ local a = refs.start[i]
238
+ if a and inside(a, refs.stop[i]) then
239
+ return { from = refs.from[i], name = refs.name[i], kind = refs.kind[i], recv = refs.recv[i],
240
+ evidence = refs.lua_binding and refs.lua_binding[i] or refs.js_receiver and refs.js_receiver[i],
241
+ first = a, last = refs.stop[i] }
242
+ end
243
+ end
244
+ end
245
+ end
246
+
247
+ local function cursor(doc, offset)
248
+ local found = find_cursor(doc, offset, true) or find_cursor(doc, offset, false)
249
+ if found then return found end
250
+ local rec, T = doc:parse(), doc:tokens()
251
+ if not T then return nil end
252
+ local t
253
+ for i = 1, T.n do
254
+ local a = T.s[i] - 1
255
+ if a > offset then break end
256
+ if T.k[i] == 'id' and offset <= T.e[i] then t = i end
257
+ end
258
+ if not t then return nil end
259
+ local kind, recv = 'symbol', nil
260
+ local member = rec.language == 'lua' and LUA_MEMBER or MEMBER
261
+ if T.k[t + 1] == 'op' and T:text(t + 1) == '(' then kind = 'call' end
262
+ local p = t - 1
263
+ if p >= 1 and T.k[p] == 'op' and member[T:text(p)] then
264
+ kind = kind == 'call' and 'member_call' or 'member_symbol'
265
+ if T.k[p - 1] == 'id' or T.k[p - 1] == 'kw' then recv = T:text(p - 1) end
266
+ elseif p >= 1 and T.k[p] == 'kw' and T:text(p) == 'new' then
267
+ kind = 'new'
268
+ end
269
+ local from, span = 0, math.huge
270
+ for n, node in ipairs(rec.nodes) do
271
+ if node.start_byte and node.start_byte <= offset and offset < node.end_byte
272
+ and node.end_byte - node.start_byte < span then
273
+ from, span = n, node.end_byte - node.start_byte
274
+ end
275
+ end
276
+ return { from = from, name = T:text(t), kind = kind, recv = recv, first = T.s[t] - 1, last = T.e[t] }
277
+ end
278
+
279
+ -- Source document for file f: its overlay, else the disk file read once per request.
280
+ local function source_doc(V, f)
281
+ if V.drafts[f] then return V.drafts[f] end
282
+ local doc = V.disk[f]
283
+ if doc == nil then
284
+ doc = documents.read(V.idx:abs(V.files[f].path)) or false
285
+ V.disk[f] = doc
286
+ end
287
+ return doc or nil
288
+ end
289
+
290
+ local function uri_of(V, f)
291
+ local doc = source_doc(V, f)
292
+ return doc and doc.uri or documents.uri(V.idx:abs(V.files[f].path))
293
+ end
294
+
295
+ local function line_range(line)
296
+ local at = { line = math.max(line - 1, 0), character = 0 }
297
+ return { start = at, ['end'] = at }
298
+ end
299
+
300
+ -- Reparsed node for id, matched by index and verified by name, else by qualified name.
301
+ local function locate(V, id)
302
+ local n, f = index_of(V, id)
303
+ local node, doc = V.nodes[id], source_doc(V, f)
304
+ if not doc then return nil end
305
+ local nodes = doc:parse().nodes
306
+ local hit = nodes[n]
307
+ if hit and hit.name == node.name and hit.qualified == node.qualified and hit.name_start then return doc, hit end
308
+ hit = nil
309
+ for _, c in ipairs(nodes) do
310
+ if c.qualified == node.qualified and c.name_start
311
+ and (not hit or math.abs(c.line - node.line) < math.abs(hit.line - node.line)) then hit = c end
312
+ end
313
+ return doc, hit
314
+ end
315
+
316
+ local function location(V, id)
317
+ local doc, hit = locate(V, id)
318
+ local f = V.node_file[id]
319
+ if hit then return { uri = doc.uri, range = doc:range(hit.name_start, hit.name_end) }, doc, hit end
320
+ return { uri = uri_of(V, f), range = line_range(V.nodes[id].line) }
321
+ end
322
+
323
+ local function item(V, id)
324
+ local loc, doc, hit = location(V, id)
325
+ local node = V.nodes[id]
326
+ local n, f = index_of(V, id)
327
+ return { name = node.name, kind = lsp.symbol_kind(node), detail = node.sig or node.qualified, uri = loc.uri,
328
+ range = hit and doc:range(hit.start_byte, hit.end_byte) or loc.range, selectionRange = loc.range,
329
+ data = { root = V.root, path = V.files[f].path, index = n, name = node.name, qualified = node.qualified } }
330
+ end
331
+
332
+ -- File-scope code (Lua chunks, Python modules, JS top level) calls from the file itself.
333
+ local function file_item(V, f)
334
+ local rel = V.files[f].path
335
+ local start = line_range(1)
336
+ return { name = rel:match('[^/]*$'), kind = 1, detail = rel, uri = uri_of(V, f), range = start,
337
+ selectionRange = start, data = { root = V.root, path = rel, index = 0 } }
338
+ end
339
+
340
+ -- Item data to a node id (nil for a file item) and file index.
341
+ local function relocate(V, data)
342
+ local f = type(data) == 'table' and type(data.path) == 'string' and V.file_index[data.path]
343
+ if not f then return nil end
344
+ if data.index == 0 then return nil, f end
345
+ local ids = V.id_of[f]
346
+ local id = type(data.index) == 'number' and ids[data.index]
347
+ if id and V.nodes[id].name == data.name and V.nodes[id].qualified == data.qualified then return id, f end
348
+ for _, cid in ipairs(ids) do
349
+ if V.nodes[cid].qualified == data.qualified and V.nodes[cid].name == data.name then return cid, f end
350
+ end
351
+ end
352
+
353
+ -- Exact range of reference i of file f, from the overlay or a reparse of the
354
+ -- disk file. A file edited since indexing is matched by name and line.
355
+ local function site_range(V, f, i)
356
+ local doc = source_doc(V, f)
357
+ if not doc then return nil end
358
+ local refs, indexed = doc:parse().refs, V.files[f].refs
359
+ if not refs or not refs.start then return nil end
360
+ local j = i
361
+ if refs.name[i] ~= indexed.name[i] or refs.line[i] ~= indexed.line[i] then
362
+ j = nil
363
+ for k = 1, #refs.name do
364
+ if refs.name[k] == indexed.name[i] and refs.line[k] == indexed.line[i] then j = k; break end
365
+ end
366
+ if not j then return nil end
367
+ end
368
+ local a, b = refs.start[j], refs.stop[j]
369
+ if not a then
370
+ -- Macro bodies record the directive token; find the name on its line.
371
+ local line = refs.line[j]
372
+ local first = doc.lines[line]
373
+ if not first then return nil end
374
+ local last = doc.lines[line + 1] or #doc.source
375
+ local s = doc.source:find(refs.name[j], first + 1, true)
376
+ if not s or s > last then return nil end
377
+ a, b = s - 1, s - 1 + #refs.name[j]
378
+ end
379
+ return doc:range(a, b)
380
+ end
381
+
382
+ local function is_decl(node) return not not graph.is_decl(node) end
383
+
384
+ -- A declaration and its definitions (prototypes, in-class declarations) as one target.
385
+ local function expand(V, set)
386
+ local out = {}
387
+ for id in pairs(set) do
388
+ out[id] = true
389
+ local node = V.nodes[id]
390
+ local family = graph.family(V.files[V.node_file[id]].language)
391
+ for _, cid in ipairs(V.by_name[node.name]) do
392
+ local c = V.nodes[cid]
393
+ if c.qualified == node.qualified and is_decl(c) ~= is_decl(node)
394
+ and graph.family(V.files[V.node_file[cid]].language) == family then out[cid] = true end
395
+ end
396
+ end
397
+ return out
398
+ end
399
+
400
+ local function sorted(set)
401
+ local list = {}
402
+ for id in pairs(set) do list[#list + 1] = id end
403
+ table.sort(list)
404
+ return list
405
+ end
406
+
407
+ -- References to name that resolve into targets, as { f, i } in file order.
408
+ -- Hot names can match thousands of files; past the budget the scan stops.
409
+ local function scan(V, targets, name)
410
+ local hits, deadline = {}, os.clock() + M.SCAN_SECONDS
411
+ local files = {}
412
+ for i, f in ipairs(V.file_order) do files[i] = f end
413
+ for _, f in ipairs(V.new_files) do files[#files + 1] = f end
414
+ for _, f in ipairs(files) do
415
+ control.check()
416
+ local refs = V.files[f].refs
417
+ local names = refs.name
418
+ local aliases = {}
419
+ for _, binding in ipairs(V.files[f].js_imports or {}) do aliases[binding.local_name] = true end
420
+ if V.files[f].language == 'kotlin' then
421
+ for _, imp in ipairs(V.files[f].imports) do
422
+ if imp.alias and imp.path:match('([^.]+)$') == name then aliases[imp.alias] = true end
423
+ end
424
+ end
425
+ for i = 1, #names do
426
+ if i % 4096 == 0 then control.check() end
427
+ if names[i] == name or aliases[names[i]] or aliases[refs.recv[i]] or (refs.lua_binding and refs.lua_binding[i] ~= '') then
428
+ if os.clock() > deadline then return hits, true end
429
+ for _, dst in ipairs(resolve_site(V, f, refs.from[i], names[i], refs.kind[i], refs.recv[i], refs.lua_binding and refs.lua_binding[i] or refs.js_receiver and refs.js_receiver[i])) do
430
+ if targets[dst] then hits[#hits + 1] = { f, i }; break end
431
+ end
432
+ if #hits >= M.MAX_RESULTS then return hits, true end
433
+ end
434
+ end
435
+ end
436
+ return hits, false
437
+ end
438
+
439
+ -- Files one import record resolves to, through the graph's dependency
440
+ -- rules: a temporary record holding only that import.
441
+ function M.import_files(V, f, imp)
442
+ local rec = V.files[f]
443
+ local fake = { path = rec.language == 'go' and '\0/import.go' or rec.path, language = rec.language,
444
+ nodes = {}, imports = { imp } }
445
+ rawset(V.files, -1, fake)
446
+ local ok, direct = pcall(graph.dependencies, V, -1)
447
+ rawset(V.files, -1, nil)
448
+ local files = {}
449
+ if ok then for g in pairs(direct) do files[#files + 1] = g end end
450
+ table.sort(files, function(x, y) return V.files[x].path < V.files[y].path end)
451
+ return files
452
+ end
453
+
454
+ -- System include directories: client includePaths, INCLUDE/CPATH-style
455
+ -- variables, then the compiler's own list (cc -E -v) or, on Windows, the
456
+ -- newest Windows Kits and the MSVC found by vswhere. Probed once.
457
+ local probed_includes
458
+ local function existing(dir)
459
+ local st = dir and xutils.stat(dir)
460
+ return st and st.type == 'directory'
461
+ end
462
+ local function newest(dir)
463
+ local entries = existing(dir) and xutils.list_dir(dir, nil, true) or {}
464
+ local best
465
+ for _, e in ipairs(entries) do
466
+ local name = e.name or e
467
+ if name:match('^%d') and (not best or name > best) then best = name end
468
+ end
469
+ return best and (dir .. '/' .. best)
470
+ end
471
+ local function probe_includes()
472
+ if probed_includes then return probed_includes end
473
+ local dirs = {}
474
+ local function add(dir)
475
+ dir = dir and paths.normalize(dir)
476
+ if existing(dir) then dirs[#dirs + 1] = dir end
477
+ end
478
+ local windows = paths.windows
479
+ for _, name in ipairs({ 'INCLUDE', 'CPATH', 'C_INCLUDE_PATH', 'CPLUS_INCLUDE_PATH' }) do
480
+ for dir in (os.getenv(name) or ''):gmatch(windows and '[^;]+' or '[^:]+') do add(dir) end
481
+ end
482
+ if windows then
483
+ local kits = newest('C:/Program Files (x86)/Windows Kits/10/Include')
484
+ if kits then
485
+ for _, sub in ipairs({ 'ucrt', 'um', 'shared', 'winrt' }) do add(kits .. '/' .. sub) end
486
+ end
487
+ local vswhere = 'C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe'
488
+ if xutils.stat(vswhere) and io.popen then
489
+ -- cmd strips one pair of quotes around a command with `(x86)` in it.
490
+ local command = '""' .. vswhere:gsub('/', '\\') .. '" -latest -products * -property installationPath 2>nul"'
491
+ local ok, pipe = pcall(io.popen, command)
492
+ local install = ok and pipe and pipe:read('*l')
493
+ if ok and pipe then pipe:close() end
494
+ local msvc = install and newest(paths.normalize(install) .. '/VC/Tools/MSVC')
495
+ if msvc then add(msvc .. '/include') end
496
+ end
497
+ elseif io.popen then
498
+ local ok, pipe = pcall(io.popen, 'cc -xc++ -E -v - </dev/null 2>&1')
499
+ local output = ok and pipe and pipe:read('*a') or ''
500
+ if ok and pipe then pipe:close() end
501
+ local list = output:match('#include <%.%.%.> search starts here:(.-)End of search list') or ''
502
+ for line in list:gmatch('[^\n]+') do add((line:gsub('^%s+', ''):gsub('%s+%(framework directory%)$', ''))) end
503
+ add('/usr/local/include'); add('/usr/include')
504
+ end
505
+ local seen, unique = {}, {}
506
+ for _, dir in ipairs(dirs) do
507
+ local key = paths.key(dir)
508
+ if not seen[key] then seen[key] = true; unique[#unique + 1] = dir end
509
+ end
510
+ probed_includes = unique
511
+ return unique
512
+ end
513
+
514
+ -- Locations of the files an import on this line names: project files by the
515
+ -- dependency rules, and C/C++ headers found in the include directories.
516
+ local function import_targets(V, f, line, include_paths)
517
+ local rec, result, seen = V.files[f], {}, {}
518
+ local function add(uri)
519
+ if not seen[uri] then seen[uri] = true; result[#result + 1] = { uri = uri, range = line_range(1) } end
520
+ end
521
+ for _, imp in ipairs(rec.imports or {}) do
522
+ if imp.line == line then
523
+ local files = imp.system and {} or M.import_files(V, f, imp)
524
+ for _, g in ipairs(files) do add(uri_of(V, g)) end
525
+ if #files == 0 and C_FAMILY[rec.language] then
526
+ local dirs = {}
527
+ if not imp.system then dirs[1] = (V.idx:abs(rec.path):match('^(.*)/[^/]*$')) end
528
+ for _, dir in ipairs(include_paths or {}) do dirs[#dirs + 1] = paths.normalize(dir) end
529
+ for _, dir in ipairs(probe_includes()) do dirs[#dirs + 1] = dir end
530
+ for _, dir in ipairs(dirs) do
531
+ local file = dir .. '/' .. imp.path:gsub('\\', '/')
532
+ local st = xutils.stat(file)
533
+ if st and st.type == 'file' then add(documents.uri(file)); break end
534
+ end
535
+ end
536
+ end
537
+ end
538
+ return result
539
+ end
540
+
541
+ -- Project-local declarative rules; read per request so configuration edits are live.
542
+ local function definition_rules(root)
543
+ local file = io.open(root .. '/.codeoutline.json', 'rb')
544
+ if not file then return {} end
545
+ local raw = file:read(65537); file:close()
546
+ assert(#raw <= 65536, '.codeoutline.json exceeds 64 KiB')
547
+ local ok, config = pcall(xutils.json_unpack, raw)
548
+ assert(ok and type(config) == 'table', 'invalid .codeoutline.json')
549
+ local rules = config.definitionRules or {}
550
+ assert(type(rules) == 'table' and #rules <= 32, 'definitionRules must contain at most 32 rules')
551
+ for _, rule in ipairs(rules) do
552
+ assert(type(rule) == 'table' and (rule.language == nil or rule.language == 'lua'),
553
+ 'definitionRules currently support language lua')
554
+ assert(type(rule.call) == 'string' and rule.call:match('^[%a_][%w_%.:]*$'),
555
+ 'definitionRules.call must be a qualified function name')
556
+ assert(type(rule.argument) == 'number' and rule.argument >= 1 and rule.argument <= 32
557
+ and rule.argument % 1 == 0,
558
+ 'definitionRules.argument must be an integer from 1 to 32')
559
+ local kind = rule.targetKind or 'call'
560
+ assert(kind == 'call' or kind == 'declaration' or kind == 'key',
561
+ "definitionRules.targetKind must be 'call', 'declaration' or 'key'")
562
+ if kind ~= 'call' then
563
+ assert(rule.target == nil and rule.targetArgument == nil,
564
+ 'declaration and key rules must not set target or targetArgument')
565
+ if rule.qualifiers ~= nil then
566
+ assert(type(rule.qualifiers) == 'table', 'definitionRules.qualifiers must be an array of names')
567
+ local qualifiers = {}
568
+ for _, q in ipairs(rule.qualifiers) do
569
+ assert(type(q) == 'string' and q:match('^[%a_][%w_]*$'),
570
+ 'definitionRules.qualifiers must contain plain names')
571
+ qualifiers[q] = true
572
+ end
573
+ rule.qualifiers = qualifiers
574
+ end
575
+ else
576
+ assert(type(rule.target) == 'string' and rule.target:match('^[%a_][%w_%.:]*$'),
577
+ 'definitionRules.target must be a qualified function name')
578
+ assert(type(rule.targetArgument) == 'number' and rule.targetArgument >= 1
579
+ and rule.targetArgument <= 32 and rule.targetArgument % 1 == 0,
580
+ 'definitionRules.targetArgument must be an integer from 1 to 32')
581
+ end
582
+ end
583
+ return rules
584
+ end
585
+
586
+ -- Decode literals without running source code. Lua long strings and quoted escapes.
587
+ local function string_value(raw)
588
+ local eq, body = raw:match('^%[(=*)%[(.*)%]%1%]$')
589
+ if eq then return body:gsub('^\r?\n', '', 1) end
590
+ local quote = raw:sub(1, 1)
591
+ if (quote ~= '"' and quote ~= "'") or raw:sub(-1) ~= quote then return nil end
592
+ local escaped = { a = '\a', b = '\b', f = '\f', n = '\n', r = '\r', t = '\t', v = '\v',
593
+ ['\\'] = '\\', ['"'] = '"', ["'"] = "'", ['\n'] = '\n' }
594
+ local out, i, stop = {}, 2, #raw - 1
595
+ while i <= stop do
596
+ local c = raw:sub(i, i)
597
+ if c ~= '\\' then out[#out + 1] = c; i = i + 1
598
+ else
599
+ c = raw:sub(i + 1, i + 1); i = i + 2
600
+ if escaped[c] then out[#out + 1] = escaped[c]
601
+ elseif c == 'z' then
602
+ while i <= stop and raw:sub(i, i):match('%s') do i = i + 1 end
603
+ elseif c == '\r' then
604
+ if raw:sub(i, i) == '\n' then i = i + 1 end
605
+ out[#out + 1] = '\n'
606
+ elseif c == 'x' then
607
+ local hex = raw:sub(i, i + 1)
608
+ if not hex:match('^%x%x$') then return nil end
609
+ out[#out + 1] = string.char(tonumber(hex, 16)); i = i + 2
610
+ elseif c:match('%d') then
611
+ local digits = (c .. raw:sub(i, stop)):match('^%d%d?%d?')
612
+ local n = tonumber(digits)
613
+ if n > 255 then return nil end
614
+ out[#out + 1] = string.char(n); i = i + #digits - 1
615
+ else return nil end
616
+ end
617
+ end
618
+ return table.concat(out)
619
+ end
620
+
621
+ local function call_name(T, i)
622
+ if T.k[i] ~= 'id' or T:text(i + 1) ~= '(' then return nil end
623
+ local name, first = T:text(i), i
624
+ while T.k[first - 2] == 'id' and (T:text(first - 1) == '.' or T:text(first - 1) == ':') do
625
+ name = T:text(first - 2) .. T:text(first - 1) .. name
626
+ first = first - 2
627
+ end
628
+ if T:text(first - 1) == 'function' then return nil end
629
+ return name
630
+ end
631
+
632
+ -- Find a single literal argument, skipping nested brackets and anonymous functions.
633
+ local function literal_argument(T, call, argument)
634
+ local open, number, first = call + 1, 1, call + 2
635
+ local close = T.m[open]
636
+ if not close then return nil end
637
+ local i = first
638
+ while i <= close do
639
+ local token = T:text(i)
640
+ if i == close or token == ',' then
641
+ if number == argument then
642
+ if i == first + 1 and T.k[first] == 'str' then
643
+ return string_value(T:text(first)), T.s[first] - 1, T.e[first]
644
+ end
645
+ return nil
646
+ end
647
+ number, first = number + 1, i + 1
648
+ elseif token == '(' or token == '[' or token == '{' then
649
+ if not T.m[i] then return nil end
650
+ i = T.m[i]
651
+ elseif T.k[i] == 'kw' and token == 'function' then
652
+ local depth = 1
653
+ while depth > 0 and i < close do
654
+ i = i + 1
655
+ local kw = T.k[i] == 'kw' and T:text(i)
656
+ if kw == 'function' or kw == 'if' or kw == 'do' or kw == 'repeat' then depth = depth + 1
657
+ elseif kw == 'end' or kw == 'until' then depth = depth - 1 end
658
+ end
659
+ if depth > 0 then return nil end
660
+ end
661
+ i = i + 1
662
+ end
663
+ end
664
+
665
+ local DECLARABLE = { ['function'] = true, method = true }
666
+
667
+ -- A string literal being written as a table key: t["name"] = ... or { ["name"] = ... }.
668
+ -- Returns the decoded value and the owner identifier for assignments (nil in constructors).
669
+ local function key_literal(T, i)
670
+ if i < 3 or i + 2 > T.n or T.k[i] ~= 'str' then return nil end
671
+ if T:text(i - 1) ~= '[' or T:text(i + 1) ~= ']' or T:text(i + 2) ~= '=' then return nil end
672
+ local value = string_value(T:text(i))
673
+ if not value then return nil end
674
+ local owner
675
+ if T.k[i - 2] == 'id' and T:text(i - 3) ~= '.' and T:text(i - 3) ~= ':' then
676
+ owner = T:text(i - 2)
677
+ end
678
+ return value, owner
679
+ end
680
+
681
+ local function qualifier_matches(rule, owner)
682
+ return not rule.qualifiers or (owner ~= nil and rule.qualifiers[owner])
683
+ end
684
+
685
+ -- A rule name also binds colon calls by their method segment: self:callCluster matches callCluster.
686
+ local function call_matches(name, rule_name)
687
+ if not name then return false end
688
+ if name == rule_name then return true end
689
+ return name:find(':') ~= nil and name:match('([%w_]+)$') == rule_name
690
+ end
691
+
692
+ local function configured_definition(V, doc, offset)
693
+ if doc:parse().language ~= 'lua' then return nil end
694
+ local rules = definition_rules(V.root)
695
+ if #rules == 0 then return nil end
696
+ local tokens = doc:tokens()
697
+ local matched = {}
698
+ for i = 1, tokens.n do
699
+ if i % 128 == 0 then control.check() end
700
+ local name = call_name(tokens, i)
701
+ for _, rule in ipairs(rules) do
702
+ if call_matches(name, rule.call) then
703
+ local value, first, last = literal_argument(tokens, i, rule.argument)
704
+ if value and first <= offset and offset < last then matched[#matched + 1] = { rule, value } end
705
+ end
706
+ end
707
+ end
708
+ if #matched == 0 then return nil end
709
+ local result, seen, files = {}, {}, {}
710
+ local function add(loc)
711
+ local start = loc.range.start
712
+ local key = loc.uri .. ':' .. start.line .. ':' .. start.character
713
+ if not seen[key] then
714
+ seen[key] = true
715
+ result[#result + 1] = loc
716
+ end
717
+ return #result >= M.MAX_RESULTS
718
+ end
719
+ local calls, keys = {}, {}
720
+ local deadline = os.clock() + M.SCAN_SECONDS
721
+ for _, match in ipairs(matched) do
722
+ if match[1].targetKind == 'declaration' then
723
+ for _, id in ipairs(V.by_name[match[2]]) do
724
+ control.check()
725
+ if os.clock() > deadline then return result, true end
726
+ local node = V.nodes[id]
727
+ if DECLARABLE[node.kind] and V.files[V.node_file[id]].language == 'lua' then
728
+ local owner = graph.owner(node.qualified or node.name)
729
+ if qualifier_matches(match[1], owner) and add(location(V, id)) then
730
+ return result, true
731
+ end
732
+ end
733
+ end
734
+ elseif match[1].targetKind == 'key' then
735
+ keys[#keys + 1] = match
736
+ else
737
+ calls[#calls + 1] = match
738
+ end
739
+ end
740
+ if #calls == 0 and #keys == 0 then return result, false end
741
+ for _, f in ipairs(V.file_order) do files[#files + 1] = f end
742
+ for _, f in ipairs(V.new_files) do files[#files + 1] = f end
743
+ table.sort(files, function(a, b) return V.files[a].path < V.files[b].path end)
744
+ for _, f in ipairs(files) do
745
+ control.check()
746
+ if os.clock() > deadline then return result, true end
747
+ if V.files[f].language == 'lua' then
748
+ local target = source_doc(V, f)
749
+ if target then
750
+ local candidate = #keys > 0
751
+ for _, match in ipairs(calls) do
752
+ local tail = match[1].target:match('([%w_]+)$')
753
+ if target.source:find(tail, 1, true) then candidate = true; break end
754
+ end
755
+ if candidate then
756
+ local T = target:tokens()
757
+ for i = 1, T.n do
758
+ if i % 128 == 0 then
759
+ control.check()
760
+ if os.clock() > deadline then return result, true end
761
+ end
762
+ local name = call_name(T, i)
763
+ for _, match in ipairs(calls) do
764
+ if call_matches(name, match[1].target) then
765
+ local value, first, last = literal_argument(T, i, match[1].targetArgument)
766
+ if value == match[2] then
767
+ if add({ uri = target.uri, range = target:range(first, last) }) then
768
+ return result, true
769
+ end
770
+ end
771
+ end
772
+ end
773
+ if #keys > 0 then
774
+ local value, owner = key_literal(T, i)
775
+ if value then
776
+ for _, match in ipairs(keys) do
777
+ if value == match[2] and qualifier_matches(match[1], owner)
778
+ and add({ uri = target.uri, range = target:range(T.s[i] - 1, T.e[i]) }) then
779
+ return result, true
780
+ end
781
+ end
782
+ end
783
+ end
784
+ end
785
+ end
786
+ end
787
+ end
788
+ end
789
+ return result, false
790
+ end
791
+
792
+ local function at(req)
793
+ local doc = request_doc(req)
794
+ if not doc then return nil end
795
+ local V = view(req.session, req.root)
796
+ local f = V.add(doc)
797
+ if not f then return nil end
798
+ local offset = doc:offset(req.position)
799
+ local c = cursor(doc, offset)
800
+ local targets = {}
801
+ if c and c.decl then targets = { V.id_of[f][c.decl] }
802
+ elseif c then targets = resolve_site(V, f, c.from, c.name, c.kind, c.recv, c.evidence) end
803
+ return V, doc, c, targets, f, offset
804
+ end
805
+
806
+ local handlers = {}
807
+
808
+ function handlers.lsp_definition(req)
809
+ local V, doc, c, targets, f, offset = at(req)
810
+ if not V then return false end
811
+ local configured, incomplete = configured_definition(V, doc, offset)
812
+ if configured then return configured, incomplete end
813
+ local line = doc:position(offset).line + 1
814
+ local importer = false
815
+ if c and not c.decl then
816
+ -- `require`/`dofile` themselves name the file they load, not a same-named project function.
817
+ for _, imp in ipairs(V.files[f].imports or {}) do
818
+ if imp.line == line and imp.kind == c.name then importer = true end
819
+ end
820
+ end
821
+ if #targets == 0 or importer then
822
+ -- An import line: `require "a.b"`, `dofile("x.lua")`, `#include <x.h>`, `from . import m`.
823
+ local files = import_targets(V, f, line, req.includePaths)
824
+ if #files > 0 or #targets == 0 then return files end
825
+ end
826
+ if c.decl and is_decl(V.nodes[targets[1]]) then
827
+ -- From a declaration, go to its definitions.
828
+ local defs = {}
829
+ for _, id in ipairs(sorted(expand(V, { [targets[1]] = true }))) do
830
+ if not is_decl(V.nodes[id]) then defs[#defs + 1] = id end
831
+ end
832
+ if #defs > 0 then targets = defs end
833
+ end
834
+ local result = {}
835
+ for _, id in ipairs(targets) do result[#result + 1] = (location(V, id)) end
836
+ return result
837
+ end
838
+
839
+ -- Follow unmatched delimiters up to the cursor. Commas in nested calls,
840
+ -- literals and indexing expressions do not advance the enclosing argument.
841
+ function handlers.lsp_signature(req)
842
+ local doc = request_doc(req)
843
+ if not doc then return false end
844
+ local T, offset = doc:tokens(), doc:offset(req.position)
845
+ if not T then return false end
846
+ local stack = {}
847
+ local close = { [')'] = '(', [']'] = '[', ['}'] = '{' }
848
+ for i = 1, T.n do
849
+ if T.s[i] - 1 >= offset then break end
850
+ if i % 128 == 0 then control.check() end
851
+ if T.k[i] == 'op' then
852
+ local s = T:text(i)
853
+ if s == '(' or s == '[' or s == '{' then
854
+ stack[#stack + 1] = { token = i, delimiter = s, argument = 0 }
855
+ elseif close[s] then
856
+ if stack[#stack] and stack[#stack].delimiter == close[s] then table.remove(stack) end
857
+ elseif s == ',' and stack[#stack] then
858
+ stack[#stack].argument = stack[#stack].argument + 1
859
+ end
860
+ end
861
+ end
862
+ local call
863
+ local kotlin = doc:parse().language == 'kotlin'
864
+ for i = #stack, 1, -1 do
865
+ local entry = stack[i]
866
+ local name_token = entry.token - 1
867
+ if kotlin and entry.delimiter == '(' and T:text(name_token) == '>' then
868
+ local depth, k = 1, name_token - 1
869
+ while k > 1 and depth > 0 do
870
+ local s = T:text(k)
871
+ if s == '>' then depth = depth + 1 elseif s == '<' then depth = depth - 1 end
872
+ k = k - 1
873
+ end
874
+ if depth == 0 then name_token = k end
875
+ end
876
+ if entry.delimiter == '(' and T.k[name_token] == 'id' then
877
+ call = entry; call.name_token = name_token; break
878
+ end
879
+ end
880
+ if not call then return false end
881
+ local name_token = call.name_token
882
+ local query = {}
883
+ for key, value in pairs(req) do query[key] = value end
884
+ query.position = doc:position(T.s[name_token] - 1)
885
+ local V, _, c, targets = at(query)
886
+ if not V or not c or c.decl then return false end
887
+ local signatures, seen = {}, {}
888
+ for _, id in ipairs(targets) do
889
+ local node = V.nodes[id]
890
+ local label = node.sig
891
+ if REFERENCE[node.kind] and label and not seen[label] then
892
+ local sig_doc = documents.new(uri_of(V, V.node_file[id]), label, 0)
893
+ local S = sig_doc:tokens()
894
+ local opening
895
+ for i = 1, S and S.n - 1 or 0 do
896
+ if S:text(i) == node.name and S:text(i + 1) == '(' then opening = i + 1; break end
897
+ end
898
+ local ending = opening and S.m[opening]
899
+ if ending then
900
+ local parameters, start, i, angle_depth = {}, S.e[opening] + 1, opening + 1, 0
901
+ while i <= ending do
902
+ local s = S:text(i)
903
+ if kotlin and S.k[i] == 'op' then
904
+ if s == '<' then angle_depth = angle_depth + 1
905
+ elseif s == '>' then angle_depth = math.max(0, angle_depth - 1) end
906
+ end
907
+ if i == ending or (s == ',' and angle_depth == 0) then
908
+ local parameter = label:sub(start, S.s[i] - 1):match('^%s*(.-)%s*$')
909
+ if parameter ~= '' and parameter ~= 'void' then parameters[#parameters + 1] = { label = parameter } end
910
+ start = S.e[i] + 1
911
+ elseif S.m[i] and S.m[i] > i then i = S.m[i] end
912
+ i = i + 1
913
+ end
914
+ signatures[#signatures + 1] = { label = label, parameters = parameters,
915
+ activeParameter = #parameters > 0 and math.min(call.argument, #parameters - 1) or nil }
916
+ seen[label] = true
917
+ end
918
+ end
919
+ end
920
+ if #signatures == 0 then return false end
921
+ return { signatures = signatures, activeSignature = 0, activeParameter = signatures[1].activeParameter }
922
+ end
923
+
924
+ function handlers.lsp_hover(req)
925
+ local V, doc, c, targets = at(req)
926
+ if not V or #targets == 0 then return false end
927
+ local parts = {}
928
+ for k, id in ipairs(targets) do
929
+ if k > M.MAX_HOVER then break end
930
+ local node, rec = V.nodes[id], V.files[V.node_file[id]]
931
+ parts[#parts + 1] = '```' .. (rec.language or '') .. '\n' .. (node.sig or node.qualified) .. '\n```'
932
+ parts[#parts + 1] = node.kind .. ' `' .. node.qualified .. '` — ' .. rec.path .. ':' .. node.line
933
+ end
934
+ return { contents = { kind = 'markdown', value = table.concat(parts, '\n\n') }, range = doc:range(c.first, c.last) }
935
+ end
936
+
937
+ function handlers.lsp_prepare_calls(req)
938
+ local V, _, _, targets = at(req)
939
+ if not V then return false end
940
+ local result = {}
941
+ for _, id in ipairs(targets) do
942
+ if CALLS[V.nodes[id].kind] then result[#result + 1] = item(V, id) end
943
+ end
944
+ return #result > 0 and result or false
945
+ end
946
+
947
+ local function positions_left(t0, incomplete)
948
+ return not incomplete and os.clock() - t0 <= M.POSITION_SECONDS
949
+ end
950
+
951
+ function handlers.lsp_incoming(req)
952
+ local V = view(req.session, req.root)
953
+ local id = relocate(V, req.data)
954
+ if not id then return {} end
955
+ local name = V.nodes[id].name
956
+ local hits, incomplete = scan(V, expand(V, { [id] = true }), name)
957
+ local result, groups, t0 = {}, {}, os.clock()
958
+ for _, hit in ipairs(hits) do
959
+ if not positions_left(t0, false) then incomplete = true; break end
960
+ local f, i = hit[1], hit[2]
961
+ local from = V.files[f].refs.from[i]
962
+ local key = f .. ':' .. from
963
+ local group = groups[key]
964
+ if not group then
965
+ group = { from = from > 0 and item(V, V.id_of[f][from]) or file_item(V, f), fromRanges = {} }
966
+ groups[key] = group
967
+ result[#result + 1] = group
968
+ end
969
+ local range = site_range(V, f, i)
970
+ if range then group.fromRanges[#group.fromRanges + 1] = range end
971
+ end
972
+ return result, incomplete
973
+ end
974
+
975
+ function handlers.lsp_outgoing(req)
976
+ local V = view(req.session, req.root)
977
+ local f = type(req.data) == 'table' and type(req.data.path) == 'string' and V.file_index[req.data.path]
978
+ if not f then return {} end
979
+ if not V.drafts[f] then
980
+ -- Reference positions of the calling file come from one exact reparse.
981
+ local doc = source_doc(V, f)
982
+ if doc then V.add(doc) end
983
+ end
984
+ local id
985
+ id, f = relocate(V, req.data)
986
+ if not f or (req.data.index ~= 0 and not id) then return {} end
987
+ local from = id and index_of(V, id) or 0
988
+ local refs = V.files[f].refs
989
+ local result, groups = {}, {}
990
+ for i = 1, #refs.name do
991
+ if i % 128 == 0 then control.check() end
992
+ if refs.from[i] == from then
993
+ for _, dst in ipairs(resolve_site(V, f, from, refs.name[i], refs.kind[i], refs.recv[i], refs.lua_binding and refs.lua_binding[i] or refs.js_receiver and refs.js_receiver[i])) do
994
+ local group = groups[dst]
995
+ if not group then
996
+ group = { to = item(V, dst), fromRanges = {} }
997
+ groups[dst] = group
998
+ result[#result + 1] = group
999
+ end
1000
+ local range = site_range(V, f, i)
1001
+ if range then group.fromRanges[#group.fromRanges + 1] = range end
1002
+ end
1003
+ end
1004
+ end
1005
+ return result
1006
+ end
1007
+
1008
+ function handlers.lsp_references(req)
1009
+ local V, _, c, targets = at(req)
1010
+ if not V or #targets == 0 then return {} end
1011
+ local set = {}
1012
+ for _, id in ipairs(targets) do
1013
+ if not REFERENCE[V.nodes[id].kind] then
1014
+ return { error = 'References currently support functions, methods, constructors and macros only' }
1015
+ end
1016
+ set[id] = true
1017
+ end
1018
+ set = expand(V, set)
1019
+ local name = V.files[V.node_file[targets[1]]].language == 'kotlin' and V.nodes[targets[1]].name or c.name
1020
+ local hits, incomplete = scan(V, set, name)
1021
+ local result, t0 = {}, os.clock()
1022
+ if req.includeDeclaration then
1023
+ for _, id in ipairs(sorted(set)) do result[#result + 1] = (location(V, id)) end
1024
+ end
1025
+ for _, hit in ipairs(hits) do
1026
+ if not positions_left(t0, false) then incomplete = true; break end
1027
+ local range = site_range(V, hit[1], hit[2])
1028
+ if range then result[#result + 1] = { uri = uri_of(V, hit[1]), range = range } end
1029
+ end
1030
+ return result, incomplete
1031
+ end
1032
+
1033
+ -- Shared with completion.lua, which registers its own handler.
1034
+ M.view, M.request_doc, M.deps, M.source_doc = view, request_doc, deps, source_doc
1035
+ function M.register(method, handler) handlers[method] = handler end
1036
+
1037
+ function M.handles(method) return handlers[method] ~= nil end
1038
+
1039
+ -- Returns { result = value (false for null), incomplete = bool } or { error = message }.
1040
+ function M.execute(req)
1041
+ local result, incomplete = handlers[req.method](req)
1042
+ if type(result) == 'table' and result.error then return result end
1043
+ return { result = result, incomplete = incomplete or false }
1044
+ end
1045
+
1046
+ return M