@codua/codeoutline-win32-x64 0.2.0 → 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
@@ -0,0 +1,360 @@
1
+ -- Static Lua module return bindings. Never execute indexed source.
2
+ local M = {}
3
+ local control = require('codeoutline.control')
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
21
+ local function literal(T, i)
22
+ if T.k[i] ~= 'str' then return nil end
23
+ local s = T:text(i)
24
+ local long = s:match('^%[(=*)%[')
25
+ if long then return s:sub(#long + 3, -#long - 3):gsub('^\r?\n', '', 1) end
26
+ if s:find('\\', 1, true) then return nil end
27
+ return s:sub(2, -2)
28
+ end
29
+
30
+ function M.collect(r, T, bm)
31
+ r.lua_imports, r.lua_exports, r.lua_locals = {}, {}, {}
32
+ local scopes, stack, params, bindings = {}, {}, {}, {}
33
+ for i = 1, T.n do
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
37
+ if T:text(i) == 'function' and T.k[i] == 'kw' then
38
+ local p = i + 1
39
+ while p < (bm[i] or i) and T:text(p) ~= '(' do p = p + 1 end
40
+ for j = p + 1, (T.m[p] or p) - 1 do if T.k[j] == 'id' then params[j] = i end end
41
+ end
42
+ end
43
+ local function add(name, token, scope, hint, imported)
44
+ bindings[name] = bindings[name] or {}
45
+ bindings[name][#bindings[name] + 1] = { token = token, a = scope, b = bm[scope] or T.n, hint = hint, imported = imported }
46
+ end
47
+ for i = 1, T.n do
48
+ if i % 4096 == 0 then control.check() end
49
+ if T.k[i] == 'id' then
50
+ local prev, next = T:text(i - 1), T:text(i + 1)
51
+ if params[i] then add(T:text(i), i, params[i], '?')
52
+ elseif prev == 'function' and T:text(i - 2) == 'local' then add(T:text(i), i, scopes[i - 2], '')
53
+ elseif prev == 'local' or (next == '=' and prev ~= '.' and prev ~= ':' and prev ~= '{' and prev ~= ',') then
54
+ local hint = '?'
55
+ if next == '=' and T:text(i + 2) == '{' then hint = 'lua-local:' .. T:text(i) end
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
60
+ local arg = T:text(call + 1) == '(' and call + 2 or call + 1
61
+ local path = literal(T, arg)
62
+ local close = T:text(call + 1) == '(' and T.m[call + 1] or arg
63
+ if close and ((close == arg) or (close == arg + 1)
64
+ or (close > arg and T:text(arg + 1) == ',')) and path then
65
+ -- A concatenation/operation after the loader is not its return value.
66
+ local tail = T:text(close + 1)
67
+ if tail ~= '..' and tail ~= '.' and tail ~= ':' and tail ~= 'or' and tail ~= 'and'
68
+ and tail ~= '(' and tail ~= '[' and tail ~= '+' and tail ~= '-' and tail ~= '*' and tail ~= '/' then
69
+ local shadowed = false
70
+ for _, b in ipairs(bindings[base] or {}) do
71
+ if b.token < call and b.a <= call and b.b >= call then shadowed = true end
72
+ end
73
+ if not shadowed then
74
+ r.lua_imports[#r.lua_imports + 1] = { path = path, kind = kind }
75
+ hint = 'lua:' .. #r.lua_imports
76
+ if kind == 'loadfile' then hint = '?' end
77
+ end
78
+ end
79
+ end
80
+ end
81
+ -- Keep ordinary local function/table lookup; block unknown imported receivers.
82
+ add(T:text(i), i, scopes[i], hint, imported)
83
+ end
84
+ end
85
+ end
86
+ for name, list in pairs(bindings) do
87
+ for _, b in ipairs(list) do
88
+ if b.hint:match('^lua%-local:') then
89
+ local members = {}
90
+ for index, n in ipairs(r.nodes) do
91
+ local scope = scopes[n.ti]
92
+ if n.ti >= b.token and n.ti <= b.b and scope == b.a
93
+ and (n.qualified == name .. '.' .. n.name or n.qualified == name .. ':' .. n.name) then members[n.name] = index end
94
+ end
95
+ r.lua_locals[#r.lua_locals + 1] = members
96
+ b.hint = 'lua-local:' .. #r.lua_locals
97
+ end
98
+ end
99
+ end
100
+ for _, ref in ipairs(r.refs) do
101
+ do
102
+ local best
103
+ for _, b in ipairs(bindings[ref.recv or ref.name] or {}) do
104
+ if b.token <= ref.tok and b.a <= ref.tok and b.b >= ref.tok
105
+ and (not best or b.a > best.a or (b.a == best.a and b.token > best.token)) then best = b end
106
+ end
107
+ if best and (ref.recv or best.imported) then ref.lua_binding = ref.recv and best.hint or '?' end
108
+ if ref.recv and (T:text(ref.tok - 3) == '.' or T:text(ref.tok - 3) == ':') then ref.lua_binding = '?' end
109
+ end
110
+ end
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
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
158
+ local ret
159
+ for i = 1, T.n do
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
176
+ end
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
190
+ end
191
+ end
192
+ return
193
+ end
194
+ local owner, table_start
195
+ if T.k[ret + 1] == 'id' and (ret + 1 == T.n or T:text(ret + 2) == ';') then
196
+ owner = T:text(ret + 1)
197
+ for i = 1, ret - 1 do
198
+ if T:text(i) == owner and T:text(i + 1) == '=' and T:text(i + 2) == '{' and scopes[i] == 0 then table_start = i + 2 end
199
+ end
200
+ elseif T:text(ret + 1) == '{' and T.m[ret + 1] then
201
+ table_start = ret + 1
202
+ owner = r.path:match('([^/\\]+)%.lua$') or r.path
203
+ else return end
204
+ if owner then
205
+ if not table_start or not T.m[table_start] then return end
206
+ for i = table_start + 1, ret - 1 do
207
+ if scopes[i] == 0 and T:text(i) == owner and T:text(i + 1) == '=' then r.lua_exports = {}; return end
208
+ end
209
+ r.lua_owner = owner
210
+ for index, n in ipairs(r.nodes) do
211
+ if not n.parent and n.ti >= table_start and (n.qualified == owner .. '.' .. n.name or n.qualified == owner .. ':' .. n.name)
212
+ and (n.kind == 'function' or n.kind == 'method') then r.lua_exports[n.name] = index end
213
+ end
214
+ end
215
+ if table_start then
216
+ local i, close = table_start + 1, T.m[table_start]
217
+ while i < close do
218
+ if T.k[i] == 'id' and T:text(i + 1) == '=' and T.k[i + 2] == 'id'
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
220
+ if T.m[i] and T.m[i] > i then i = T.m[i]
221
+ elseif bm[i] and bm[i] > i then i = bm[i] end
222
+ i = i + 1
223
+ end
224
+ end
225
+ for i = 1, ret - 1 do
226
+ if scopes[i] == 0 and T:text(i) == owner and T:text(i + 1) == '.' and T.k[i + 2] == 'id'
227
+ and T:text(i + 3) == '=' and T:text(i + 4) ~= 'function' then
228
+ r.lua_exports[T:text(i + 2)] = nil
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
230
+ end
231
+ end
232
+ end
233
+
234
+ local function normalize(p)
235
+ local parts = {}
236
+ for s in p:gsub('\\', '/'):gmatch('[^/]+') do
237
+ if s == '..' and #parts > 0 and parts[#parts] ~= '..' then parts[#parts] = nil
238
+ elseif s ~= '.' then parts[#parts + 1] = s end
239
+ end
240
+ return table.concat(parts, '/')
241
+ end
242
+ function M.context(G)
243
+ local ctx = { directory = '', modules = {}, global_export_tables = { 'g_exports' } }
244
+ local f = G.root and io.open(G.root .. '/.codeoutline.json', 'rb')
245
+ if f then
246
+ local raw = f:read(65537); f:close()
247
+ assert(#raw <= 65536, '.codeoutline.json exceeds 64 KiB')
248
+ local ok, config = pcall(xutils.json_unpack, raw)
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
263
+ local value = config.luaRuntimeDirectory
264
+ if value ~= nil then
265
+ assert(type(value) == 'string' and not value:match('^[/\\]') and not value:find(':', 1, true), 'luaRuntimeDirectory must be project-relative')
266
+ ctx.directory = normalize(value)
267
+ assert(not ctx.directory:match('^%.%.'), 'luaRuntimeDirectory must stay inside project')
268
+ end
269
+ end
270
+ return ctx
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
284
+ function M.modules(G, imp, ctx)
285
+ ctx = ctx or M.context(G)
286
+ local key = imp.kind .. '\0' .. imp.path
287
+ if ctx.modules[key] then return ctx.modules[key] end
288
+ local result = {}
289
+ if imp.kind == 'require' then
290
+ for _, f in ipairs(M.native_modules(G, imp.path, ctx)) do result[#result + 1] = f end
291
+ local sub = imp.path:gsub('%.', '/')
292
+ for _, want in ipairs({ sub .. '.lua', sub .. '/init.lua' }) do
293
+ local candidates = {}
294
+ for _, f in ipairs(G.by_base[want:match('([^/]+)$')] or {}) do candidates[#candidates + 1] = f end
295
+ for _, f in ipairs(G.new_files or {}) do candidates[#candidates + 1] = f end
296
+ for _, f in ipairs(candidates) do
297
+ local rec = G.files[f]
298
+ if rec.language == 'lua' and (rec.path == want or rec.path:sub(-#want - 1) == '/' .. want) then result[#result + 1] = f end
299
+ end
300
+ end
301
+ elseif not imp.path:match('^[/\\]') and not imp.path:find(':', 1, true) then
302
+ local path = normalize(ctx.directory .. '/' .. imp.path)
303
+ local f = G.file_index[path]
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
324
+ end
325
+ ctx.modules[key] = result
326
+ return result
327
+ 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
342
+ if hint == '?' then return {} end
343
+ local local_index = tonumber(hint:match('^lua%-local:(%d+)$'))
344
+ if local_index then
345
+ local n = ((G.files[f].lua_locals or {})[local_index] or {})[name]
346
+ return n and { G.id_of[f][n] } or {}
347
+ end
348
+ local index = tonumber(hint:match('^lua:(%d+)$'))
349
+ local imp = index and (G.files[f].lua_imports or {})[index]
350
+ if not imp then return nil end
351
+ local result = {}
352
+ for _, target in ipairs(M.modules(G, imp, ctx)) do
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]
356
+ if n then result[#result + 1] = G.id_of[target][n] end
357
+ end
358
+ return result
359
+ end
360
+ return M
@@ -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