-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathincremental.ts
More file actions
1637 lines (1528 loc) · 58.8 KB
/
Copy pathincremental.ts
File metadata and controls
1637 lines (1528 loc) · 58.8 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Incremental single-file rebuild — used by watch mode.
*
* Reuses pipeline helpers instead of duplicating node insertion and edge building
* logic from the main builder. This eliminates the watcher.js divergence (ROADMAP 3.9).
*
* Reverse-dep cascade: when a file changes, files that have edges targeting it
* must have their outgoing edges rebuilt (since the changed file's node IDs change).
*/
import fs from 'node:fs';
import path from 'node:path';
import { bulkNodeIdsByFile, purgeFileData } from '../../../db/index.js';
import { PROPAGATION_HOP_PENALTY } from '../../../extractors/javascript.js';
import { debug, warn } from '../../../infrastructure/logger.js';
import { normalizePath, TS_NATIVE_CONFIDENCE_FLOOR } from '../../../shared/constants.js';
import { FLAG_ONLY_DYNAMIC_KINDS, isTypeErasedImportTarget } from '../../../shared/kinds.js';
import type {
BetterSqlite3Database,
Call,
EngineOpts,
ExtractorOutput,
PathAliases,
SqliteStatement,
} from '../../../types.js';
import { parseFileIncremental } from '../../parser.js';
import { computeConfidence, resolveImportPath } from '../resolve.js';
import {
buildPointsToMapForFile,
type PointsToMap,
resolveViaPointsTo,
} from '../resolver/points-to.js';
import {
type CallNodeLookup,
collectInvokedPropertyNames,
findCaller,
isModuleScopedLanguage,
resolveCallTargets,
resolveDefinePropertyAccessorTarget,
resolveHierarchyTargets,
resolveReceiverEdge,
resolveSameClassQualifiedMethod,
} from './call-resolver.js';
import {
buildChaContextFromDb,
type ChaContext,
resolveChaTargets,
resolveThisDispatch,
} from './cha.js';
import {
BUILTIN_RECEIVERS,
CHA_DISPATCH_PENALTY,
CHA_TYPED_DISPATCH_CONFIDENCE,
fileHash,
fileStat,
readFileSafe,
} from './helpers.js';
import { importNamePairs } from './import-utils.js';
// ── Local types ─────────────────────────────────────────────────────────
export interface IncrementalStmts {
insertNode: { run: (...params: unknown[]) => unknown };
insertEdge: { run: (...params: unknown[]) => unknown };
getNodeId: { get: (...params: unknown[]) => { id: number } | undefined };
countNodes: { get: (...params: unknown[]) => { c: number } | undefined };
countEdges: { get: (...params: unknown[]) => { c: number } | undefined };
listSymbols: { all: (...params: unknown[]) => unknown[] };
findNodeInFile: { all: (...params: unknown[]) => unknown[] };
findNodeByName: { all: (...params: unknown[]) => unknown[] };
/**
* Upsert a `file_hashes` row: `(relPath, hash, mtime, size)`. Called only
* after a file's edges have been fully rebuilt (#1731) — see the call site
* in `rebuildFile` for why this can't happen any earlier.
*/
upsertFileHash: { run: (...params: unknown[]) => unknown };
/** Delete a `file_hashes` row for a file removed from disk. */
deleteFileHash: { run: (...params: unknown[]) => unknown };
}
interface RebuildResult {
file: string;
nodesAdded: number;
nodesRemoved: number;
edgesAdded: number;
edgesBefore: number;
deleted?: boolean;
event?: string;
symbolDiff?: unknown;
nodesBefore?: number;
nodesAfter?: number;
}
// ── Node insertion ──────────────────────────────────────────────────────
function insertFileNodes(stmts: IncrementalStmts, relPath: string, symbols: ExtractorOutput): void {
stmts.insertNode.run(relPath, 'file', relPath, 0, null);
for (const def of symbols.definitions) {
stmts.insertNode.run(def.name, def.kind, relPath, def.line, def.endLine || null);
if (def.children?.length) {
for (const child of def.children) {
stmts.insertNode.run(child.name, child.kind, relPath, child.line, child.endLine || null);
}
}
}
for (const exp of symbols.exports) {
stmts.insertNode.run(exp.name, exp.kind, relPath, exp.line, null);
}
}
// ── Containment edges ──────────────────────────────────────────────────
function buildContainmentEdges(
db: BetterSqlite3Database,
stmts: IncrementalStmts,
relPath: string,
symbols: ExtractorOutput,
): number {
const nodeIdMap = new Map<string, number>();
for (const row of bulkNodeIdsByFile(db, relPath)) {
nodeIdMap.set(`${row.name}|${row.kind}|${row.line}`, row.id);
}
const fileId = nodeIdMap.get(`${relPath}|file|0`);
let edgesAdded = 0;
for (const def of symbols.definitions) {
const defId = nodeIdMap.get(`${def.name}|${def.kind}|${def.line}`);
if (fileId && defId) {
stmts.insertEdge.run(fileId, defId, 'contains', 1.0, 0);
edgesAdded++;
}
if (def.children?.length && defId) {
for (const child of def.children) {
const childId = nodeIdMap.get(`${child.name}|${child.kind}|${child.line}`);
if (childId) {
stmts.insertEdge.run(defId, childId, 'contains', 1.0, 0);
edgesAdded++;
if (child.kind === 'parameter') {
stmts.insertEdge.run(childId, defId, 'parameter_of', 1.0, 0);
edgesAdded++;
}
}
}
}
}
return edgesAdded;
}
// ── Reverse-dep cascade ────────────────────────────────────────────────
// Lazily-cached prepared statements for reverse-dep operations
let _revDepDb: BetterSqlite3Database | null = null;
let _findRevDepsStmt: SqliteStatement | null = null;
let _deleteDataflowByCallEdgeStmt: SqliteStatement | null | undefined; // undefined = not yet tried
let _deleteOutEdgesStmt: SqliteStatement | null = null;
function getRevDepStmts(db: BetterSqlite3Database): {
findRevDepsStmt: SqliteStatement;
deleteDataflowByCallEdgeStmt: SqliteStatement | null;
deleteOutEdgesStmt: SqliteStatement;
} {
if (_revDepDb !== db) {
_revDepDb = db;
_findRevDepsStmt = db.prepare(
`SELECT DISTINCT n_src.file FROM edges e
JOIN nodes n_src ON e.source_id = n_src.id
JOIN nodes n_tgt ON e.target_id = n_tgt.id
WHERE n_tgt.file = ? AND n_src.file != ? AND n_src.kind != 'directory'`,
);
// Delete inter-procedural dataflow rows whose call_edge_id references an
// outgoing edge from this file. Must run before deleteOutEdgesStmt to avoid
// SQLITE_CONSTRAINT_FOREIGNKEY: dataflow.call_edge_id REFERENCES edges(id).
try {
_deleteDataflowByCallEdgeStmt = db.prepare(
`DELETE FROM dataflow WHERE call_edge_id IN
(SELECT id FROM edges WHERE source_id IN (SELECT id FROM nodes WHERE file = ?))`,
);
} catch {
_deleteDataflowByCallEdgeStmt = null; // dataflow table or call_edge_id column absent
}
_deleteOutEdgesStmt = db.prepare(
'DELETE FROM edges WHERE source_id IN (SELECT id FROM nodes WHERE file = ?)',
);
}
return {
findRevDepsStmt: _findRevDepsStmt!,
deleteDataflowByCallEdgeStmt: _deleteDataflowByCallEdgeStmt ?? null,
deleteOutEdgesStmt: _deleteOutEdgesStmt!,
};
}
function findReverseDeps(db: BetterSqlite3Database, relPath: string): string[] {
const { findRevDepsStmt } = getRevDepStmts(db);
return (findRevDepsStmt.all(relPath, relPath) as Array<{ file: string }>).map((r) => r.file);
}
function deleteOutgoingEdges(db: BetterSqlite3Database, relPath: string): void {
const { deleteDataflowByCallEdgeStmt, deleteOutEdgesStmt } = getRevDepStmts(db);
// Clear any inter-procedural dataflow rows that reference outgoing edges via
// call_edge_id before deleting those edges (FK: dataflow.call_edge_id → edges.id).
deleteDataflowByCallEdgeStmt?.run(relPath);
deleteOutEdgesStmt.run(relPath);
}
async function parseReverseDep(
rootDir: string,
depRelPath: string,
engineOpts: EngineOpts,
cache: unknown,
): Promise<ExtractorOutput | null> {
const absPath = path.join(rootDir, depRelPath);
if (!fs.existsSync(absPath)) return null;
let code: string;
try {
code = readFileSafe(absPath);
} catch (e: unknown) {
debug(`parseReverseDep: cannot read ${absPath}: ${e instanceof Error ? e.message : String(e)}`);
return null;
}
return parseFileIncremental(cache, absPath, code, engineOpts);
}
function rebuildReverseDepEdges(
db: BetterSqlite3Database,
rootDir: string,
depRelPath: string,
symbols: ExtractorOutput,
stmts: IncrementalStmts,
skipBarrel: boolean,
): number {
const fileNodeRow = stmts.getNodeId.get(depRelPath, 'file', depRelPath, 0);
if (!fileNodeRow) return 0;
const aliases: PathAliases = { baseUrl: null, paths: {} };
let edgesAdded = buildContainmentEdges(db, stmts, depRelPath, symbols);
// Don't rebuild dir->file containment for reverse-deps (it was never deleted)
edgesAdded += buildImportEdges(
stmts,
depRelPath,
symbols,
rootDir,
fileNodeRow.id,
aliases,
skipBarrel ? null : db,
);
const { importedNames, importedOriginalNames } = buildImportedNamesMap(
symbols,
rootDir,
depRelPath,
aliases,
db,
);
edgesAdded += buildCallEdges(
db,
stmts,
depRelPath,
symbols,
fileNodeRow,
importedNames,
importedOriginalNames,
);
edgesAdded += buildClassHierarchyEdges(
db,
stmts,
depRelPath,
symbols,
importedNames,
importedOriginalNames,
);
return edgesAdded;
}
// ── Directory containment edges ────────────────────────────────────────
function rebuildDirContainment(
_db: BetterSqlite3Database,
stmts: IncrementalStmts,
relPath: string,
): number {
const dir = normalizePath(path.dirname(relPath));
if (!dir || dir === '.') return 0;
const dirRow = stmts.getNodeId.get(dir, 'directory', dir, 0);
const fileRow = stmts.getNodeId.get(relPath, 'file', relPath, 0);
if (dirRow && fileRow) {
stmts.insertEdge.run(dirRow.id, fileRow.id, 'contains', 1.0, 0);
return 1;
}
return 0;
}
// ── Import edge building ────────────────────────────────────────────────
// Lazily-cached prepared statements for barrel resolution (avoid re-preparing in hot loops)
let _barrelDb: BetterSqlite3Database | null = null;
let _isBarrelStmt: SqliteStatement | null = null;
let _reexportTargetsStmt: SqliteStatement | null = null;
let _hasDefStmt: SqliteStatement | null = null;
function getBarrelStmts(db: BetterSqlite3Database): {
isBarrelStmt: SqliteStatement;
reexportTargetsStmt: SqliteStatement;
hasDefStmt: SqliteStatement;
} {
if (_barrelDb !== db) {
_barrelDb = db;
_isBarrelStmt = db.prepare(
`SELECT COUNT(*) as c FROM edges e
JOIN nodes n ON e.source_id = n.id
WHERE e.kind = 'reexports' AND n.file = ? AND n.kind = 'file'`,
);
_reexportTargetsStmt = db.prepare(
`SELECT DISTINCT n2.file FROM edges e
JOIN nodes n1 ON e.source_id = n1.id
JOIN nodes n2 ON e.target_id = n2.id
WHERE e.kind = 'reexports' AND n1.file = ? AND n1.kind = 'file'`,
);
_hasDefStmt = db.prepare(
`SELECT 1 FROM nodes WHERE name = ? AND file = ? AND kind != 'file' AND kind != 'directory' LIMIT 1`,
);
}
return {
isBarrelStmt: _isBarrelStmt!,
reexportTargetsStmt: _reexportTargetsStmt!,
hasDefStmt: _hasDefStmt!,
};
}
function isBarrelFile(db: BetterSqlite3Database, relPath: string): boolean {
const { isBarrelStmt } = getBarrelStmts(db);
const reexportCount = (isBarrelStmt.get(relPath) as { c: number } | undefined)?.c;
return (reexportCount || 0) > 0;
}
/**
* KNOWN LIMITATION, tracked separately in #1967: this is `codegraph watch`'s
* single-file rebuild path (see `watcher.ts`) — unlike the `codegraph build`
* resolver (`resolveBarrelExport` in resolve-imports.ts, fixed for #1823),
* this has no way to recover a barrel's `export { X as Y } from …` rename
* table when the barrel file itself isn't part of the current watch batch —
* that mapping only exists in the barrel's freshly-parsed `Import.renamedImports`,
* which isn't persisted to the DB and this function has no reparse access to.
* It therefore still resolves purely by direct name match — renamed barrel
* re-exports are not resolved when only a consumer file changes under watch.
* `name` in the result mirrors the shared `CallNodeLookup.resolveBarrel`
* shape but is always just the input `symbolName` unchanged.
*/
function resolveBarrelTarget(
db: BetterSqlite3Database,
barrelPath: string,
symbolName: string,
visited: Set<string> = new Set(),
): { file: string; name: string } | null {
if (visited.has(barrelPath)) return null;
visited.add(barrelPath);
const { reexportTargetsStmt, hasDefStmt } = getBarrelStmts(db);
// Find re-export targets from this barrel
const reexportTargets = reexportTargetsStmt.all(barrelPath) as Array<{ file: string }>;
for (const { file: targetFile } of reexportTargets) {
// Check if the symbol is defined in this target file
const hasDef = hasDefStmt.get(symbolName, targetFile);
if (hasDef) return { file: targetFile, name: symbolName };
// Recurse through barrel chains
if (isBarrelFile(db, targetFile)) {
const deeper = resolveBarrelTarget(db, targetFile, symbolName, visited);
if (deeper) return deeper;
}
}
return null;
}
/**
* Resolve barrel imports for a single import statement and create edges to actual source files.
* Shared by buildImportEdges (primary file) and Pass 2 of the reverse-dep cascade.
*/
function resolveBarrelImportEdges(
db: BetterSqlite3Database,
stmts: IncrementalStmts,
fileNodeId: number,
resolvedPath: string,
imp: ExtractorOutput['imports'][number],
): number {
let edgesAdded = 0;
if (!isBarrelFile(db, resolvedPath)) return edgesAdded;
const resolvedSources = new Set<string>();
for (const { original } of importNamePairs(imp)) {
const resolved = resolveBarrelTarget(db, resolvedPath, original);
const actualSource = resolved?.file;
if (actualSource && actualSource !== resolvedPath && !resolvedSources.has(actualSource)) {
resolvedSources.add(actualSource);
const actualRow = stmts.getNodeId.get(actualSource, 'file', actualSource, 0);
if (actualRow) {
const kind = imp.typeOnly ? 'imports-type' : 'imports';
stmts.insertEdge.run(fileNodeId, actualRow.id, kind, 0.9, 0);
edgesAdded++;
}
}
}
return edgesAdded;
}
/**
* Emit one symbol-level edge per named specifier — shared by `import type`
* statements (`imports-type`, #1724) and named re-exports (`reexports`,
* #1742). Wildcard re-exports (`export * from 'Y'`) carry no specific names,
* so the loop is a no-op for them; the query layer falls back to the
* target's full export list for anything reached only by the file-level
* edge. Mirrors `emitNamedSymbolEdges` in build-edges.ts (full-build path).
*
* For `edgeKind === 'imports-type'`, a specifier gets an edge when either
* it's actually marked type-only (whole-statement or inline per-specifier,
* #1813 — a mixed `import { value, type Foo }` must not credit `value` on
* this basis alone), or the resolved target is a TypeScript
* interface/type-alias declaration (`isTypeErasedImportTarget`) — those
* kinds are erased before runtime, so a plain `import { Foo } from 'y'` (no
* `type` keyword) is the only consumption signal `codegraph exports` can
* observe for them (#1833).
*/
function emitNamedSymbolEdges(
db: BetterSqlite3Database | null,
stmts: IncrementalStmts,
imp: ExtractorOutput['imports'][number],
resolvedPath: string,
fileNodeId: number,
edgeKind: 'imports-type' | 'reexports',
): number {
let edgesAdded = 0;
for (const { original, typeOnly } of importNamePairs(imp)) {
let targetFile = resolvedPath;
let targetName = original;
if (db && isBarrelFile(db, resolvedPath)) {
const resolved = resolveBarrelTarget(db, resolvedPath, original);
if (resolved) {
targetFile = resolved.file;
targetName = resolved.name;
}
}
const candidates = stmts.findNodeInFile.all(targetName, targetFile) as Array<{
id: number;
file: string;
kind: string;
}>;
if (candidates.length === 0) continue;
const target = candidates[0]!;
if (
edgeKind === 'imports-type' &&
!typeOnly &&
!isTypeErasedImportTarget(target.kind, targetFile)
) {
continue;
}
stmts.insertEdge.run(fileNodeId, target.id, edgeKind, 1.0, 0);
edgesAdded++;
}
return edgesAdded;
}
/**
* Process a single import statement: emit the file→file edge, any
* symbol-level type-only edges, and barrel re-export edges.
*/
function emitEdgesForImport(
stmts: IncrementalStmts,
imp: ExtractorOutput['imports'][number],
fileNodeId: number,
relPath: string,
rootDir: string,
aliases: PathAliases,
db: BetterSqlite3Database | null,
): number {
const resolvedPath = resolveImportPath(path.join(rootDir, relPath), imp.source, rootDir, aliases);
const targetRow = stmts.getNodeId.get(resolvedPath, 'file', resolvedPath, 0);
if (!targetRow) return 0;
const edgeKind = imp.reexport
? 'reexports'
: imp.typeOnly
? 'imports-type'
: imp.dynamicImport
? 'dynamic-imports'
: 'imports';
stmts.insertEdge.run(fileNodeId, targetRow.id, edgeKind, 1.0, 0);
let edgesAdded = 1;
// Always attempted (not just for `import type`/inline-`type` specifiers) —
// emitNamedSymbolEdges also credits plain specifiers that resolve to a
// TypeScript interface/type-alias declaration (#1833).
if (!imp.reexport) {
edgesAdded += emitNamedSymbolEdges(db, stmts, imp, resolvedPath, fileNodeId, 'imports-type');
}
if (imp.reexport && !imp.wildcardReexport) {
edgesAdded += emitNamedSymbolEdges(db, stmts, imp, resolvedPath, fileNodeId, 'reexports');
} else if (imp.reexport && imp.wildcardReexport) {
// Mirrors build-edges.ts (full-build path): a genuine wildcard must stay
// distinguishable from a named reexport even when a *different*
// statement in this file names specific symbols from the same target
// (#1849 review). See `collectReexportedSymbols` in
// domain/analysis/exports.ts.
stmts.insertEdge.run(fileNodeId, targetRow.id, 'reexports-wildcard', 1.0, 0);
edgesAdded++;
}
if (!imp.reexport && db) {
edgesAdded += resolveBarrelImportEdges(db, stmts, fileNodeId, resolvedPath, imp);
}
return edgesAdded;
}
function buildImportEdges(
stmts: IncrementalStmts,
relPath: string,
symbols: ExtractorOutput,
rootDir: string,
fileNodeId: number,
aliases: PathAliases,
db: BetterSqlite3Database | null,
): number {
let edgesAdded = 0;
for (const imp of symbols.imports) {
edgesAdded += emitEdgesForImport(stmts, imp, fileNodeId, relPath, rootDir, aliases, db);
}
return edgesAdded;
}
/**
* Mirrors the full-build `buildImportedNamesMap` in build-edges.ts: maps each
* locally-bound import name to its defining file (`importedNames`), plus, for
* renamed specifiers (`import { X as Y }`), the *original* exported name
* (`importedOriginalNames`, keyed by local name Y). Barrel tracing and the
* downstream target-file symbol lookup must use the original name — the
* renamed local alias only exists in the importing file (#1730).
*/
function buildImportedNamesMap(
symbols: ExtractorOutput,
rootDir: string,
relPath: string,
aliases: PathAliases,
db: BetterSqlite3Database,
): { importedNames: Map<string, string>; importedOriginalNames: Map<string, string> } {
const importedNames = new Map<string, string>();
const importedOriginalNames = new Map<string, string>();
for (const imp of symbols.imports) {
const resolvedPath = resolveImportPath(
path.join(rootDir, relPath),
imp.source,
rootDir,
aliases,
);
for (const { local, original } of importNamePairs(imp)) {
// Mirror full-build's `buildImportedNamesMap`: follow barrel re-exports so
// `importedNames` maps to the *defining* file, not the barrel. This ensures
// `computeConfidence` gets `importedFrom === targetFile` and returns 1.0
// instead of the cross-directory fallback (0.3).
let targetFile = resolvedPath;
let targetName = original;
if (isBarrelFile(db, resolvedPath)) {
const resolved = resolveBarrelTarget(db, resolvedPath, original);
if (resolved) {
targetFile = resolved.file;
targetName = resolved.name;
}
}
importedNames.set(local, targetFile);
if (targetName !== local) importedOriginalNames.set(local, targetName);
}
}
return { importedNames, importedOriginalNames };
}
// ── Class hierarchy edges ───────────────────────────────────────────────
type NodeWithKind = { id: number; kind: string; file: string };
const HIERARCHY_SOURCE_KINDS = new Set(['class', 'struct', 'record', 'enum']);
const EXTENDS_TARGET_KINDS = new Set(['class', 'struct', 'trait', 'record']);
const IMPLEMENTS_TARGET_KINDS = new Set(['interface', 'trait', 'class']);
/**
* Emit `extends`/`implements` edges for class/struct/trait heritage clauses.
*
* Target resolution goes through `resolveHierarchyTargets` (#1812) — same-file
* declaration first, then the file's actually-resolved import, only falling
* back to a same-language-family global-by-name match as a last resort —
* instead of matching the heritage name against every node in the graph
* regardless of file or language. Mirrors the full-build `buildClassHierarchyEdges`
* in build-edges.ts.
*/
function buildClassHierarchyEdges(
db: BetterSqlite3Database,
stmts: IncrementalStmts,
relPath: string,
symbols: ExtractorOutput,
importedNames: ReadonlyMap<string, string>,
importedOriginalNames?: ReadonlyMap<string, string>,
): number {
let edgesAdded = 0;
const lookup = makeIncrementalLookup(db, stmts);
for (const cls of symbols.classes) {
const sourceRow = (stmts.findNodeInFile.all(cls.name, relPath) as NodeWithKind[]).find((n) =>
HIERARCHY_SOURCE_KINDS.has(n.kind),
);
if (!sourceRow) continue;
if (cls.extends) {
for (const t of resolveHierarchyTargets(
lookup,
cls.extends,
relPath,
importedNames,
EXTENDS_TARGET_KINDS,
importedOriginalNames,
)) {
stmts.insertEdge.run(sourceRow.id, t.id, 'extends', 1.0, 0);
edgesAdded++;
}
}
if (cls.implements) {
for (const t of resolveHierarchyTargets(
lookup,
cls.implements,
relPath,
importedNames,
IMPLEMENTS_TARGET_KINDS,
importedOriginalNames,
)) {
stmts.insertEdge.run(sourceRow.id, t.id, 'implements', 1.0, 0);
edgesAdded++;
}
}
}
return edgesAdded;
}
// ── Extended edge insertion (technique / dynamic_kind) ──────────────────
// Lazily-cached prepared statement for `calls` edges that need `technique`
// and/or `dynamic_kind` set at insert time — points-to (#1852), CHA/RTA
// dispatch (#1852), and dynamic-sink edges (#1852). The shared
// `IncrementalStmts.insertEdge` (built by `prepareWatcherStatements` in
// watcher.ts) only covers the 5 base columns and always leaves `technique`
// NULL, which `backfillIncrementalEdgeTechniques` below then backfills to
// 'ts-native' — correct for direct-resolution edges, but wrong for these.
// Runs its own INSERT directly against `db`, bypassing the `stmts`
// abstraction, mirroring how `deleteOutgoingEdges`/`backfillIncrementalEdgeTechniques`
// already do for statements outside the shared watcher.ts pool.
let _extEdgeDb: BetterSqlite3Database | null = null;
let _insertCallEdgeExtStmt: SqliteStatement | null = null;
function getInsertCallEdgeExtStmt(db: BetterSqlite3Database): SqliteStatement {
if (_extEdgeDb !== db) {
_extEdgeDb = db;
_insertCallEdgeExtStmt = db.prepare(
`INSERT INTO edges (source_id, target_id, kind, confidence, dynamic, technique, dynamic_kind)
VALUES (?, ?, 'calls', ?, ?, ?, ?)`,
);
}
return _insertCallEdgeExtStmt!;
}
/** Insert a `calls` edge with an explicit technique and/or dynamic_kind. */
function insertCallEdgeExt(
db: BetterSqlite3Database,
sourceId: number,
targetId: number,
confidence: number,
dynamic: 0 | 1,
technique: string | null,
dynamicKind: string | null,
): void {
getInsertCallEdgeExtStmt(db).run(sourceId, targetId, confidence, dynamic, technique, dynamicKind);
}
// ── Call edge building ──────────────────────────────────────────────────
function makeIncrementalLookup(db: BetterSqlite3Database, stmts: IncrementalStmts): CallNodeLookup {
return {
byNameAndFile: (name, file) =>
stmts.findNodeInFile.all(name, file) as Array<{ id: number; file: string; kind?: string }>,
byName: (name) =>
stmts.findNodeByName.all(name) as Array<{ id: number; file: string; kind?: string }>,
isBarrel: (file) => isBarrelFile(db, file),
resolveBarrel: (barrelFile, symbolName) => resolveBarrelTarget(db, barrelFile, symbolName),
nodeId: (name, kind, file, line) =>
stmts.getNodeId.get(name, kind, file, line) as { id: number } | undefined,
};
}
/** Coerce symbols.typeMap (Map, Array, or undefined) to a canonical Map. */
function coerceTypeMap(symbols: ExtractorOutput): Map<string, unknown> {
const rawTM: unknown = symbols.typeMap;
if (rawTM instanceof Map) return rawTM;
if (Array.isArray(rawTM) && rawTM.length > 0) {
return new Map(
(rawTM as Array<{ name: string; typeName?: string; type?: string }>).map((e) => [
e.name,
e.typeName ?? e.type ?? null,
]),
);
}
return new Map();
}
/**
* Seed scoped rest-param keys into typeMap (Phase 8.3f).
* Mirrors buildObjectRestParamPostPass in the full build.
*
* Scoped keys (`callee::restName`) prevent same-name rest-param collisions
* when two functions in the same file both use `...rest` (#1358). The
* unscoped key is also seeded when only one callee uses a given rest name,
* preserving resolution when callerName is null.
*/
function seedRestParamTypeMap(typeMap: Map<string, unknown>, symbols: ExtractorOutput): void {
if (!symbols.objectRestParamBindings?.length || !symbols.paramBindings?.length) return;
const restNameCallees = new Map<string, Set<string>>();
for (const orpb of symbols.objectRestParamBindings) {
if (!restNameCallees.has(orpb.restName)) restNameCallees.set(orpb.restName, new Set());
restNameCallees.get(orpb.restName)!.add(orpb.callee);
}
for (const orpb of symbols.objectRestParamBindings) {
for (const pb of symbols.paramBindings) {
if (pb.callee === orpb.callee && pb.argIndex === orpb.argIndex) {
const scopedKey = `${orpb.callee}::${orpb.restName}`;
if (!typeMap.has(scopedKey)) {
typeMap.set(scopedKey, { type: pb.argName, confidence: 0.65 });
if (restNameCallees.get(orpb.restName)!.size === 1 && !typeMap.has(orpb.restName)) {
typeMap.set(orpb.restName, { type: pb.argName, confidence: 0.65 });
}
}
}
}
}
}
/**
* Normalize symbols.typeMap into a canonical Map and seed scoped rest-param
* keys (Phase 8.3f). Mirrors buildObjectRestParamPostPass in the full build.
*/
function buildIncrementalTypeMap(symbols: ExtractorOutput): Map<string, unknown> {
const typeMap = coerceTypeMap(symbols);
seedRestParamTypeMap(typeMap, symbols);
return typeMap;
}
/**
* Apply fallback resolution strategies for a single call site when the
* primary resolveCallTargets pass returned no targets.
*
* Runs in order:
* 1. Same-class `this.method()` fallback.
* 2. Same-class bare-call fallback for non-JS/TS class-scoped languages
* (e.g. C# static sibling calls: `IsValidEmail()` inside
* `Validators.ValidateUser` resolves to `Validators.IsValidEmail`).
* 3. Object.defineProperty accessor fallback (this-calls inside getter/setter).
*
* Mirrors the same-class fallback strategies in `resolveFallbackTargets`
* (stages/build-edges.ts, full-build path). The Kotlin-reflection
* pre-qualify and reflection-keyExpr fallbacks are intentionally not
* mirrored here — that narrower, language-specific gap is tracked
* separately (#1993), not by this function. The broader points-to/CHA/
* dynamic-sink gap this comment used to reference is now fixed by
* `buildCallEdges`/`applyChaDispatchPostPass` below (#1852).
*/
function applyCallFallbacks(
call: { name: string; receiver?: string | null },
callerName: string | null,
relPath: string,
typeMap: Map<string, unknown>,
lookup: CallNodeLookup,
definePropertyReceivers: Map<string, string> | undefined,
initialTargets: Array<{ id: number; file: string; kind?: string }>,
): Array<{ id: number; file: string; kind?: string }> {
if (initialTargets.length > 0) return initialTargets;
// Strategy 1: same-class `this.method()` fallback.
if (call.receiver === 'this' && callerName != null) {
const s1 = resolveSameClassQualifiedMethod(call.name, callerName, relPath, lookup);
if (s1.length > 0) return s1;
}
// Strategy 2: same-class bare-call fallback. Skipped for JS/TS, where a
// bare call is module-scoped, not class-scoped (mirrors
// resolveSameClassBareCallFallback in stages/build-edges.ts).
if (!call.receiver && callerName != null && !isModuleScopedLanguage(relPath)) {
const s2 = resolveSameClassQualifiedMethod(call.name, callerName, relPath, lookup);
if (s2.length > 0) return s2;
}
// Strategy 3: Object.defineProperty accessor fallback. Shared with the
// full-build path (stages/build-edges.ts) via call-resolver.ts so both
// paths apply the same function/method kind filter (issue #1766).
if (call.receiver === 'this' && callerName != null && definePropertyReceivers) {
return resolveDefinePropertyAccessorTarget(
call.name,
callerName,
relPath,
typeMap,
lookup,
definePropertyReceivers,
);
}
return initialTargets;
}
/**
* Emit direct `calls` edges for the resolved targets of a single call site,
* then emit a `receiver` edge when the call has a non-this/self/super receiver.
* Returns the number of edges inserted.
*/
function emitIncrementalCallEdges(
call: { name: string; receiver?: string | null; dynamic?: boolean },
caller: { id: number; callerName: string | null },
targets: Array<{ id: number; file: string; kind?: string }>,
importedFrom: string | null | undefined,
relPath: string,
typeMap: Map<string, unknown>,
lookup: CallNodeLookup,
importedNames: Map<string, string>,
seenCallEdges: Set<string>,
stmts: IncrementalStmts,
): number {
let edgesAdded = 0;
for (const t of targets) {
const edgeKey = `${caller.id}|${t.id}`;
if (t.id !== caller.id && !seenCallEdges.has(edgeKey)) {
seenCallEdges.add(edgeKey);
const confidence = computeConfidence(relPath, t.file, importedFrom ?? null);
stmts.insertEdge.run(caller.id, t.id, 'calls', confidence, call.dynamic ? 1 : 0);
edgesAdded++;
}
}
if (
call.receiver &&
!BUILTIN_RECEIVERS.has(call.receiver) &&
call.receiver !== 'this' &&
call.receiver !== 'self' &&
call.receiver !== 'super'
) {
const recv = resolveReceiverEdge(
lookup,
{ name: call.name, receiver: call.receiver },
caller,
relPath,
typeMap,
seenCallEdges,
importedNames,
);
if (recv) {
stmts.insertEdge.run(recv.callerId, recv.receiverId, 'receiver', recv.confidence, 0);
edgesAdded++;
}
}
return edgesAdded;
}
/**
* Phase 8.3/8.3c pts fallback for calls with no receiver, when the primary
* resolveCallTargets + applyCallFallbacks chain found nothing. Mirrors
* `emitPtsNoReceiverEdges` (stages/build-edges.ts, full-build path) — see
* that function's docstring for the full case breakdown (dynamic calls,
* scoped/module/flat pts keys).
*
* Unlike the full-build version, a pts edge here shares `seenCallEdges` with
* direct-call edges rather than a separate `ptsEdgeRows` map, so a later
* direct call to the same target in the same file is skipped (not upgraded
* to the higher direct-call confidence) if a pts edge already claimed the
* pair — a narrow, documented gap from full-build parity (tracked in #1852's
* follow-up), not a missing edge.
*/
function emitIncrementalPtsNoReceiverEdges(
db: BetterSqlite3Database,
call: Call,
caller: { id: number; callerName: string | null },
relPath: string,
importedNames: Map<string, string>,
lookup: CallNodeLookup,
typeMap: Map<string, unknown>,
ptsMap: PointsToMap,
fnRefBindingLhs: ReadonlySet<string>,
seenCallEdges: Set<string>,
importedOriginalNames: ReadonlyMap<string, string> | undefined,
): number {
const scopedPtsKey = caller.callerName != null ? `${caller.callerName}::${call.name}` : null;
// Module-level calls (callerName === null) use the '<module>' sentinel emitted by
// extractSpreadForOfWalk for top-level for-of loops.
const modulePtsKey =
caller.callerName === null && ptsMap.has(`<module>::${call.name}`)
? `<module>::${call.name}`
: null;
const flatPtsKey =
!call.dynamic && fnRefBindingLhs.has(call.name) && ptsMap.has(call.name) ? call.name : null;
if (
!(
call.dynamic ||
(scopedPtsKey != null && ptsMap.has(scopedPtsKey)) ||
modulePtsKey != null ||
flatPtsKey != null
)
)
return 0;
const ptsLookupName = call.dynamic
? call.name
: scopedPtsKey != null && ptsMap.has(scopedPtsKey)
? scopedPtsKey
: modulePtsKey != null
? modulePtsKey
: flatPtsKey!;
let edgesAdded = 0;
const isDynamic: 0 | 1 = call.dynamic ? 1 : 0;
for (const alias of resolveViaPointsTo(ptsLookupName, ptsMap)) {
const { targets: aliasTargets, importedFrom: aliasFrom } = resolveCallTargets(
lookup,
{ name: alias },
relPath,
importedNames,
typeMap,
undefined,
importedOriginalNames,
);
const sortedAliasTargets =
aliasTargets.length > 1
? [...aliasTargets].sort(
(a, b) =>
computeConfidence(relPath, b.file, aliasFrom ?? null) -
computeConfidence(relPath, a.file, aliasFrom ?? null),
)
: aliasTargets;
for (const t of sortedAliasTargets) {
const edgeKey = `${caller.id}|${t.id}`;
if (t.id !== caller.id && !seenCallEdges.has(edgeKey)) {
const conf =
computeConfidence(relPath, t.file, aliasFrom ?? null) - PROPAGATION_HOP_PENALTY;
if (conf > 0) {
seenCallEdges.add(edgeKey);
insertCallEdgeExt(db, caller.id, t.id, conf, isDynamic, 'points-to', null);
edgesAdded++;
}
}
}
}
return edgesAdded;
}
/**
* Phase 8.3f pts fallback for unresolved receiver calls via object-rest
* param bindings (`rest.prop()`). Mirrors `emitPtsReceiverEdges`
* (stages/build-edges.ts, full-build path).
*/
function emitIncrementalPtsReceiverEdges(
db: BetterSqlite3Database,
call: Call,
caller: { id: number; callerName: string | null },
relPath: string,
importedNames: Map<string, string>,
lookup: CallNodeLookup,
typeMap: Map<string, unknown>,
ptsMap: PointsToMap,
seenCallEdges: Set<string>,
importedOriginalNames: ReadonlyMap<string, string> | undefined,
): number {
const receiverKey = `${call.receiver}.${call.name}`;
if (!ptsMap.has(receiverKey)) return 0;
let edgesAdded = 0;
const isDynamic: 0 | 1 = call.dynamic ? 1 : 0;
for (const alias of resolveViaPointsTo(receiverKey, ptsMap)) {
const { targets: aliasTargets, importedFrom: aliasFrom } = resolveCallTargets(
lookup,
{ name: alias },
relPath,
importedNames,
typeMap,
undefined,
importedOriginalNames,
);
const sortedAliasTargets =
aliasTargets.length > 1
? [...aliasTargets].sort(
(a, b) =>
computeConfidence(relPath, b.file, aliasFrom ?? null) -
computeConfidence(relPath, a.file, aliasFrom ?? null),
)
: aliasTargets;
for (const t of sortedAliasTargets) {
const edgeKey = `${caller.id}|${t.id}`;
if (t.id !== caller.id && !seenCallEdges.has(edgeKey)) {
const conf =
computeConfidence(relPath, t.file, aliasFrom ?? null) - PROPAGATION_HOP_PENALTY;
if (conf > 0) {
seenCallEdges.add(edgeKey);
insertCallEdgeExt(db, caller.id, t.id, conf, isDynamic, 'points-to', null);