Files
2026-11-27 06:03:56 +00:00

47 lines
2.4 KiB
JavaScript

// 编译器结果按身份建立邻接索引;每个 CodeLens 不再扫描整张调用图。
const indices = new WeakMap();
function graph(index) {
if (indices.has(index)) return indices.get(index);
const symbols = new Map(index.symbols.map(symbol => [symbol.id, symbol]));
const names = new Map(index.symbols.map(symbol => [symbol.name, symbol]));
const incoming = new Map(), outgoing = new Map(), sites = new Map(), declarations = new Map();
for (const call of index.calls) {
for (const [map, key] of [[incoming, call.callee], [outgoing, call.caller], [sites, call.site.file]]) {
if (!map.has(key)) map.set(key, []);
map.get(key).push(call);
}
}
for (const symbol of index.symbols) for (const site of symbol.declarations) {
if (!declarations.has(site.file)) declarations.set(site.file, []);
declarations.get(site.file).push(symbol);
}
const result = { symbols, names, incoming, outgoing, sites, declarations };
indices.set(index, result);
return result;
}
function compare(left, right) { return left.line - right.line || left.character - right.character; }
function contains(range, position) { return compare(range.start, position) <= 0 && compare(position, range.end) < 0; }
function at(index, file, position) {
const edges = graph(index).sites.get(file) || [];
const calls = edges.filter(call => contains(call.site, position));
// 嵌套调用点击优先采用最小范围,不把外层调用也当成定义目标。
calls.sort((a, b) => compare(b.site.start, a.site.start) || compare(a.site.end, b.site.end));
if (calls.length) {
const first = calls[0].site;
return [...new Set(calls.filter(call => compare(call.site.start, first.start) === 0
&& compare(call.site.end, first.end) === 0).map(call => call.callee))].map(id => graph(index).symbols.get(id));
}
return (graph(index).declarations.get(file) || []).filter(symbol => symbol.declarations.some(site => contains(site, position)));
}
function relations(index, id, incoming) {
const adjacency = incoming ? graph(index).incoming : graph(index).outgoing;
const grouped = new Map();
for (const call of adjacency.get(id) || []) {
const target = incoming ? call.caller : call.callee;
if (!grouped.has(target)) grouped.set(target, []);
grouped.get(target).push(call);
}
return [...grouped].map(([id, calls]) => ({ symbol: graph(index).symbols.get(id), calls }));
}
module.exports = { graph, at, relations, contains };