-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcall-resolver.ts
More file actions
250 lines (238 loc) · 9.63 KB
/
Copy pathcall-resolver.ts
File metadata and controls
250 lines (238 loc) · 9.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/**
* Shared call-edge resolution — used by both the full build pipeline
* (build-edges.ts) and the incremental watch path (incremental.ts).
*
* Both callers supply a `CallNodeLookup` adapter that abstracts their
* node-lookup mechanism (pre-loaded Maps vs. per-query SQLite statements).
* The resolution logic lives here exactly once.
*/
import { computeConfidence } from '../resolve.js';
// ── Public interface ─────────────────────────────────────────────────────
export interface CallNodeLookup {
byNameAndFile(
name: string,
file: string,
): ReadonlyArray<{ id: number; file: string; kind?: string }>;
byName(name: string): ReadonlyArray<{ id: number; file: string; kind?: string }>;
isBarrel(file: string): boolean;
resolveBarrel(barrelFile: string, symbolName: string): string | null;
nodeId(name: string, kind: string, file: string, line: number): { id: number } | undefined;
}
export const RECEIVER_KINDS = new Set(['class', 'struct', 'interface', 'type', 'module']);
// ── Shared resolution functions ──────────────────────────────────────────
export function findCaller(
lookup: CallNodeLookup,
call: { line: number },
definitions: ReadonlyArray<{
name: string;
kind: string;
line: number;
endLine?: number | null;
}>,
relPath: string,
fileNodeRow: { id: number },
): { id: number; callerName: string | null } {
let caller: { id: number } | null = null;
let callerName: string | null = null;
let callerSpan = Infinity;
for (const def of definitions) {
if (def.line <= call.line) {
const end = def.endLine || Infinity;
if (call.line <= end) {
const span = end - def.line;
if (span < callerSpan) {
const row = lookup.nodeId(def.name, def.kind, relPath, def.line);
if (row) {
caller = row;
callerName = def.name;
callerSpan = span;
}
}
}
}
}
return { ...(caller ?? fileNodeRow), callerName };
}
export function resolveByMethodOrGlobal(
lookup: CallNodeLookup,
call: { name: string; receiver?: string | null },
relPath: string,
typeMap: Map<string, unknown>,
callerName?: string | null,
): ReadonlyArray<{ id: number; file: string }> {
if (call.receiver) {
// Strip "this." so `this.repo.method()` resolves via typeMap["repo"]
// (or the "this.repo" key seeded directly by the TSC property-declaration enricher).
const effectiveReceiver = call.receiver.startsWith('this.')
? call.receiver.slice('this.'.length)
: call.receiver;
const typeEntry = typeMap.get(effectiveReceiver) ?? typeMap.get(call.receiver);
const typeName = typeEntry
? typeof typeEntry === 'string'
? typeEntry
: (typeEntry as { type?: string }).type
: null;
if (typeName) {
const typed = lookup.byName(`${typeName}.${call.name}`).filter((n) => n.kind === 'method');
if (typed.length > 0) return typed;
// Prototype alias: `Foo.prototype.bar = fn` seeds typeMap['Foo.bar'] = { type: 'fn' }
const protoAlias = (typeMap.get(`${typeName}.${call.name}`) as { type?: string } | undefined)
?.type;
if (protoAlias) {
const resolved = lookup
.byName(protoAlias)
.filter((t) => computeConfidence(relPath, t.file, null) >= 0.5);
if (resolved.length > 0) return resolved;
}
}
// Inline new-expression receiver: `(new Foo).bar()` — extract class name for type lookup
if (!typeName && call.receiver) {
const m = /^\(?\s*new\s+([A-Z_$][A-Za-z0-9_$]*)/.exec(call.receiver);
if (m?.[1]) {
const inlineType = m[1];
const typed = lookup.byName(`${inlineType}.${call.name}`).filter((n) => n.kind === 'method');
if (typed.length > 0) return typed;
const protoAlias = (
typeMap.get(`${inlineType}.${call.name}`) as { type?: string } | undefined
)?.type;
if (protoAlias) {
const resolved = lookup
.byName(protoAlias)
.filter((t) => computeConfidence(relPath, t.file, null) >= 0.5);
if (resolved.length > 0) return resolved;
}
}
}
// Phase 8.3d: composite pts key — `obj.prop = fn` seeds typeMap['obj.prop'] = { type: 'fn' }.
// When a call site references `obj.prop` as a callback, resolve directly to the target fn.
const compositeEntry = typeMap.get(`${call.receiver}.${call.name}`);
const ptsTarget = compositeEntry
? typeof compositeEntry === 'string'
? compositeEntry
: (compositeEntry as { type?: string }).type
: null;
if (ptsTarget) {
const resolved = lookup
.byName(ptsTarget)
.filter((t) => computeConfidence(relPath, t.file, null) >= 0.5);
if (resolved.length > 0) return resolved;
}
}
if (
!call.receiver ||
call.receiver === 'this' ||
call.receiver === 'self' ||
call.receiver === 'super'
) {
const exact = lookup
.byName(call.name)
.filter((t) => computeConfidence(relPath, t.file, null) >= 0.5);
if (exact.length > 0) return exact;
// For this/self/super receiver: try same-class method lookup via callerName.
// e.g. `this.area()` inside `Shape.describe` → try `Shape.area`.
// This seeds the initial edge that runChaPostPass later expands to subclass overrides.
if (call.receiver && callerName) {
const dotIdx = callerName.lastIndexOf('.');
if (dotIdx > -1) {
const callerClass = callerName.slice(0, dotIdx);
const qualifiedName = `${callerClass}.${call.name}`;
const sameClass = lookup
.byName(qualifiedName)
.filter((t) => t.kind === 'method' && computeConfidence(relPath, t.file, null) >= 0.5);
if (sameClass.length > 0) return sameClass;
}
}
return exact; // empty
}
return [];
}
export function resolveCallTargets(
lookup: CallNodeLookup,
call: { name: string; receiver?: string | null },
relPath: string,
importedNames: Map<string, string>,
typeMap: Map<string, unknown>,
callerName?: string | null,
): { targets: Array<{ id: number; file: string }>; importedFrom: string | undefined } {
const importedFrom = importedNames.get(call.name);
let targets: ReadonlyArray<{ id: number; file: string }> | undefined;
if (importedFrom) {
targets = lookup.byNameAndFile(call.name, importedFrom);
if (targets.length === 0 && lookup.isBarrel(importedFrom)) {
const actualSource = lookup.resolveBarrel(importedFrom, call.name);
if (actualSource) {
targets = lookup.byNameAndFile(call.name, actualSource);
}
}
}
if (!targets || targets.length === 0) {
targets = lookup.byNameAndFile(call.name, relPath);
if (targets.length === 0) {
targets = resolveByMethodOrGlobal(lookup, call, relPath, typeMap, callerName);
}
}
const resolved = [...(targets ?? [])];
if (resolved.length > 1) {
resolved.sort((a, b) => {
const confA = computeConfidence(relPath, a.file, importedFrom ?? null);
const confB = computeConfidence(relPath, b.file, importedFrom ?? null);
return confB - confA;
});
}
return { targets: resolved, importedFrom };
}
/**
* Resolve the receiver-type edge for a call site.
* Returns the edge tuple to insert, or null if nothing matched or the edge
* was already seen. Callers are responsible for the actual DB/array insert.
*
* Receiver resolution collects all same-file candidates first (no kind
* filter), falls back to global candidates only when the same-file set is
* entirely empty, then filters the chosen set by RECEIVER_KINDS. This
* matches the native Rust build path: if a file imports a name that happens
* to be emitted as `kind='function'` in the importer, the same-file set is
* non-empty and blocks the global fallback, so no receiver edge is emitted.
* Keeping this behaviour identical to the Rust path maintains engine parity.
*/
export function resolveReceiverEdge(
lookup: CallNodeLookup,
call: { name: string; receiver: string },
caller: { id: number },
relPath: string,
typeMap: Map<string, unknown>,
seenCallEdges: Set<string>,
): { callerId: number; receiverId: number; confidence: number } | null {
const typeEntry = typeMap.get(call.receiver);
const typeName = typeEntry
? typeof typeEntry === 'string'
? typeEntry
: ((typeEntry as { type?: string }).type ?? null)
: null;
const typeConfidence =
typeEntry && typeof typeEntry !== 'string'
? ((typeEntry as { confidence?: number }).confidence ?? null)
: null;
const effectiveReceiver = typeName || call.receiver;
// Filter-before: apply RECEIVER_KINDS to same-file candidates first, then
// fall back to global candidates (also filtered) only when same-file yields
// nothing. This prevents an imported name emitted as kind='function' in the
// importing file from blocking the fallback to the actual class/struct/etc.
// node in the defining file.
const sameFileCandidates = lookup
.byNameAndFile(effectiveReceiver, relPath)
.filter((n) => RECEIVER_KINDS.has(n.kind ?? ''));
const candidates =
sameFileCandidates.length > 0
? sameFileCandidates
: lookup.byName(effectiveReceiver).filter((n) => RECEIVER_KINDS.has(n.kind ?? ''));
if (candidates.length === 0) return null;
const recvTarget = candidates[0]!;
const recvKey = `recv|${caller.id}|${recvTarget.id}`;
if (seenCallEdges.has(recvKey)) return null;
seenCallEdges.add(recvKey);
return {
callerId: caller.id,
receiverId: recvTarget.id,
confidence: typeConfidence ?? (typeName ? 0.9 : 0.7),
};
}