forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport-resolver.ts
More file actions
1353 lines (1237 loc) · 44.5 KB
/
Copy pathimport-resolver.ts
File metadata and controls
1353 lines (1237 loc) · 44.5 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
/**
* Import Resolver
*
* Resolves import paths to actual files and symbols.
*/
import * as fs from 'fs';
import * as path from 'path';
import { Language, Node } from '../types';
import { UnresolvedRef, ResolvedRef, ResolutionContext, ImportMapping, ReExport } from './types';
import { applyAliases } from './path-aliases';
import { resolveWorkspaceImport } from './workspace-packages';
/**
* Extension resolution order by language
*/
const EXTENSION_RESOLUTION: Record<string, string[]> = {
typescript: ['.ts', '.tsx', '.d.ts', '.js', '.jsx', '/index.ts', '/index.tsx', '/index.js'],
javascript: ['.js', '.jsx', '.mjs', '.cjs', '/index.js', '/index.jsx'],
tsx: ['.tsx', '.ts', '.d.ts', '.js', '.jsx', '/index.tsx', '/index.ts', '/index.js'],
jsx: ['.jsx', '.js', '/index.jsx', '/index.js'],
// SFC consumers import plain TS/JS, sibling components, and barrels
// (`./lib` → `./lib/index.ts`). Without a list, relative imports from a
// `.svelte`/`.vue` file resolve to nothing, so barrel callers vanish (#629).
svelte: ['.ts', '.js', '.svelte', '.tsx', '.jsx', '/index.ts', '/index.js', '/index.svelte'],
vue: ['.ts', '.js', '.vue', '.tsx', '.jsx', '/index.ts', '/index.js', '/index.vue'],
python: ['.py', '/__init__.py'],
go: ['.go'],
rust: ['.rs', '/mod.rs'],
java: ['.java'],
c: ['.h', '.c'],
cpp: ['.h', '.hpp', '.hxx', '.cpp', '.cc', '.cxx'],
csharp: ['.cs'],
php: ['.php'],
ruby: ['.rb'],
objc: ['.h', '.m', '.mm'],
};
/**
* Resolve an import path to an actual file
*/
export function resolveImportPath(
importPath: string,
fromFile: string,
language: Language,
context: ResolutionContext
): string | null {
// Skip external/npm packages — but pass the context so the
// bare-specifier heuristic can consult the project's tsconfig
// alias map first (custom prefixes like `@components/*` would
// otherwise be misclassified as npm).
if (isExternalImport(importPath, language, context)) {
return null;
}
const projectRoot = context.getProjectRoot();
const fromDir = path.dirname(path.join(projectRoot, fromFile));
// Handle relative imports
if (importPath.startsWith('.')) {
return resolveRelativeImport(importPath, fromDir, language, context);
}
// Handle absolute/aliased imports (like @/ or src/)
const aliased = resolveAliasedImport(importPath, projectRoot, language, context);
if (aliased) return aliased;
// C/C++ include directory search: when neither relative nor aliased
// resolution found a match, search -I directories from
// compile_commands.json or heuristic probing.
if (language === 'c' || language === 'cpp') {
return resolveCppIncludePath(importPath, language, context);
}
return null;
}
/**
* C and C++ standard library header names (without delimiters).
* Used by isExternalImport to filter system includes from resolution.
*/
const C_CPP_STDLIB_HEADERS = new Set([
// C standard library headers
'assert.h', 'complex.h', 'ctype.h', 'errno.h', 'fenv.h', 'float.h',
'inttypes.h', 'iso646.h', 'limits.h', 'locale.h', 'math.h', 'setjmp.h',
'signal.h', 'stdalign.h', 'stdarg.h', 'stdatomic.h', 'stdbool.h',
'stddef.h', 'stdint.h', 'stdio.h', 'stdlib.h', 'stdnoreturn.h',
'string.h', 'tgmath.h', 'threads.h', 'time.h', 'uchar.h', 'wchar.h',
'wctype.h',
// C++ C-library wrappers (cname form)
'cassert', 'ccomplex', 'cctype', 'cerrno', 'cfenv', 'cfloat',
'cinttypes', 'ciso646', 'climits', 'clocale', 'cmath', 'csetjmp',
'csignal', 'cstdalign', 'cstdarg', 'cstdbool', 'cstddef', 'cstdint',
'cstdio', 'cstdlib', 'cstring', 'ctgmath', 'ctime', 'cuchar',
'cwchar', 'cwctype',
// C++ STL headers
'algorithm', 'any', 'array', 'atomic', 'barrier', 'bit', 'bitset',
'charconv', 'chrono', 'codecvt', 'compare', 'complex', 'concepts',
'condition_variable', 'coroutine', 'deque', 'exception', 'execution',
'expected', 'filesystem', 'format', 'forward_list', 'fstream',
'functional', 'future', 'generator', 'initializer_list', 'iomanip',
'ios', 'iosfwd', 'iostream', 'istream', 'iterator', 'latch',
'limits', 'list', 'locale', 'map', 'mdspan', 'memory', 'memory_resource',
'mutex', 'new', 'numbers', 'numeric', 'optional', 'ostream', 'print',
'queue', 'random', 'ranges', 'ratio', 'regex', 'scoped_allocator',
'semaphore', 'set', 'shared_mutex', 'source_location', 'span',
'spanstream', 'sstream', 'stack', 'stacktrace', 'stdexcept',
'stdfloat', 'stop_token', 'streambuf', 'string', 'string_view',
'strstream', 'syncstream', 'system_error', 'thread', 'tuple',
'type_traits', 'typeindex', 'typeinfo', 'unordered_map',
'unordered_set', 'utility', 'valarray', 'variant', 'vector',
'version',
]);
/**
* Check if an import is external (npm package, etc.)
*
* `context` is consulted for project-defined path aliases
* (tsconfig/jsconfig `paths`). Without that check, custom prefixes
* like `@components/*` would fail the bare-specifier heuristic and
* be classified as external before alias resolution can run.
*/
function isExternalImport(
importPath: string,
language: Language,
context?: ResolutionContext
): boolean {
// Relative imports are not external
if (importPath.startsWith('.')) {
return false;
}
// Workspace-member imports (`@scope/ui`, `@scope/ui/widgets`) are LOCAL to
// a monorepo even though they look like bare npm specifiers. Consult the
// workspace map first so they aren't misclassified as external (#629). The
// map is null for single-package repos, so this is a no-op there.
const workspaces = context?.getWorkspacePackages?.();
if (workspaces && resolveWorkspaceImport(importPath, workspaces)) {
return false;
}
// Common external patterns
if (language === 'typescript' || language === 'javascript' || language === 'tsx' || language === 'jsx') {
// Node built-ins
if (['fs', 'path', 'os', 'crypto', 'http', 'https', 'url', 'util', 'events', 'stream', 'child_process', 'buffer'].includes(importPath)) {
return true;
}
// Project-defined alias prefix? Treat as local.
const aliases = context?.getProjectAliases?.();
if (aliases) {
for (const pat of aliases.patterns) {
if (importPath.startsWith(pat.prefix)) return false;
}
}
// Scoped packages or bare specifiers that don't start with aliases
if (!importPath.startsWith('@/') && !importPath.startsWith('~/') && !importPath.startsWith('src/')) {
// Likely an npm package
return true;
}
}
if (language === 'python') {
// Standard library modules
const stdLibs = ['os', 'sys', 'json', 're', 'math', 'datetime', 'collections', 'typing', 'pathlib', 'logging'];
if (stdLibs.includes(importPath.split('.')[0]!)) {
return true;
}
}
if (language === 'go') {
// Relative imports (rare in idiomatic Go but the grammar allows them).
if (importPath.startsWith('.')) {
return false;
}
// In-module imports look like `<module-path>/sub/pkg` — local to
// this project. Without the module-path check we'd flag every
// cross-package call in a Go monorepo as external (issue #388).
const mod = context?.getGoModule?.();
if (mod && (importPath === mod.modulePath || importPath.startsWith(mod.modulePath + '/'))) {
return false;
}
// `internal/` packages stay local even when go.mod is missing —
// preserves the pre-#388 escape hatch for repos without a parsed module path.
if (importPath.includes('/internal/')) {
return false;
}
// Anything else is the Go standard library or a third-party module.
return true;
}
if (language === 'c' || language === 'cpp') {
// C/C++ standard library headers — both C-style (<stdio.h>) and
// C++-style (<cstdio>, <vector>) forms. Checked against the import
// path (which the extractor strips of <> or "" delimiters).
if (C_CPP_STDLIB_HEADERS.has(importPath)) return true;
// C++ headers without .h extension (e.g. "vector", "string")
const withoutExt = importPath.replace(/\.h$/, '');
if (C_CPP_STDLIB_HEADERS.has(withoutExt)) return true;
}
return false;
}
/**
* Resolve a relative import
*/
function resolveRelativeImport(
importPath: string,
fromDir: string,
language: Language,
context: ResolutionContext
): string | null {
const projectRoot = context.getProjectRoot();
const extensions = EXTENSION_RESOLUTION[language] || [];
// Try the path as-is first
const basePath = path.resolve(fromDir, importPath);
const relativePath = path.relative(projectRoot, basePath).replace(/\\/g, '/');
// Try each extension
for (const ext of extensions) {
const candidatePath = relativePath + ext;
if (context.fileExists(candidatePath)) {
return candidatePath;
}
}
// Try without extension (might already have one)
if (context.fileExists(relativePath)) {
return relativePath;
}
return null;
}
/**
* Resolve an aliased/absolute import.
*
* Tries, in order:
* 1. Project-defined `compilerOptions.paths` (tsconfig/jsconfig).
* Each pattern can have multiple replacements; tried in tsconfig
* priority order with extension permutations.
* 2. The legacy hard-coded fallback list (`@/`, `~/`, `src/`, ...)
* for projects that have aliases but no tsconfig paths block.
* 3. Direct path lookup (with extensions).
*/
function resolveAliasedImport(
importPath: string,
projectRoot: string,
language: Language,
context: ResolutionContext
): string | null {
const extensions = EXTENSION_RESOLUTION[language] || [];
const tryWithExt = (basePath: string): string | null => {
for (const ext of extensions) {
const candidate = basePath + ext;
if (context.fileExists(candidate)) return candidate;
}
if (context.fileExists(basePath)) return basePath;
return null;
};
// 1. Project tsconfig/jsconfig paths.
const aliasMap = context.getProjectAliases?.();
if (aliasMap) {
const candidates = applyAliases(importPath, aliasMap, projectRoot);
for (const c of candidates) {
const hit = tryWithExt(c);
if (hit) return hit;
}
}
// 1.5 Workspace packages (`@scope/ui/widgets` → `packages/ui/widgets`).
// Resolves a monorepo member import to the member's directory; the
// extension/index permutations below then find its barrel (#629).
const workspaces = context.getWorkspacePackages?.();
if (workspaces) {
const base = resolveWorkspaceImport(importPath, workspaces);
if (base) {
const hit = tryWithExt(base);
if (hit) return hit;
}
}
// 2. Hard-coded fallback list. Kept for projects that use these
// conventional aliases without declaring them in tsconfig.
const fallbackAliases: Record<string, string> = {
'@/': 'src/',
'~/': 'src/',
'@src/': 'src/',
'src/': 'src/',
'@app/': 'app/',
'app/': 'app/',
};
for (const [alias, replacement] of Object.entries(fallbackAliases)) {
if (importPath.startsWith(alias)) {
const hit = tryWithExt(importPath.replace(alias, replacement));
if (hit) return hit;
}
}
// 3. Direct path.
return tryWithExt(importPath);
}
/**
* C/C++ include directory cache (keyed by project root).
* Loaded once per resolver instance, shared across calls.
*/
const cppIncludeDirCache = new Map<string, string[]>();
/**
* Clear the C/C++ include directory cache (call between indexing runs)
*/
export function clearCppIncludeDirCache(): void {
cppIncludeDirCache.clear();
}
/**
* Discover C/C++ include search directories for a project.
*
* Strategy:
* 1. Look for compile_commands.json (Clang compilation database) in the
* project root and common build subdirectories. Parse -I and -isystem
* flags from compiler commands.
* 2. If no compilation database is found, probe for common convention
* directories (include/, src/, lib/, api/) and top-level directories
* containing .h/.hpp files.
*
* Returns paths relative to projectRoot.
*/
export function loadCppIncludeDirs(projectRoot: string): string[] {
const cached = cppIncludeDirCache.get(projectRoot);
if (cached !== undefined) return cached;
const dirs = loadCppIncludeDirsFromCompileDB(projectRoot)
|| loadCppIncludeDirsHeuristic(projectRoot);
cppIncludeDirCache.set(projectRoot, dirs);
return dirs;
}
/**
* Try to load include directories from compile_commands.json.
* Returns null if no compilation database is found (so the heuristic
* fallback can run). Returns an array (possibly empty) otherwise.
*/
function loadCppIncludeDirsFromCompileDB(projectRoot: string): string[] | null {
const candidates = [
path.join(projectRoot, 'compile_commands.json'),
path.join(projectRoot, 'build', 'compile_commands.json'),
path.join(projectRoot, 'cmake-build-debug', 'compile_commands.json'),
path.join(projectRoot, 'cmake-build-release', 'compile_commands.json'),
path.join(projectRoot, 'out', 'compile_commands.json'),
];
let dbPath: string | undefined;
for (const c of candidates) {
try {
if (fs.existsSync(c)) {
dbPath = c;
break;
}
} catch {
// ignore
}
}
if (!dbPath) return null;
try {
const content = fs.readFileSync(dbPath, 'utf-8');
const entries = JSON.parse(content) as Array<{
directory: string;
command?: string;
arguments?: string[];
}>;
if (!Array.isArray(entries)) return null;
const dirSet = new Set<string>();
for (const entry of entries) {
const dir = entry.directory || projectRoot;
const args = entry.arguments || (entry.command ? shlexSplit(entry.command) : []);
for (let i = 0; i < args.length; i++) {
const arg = args[i]!;
let includeDir: string | undefined;
// -I<dir> (no space)
if (arg.startsWith('-I') && arg.length > 2) {
includeDir = arg.substring(2);
}
// -isystem <dir> (space-separated)
else if ((arg === '-isystem' || arg === '-I') && i + 1 < args.length) {
includeDir = args[i + 1];
i++; // skip next arg
}
if (includeDir) {
// Normalize: resolve relative to the compilation directory
const absPath = path.isAbsolute(includeDir)
? includeDir
: path.resolve(dir, includeDir);
const relPath = path.relative(projectRoot, absPath).replace(/\\/g, '/');
// Skip system directories and paths outside the project
// (relative paths starting with .. or absolute paths like
// /usr/include or C:\usr on Windows)
if (!relPath.startsWith('..') && relPath.length > 0 && !path.isAbsolute(relPath)) {
dirSet.add(relPath);
}
}
}
}
return Array.from(dirSet);
} catch {
return null;
}
}
/**
* Minimal shlex-style split for compiler command strings.
* Handles double-quoted and single-quoted arguments.
*/
function shlexSplit(cmd: string): string[] {
const result: string[] = [];
let i = 0;
while (i < cmd.length) {
// Skip whitespace
while (i < cmd.length && /\s/.test(cmd[i]!)) i++;
if (i >= cmd.length) break;
const ch = cmd[i]!;
if (ch === '"') {
i++;
let arg = '';
while (i < cmd.length && cmd[i] !== '"') {
if (cmd[i] === '\\' && i + 1 < cmd.length) { i++; arg += cmd[i]; }
else { arg += cmd[i]; }
i++;
}
i++; // closing quote
result.push(arg);
} else if (ch === "'") {
i++;
let arg = '';
while (i < cmd.length && cmd[i] !== "'") { arg += cmd[i]; i++; }
i++; // closing quote
result.push(arg);
} else {
let arg = '';
while (i < cmd.length && !/\s/.test(cmd[i]!)) { arg += cmd[i]; i++; }
result.push(arg);
}
}
return result;
}
/**
* Heuristic include directory discovery when no compile_commands.json exists.
* Checks common convention directories and scans top-level dirs for headers.
*/
function loadCppIncludeDirsHeuristic(projectRoot: string): string[] {
const dirs: string[] = [];
const conventionDirs = ['include', 'src', 'lib', 'api', 'inc'];
try {
const entries = fs.readdirSync(projectRoot, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const name = entry.name;
// Convention directories
if (conventionDirs.includes(name.toLowerCase())) {
dirs.push(name);
continue;
}
// Any top-level directory containing .h or .hpp files
try {
const subFiles = fs.readdirSync(path.join(projectRoot, name));
if (subFiles.some(f => /\.(h|hpp|hxx|hh)$/i.test(f))) {
dirs.push(name);
}
} catch {
// ignore permission errors
}
}
} catch {
// ignore
}
return dirs;
}
/**
* Resolve a C/C++ include path by searching include directories.
* Called as a fallback after relative and aliased resolution fail.
*/
function resolveCppIncludePath(
importPath: string,
language: Language,
context: ResolutionContext
): string | null {
const includeDirs = context.getCppIncludeDirs?.() ?? [];
const extensions = EXTENSION_RESOLUTION[language] ?? [];
for (const dir of includeDirs) {
const normalizedDir = dir.replace(/\\/g, '/');
for (const ext of extensions) {
const candidate = normalizedDir + '/' + importPath + ext;
if (context.fileExists(candidate)) return candidate;
}
// Try as-is (already has extension)
const candidate = normalizedDir + '/' + importPath;
if (context.fileExists(candidate)) return candidate;
}
return null;
}
/**
* Extract import mappings from a file
*/
export function extractImportMappings(
_filePath: string,
content: string,
language: Language
): ImportMapping[] {
const mappings: ImportMapping[] = [];
if (language === 'typescript' || language === 'javascript' || language === 'tsx' || language === 'jsx') {
mappings.push(...extractJSImports(content));
} else if (language === 'svelte' || language === 'vue') {
// Svelte/Vue single-file components import via plain ES6 inside their
// `<script>` block. Without this, a `.svelte`/`.vue` consumer produces
// zero import mappings, so `resolveViaImport` can't run and a barrel
// import (`import { Foo } from './lib'`) falls back to name-matching —
// which silently fails whenever the re-export alias differs from the
// component's real name, yielding a false 0 callers (#629). The ES6
// import regex only matches `import … from '…'`, so running it over the
// whole SFC (markup + styles included) is safe.
mappings.push(...extractJSImports(content));
} else if (language === 'python') {
mappings.push(...extractPythonImports(content));
} else if (language === 'go') {
mappings.push(...extractGoImports(content));
} else if (language === 'java' || language === 'kotlin') {
mappings.push(...extractJavaImports(content));
} else if (language === 'php') {
mappings.push(...extractPHPImports(content));
} else if (language === 'c' || language === 'cpp') {
mappings.push(...extractCppImports(content));
}
return mappings;
}
/**
* Extract JS/TS import mappings
*/
function extractJSImports(content: string): ImportMapping[] {
const mappings: ImportMapping[] = [];
// ES6 imports
const importRegex = /import\s+(?:(\w+)\s*,?\s*)?(?:\{([^}]+)\})?\s*(?:(\*)\s+as\s+(\w+))?\s*from\s*['"]([^'"]+)['"]/g;
let match;
while ((match = importRegex.exec(content)) !== null) {
const [, defaultImport, namedImports, star, namespaceAlias, source] = match;
// Default import
if (defaultImport) {
mappings.push({
localName: defaultImport,
exportedName: 'default',
source: source!,
isDefault: true,
isNamespace: false,
});
}
// Named imports
if (namedImports) {
const names = namedImports.split(',').map((s) => s.trim());
for (const name of names) {
const aliasMatch = name.match(/(\w+)\s+as\s+(\w+)/);
if (aliasMatch) {
mappings.push({
localName: aliasMatch[2]!,
exportedName: aliasMatch[1]!,
source: source!,
isDefault: false,
isNamespace: false,
});
} else if (name) {
mappings.push({
localName: name,
exportedName: name,
source: source!,
isDefault: false,
isNamespace: false,
});
}
}
}
// Namespace import
if (star && namespaceAlias) {
mappings.push({
localName: namespaceAlias,
exportedName: '*',
source: source!,
isDefault: false,
isNamespace: true,
});
}
}
// Require statements
const requireRegex = /(?:const|let|var)\s+(?:(\w+)|{([^}]+)})\s*=\s*require\(['"]([^'"]+)['"]\)/g;
while ((match = requireRegex.exec(content)) !== null) {
const [, defaultName, destructured, source] = match;
if (defaultName) {
mappings.push({
localName: defaultName,
exportedName: 'default',
source: source!,
isDefault: true,
isNamespace: false,
});
}
if (destructured) {
const names = destructured.split(',').map((s) => s.trim());
for (const name of names) {
const aliasMatch = name.match(/(\w+)\s*:\s*(\w+)/);
if (aliasMatch) {
mappings.push({
localName: aliasMatch[2]!,
exportedName: aliasMatch[1]!,
source: source!,
isDefault: false,
isNamespace: false,
});
} else if (name) {
mappings.push({
localName: name,
exportedName: name,
source: source!,
isDefault: false,
isNamespace: false,
});
}
}
}
}
return mappings;
}
/**
* Extract Python import mappings
*/
function extractPythonImports(content: string): ImportMapping[] {
const mappings: ImportMapping[] = [];
// from X import Y
const fromImportRegex = /from\s+([\w.]+)\s+import\s+([^#\n]+)/g;
let match;
while ((match = fromImportRegex.exec(content)) !== null) {
const [, source, imports] = match;
const names = imports!.split(',').map((s) => s.trim());
for (const name of names) {
const aliasMatch = name.match(/(\w+)\s+as\s+(\w+)/);
if (aliasMatch) {
mappings.push({
localName: aliasMatch[2]!,
exportedName: aliasMatch[1]!,
source: source!,
isDefault: false,
isNamespace: false,
});
} else if (name && name !== '*') {
mappings.push({
localName: name,
exportedName: name,
source: source!,
isDefault: false,
isNamespace: false,
});
}
}
}
// import X
const importRegex = /^import\s+([\w.]+)(?:\s+as\s+(\w+))?/gm;
while ((match = importRegex.exec(content)) !== null) {
const [, source, alias] = match;
const localName = alias || source!.split('.').pop()!;
mappings.push({
localName,
exportedName: '*',
source: source!,
isDefault: false,
isNamespace: true,
});
}
return mappings;
}
/**
* Extract Go import mappings
*/
function extractGoImports(content: string): ImportMapping[] {
const mappings: ImportMapping[] = [];
// import "path" or import alias "path"
const singleImportRegex = /import\s+(?:(\w+)\s+)?["']([^"']+)["']/g;
let match;
while ((match = singleImportRegex.exec(content)) !== null) {
const [, alias, source] = match;
const packageName = source!.split('/').pop()!;
mappings.push({
localName: alias || packageName,
exportedName: '*',
source: source!,
isDefault: false,
isNamespace: true,
});
}
// import ( ... ) block
const blockImportRegex = /import\s*\(\s*([^)]+)\s*\)/gs;
while ((match = blockImportRegex.exec(content)) !== null) {
const block = match[1]!;
const lineRegex = /(?:(\w+)\s+)?["']([^"']+)["']/g;
let lineMatch;
while ((lineMatch = lineRegex.exec(block)) !== null) {
const [, alias, source] = lineMatch;
const packageName = source!.split('/').pop()!;
mappings.push({
localName: alias || packageName,
exportedName: '*',
source: source!,
isDefault: false,
isNamespace: true,
});
}
}
return mappings;
}
/**
* Extract Java / Kotlin import mappings.
*
* Java/Kotlin imports carry the full qualified name of the imported
* symbol — `import com.example.dao.converter.FooConverter;` — which is
* exactly the disambiguation signal we need when two packages both
* declare a `FooConverter`. Pre-#314 the resolver had no Java branch
* here at all, so this mapping was empty and cross-module name
* collisions were resolved by file-path proximity (often wrongly).
*
* `import static com.example.Foo.bar;` is parsed as a local-name `bar`
* pointing at FQN `com.example.Foo.bar` so static-method call sites
* (`bar(...)`) can resolve through the same import lookup.
*/
function extractJavaImports(content: string): ImportMapping[] {
const mappings: ImportMapping[] = [];
// Strip line and block comments so `// import foo;` doesn't false-match.
const stripped = content
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/\/\/[^\n]*/g, '');
// `import [static] <fqn>[.*];`
const re = /^\s*import\s+(static\s+)?([\w.]+(?:\.\*)?)\s*;/gm;
let match: RegExpExecArray | null;
while ((match = re.exec(stripped)) !== null) {
const fqn = match[2]!;
// `import com.example.*;` — wildcard. We can't materialize a single
// local name; skip and let name-matching handle members reachable
// through the wildcard. (Future enhancement: enumerate package files.)
if (fqn.endsWith('.*')) continue;
const parts = fqn.split('.');
const localName = parts[parts.length - 1];
if (!localName) continue;
mappings.push({
localName,
exportedName: localName,
source: fqn,
isDefault: false,
isNamespace: false,
});
}
return mappings;
}
/**
* Extract PHP import mappings (use statements)
*/
function extractPHPImports(content: string): ImportMapping[] {
const mappings: ImportMapping[] = [];
// use Namespace\Class; or use Namespace\Class as Alias;
const useRegex = /use\s+([\w\\]+)(?:\s+as\s+(\w+))?;/g;
let match;
while ((match = useRegex.exec(content)) !== null) {
const [, fullPath, alias] = match;
const className = fullPath!.split('\\').pop()!;
mappings.push({
localName: alias || className,
exportedName: className,
source: fullPath!,
isDefault: false,
isNamespace: false,
});
}
return mappings;
}
/**
* Extract C/C++ import mappings from #include directives.
*
* #include brings all symbols from the included header into scope
* (namespace import), so each mapping uses isNamespace: true and
* exportedName: '*'. The localName is set to the header's basename
* without extension so that symbol references like `MyClass` can
* match against any include that might provide it.
*/
function extractCppImports(content: string): ImportMapping[] {
const mappings: ImportMapping[] = [];
// Match both #include <...> and #include "..."
const includeRegex = /^\s*#\s*include\s+[<"]([^>"]+)[>"]/gm;
let match;
while ((match = includeRegex.exec(content)) !== null) {
const modulePath = match[1]!;
// Basename without extension for localName matching
const basename = modulePath.split('/').pop()!.replace(/\.(h|hpp|hxx|hh|inl|ipp|cxx|cc|cpp)$/,'');
mappings.push({
localName: basename || modulePath,
exportedName: '*',
source: modulePath,
isDefault: false,
isNamespace: true,
});
}
return mappings;
}
// Cache import mappings per file to avoid re-reading and re-parsing
const importMappingCache = new Map<string, ImportMapping[]>();
/**
* Clear the import mapping cache (call between indexing runs)
*/
export function clearImportMappingCache(): void {
importMappingCache.clear();
cppIncludeDirCache.clear();
}
/**
* Strip JS line + block comments from `content` while preserving
* string literals (so `"//"` inside a string stays intact). Used by
* {@link extractReExports} so commented-out export-from statements
* don't generate phantom re-export edges.
*
* Scanner is deliberately small: it only tracks the three contexts
* relevant for JS/TS — single-quote string, double-quote string, and
* template literal. Comment recognition is the JS spec subset, no
* regex-literal awareness (which is fine for our use case: we don't
* apply this to function bodies, only to top-level files).
*/
function stripJsComments(content: string): string {
let out = '';
let i = 0;
let str: '"' | "'" | '`' | null = null;
while (i < content.length) {
const ch = content[i]!;
if (str !== null) {
out += ch;
if (ch === '\\' && i + 1 < content.length) {
out += content[i + 1]!;
i += 2;
continue;
}
if (ch === str) str = null;
i++;
continue;
}
if (ch === '"' || ch === "'" || ch === '`') {
str = ch;
out += ch;
i++;
continue;
}
if (ch === '/' && content[i + 1] === '/') {
while (i < content.length && content[i] !== '\n') i++;
continue;
}
if (ch === '/' && content[i + 1] === '*') {
i += 2;
while (i < content.length && !(content[i] === '*' && content[i + 1] === '/')) i++;
i += 2;
continue;
}
out += ch;
i++;
}
return out;
}
/**
* Extract JS/TS re-export declarations from `content`.
*
* Recognised forms:
* export { foo } from './a';
* export { foo as bar } from './a';
* export * from './a';
* export * as ns from './a'; (treated as wildcard for chasing)
* export { default as Foo } from './a';
*
* The walker intentionally stays regex-based — the import-resolver
* elsewhere in this file already chooses regex over a fresh
* tree-sitter pass, and this function shares that trade-off. Errors
* fall through silently; resolution simply skips the broken file.
*/
export function extractReExports(content: string, language: Language): ReExport[] {
if (
language !== 'typescript' &&
language !== 'javascript' &&
language !== 'tsx' &&
language !== 'jsx'
) {
return [];
}
const out: ReExport[] = [];
// Pre-strip block comments + line comments so a commented-out
// `// export { x } from '...'` doesn't produce a phantom edge.
// (Template literals are still a possible source of false positives;
// a project that builds export statements as runtime strings is
// out of scope.)
const cleaned = stripJsComments(content);
// Wildcard: `export * from '...'` or `export * as ns from '...'`
const wildcardRe = /export\s*\*(?:\s+as\s+\w+)?\s*from\s*['"]([^'"]+)['"]/g;
let m: RegExpExecArray | null;
while ((m = wildcardRe.exec(cleaned)) !== null) {
out.push({ kind: 'wildcard', source: m[1]! });
}
// Named: `export { a, b as c } from '...'`
const namedRe = /export\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g;
while ((m = namedRe.exec(cleaned)) !== null) {
const inner = m[1]!;
const source = m[2]!;
for (const raw of inner.split(',')) {
const item = raw.trim();
if (!item) continue;
const aliasMatch = item.match(/^(\w+)\s+as\s+(\w+)$/);
if (aliasMatch) {
out.push({
kind: 'named',
exportedName: aliasMatch[2]!,
originalName: aliasMatch[1]!,
source,
});
} else if (/^\w+$/.test(item)) {
out.push({
kind: 'named',
exportedName: item,
originalName: item,
source,
});
}
}
}
return out;
}
/**
* Resolve a reference using import mappings
*/
/**
* JVM (Java / Kotlin) imports use fully-qualified names (`import
* com.example.foo.Bar`) decoupled from filenames, so the JS/Python
* style filesystem path lookup misses them whenever the file isn't
* named after its primary symbol (Kotlin `Utils.kt` exporting `Bar`,
* top-level fns, extension fns). Resolve them through the
* `qualifiedName` index instead — populated by the package_header /
* package_declaration namespace wrappers in the extractor.
*/
export function resolveJvmImport(
ref: UnresolvedRef,
context: ResolutionContext
): ResolvedRef | null {