@codua/codeoutline-win32-x64 0.2.1 → 0.2.4

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.
@@ -89,7 +89,7 @@ local feature_of = { ['textDocument/documentSymbol'] = 'documentSymbol', ['works
89
89
  ['textDocument/completion'] = 'completion', ['textDocument/signatureHelp'] = 'signatureHelp' }
90
90
  local sessions = 0
91
91
 
92
- function M.new(config, emit, submit, cancel, stop)
92
+ function M.new(config, emit, submit, cancel, stop, await_worker)
93
93
  config = config or {}
94
94
  sessions = sessions + 1
95
95
  local self = { state = 'new', documents = {}, roots = {}, pending = {}, scans = {}, ready = {},
@@ -360,27 +360,41 @@ function M.new(config, emit, submit, cancel, stop)
360
360
  local doc = document(params)
361
361
  reply(id, doc and M.document_symbols(doc, self.hierarchical) or array())
362
362
  end
363
- -- One worker job per request; late results of cancelled requests are dropped.
364
- local function request(id, req, finish)
363
+ -- Callback transports remain usable by embedders/tests. Production LSP
364
+ -- supplies an RPC transport; both expose the same yielding interface.
365
+ await_worker = await_worker or function(req, started)
366
+ local co = assert(coroutine.running())
367
+ local waiting, completed, outcome, value = false, false, nil, nil
368
+ local id, err = submit(req, function(ok, result)
369
+ completed, outcome, value = true, ok, result
370
+ if waiting then assert(coroutine.resume(co)) end
371
+ end)
372
+ if not id then return false, err end
373
+ started(id)
374
+ if not completed then waiting = true; coroutine.yield() end
375
+ return outcome, value
376
+ end
377
+ -- Each query owns a coroutine; cancelled/replaced requests discard replies.
378
+ local function request(id, req, started)
365
379
  local count = 0
366
380
  for _ in pairs(self.pending) do count = count + 1 end
367
381
  assert(count < M.MAX_PENDING, 'too many pending requests')
368
- local job = {}
382
+ local job = { coroutine = coroutine.running() }
369
383
  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)
384
+ local called, ok, result = pcall(await_worker, req, function(job_id)
385
+ job.id = job_id
386
+ if started then started() end
378
387
  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)
388
+ if not called then result, ok = ok, false end
389
+ -- Even a cancelled request may fail before its drafts reach the worker.
390
+ if not ok and req.changed then self.synced = {} end
391
+ if self.pending[id] ~= job then return nil, false end
392
+ self.pending[id] = nil
393
+ if not ok then
394
+ error_response(id, -32603, tostring(result))
395
+ return nil, false
382
396
  end
383
- return job_id ~= nil
397
+ return result, true
384
398
  end
385
399
  handlers['workspace/symbol'] = function(id, params)
386
400
  assert(id ~= nil, 'symbol query must be a request')
@@ -406,11 +420,11 @@ function M.new(config, emit, submit, cancel, stop)
406
420
  for _, root in ipairs(self.roots) do
407
421
  if not self.ready[root] then reply(id, result); return end
408
422
  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)
423
+ local symbols, ok = request(id, { method = 'lsp_symbols', roots = self.roots, exclude = exclude,
424
+ query = params.query, limit = M.MAX_SYMBOLS - #result })
425
+ if not ok then return end
426
+ for _, symbol in ipairs(to_client(symbols)) do result[#result + 1] = symbol end
427
+ reply(id, result)
414
428
  end
415
429
  -- Navigation runs in the worker against the session's drafts: every request
416
430
  -- carries the open set and the text of versions the worker has not seen.
@@ -429,17 +443,18 @@ function M.new(config, emit, submit, cancel, stop)
429
443
  end
430
444
  req.session, req.open, req.changed = self.session, open, changed
431
445
  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
446
+ local value, ok = request(id, req, function()
447
+ -- Record submission before yielding so subsequent requests send only
448
+ -- newer drafts. The worker applies drafts even to cancelled jobs.
441
449
  for uri, version in pairs(sent) do self.synced[uri] = version end
450
+ end)
451
+ if not ok then return end
452
+ if value.error then error_response(id, -32803, value.error); return end
453
+ if value.incomplete then
454
+ emit({ jsonrpc = '2.0', method = 'window/showMessage', params = { type = 2,
455
+ message = 'CodeOutline: results were truncated; too many matching references' } })
442
456
  end
457
+ reply(id, to_client(finish(value.result)))
443
458
  end
444
459
  -- Worker results lose array metatables in transit; empty lists must stay JSON arrays.
445
460
  local function list(value) return array(value or nil) end
@@ -562,11 +577,20 @@ function M.new(config, emit, submit, cancel, stop)
562
577
  error_response(object(msg) and valid_id(msg.id) and msg.id or nil, -32600, 'Invalid JSON-RPC request'); return
563
578
  end
564
579
  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
580
+ local function handle()
581
+ local dispatched, err = pcall(dispatch, msg)
582
+ if not dispatched then
583
+ if msg.id ~= nil then error_response(msg.id, -32602, tostring(err))
584
+ else io.stderr:write('[codeoutline lsp] ', tostring(err), '\n') end
585
+ end
569
586
  end
587
+ -- Lifecycle and document notifications remain ordered on the main loop.
588
+ -- Queries run immediately up to their first wait, capturing that state.
589
+ if msg.id ~= nil and feature_of[msg.method] then
590
+ local co = coroutine.create(handle)
591
+ local resumed, err = coroutine.resume(co)
592
+ if not resumed then error_response(msg.id, -32603, tostring(err)) end
593
+ else handle() end
570
594
  end
571
595
  return self
572
596
  end
@@ -2,6 +2,22 @@
2
2
  local M = {}
3
3
  local control = require('codeoutline.control')
4
4
  local loaders = { require = true, dofile = true, loadfile = true }
5
+ local EXPORT_OWNER = '__exports'
6
+ -- Loader call at token j: a known loader name, or any dotted/plain name whose
7
+ -- last segment ends in `import` (`ks.import`, `skynet_import`). Returns the
8
+ -- kind recorded in lua_imports, the callee's last token, and the base name
9
+ -- used for shadow checks.
10
+ local function loader_call(T, j)
11
+ if T.k[j] ~= 'id' then return nil end
12
+ local k = j
13
+ while T.k[k + 1] == 'op' and T:text(k + 1) == '.' and T.k[k + 2] == 'id' do k = k + 2 end
14
+ local name = T:text(k)
15
+ if k == j and loaders[name] then return name, k, name end
16
+ if name:sub(-6) ~= 'import' then return nil end
17
+ local parts = {}
18
+ for x = j, k, 2 do parts[#parts + 1] = T:text(x) end
19
+ return table.concat(parts, '.'), k, T:text(j)
20
+ end
5
21
  local function literal(T, i)
6
22
  if T.k[i] ~= 'str' then return nil end
7
23
  local s = T:text(i)
@@ -15,9 +31,9 @@ function M.collect(r, T, bm)
15
31
  r.lua_imports, r.lua_exports, r.lua_locals = {}, {}, {}
16
32
  local scopes, stack, params, bindings = {}, {}, {}, {}
17
33
  for i = 1, T.n do
18
- if bm[i] and bm[i] > i then stack[#stack + 1] = i end
19
- scopes[i] = stack[#stack] or 0
20
34
  if stack[#stack] and bm[stack[#stack]] == i then stack[#stack] = nil end
35
+ scopes[i] = stack[#stack] or 0
36
+ if bm[i] and bm[i] > i then stack[#stack + 1] = i end
21
37
  if T:text(i) == 'function' and T.k[i] == 'kw' then
22
38
  local p = i + 1
23
39
  while p < (bm[i] or i) and T:text(p) ~= '(' do p = p + 1 end
@@ -37,19 +53,21 @@ function M.collect(r, T, bm)
37
53
  elseif prev == 'local' or (next == '=' and prev ~= '.' and prev ~= ':' and prev ~= '{' and prev ~= ',') then
38
54
  local hint = '?'
39
55
  if next == '=' and T:text(i + 2) == '{' then hint = 'lua-local:' .. T:text(i) end
40
- local imported = next == '=' and loaders[T:text(i + 2)]
41
- if next == '=' and loaders[T:text(i + 2)] then
42
- local kind, call = T:text(i + 2), i + 2
56
+ local kind, call, base
57
+ if next == '=' then kind, call, base = loader_call(T, i + 2) end
58
+ local imported = kind ~= nil
59
+ if kind then
43
60
  local arg = T:text(call + 1) == '(' and call + 2 or call + 1
44
61
  local path = literal(T, arg)
45
62
  local close = T:text(call + 1) == '(' and T.m[call + 1] or arg
46
- if close and ((close == arg) or (close == arg + 1)) and path then
63
+ if close and ((close == arg) or (close == arg + 1)
64
+ or (close > arg and T:text(arg + 1) == ',')) and path then
47
65
  -- A concatenation/operation after the loader is not its return value.
48
66
  local tail = T:text(close + 1)
49
67
  if tail ~= '..' and tail ~= '.' and tail ~= ':' and tail ~= 'or' and tail ~= 'and'
50
68
  and tail ~= '(' and tail ~= '[' and tail ~= '+' and tail ~= '-' and tail ~= '*' and tail ~= '/' then
51
69
  local shadowed = false
52
- for _, b in ipairs(bindings[kind] or {}) do
70
+ for _, b in ipairs(bindings[base] or {}) do
53
71
  if b.token < call and b.a <= call and b.b >= call then shadowed = true end
54
72
  end
55
73
  if not shadowed then
@@ -70,7 +88,7 @@ function M.collect(r, T, bm)
70
88
  if b.hint:match('^lua%-local:') then
71
89
  local members = {}
72
90
  for index, n in ipairs(r.nodes) do
73
- local scope = T:text(n.ti) == 'function' and scopes[n.ti - 1] or scopes[n.ti]
91
+ local scope = scopes[n.ti]
74
92
  if n.ti >= b.token and n.ti <= b.b and scope == b.a
75
93
  and (n.qualified == name .. '.' .. n.name or n.qualified == name .. ':' .. n.name) then members[n.name] = index end
76
94
  end
@@ -91,21 +109,88 @@ function M.collect(r, T, bm)
91
109
  end
92
110
  end
93
111
 
112
+ local function alias(into, key, target)
113
+ for index, n in ipairs(r.nodes) do
114
+ if not n.parent and n.name == target and n.qualified == target and (n.kind == 'function' or n.kind == 'method') then
115
+ into[key] = index
116
+ end
117
+ end
118
+ end
119
+ -- A global alias is a statement of its own: the right-hand side is a bare
120
+ -- identifier and nothing but a separator follows it on that line. The key
121
+ -- is dotted (`g_exports.name`) or a literal (`g_exports['name']`).
122
+ local globals = {}
123
+ for i = 1, T.n - 4 do
124
+ if i % 4096 == 0 then control.check() end
125
+ local owner = T:text(i)
126
+ if T.k[i] == 'id' and not bindings[owner] and T:text(i - 1) ~= '.' and T:text(i - 1) ~= ':' then
127
+ local key, eq
128
+ if T:text(i + 1) == '.' and T.k[i + 2] == 'id' then key, eq = T:text(i + 2), i + 3
129
+ elseif T:text(i + 1) == '[' and T.m[i + 1] == i + 3 and T.k[i + 2] == 'str' then key, eq = literal(T, i + 2), i + 4 end
130
+ local target = key and T:text(eq) == '=' and T.k[eq + 1] == 'id' and T:text(eq + 1)
131
+ if key and T:text(eq) == '=' then
132
+ globals[owner] = globals[owner] or {}
133
+ globals[owner][key] = nil
134
+ end
135
+ if target and target ~= key and (T.l[eq + 2] ~= T.l[eq + 1] or T:text(eq + 2) == ';') then
136
+ alias(globals[owner], key, target)
137
+ end
138
+ end
139
+ end
140
+ -- Keep candidates independent of project configuration, including in caches.
141
+ for owner, exports in pairs(globals) do
142
+ for name, index in pairs(exports) do
143
+ local node = r.nodes[index]
144
+ node.lua_aliases = node.lua_aliases or {}
145
+ node.lua_aliases[owner] = node.lua_aliases[owner] or {}
146
+ node.lua_aliases[owner][#node.lua_aliases[owner] + 1] = name
147
+ end
148
+ end
94
149
  -- A single unconditional top-level return is the supported module contract.
150
+ -- Files with no module-level return may use the `__exports` contract below;
151
+ -- conditional or multiple returns invalidate both contracts. Function depth
152
+ -- comes from token blocks, so returns inside anonymous callbacks (which are
153
+ -- not nodes) do not pose as module-level returns.
154
+ local fn_close, depth = {}, 0
155
+ for i = 1, T.n do
156
+ if T.k[i] == 'kw' and T:text(i) == 'function' and bm[i] then fn_close[bm[i]] = true end
157
+ end
95
158
  local ret
96
159
  for i = 1, T.n do
97
- if T:text(i) == 'return' and T.k[i] == 'kw' then
98
- local in_function = false
99
- for _, n in ipairs(r.nodes) do
100
- if (n.kind == 'function' or n.kind == 'method') and n.ti <= i and n.tj >= i then in_function = true; break end
160
+ if T.k[i] == 'kw' and T:text(i) == 'function' then depth = depth + 1 end
161
+ if T:text(i) == 'return' and T.k[i] == 'kw' and depth == 0 then
162
+ if ret or scopes[i] ~= 0 then ret = false else ret = i end
163
+ end
164
+ if fn_close[i] then depth = depth - 1 end
165
+ if ret == false then break end
166
+ end
167
+ if not ret then
168
+ -- Return-less module (kslua-style): top-level `__exports` members are the
169
+ -- contract, unless the file defines `__exports` itself.
170
+ if ret == false or bindings[EXPORT_OWNER] and #bindings[EXPORT_OWNER] > 0 then return end
171
+ local count = 0
172
+ for _, n in ipairs(r.nodes) do
173
+ if not n.parent and (n.kind == 'function' or n.kind == 'method')
174
+ and (n.qualified == EXPORT_OWNER .. '.' .. n.name or n.qualified == EXPORT_OWNER .. ':' .. n.name) then
175
+ count = count + 1
101
176
  end
102
- if not in_function then
103
- if ret or scopes[i] ~= 0 then r.lua_exports = {}; return end
104
- ret = i
177
+ end
178
+ if count == 0 then return end
179
+ for index, n in ipairs(r.nodes) do
180
+ if not n.parent and (n.kind == 'function' or n.kind == 'method')
181
+ and (n.qualified == EXPORT_OWNER .. '.' .. n.name or n.qualified == EXPORT_OWNER .. ':' .. n.name) then
182
+ r.lua_exports[n.name] = index
183
+ end
184
+ end
185
+ for i = 1, T.n - 4 do
186
+ if scopes[i] == 0 and T.k[i] == 'id' and T:text(i) == EXPORT_OWNER and T:text(i + 1) == '.' and T.k[i + 2] == 'id'
187
+ and T:text(i + 3) == '=' and T:text(i + 4) ~= 'function' then
188
+ r.lua_exports[T:text(i + 2)] = nil
189
+ if T.k[i + 4] == 'id' and (T.l[i + 5] ~= T.l[i + 4] or T:text(i + 5) == ';') then alias(r.lua_exports, T:text(i + 2), T:text(i + 4)) end
105
190
  end
106
191
  end
192
+ return
107
193
  end
108
- if not ret then return end
109
194
  local owner, table_start
110
195
  if T.k[ret + 1] == 'id' and (ret + 1 == T.n or T:text(ret + 2) == ';') then
111
196
  owner = T:text(ret + 1)
@@ -121,23 +206,17 @@ function M.collect(r, T, bm)
121
206
  for i = table_start + 1, ret - 1 do
122
207
  if scopes[i] == 0 and T:text(i) == owner and T:text(i + 1) == '=' then r.lua_exports = {}; return end
123
208
  end
209
+ r.lua_owner = owner
124
210
  for index, n in ipairs(r.nodes) do
125
211
  if not n.parent and n.ti >= table_start and (n.qualified == owner .. '.' .. n.name or n.qualified == owner .. ':' .. n.name)
126
212
  and (n.kind == 'function' or n.kind == 'method') then r.lua_exports[n.name] = index end
127
213
  end
128
214
  end
129
- local function alias(key, target)
130
- for index, n in ipairs(r.nodes) do
131
- if not n.parent and n.name == target and n.qualified == target and (n.kind == 'function' or n.kind == 'method') then
132
- r.lua_exports[key] = index
133
- end
134
- end
135
- end
136
215
  if table_start then
137
216
  local i, close = table_start + 1, T.m[table_start]
138
217
  while i < close do
139
218
  if T.k[i] == 'id' and T:text(i + 1) == '=' and T.k[i + 2] == 'id'
140
- and (T:text(i + 3) == ',' or T:text(i + 3) == ';' or i + 3 == close) then alias(T:text(i), T:text(i + 2)) end
219
+ and (T:text(i + 3) == ',' or T:text(i + 3) == ';' or i + 3 == close) then alias(r.lua_exports, T:text(i), T:text(i + 2)) end
141
220
  if T.m[i] and T.m[i] > i then i = T.m[i]
142
221
  elseif bm[i] and bm[i] > i then i = bm[i] end
143
222
  i = i + 1
@@ -147,7 +226,7 @@ function M.collect(r, T, bm)
147
226
  if scopes[i] == 0 and T:text(i) == owner and T:text(i + 1) == '.' and T.k[i + 2] == 'id'
148
227
  and T:text(i + 3) == '=' and T:text(i + 4) ~= 'function' then
149
228
  r.lua_exports[T:text(i + 2)] = nil
150
- if T.k[i + 4] == 'id' and (T.l[i + 5] ~= T.l[i + 4] or T:text(i + 5) == ';') then alias(T:text(i + 2), T:text(i + 4)) end
229
+ if T.k[i + 4] == 'id' and (T.l[i + 5] ~= T.l[i + 4] or T:text(i + 5) == ';') then alias(r.lua_exports, T:text(i + 2), T:text(i + 4)) end
151
230
  end
152
231
  end
153
232
  end
@@ -161,13 +240,26 @@ local function normalize(p)
161
240
  return table.concat(parts, '/')
162
241
  end
163
242
  function M.context(G)
164
- local ctx = { directory = '', modules = {} }
243
+ local ctx = { directory = '', modules = {}, global_export_tables = { 'g_exports' } }
165
244
  local f = G.root and io.open(G.root .. '/.codeoutline.json', 'rb')
166
245
  if f then
167
246
  local raw = f:read(65537); f:close()
168
247
  assert(#raw <= 65536, '.codeoutline.json exceeds 64 KiB')
169
248
  local ok, config = pcall(xutils.json_unpack, raw)
170
249
  assert(ok and type(config) == 'table', 'invalid .codeoutline.json')
250
+ local owners = config.luaGlobalExportTables
251
+ if owners ~= nil then
252
+ assert(type(owners) == 'table', 'luaGlobalExportTables must be an array of Lua identifiers')
253
+ local seen, names = {}, {}
254
+ for key, name in pairs(owners) do
255
+ assert(type(key) == 'number' and key >= 1 and key <= #owners and key % 1 == 0
256
+ and type(name) == 'string' and name:match('^[%a_][%w_]*$'),
257
+ 'luaGlobalExportTables must be an array of Lua identifiers')
258
+ if not seen[name] then names[#names + 1], seen[name] = name, true end
259
+ end
260
+ table.sort(names)
261
+ ctx.global_export_tables = names
262
+ end
171
263
  local value = config.luaRuntimeDirectory
172
264
  if value ~= nil then
173
265
  assert(type(value) == 'string' and not value:match('^[/\\]') and not value:find(':', 1, true), 'luaRuntimeDirectory must be project-relative')
@@ -177,12 +269,25 @@ function M.context(G)
177
269
  end
178
270
  return ctx
179
271
  end
272
+ -- Project-selected aliases share the normal name index and overlay path.
273
+ local EMPTY = {}
274
+ function M.aliases(node, owners)
275
+ if not node.lua_aliases then return EMPTY end
276
+ local names, seen = {}, {}
277
+ for _, owner in ipairs(owners) do
278
+ for _, name in ipairs((node.lua_aliases or {})[owner] or {}) do
279
+ if not seen[name] then names[#names + 1], seen[name] = name, true end
280
+ end
281
+ end
282
+ return names
283
+ end
180
284
  function M.modules(G, imp, ctx)
181
285
  ctx = ctx or M.context(G)
182
286
  local key = imp.kind .. '\0' .. imp.path
183
287
  if ctx.modules[key] then return ctx.modules[key] end
184
288
  local result = {}
185
289
  if imp.kind == 'require' then
290
+ for _, f in ipairs(M.native_modules(G, imp.path, ctx)) do result[#result + 1] = f end
186
291
  local sub = imp.path:gsub('%.', '/')
187
292
  for _, want in ipairs({ sub .. '.lua', sub .. '/init.lua' }) do
188
293
  local candidates = {}
@@ -197,12 +302,43 @@ function M.modules(G, imp, ctx)
197
302
  local path = normalize(ctx.directory .. '/' .. imp.path)
198
303
  local f = G.file_index[path]
199
304
  if f and G.files[f].language == 'lua' then result[1] = f end
305
+ if not result[1] and not loaders[imp.kind] then
306
+ -- `*import` pattern loader: bind when any indexed Lua file's path
307
+ -- ends with the quoted path, regardless of directory prefix.
308
+ local want = normalize(imp.path)
309
+ local base = want:match('([^/]+)$')
310
+ if base then
311
+ local candidates, seen = {}, {}
312
+ for _, g in ipairs(G.by_base[base] or {}) do candidates[#candidates + 1] = g end
313
+ for _, g in ipairs(G.new_files or {}) do candidates[#candidates + 1] = g end
314
+ for _, g in ipairs(candidates) do
315
+ local rec = G.files[g]
316
+ if rec and rec.language == 'lua' and not seen[g]
317
+ and (rec.path == want or rec.path:sub(-#want - 1) == '/' .. want) then
318
+ seen[g] = true
319
+ result[#result + 1] = g
320
+ end
321
+ end
322
+ end
323
+ end
200
324
  end
201
325
  ctx.modules[key] = result
202
326
  return result
203
327
  end
204
- function M.resolve(G, f, name, hint, ctx)
205
- if G.files[f].language ~= 'lua' or not hint or hint == '' then return nil end
328
+ function M.native_modules(G, name, ctx)
329
+ return require('codeoutline.foreign').modules(G, 'lua', name, ctx)
330
+ end
331
+
332
+ function M.resolve(G, f, name, hint, ctx, recv)
333
+ if G.files[f].language ~= 'lua' then return nil end
334
+ if not hint or hint == '' then
335
+ local result = {}
336
+ for _, target in ipairs(M.native_modules(G, recv, ctx)) do
337
+ local n = require('codeoutline.foreign').exports(G.files[target], 'lua', recv)[name]
338
+ if n then result[#result + 1] = G.id_of[target][n] end
339
+ end
340
+ return #result > 0 and result or nil
341
+ end
206
342
  if hint == '?' then return {} end
207
343
  local local_index = tonumber(hint:match('^lua%-local:(%d+)$'))
208
344
  if local_index then
@@ -214,7 +350,9 @@ function M.resolve(G, f, name, hint, ctx)
214
350
  if not imp then return nil end
215
351
  local result = {}
216
352
  for _, target in ipairs(M.modules(G, imp, ctx)) do
217
- local n = (G.files[target].lua_exports or {})[name]
353
+ local rec = G.files[target]
354
+ local exports = require('codeoutline.foreign').exports(rec, 'lua', imp.path) or rec.lua_exports
355
+ local n = (exports or {})[name]
218
356
  if n then result[#result + 1] = G.id_of[target][n] end
219
357
  end
220
358
  return result
@@ -77,6 +77,21 @@ local function submit(req, done)
77
77
  return id
78
78
  end
79
79
  local function cancel(id) if id and jobs[id] then shared:set('cancel:' .. id, true) end end
80
+ -- LSP queries wait in their own coroutine. MCP and background refresh jobs
81
+ -- retain the callback/post transport above.
82
+ local function await_worker(req, started)
83
+ if job_count >= 64 then return false, 'Request queue is full; retry later' end
84
+ next_id = next_id + 1
85
+ local id = tostring(next_id)
86
+ req.deadline = xtimer.now_ms() + 120000
87
+ jobs[id], job_count = { request = req, rpc = true, waiter = coroutine.running() }, job_count + 1
88
+ started(id)
89
+ if not worker_ready then coroutine.yield() end
90
+ local called, ok, result = pcall(xthread.rpc, 2, 'run_rpc', math.max(1, req.deadline - xtimer.now_ms()), id, req)
91
+ jobs[id], job_count = nil, job_count - 1
92
+ if not called then return false, tostring(ok) end
93
+ return ok, result
94
+ end
80
95
  local function send(response)
81
96
  if response then
82
97
  io.stdout:write(lsp_mode and lsp.frame(response) or (xutils.json_pack(response) .. '\n'))
@@ -119,7 +134,8 @@ return {
119
134
  assert(xutils.read_stdin, 'Rebuild runtime for nonblocking stdin support')
120
135
  if lsp_mode then
121
136
  assert(xutils.stdout_binary and xutils.stdout_binary(), 'Rebuild runtime for binary stdout support')
122
- stdio = lsp.new(config, send, submit, cancel, stop)
137
+ xtimer.init(16) -- RPC deadlines use the runtime's timer callbacks.
138
+ stdio = lsp.new(config, send, submit, cancel, stop, await_worker)
123
139
  else stdio = mcp.new(config, submit, cancel) end
124
140
  else
125
141
  -- Packages ship the codec as lib/xhttp_codec.lua; a source checkout
@@ -150,8 +166,13 @@ return {
150
166
  table.sort(waiting, function(a, b) return tonumber(a) < tonumber(b) end)
151
167
  for _, job_id in ipairs(waiting) do
152
168
  local job = jobs[job_id]
153
- local posted, err = xthread.post(2, 'run', job_id, job.request)
154
- if not posted then jobs[job_id], job_count = nil, job_count - 1; job.done(false, tostring(err)) end
169
+ if job.rpc then
170
+ local resumed, err = coroutine.resume(job.waiter)
171
+ if not resumed then error(err) end
172
+ else
173
+ local posted, err = xthread.post(2, 'run', job_id, job.request)
174
+ if not posted then jobs[job_id], job_count = nil, job_count - 1; job.done(false, tostring(err)) end
175
+ end
155
176
  end
156
177
  elseif op == 'worker_result' then
157
178
  local job = jobs[id]
@@ -1,5 +1,6 @@
1
1
  local paths = require('codeoutline.path')
2
2
  local explore = require('codeoutline.explore')
3
+ local callers = require('codeoutline.callers')
3
4
  local text = require('codeoutline.text')
4
5
  local version = require('codeoutline.version')
5
6
  local M = { VERSION = '2025-06-18' }
@@ -9,6 +10,13 @@ local function object(t) return type(t) == 'table' and getmetatable(t) ~= xutils
9
10
  local project = { type = 'string', minLength = 1,
10
11
  description = 'Project directory on the server machine; defaults to PROJECT, the first client root, then the stdio working directory.' }
11
12
  M.tools = array({
13
+ { name = 'codeoutline_callers', description = 'Find potential callers recursively, with shortest call paths and affected files. Matches an exact symbol or qualified name; defaults to 3 levels. Refreshes automatically.',
14
+ inputSchema = { type = 'object', properties = { projectPath = project,
15
+ query = { type = 'string', minLength = 1, maxLength = 4096 },
16
+ depth = { type = 'integer', minimum = 1, maximum = 8, default = 3 },
17
+ max_nodes = { type = 'integer', minimum = 1, maximum = 2000, default = 200 },
18
+ budget = { type = 'integer', minimum = 256, maximum = 262144, default = 16000 } },
19
+ required = array({ 'query' }), additionalProperties = false } },
12
20
  { name = 'codeoutline_explore', description = 'Query symbols, line-numbered source, call paths and neighbors. Refreshes automatically.',
13
21
  inputSchema = { type = 'object', properties = { projectPath = project,
14
22
  query = { type = 'string', minLength = 1, maxLength = 4096 },
@@ -146,8 +154,9 @@ function M.new(config, submit, cancel)
146
154
  if args.projectPath ~= nil and (type(args.projectPath) ~= 'string' or args.projectPath == '') then
147
155
  error_result(-32602, 'projectPath must be a non-empty string'); return
148
156
  end
149
- if tool.name == 'codeoutline_explore' then
150
- local ok, err = pcall(explore.validate, args.query, { budget = args.budget })
157
+ if tool.name == 'codeoutline_explore' or tool.name == 'codeoutline_callers' then
158
+ local engine = tool.name == 'codeoutline_callers' and callers or explore
159
+ local ok, err = pcall(engine.validate, args.query, { budget = args.budget, depth = args.depth, max_nodes = args.max_nodes })
151
160
  if not ok then error_result(-32602, tostring(err)); return end
152
161
  end
153
162
  local token = object(params._meta) and params._meta.progressToken or nil
@@ -166,10 +175,10 @@ function M.new(config, submit, cancel)
166
175
  result({ content = array({ { type = 'text', text = err or 'projectPath is outside allowed roots' } }), isError = true }); return
167
176
  end
168
177
  local job, submit_error = submit({ method = tool.name:sub(#'codeoutline_' + 1), projectPath = root,
169
- allowedRoots = config.roots, query = args.query, budget = args.budget }, function(ok, value)
178
+ allowedRoots = config.roots, query = args.query, budget = args.budget, depth = args.depth, max_nodes = args.max_nodes }, function(ok, value)
170
179
  if self.pending[id] ~= p then return end
171
180
  self.pending[id] = nil
172
- local output = ok and (tool.name == 'codeoutline_explore' and value.text or xutils.json_pack(value)) or tostring(value)
181
+ local output = ok and ((tool.name == 'codeoutline_explore' or tool.name == 'codeoutline_callers') and value.text or xutils.json_pack(value)) or tostring(value)
173
182
  result({ content = array({ { type = 'text', text = text.valid(output) } }), isError = not ok })
174
183
  end)
175
184
  p.job = job
@@ -109,6 +109,10 @@ local function view(session, root)
109
109
  local list = added[node.name]
110
110
  if not list then list = {}; added[node.name] = list end
111
111
  list[#list + 1] = id
112
+ for _, alias in ipairs(require('codeoutline.lua_bindings').aliases(node, V.lua_global_export_tables)) do
113
+ added[alias] = added[alias] or {}
114
+ added[alias][#added[alias] + 1] = id
115
+ end
112
116
  end
113
117
  return f
114
118
  end
@@ -408,6 +412,10 @@ end
408
412
  -- Hot names can match thousands of files; past the budget the scan stops.
409
413
  local function scan(V, targets, name)
410
414
  local hits, deadline = {}, os.clock() + M.SCAN_SECONDS
415
+ local wanted = { [name] = true }
416
+ for id in pairs(targets) do
417
+ for _, alias in ipairs(require('codeoutline.lua_bindings').aliases(V.nodes[id], V.lua_global_export_tables)) do wanted[alias] = true end
418
+ end
411
419
  local files = {}
412
420
  for i, f in ipairs(V.file_order) do files[i] = f end
413
421
  for _, f in ipairs(V.new_files) do files[#files + 1] = f end
@@ -424,7 +432,7 @@ local function scan(V, targets, name)
424
432
  end
425
433
  for i = 1, #names do
426
434
  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
435
+ if wanted[names[i]] or aliases[names[i]] or aliases[refs.recv[i]] or (refs.lua_binding and refs.lua_binding[i] ~= '') then
428
436
  if os.clock() > deadline then return hits, true end
429
437
  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
438
  if targets[dst] then hits[#hits + 1] = { f, i }; break end
@@ -887,8 +895,13 @@ function handlers.lsp_signature(req)
887
895
  local signatures, seen = {}, {}
888
896
  for _, id in ipairs(targets) do
889
897
  local node = V.nodes[id]
898
+ local foreign = require('codeoutline.foreign').signature(node, doc:parse().language, T:text(name_token))
890
899
  local label = node.sig
891
- if REFERENCE[node.kind] and label and not seen[label] then
900
+ if foreign and not seen[foreign.label] then
901
+ foreign.activeParameter = #foreign.parameters > 0 and math.min(call.argument, #foreign.parameters - 1) or nil
902
+ signatures[#signatures + 1] = foreign
903
+ seen[foreign.label] = true
904
+ elseif not foreign and REFERENCE[node.kind] and label and not seen[label] then
892
905
  local sig_doc = documents.new(uri_of(V, V.node_file[id]), label, 0)
893
906
  local S = sig_doc:tokens()
894
907
  local opening
@@ -928,7 +941,9 @@ function handlers.lsp_hover(req)
928
941
  for k, id in ipairs(targets) do
929
942
  if k > M.MAX_HOVER then break end
930
943
  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```'
944
+ local foreign = require('codeoutline.foreign').signature(node, doc:parse().language, doc.source:sub(c.first + 1, c.last))
945
+ parts[#parts + 1] = '```' .. (foreign and doc:parse().language or rec.language or '') .. '\n'
946
+ .. (foreign and foreign.label or node.sig or node.qualified) .. '\n```'
932
947
  parts[#parts + 1] = node.kind .. ' `' .. node.qualified .. '` — ' .. rec.path .. ':' .. node.line
933
948
  end
934
949
  return { contents = { kind = 'markdown', value = table.concat(parts, '\n\n') }, range = doc:range(c.first, c.last) }
@@ -49,6 +49,8 @@ function M.parse_tokens(path, src, opts)
49
49
  end
50
50
 
51
51
  -- opts.ranges=false emits compact index nodes; default parsing retains positions.
52
+ -- opts.dispatch_only=true is transient query data, not an index record: it
53
+ -- retains parser nodes/refs and skips binding evidence and record packing.
52
54
  function M.parse(path, src, opts)
53
55
  return (M.parse_tokens(path, src, opts))
54
56
  end
@@ -0,0 +1,36 @@
1
+ -- Bounded, query-owned explanations; never stored on index records.
2
+ local M = {}
3
+
4
+ function M.new(limit)
5
+ local report = { entries = {}, truncated = false, scope = 'indexed references and configured dispatch rules' }
6
+ local seen = {}
7
+ function report:add(entry)
8
+ local key = table.concat({ entry.source or '', entry.target or '', entry.line or '',
9
+ entry.kind or '', entry.reason or '', entry.rule or '', entry.call or '' }, ':')
10
+ if seen[key] then return end
11
+ if #self.entries >= (limit or 64) then self.truncated = true; return end
12
+ seen[key] = true
13
+ self.entries[#self.entries + 1] = entry
14
+ end
15
+ return report
16
+ end
17
+
18
+ function M.render(report, G)
19
+ local lines = { '\n## Relationship evidence / unresolved references',
20
+ 'Scope: indexed references and configured dispatch rules; unresolved does not mean no runtime call.' }
21
+ for _, e in ipairs(report.entries) do
22
+ local source = G.nodes[e.source]
23
+ local path = source and G.files[G.node_file[e.source]].path or '?'
24
+ local target = e.target and G.nodes[e.target].qualified
25
+ local detail = e.reason or e.kind
26
+ if e.call then detail = detail .. ' via ' .. e.call end
27
+ if e.rule then detail = detail .. ' (rule #' .. e.rule .. ', argument ' .. e.argument .. ')' end
28
+ if e.registered_at then detail = detail .. '; registered at ' .. e.registered_at end
29
+ lines[#lines + 1] = string.format('- %s:%d %s%s: %s', path, e.line or 0,
30
+ source and source.qualified or '?', target and ' -> ' .. target or '', detail)
31
+ end
32
+ if report.truncated then lines[#lines + 1] = 'Evidence limit reached; additional explanations omitted.' end
33
+ return table.concat(lines, '\n')
34
+ end
35
+
36
+ return M