import-resolver.ts 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275
  1. /**
  2. * Import Resolver
  3. *
  4. * Resolves import paths to actual files and symbols.
  5. */
  6. import * as fs from 'fs';
  7. import * as path from 'path';
  8. import { Language, Node } from '../types';
  9. import { UnresolvedRef, ResolvedRef, ResolutionContext, ImportMapping, ReExport } from './types';
  10. import { applyAliases } from './path-aliases';
  11. import { resolveWorkspaceImport } from './workspace-packages';
  12. import {
  13. resolveMethodOnType,
  14. localReceiverTypePatterns,
  15. normalizeInferredTypeName,
  16. } from './name-matcher';
  17. /**
  18. * Extension resolution order by language
  19. */
  20. const EXTENSION_RESOLUTION: Record<string, string[]> = {
  21. typescript: ['.ts', '.tsx', '.d.ts', '.js', '.jsx', '/index.ts', '/index.tsx', '/index.js'],
  22. // ArkTS imports both `.ets` components and plain `.ts` logic modules —
  23. // HarmonyOS projects are always a mix. `/Index.ets` (capital I) is ohpm's
  24. // module-entry convention, hit when a bare workspace import ("data") is
  25. // rewritten to the member's directory; lowercase variants for safety.
  26. arkts: ['.ets', '.ts', '.d.ts', '.js', '/Index.ets', '/index.ets', '/index.ts', '/index.js'],
  27. javascript: ['.js', '.jsx', '.mjs', '.cjs', '/index.js', '/index.jsx'],
  28. tsx: ['.tsx', '.ts', '.d.ts', '.js', '.jsx', '/index.tsx', '/index.ts', '/index.js'],
  29. jsx: ['.jsx', '.js', '/index.jsx', '/index.js'],
  30. // SFC consumers import plain TS/JS, sibling components, and barrels
  31. // (`./lib` → `./lib/index.ts`). Without a list, relative imports from a
  32. // `.svelte`/`.vue` file resolve to nothing, so barrel callers vanish (#629).
  33. svelte: ['.ts', '.js', '.svelte', '.tsx', '.jsx', '/index.ts', '/index.js', '/index.svelte'],
  34. vue: ['.ts', '.js', '.vue', '.tsx', '.jsx', '/index.ts', '/index.js', '/index.vue'],
  35. astro: ['.ts', '.js', '.astro', '.tsx', '.jsx', '/index.ts', '/index.js', '/index.astro'],
  36. python: ['.py', '/__init__.py'],
  37. go: ['.go'],
  38. rust: ['.rs', '/mod.rs'],
  39. java: ['.java'],
  40. c: ['.h', '.c'],
  41. cpp: ['.h', '.hpp', '.hxx', '.cpp', '.cc', '.cxx'],
  42. csharp: ['.cs'],
  43. php: ['.php'],
  44. ruby: ['.rb'],
  45. objc: ['.h', '.m', '.mm'],
  46. nix: ['.nix', '/default.nix'],
  47. };
  48. export function isNixPathImportRef(ref: UnresolvedRef): boolean {
  49. return (
  50. ref.language === 'nix' &&
  51. ref.referenceKind === 'imports' &&
  52. (ref.referenceName.startsWith('./') || ref.referenceName.startsWith('../')) &&
  53. !/[\s{}()[\];"'<>$]/.test(ref.referenceName)
  54. );
  55. }
  56. /**
  57. * Resolve an import path to an actual file
  58. */
  59. // Per-context memos for the two hottest pure lookups on the resolution path:
  60. // import-specifier → file resolution and exported-symbol lookup. Both are pure
  61. // given a stable file set + node table, which is exactly the window between
  62. // ReferenceResolver.clearCaches() calls — clearImportResolverMemos() is invoked
  63. // there, so the staleness discipline matches the resolver's own caches.
  64. const importPathMemos = new WeakMap<ResolutionContext, Map<string, string | null>>();
  65. const exportedSymbolMemos = new WeakMap<ResolutionContext, Map<string, Node | undefined>>();
  66. /**
  67. * Per-file index of exported symbols, replacing repeated linear `.find`s over
  68. * `getNodesInFile` arrays (a barrel-heavy repo scans its biggest files once
  69. * per referencing symbol otherwise). First-wins insertion preserves exactly
  70. * the array-order semantics of the `.find` calls it replaces.
  71. */
  72. interface FileExportIndex {
  73. byName: Map<string, Node>;
  74. defaultComponent: Node | undefined;
  75. defaultFnClass: Node | undefined;
  76. }
  77. const fileExportIndexes = new WeakMap<ResolutionContext, Map<string, FileExportIndex>>();
  78. function getFileExportIndex(filePath: string, context: ResolutionContext): FileExportIndex {
  79. let perFile = fileExportIndexes.get(context);
  80. if (!perFile) {
  81. perFile = new Map();
  82. fileExportIndexes.set(context, perFile);
  83. }
  84. let idx = perFile.get(filePath);
  85. if (!idx) {
  86. idx = { byName: new Map(), defaultComponent: undefined, defaultFnClass: undefined };
  87. for (const n of context.getNodesInFile(filePath)) {
  88. if (!n.isExported) continue;
  89. if (!idx.byName.has(n.name)) idx.byName.set(n.name, n);
  90. if (idx.defaultComponent === undefined && n.kind === 'component') idx.defaultComponent = n;
  91. if (idx.defaultFnClass === undefined && (n.kind === 'function' || n.kind === 'class')) idx.defaultFnClass = n;
  92. }
  93. perFile.set(filePath, idx);
  94. }
  95. return idx;
  96. }
  97. /** Drop the per-context memo tables (see ReferenceResolver.clearCaches). */
  98. export function clearImportResolverMemos(context: ResolutionContext): void {
  99. importPathMemos.delete(context);
  100. exportedSymbolMemos.delete(context);
  101. fileExportIndexes.delete(context);
  102. luaFileBasenameIndexes.delete(context);
  103. cobolCopybookIndexes.delete(context);
  104. }
  105. export function resolveImportPath(
  106. importPath: string,
  107. fromFile: string,
  108. language: Language,
  109. context: ResolutionContext
  110. ): string | null {
  111. let memo = importPathMemos.get(context);
  112. if (!memo) {
  113. memo = new Map();
  114. importPathMemos.set(context, memo);
  115. }
  116. const key = `${language}\0${fromFile}\0${importPath}`;
  117. const hit = memo.get(key);
  118. if (hit !== undefined || memo.has(key)) return hit ?? null;
  119. const resolved = resolveImportPathUncached(importPath, fromFile, language, context);
  120. memo.set(key, resolved);
  121. return resolved;
  122. }
  123. function resolveImportPathUncached(
  124. importPath: string,
  125. fromFile: string,
  126. language: Language,
  127. context: ResolutionContext
  128. ): string | null {
  129. // COBOL COPY/EXEC SQL INCLUDE names a copybook member, not a path — the
  130. // compiler searches a library, so we match against indexed file basenames.
  131. // Must run before isExternalImport: a bare member name would otherwise be
  132. // misclassified as an external package.
  133. if (language === 'cobol') {
  134. return resolveCobolCopybook(importPath, fromFile, context);
  135. }
  136. // Skip external/npm packages — but pass the context so the
  137. // bare-specifier heuristic can consult the project's tsconfig
  138. // alias map first (custom prefixes like `@components/*` would
  139. // otherwise be misclassified as npm).
  140. if (isExternalImport(importPath, language, context)) {
  141. return null;
  142. }
  143. const projectRoot = context.getProjectRoot();
  144. const fromDir = path.dirname(path.join(projectRoot, fromFile));
  145. // Handle relative imports
  146. if (importPath.startsWith('.')) {
  147. return resolveRelativeImport(importPath, fromDir, language, context);
  148. }
  149. // Handle absolute/aliased imports (like @/ or src/)
  150. const aliased = resolveAliasedImport(importPath, projectRoot, language, context);
  151. if (aliased) return aliased;
  152. // C/C++ include directory search: when neither relative nor aliased
  153. // resolution found a match, search -I directories from
  154. // compile_commands.json or heuristic probing.
  155. if (language === 'c' || language === 'cpp') {
  156. return resolveCppIncludePath(importPath, language, context);
  157. }
  158. return null;
  159. }
  160. /**
  161. * COBOL copybook lookup: `COPY CVACT01Y` (or `EXEC SQL INCLUDE X`) names a
  162. * library member resolved by the compiler's copybook search path, so we match
  163. * the member against indexed file basenames, case-insensitively. `.cpy` wins
  164. * over a same-named program; a same-directory hit wins within a tier. The
  165. * stem index is built once per resolution context (a per-ref scan of every
  166. * file node would go quadratic on copybook-heavy repos).
  167. */
  168. const cobolCopybookIndexes = new WeakMap<ResolutionContext, Map<string, string[]>>();
  169. /**
  170. * Per-context basename → file-paths index for Lua/Luau require resolution
  171. * (cobolCopybookIndexes pattern). resolveLuaRequire previously ran
  172. * `getAllFiles().filter(endsWith)` FOUR times per require ref — ~7.5k string
  173. * suffix scans each, measured at ~0.9ms/ref (2.7s combined on kong's 3k
  174. * requires). Buckets preserve getAllFiles() iteration order so the per-suffix
  175. * candidate list filters to exactly the array the full scan produced —
  176. * identical matches, identical stable sort, identical winner.
  177. */
  178. const luaFileBasenameIndexes = new WeakMap<ResolutionContext, Map<string, string[]>>();
  179. function luaBasenameIndex(context: ResolutionContext): Map<string, string[]> {
  180. let index = luaFileBasenameIndexes.get(context);
  181. if (!index) {
  182. index = new Map();
  183. for (const f of context.getAllFiles()) {
  184. const base = f.split('/').pop() ?? '';
  185. const paths = index.get(base);
  186. if (paths) paths.push(f);
  187. else index.set(base, [f]);
  188. }
  189. luaFileBasenameIndexes.set(context, index);
  190. }
  191. return index;
  192. }
  193. function resolveCobolCopybook(
  194. member: string,
  195. fromFile: string,
  196. context: ResolutionContext
  197. ): string | null {
  198. let index = cobolCopybookIndexes.get(context);
  199. if (!index) {
  200. index = new Map();
  201. for (const fileNode of context.getNodesByKind('file')) {
  202. const normalized = fileNode.filePath.replace(/\\/g, '/');
  203. const base = normalized.split('/').pop() ?? '';
  204. const dot = base.lastIndexOf('.');
  205. const stem = (dot > 0 ? base.slice(0, dot) : base).toLowerCase();
  206. const paths = index.get(stem);
  207. if (paths) paths.push(fileNode.filePath);
  208. else index.set(stem, [fileNode.filePath]);
  209. }
  210. cobolCopybookIndexes.set(context, index);
  211. }
  212. const candidates = index.get(member.toLowerCase());
  213. if (!candidates || candidates.length === 0) return null;
  214. const fromDir = fromFile.replace(/\\/g, '/').split('/').slice(0, -1).join('/');
  215. let best: string | null = null;
  216. let bestScore = -1;
  217. for (const candidate of candidates) {
  218. const normalized = candidate.replace(/\\/g, '/');
  219. const ext = normalized.slice(normalized.lastIndexOf('.')).toLowerCase();
  220. let score = 0;
  221. if (ext === '.cpy') score += 4;
  222. else if (ext === '.cbl' || ext === '.cob' || ext === '.cobol') score += 2;
  223. if (normalized.split('/').slice(0, -1).join('/') === fromDir) score += 1;
  224. if (score > bestScore) {
  225. bestScore = score;
  226. best = candidate;
  227. }
  228. }
  229. return best;
  230. }
  231. /**
  232. * C and C++ standard library header names (without delimiters).
  233. * Used by isExternalImport to filter system includes from resolution.
  234. */
  235. const C_CPP_STDLIB_HEADERS = new Set([
  236. // C standard library headers
  237. 'assert.h', 'complex.h', 'ctype.h', 'errno.h', 'fenv.h', 'float.h',
  238. 'inttypes.h', 'iso646.h', 'limits.h', 'locale.h', 'math.h', 'setjmp.h',
  239. 'signal.h', 'stdalign.h', 'stdarg.h', 'stdatomic.h', 'stdbool.h',
  240. 'stddef.h', 'stdint.h', 'stdio.h', 'stdlib.h', 'stdnoreturn.h',
  241. 'string.h', 'tgmath.h', 'threads.h', 'time.h', 'uchar.h', 'wchar.h',
  242. 'wctype.h',
  243. // C++ C-library wrappers (cname form)
  244. 'cassert', 'ccomplex', 'cctype', 'cerrno', 'cfenv', 'cfloat',
  245. 'cinttypes', 'ciso646', 'climits', 'clocale', 'cmath', 'csetjmp',
  246. 'csignal', 'cstdalign', 'cstdarg', 'cstdbool', 'cstddef', 'cstdint',
  247. 'cstdio', 'cstdlib', 'cstring', 'ctgmath', 'ctime', 'cuchar',
  248. 'cwchar', 'cwctype',
  249. // C++ STL headers
  250. 'algorithm', 'any', 'array', 'atomic', 'barrier', 'bit', 'bitset',
  251. 'charconv', 'chrono', 'codecvt', 'compare', 'complex', 'concepts',
  252. 'condition_variable', 'coroutine', 'deque', 'exception', 'execution',
  253. 'expected', 'filesystem', 'format', 'forward_list', 'fstream',
  254. 'functional', 'future', 'generator', 'initializer_list', 'iomanip',
  255. 'ios', 'iosfwd', 'iostream', 'istream', 'iterator', 'latch',
  256. 'limits', 'list', 'locale', 'map', 'mdspan', 'memory', 'memory_resource',
  257. 'mutex', 'new', 'numbers', 'numeric', 'optional', 'ostream', 'print',
  258. 'queue', 'random', 'ranges', 'ratio', 'regex', 'scoped_allocator',
  259. 'semaphore', 'set', 'shared_mutex', 'source_location', 'span',
  260. 'spanstream', 'sstream', 'stack', 'stacktrace', 'stdexcept',
  261. 'stdfloat', 'stop_token', 'streambuf', 'string', 'string_view',
  262. 'strstream', 'syncstream', 'system_error', 'thread', 'tuple',
  263. 'type_traits', 'typeindex', 'typeinfo', 'unordered_map',
  264. 'unordered_set', 'utility', 'valarray', 'variant', 'vector',
  265. 'version',
  266. ]);
  267. /**
  268. * Check if an import is external (npm package, etc.)
  269. *
  270. * `context` is consulted for project-defined path aliases
  271. * (tsconfig/jsconfig `paths`). Without that check, custom prefixes
  272. * like `@components/*` would fail the bare-specifier heuristic and
  273. * be classified as external before alias resolution can run.
  274. */
  275. function isExternalImport(
  276. importPath: string,
  277. language: Language,
  278. context?: ResolutionContext
  279. ): boolean {
  280. // Relative imports are not external
  281. if (importPath.startsWith('.')) {
  282. return false;
  283. }
  284. // Workspace-member imports (`@scope/ui`, `@scope/ui/widgets`) are LOCAL to
  285. // a monorepo even though they look like bare npm specifiers. Consult the
  286. // workspace map first so they aren't misclassified as external (#629). The
  287. // map is null for single-package repos, so this is a no-op there.
  288. const workspaces = context?.getWorkspacePackages?.();
  289. if (workspaces && resolveWorkspaceImport(importPath, workspaces)) {
  290. return false;
  291. }
  292. // Common external patterns
  293. if (language === 'typescript' || language === 'javascript' || language === 'tsx' || language === 'jsx' || language === 'arkts') {
  294. // Node built-ins
  295. if (['fs', 'path', 'os', 'crypto', 'http', 'https', 'url', 'util', 'events', 'stream', 'child_process', 'buffer'].includes(importPath)) {
  296. return true;
  297. }
  298. // Project-defined alias prefix? Treat as local.
  299. const aliases = context?.getProjectAliases?.();
  300. if (aliases) {
  301. for (const pat of aliases.patterns) {
  302. if (importPath.startsWith(pat.prefix)) return false;
  303. }
  304. }
  305. // Scoped packages or bare specifiers that don't start with aliases
  306. if (!importPath.startsWith('@/') && !importPath.startsWith('~/') && !importPath.startsWith('src/')) {
  307. // Likely an npm package
  308. return true;
  309. }
  310. }
  311. if (language === 'python') {
  312. // Standard library modules
  313. const stdLibs = ['os', 'sys', 'json', 're', 'math', 'datetime', 'collections', 'typing', 'pathlib', 'logging'];
  314. if (stdLibs.includes(importPath.split('.')[0]!)) {
  315. return true;
  316. }
  317. }
  318. if (language === 'go') {
  319. // Relative imports (rare in idiomatic Go but the grammar allows them).
  320. if (importPath.startsWith('.')) {
  321. return false;
  322. }
  323. // In-module imports look like `<module-path>/sub/pkg` — local to
  324. // this project. Without the module-path check we'd flag every
  325. // cross-package call in a Go monorepo as external (issue #388).
  326. const mod = context?.getGoModule?.();
  327. if (mod && (importPath === mod.modulePath || importPath.startsWith(mod.modulePath + '/'))) {
  328. return false;
  329. }
  330. // `internal/` packages stay local even when go.mod is missing —
  331. // preserves the pre-#388 escape hatch for repos without a parsed module path.
  332. if (importPath.includes('/internal/')) {
  333. return false;
  334. }
  335. // Anything else is the Go standard library or a third-party module.
  336. return true;
  337. }
  338. if (language === 'c' || language === 'cpp') {
  339. // C/C++ standard library headers — both C-style (<stdio.h>) and
  340. // C++-style (<cstdio>, <vector>) forms. Checked against the import
  341. // path (which the extractor strips of <> or "" delimiters).
  342. if (C_CPP_STDLIB_HEADERS.has(importPath)) return true;
  343. // C++ headers without .h extension (e.g. "vector", "string")
  344. const withoutExt = importPath.replace(/\.h$/, '');
  345. if (C_CPP_STDLIB_HEADERS.has(withoutExt)) return true;
  346. }
  347. return false;
  348. }
  349. /**
  350. * Resolve a relative import
  351. */
  352. function resolveRelativeImport(
  353. importPath: string,
  354. fromDir: string,
  355. language: Language,
  356. context: ResolutionContext
  357. ): string | null {
  358. const projectRoot = context.getProjectRoot();
  359. const extensions = EXTENSION_RESOLUTION[language] || [];
  360. // Python dotted-relative imports (`from .certs import x`, `from ..pkg.mod
  361. // import y`): leading dots are PACKAGE levels (1 = current package), and the
  362. // remainder is a dotted submodule path. `path.resolve(dir, '.certs')` would
  363. // treat `.certs` as a literal hidden filename, so translate the Python form
  364. // to a real filesystem-relative path before resolving.
  365. if (language === 'python' && importPath.startsWith('.')) {
  366. const dots = importPath.length - importPath.replace(/^\.+/, '').length;
  367. const up = '../'.repeat(Math.max(0, dots - 1)); // 1 dot = current dir
  368. const rest = importPath.slice(dots).replace(/\./g, '/'); // 'sub.mod' -> 'sub/mod'
  369. const pyBase = path.resolve(fromDir, up + rest);
  370. const pyRel = path.relative(projectRoot, pyBase).replace(/\\/g, '/');
  371. for (const ext of extensions) {
  372. if (context.fileExists(pyRel + ext)) return pyRel + ext;
  373. }
  374. if (pyRel && context.fileExists(pyRel)) return pyRel;
  375. return null;
  376. }
  377. // Try the path as-is first
  378. const basePath = path.resolve(fromDir, importPath);
  379. const relativePath = path.relative(projectRoot, basePath).replace(/\\/g, '/');
  380. // Try each extension
  381. for (const ext of extensions) {
  382. const candidatePath = relativePath + ext;
  383. if (context.fileExists(candidatePath)) {
  384. return candidatePath;
  385. }
  386. }
  387. // Try without extension (might already have one)
  388. if (context.fileExists(relativePath)) {
  389. return relativePath;
  390. }
  391. return null;
  392. }
  393. /**
  394. * Resolve an aliased/absolute import.
  395. *
  396. * Tries, in order:
  397. * 1. Project-defined `compilerOptions.paths` (tsconfig/jsconfig).
  398. * Each pattern can have multiple replacements; tried in tsconfig
  399. * priority order with extension permutations.
  400. * 2. The legacy hard-coded fallback list (`@/`, `~/`, `src/`, ...)
  401. * for projects that have aliases but no tsconfig paths block.
  402. * 3. Direct path lookup (with extensions).
  403. */
  404. function resolveAliasedImport(
  405. importPath: string,
  406. projectRoot: string,
  407. language: Language,
  408. context: ResolutionContext
  409. ): string | null {
  410. const extensions = EXTENSION_RESOLUTION[language] || [];
  411. const tryWithExt = (basePath: string): string | null => {
  412. for (const ext of extensions) {
  413. const candidate = basePath + ext;
  414. if (context.fileExists(candidate)) return candidate;
  415. }
  416. if (context.fileExists(basePath)) return basePath;
  417. return null;
  418. };
  419. // 1. Project tsconfig/jsconfig paths.
  420. const aliasMap = context.getProjectAliases?.();
  421. if (aliasMap) {
  422. const candidates = applyAliases(importPath, aliasMap, projectRoot);
  423. for (const c of candidates) {
  424. const hit = tryWithExt(c);
  425. if (hit) return hit;
  426. }
  427. }
  428. // 1.5 Workspace packages (`@scope/ui/widgets` → `packages/ui/widgets`).
  429. // Resolves a monorepo member import to the member's directory; the
  430. // extension/index permutations below then find its barrel (#629).
  431. const workspaces = context.getWorkspacePackages?.();
  432. if (workspaces) {
  433. const base = resolveWorkspaceImport(importPath, workspaces);
  434. if (base) {
  435. const hit = tryWithExt(base);
  436. if (hit) return hit;
  437. }
  438. }
  439. // 2. Hard-coded fallback list. Kept for projects that use these
  440. // conventional aliases without declaring them in tsconfig.
  441. const fallbackAliases: Record<string, string> = {
  442. '@/': 'src/',
  443. '~/': 'src/',
  444. '@src/': 'src/',
  445. 'src/': 'src/',
  446. '@app/': 'app/',
  447. 'app/': 'app/',
  448. };
  449. for (const [alias, replacement] of Object.entries(fallbackAliases)) {
  450. if (importPath.startsWith(alias)) {
  451. const hit = tryWithExt(importPath.replace(alias, replacement));
  452. if (hit) return hit;
  453. }
  454. }
  455. // 3. Direct path.
  456. return tryWithExt(importPath);
  457. }
  458. /**
  459. * C/C++ include directory cache (keyed by project root).
  460. * Loaded once per resolver instance, shared across calls.
  461. */
  462. const cppIncludeDirCache = new Map<string, string[]>();
  463. /**
  464. * Clear the C/C++ include directory cache (call between indexing runs)
  465. */
  466. export function clearCppIncludeDirCache(): void {
  467. cppIncludeDirCache.clear();
  468. }
  469. /**
  470. * Discover C/C++ include search directories for a project.
  471. *
  472. * Strategy:
  473. * 1. Look for compile_commands.json (Clang compilation database) in the
  474. * project root and common build subdirectories. Parse -I and -isystem
  475. * flags from compiler commands.
  476. * 2. If no compilation database is found, probe for common convention
  477. * directories (include/, src/, lib/, api/) and top-level directories
  478. * containing .h/.hpp files.
  479. *
  480. * Returns paths relative to projectRoot.
  481. */
  482. export function loadCppIncludeDirs(projectRoot: string): string[] {
  483. const cached = cppIncludeDirCache.get(projectRoot);
  484. if (cached !== undefined) return cached;
  485. const dirs = loadCppIncludeDirsFromCompileDB(projectRoot)
  486. || loadCppIncludeDirsHeuristic(projectRoot);
  487. cppIncludeDirCache.set(projectRoot, dirs);
  488. return dirs;
  489. }
  490. /**
  491. * Try to load include directories from compile_commands.json.
  492. * Returns null if no compilation database is found (so the heuristic
  493. * fallback can run). Returns an array (possibly empty) otherwise.
  494. */
  495. function loadCppIncludeDirsFromCompileDB(projectRoot: string): string[] | null {
  496. const candidates = [
  497. path.join(projectRoot, 'compile_commands.json'),
  498. path.join(projectRoot, 'build', 'compile_commands.json'),
  499. path.join(projectRoot, 'cmake-build-debug', 'compile_commands.json'),
  500. path.join(projectRoot, 'cmake-build-release', 'compile_commands.json'),
  501. path.join(projectRoot, 'out', 'compile_commands.json'),
  502. ];
  503. let dbPath: string | undefined;
  504. for (const c of candidates) {
  505. try {
  506. if (fs.existsSync(c)) {
  507. dbPath = c;
  508. break;
  509. }
  510. } catch {
  511. // ignore
  512. }
  513. }
  514. if (!dbPath) return null;
  515. try {
  516. const content = fs.readFileSync(dbPath, 'utf-8');
  517. const entries = JSON.parse(content) as Array<{
  518. directory: string;
  519. command?: string;
  520. arguments?: string[];
  521. }>;
  522. if (!Array.isArray(entries)) return null;
  523. const dirSet = new Set<string>();
  524. for (const entry of entries) {
  525. const dir = entry.directory || projectRoot;
  526. const args = entry.arguments || (entry.command ? shlexSplit(entry.command) : []);
  527. for (let i = 0; i < args.length; i++) {
  528. const arg = args[i]!;
  529. let includeDir: string | undefined;
  530. // -I<dir> (no space)
  531. if (arg.startsWith('-I') && arg.length > 2) {
  532. includeDir = arg.substring(2);
  533. }
  534. // -isystem <dir> (space-separated)
  535. else if ((arg === '-isystem' || arg === '-I') && i + 1 < args.length) {
  536. includeDir = args[i + 1];
  537. i++; // skip next arg
  538. }
  539. if (includeDir) {
  540. // Normalize: resolve relative to the compilation directory
  541. const absPath = path.isAbsolute(includeDir)
  542. ? includeDir
  543. : path.resolve(dir, includeDir);
  544. const relPath = path.relative(projectRoot, absPath).replace(/\\/g, '/');
  545. // Skip system directories and paths outside the project
  546. // (relative paths starting with .. or absolute paths like
  547. // /usr/include or C:\usr on Windows)
  548. if (!relPath.startsWith('..') && relPath.length > 0 && !path.isAbsolute(relPath)) {
  549. dirSet.add(relPath);
  550. }
  551. }
  552. }
  553. }
  554. return Array.from(dirSet);
  555. } catch {
  556. return null;
  557. }
  558. }
  559. /**
  560. * Minimal shlex-style split for compiler command strings.
  561. * Handles double-quoted and single-quoted arguments.
  562. */
  563. function shlexSplit(cmd: string): string[] {
  564. const result: string[] = [];
  565. let i = 0;
  566. while (i < cmd.length) {
  567. // Skip whitespace
  568. while (i < cmd.length && /\s/.test(cmd[i]!)) i++;
  569. if (i >= cmd.length) break;
  570. const ch = cmd[i]!;
  571. if (ch === '"') {
  572. i++;
  573. let arg = '';
  574. while (i < cmd.length && cmd[i] !== '"') {
  575. if (cmd[i] === '\\' && i + 1 < cmd.length) { i++; arg += cmd[i]; }
  576. else { arg += cmd[i]; }
  577. i++;
  578. }
  579. i++; // closing quote
  580. result.push(arg);
  581. } else if (ch === "'") {
  582. i++;
  583. let arg = '';
  584. while (i < cmd.length && cmd[i] !== "'") { arg += cmd[i]; i++; }
  585. i++; // closing quote
  586. result.push(arg);
  587. } else {
  588. let arg = '';
  589. while (i < cmd.length && !/\s/.test(cmd[i]!)) { arg += cmd[i]; i++; }
  590. result.push(arg);
  591. }
  592. }
  593. return result;
  594. }
  595. /**
  596. * Heuristic include directory discovery when no compile_commands.json exists.
  597. * Checks common convention directories and scans top-level dirs for headers.
  598. */
  599. function loadCppIncludeDirsHeuristic(projectRoot: string): string[] {
  600. const dirs: string[] = [];
  601. const conventionDirs = ['include', 'src', 'lib', 'api', 'inc'];
  602. try {
  603. const entries = fs.readdirSync(projectRoot, { withFileTypes: true });
  604. for (const entry of entries) {
  605. if (!entry.isDirectory()) continue;
  606. const name = entry.name;
  607. // Convention directories
  608. if (conventionDirs.includes(name.toLowerCase())) {
  609. dirs.push(name);
  610. continue;
  611. }
  612. // Any top-level directory containing .h or .hpp files
  613. try {
  614. const subFiles = fs.readdirSync(path.join(projectRoot, name));
  615. if (subFiles.some(f => /\.(h|hpp|hxx|hh)$/i.test(f))) {
  616. dirs.push(name);
  617. }
  618. } catch {
  619. // ignore permission errors
  620. }
  621. }
  622. } catch {
  623. // ignore
  624. }
  625. return dirs;
  626. }
  627. /**
  628. * Resolve a C/C++ include path by searching include directories.
  629. * Called as a fallback after relative and aliased resolution fail.
  630. */
  631. function resolveCppIncludePath(
  632. importPath: string,
  633. language: Language,
  634. context: ResolutionContext
  635. ): string | null {
  636. const includeDirs = context.getCppIncludeDirs?.() ?? [];
  637. const extensions = EXTENSION_RESOLUTION[language] ?? [];
  638. for (const dir of includeDirs) {
  639. const normalizedDir = dir.replace(/\\/g, '/');
  640. for (const ext of extensions) {
  641. const candidate = normalizedDir + '/' + importPath + ext;
  642. if (context.fileExists(candidate)) return candidate;
  643. }
  644. // Try as-is (already has extension)
  645. const candidate = normalizedDir + '/' + importPath;
  646. if (context.fileExists(candidate)) return candidate;
  647. }
  648. return null;
  649. }
  650. /**
  651. * Is this reference a PHP include/require PATH (vs a namespace `use` symbol)?
  652. *
  653. * include/require emit a file path ("lib.php", "inc/db.php", "../x.php"),
  654. * whereas namespace use is an FQN (App\Foo\Bar) or a bare class symbol
  655. * (Closure). PHP identifiers contain neither '/' nor '.', so a slash or dot
  656. * marks a path-shaped include. Such references resolve to files only — never
  657. * to a same-named symbol — so callers must not fall back to the name-matcher.
  658. */
  659. export function isPhpIncludePathRef(ref: UnresolvedRef): boolean {
  660. return (
  661. ref.language === 'php' &&
  662. ref.referenceKind === 'imports' &&
  663. (ref.referenceName.includes('/') || ref.referenceName.includes('.'))
  664. );
  665. }
  666. /**
  667. * Is this a COBOL COPY / EXEC SQL INCLUDE copybook reference? These resolve
  668. * to files only (or stay unresolved for compiler-supplied members) — never
  669. * to a same-named symbol via the name-matcher.
  670. */
  671. export function isCobolCopybookRef(ref: UnresolvedRef): boolean {
  672. return ref.language === 'cobol' && ref.referenceKind === 'imports';
  673. }
  674. /**
  675. * Resolve a PHP include/require path to a project-relative file path.
  676. *
  677. * PHP resolves includes relative to the including file's directory (the
  678. * common case for procedural codebases); php.ini `include_path` is not
  679. * modeled. Callers pass an already-extracted static literal path.
  680. */
  681. function resolvePhpIncludePath(
  682. includePath: string,
  683. fromFile: string,
  684. context: ResolutionContext
  685. ): string | null {
  686. const projectRoot = context.getProjectRoot();
  687. const fromDir = path.dirname(path.join(projectRoot, fromFile));
  688. const basePath = path.resolve(fromDir, includePath);
  689. const relativePath = path.relative(projectRoot, basePath).replace(/\\/g, '/');
  690. if (context.fileExists(relativePath)) return relativePath;
  691. // The literal may omit the .php extension (e.g. include "config").
  692. for (const ext of EXTENSION_RESOLUTION.php ?? []) {
  693. if (context.fileExists(relativePath + ext)) return relativePath + ext;
  694. }
  695. return null;
  696. }
  697. /**
  698. * Extract import mappings from a file
  699. */
  700. export function extractImportMappings(
  701. _filePath: string,
  702. content: string,
  703. language: Language
  704. ): ImportMapping[] {
  705. const mappings: ImportMapping[] = [];
  706. if (language === 'typescript' || language === 'javascript' || language === 'tsx' || language === 'jsx' || language === 'arkts') {
  707. mappings.push(...extractJSImports(content));
  708. } else if (language === 'svelte' || language === 'vue' || language === 'astro') {
  709. // Svelte/Vue single-file components import via plain ES6 inside their
  710. // `<script>` block (Astro: the `---` frontmatter). Without this, a
  711. // `.svelte`/`.vue`/`.astro` consumer produces
  712. // zero import mappings, so `resolveViaImport` can't run and a barrel
  713. // import (`import { Foo } from './lib'`) falls back to name-matching —
  714. // which silently fails whenever the re-export alias differs from the
  715. // component's real name, yielding a false 0 callers (#629). The ES6
  716. // import regex only matches `import … from '…'`, so running it over the
  717. // whole SFC (markup + styles included) is safe.
  718. mappings.push(...extractJSImports(content));
  719. } else if (language === 'python') {
  720. mappings.push(...extractPythonImports(content));
  721. } else if (language === 'go') {
  722. mappings.push(...extractGoImports(content));
  723. } else if (language === 'java' || language === 'kotlin') {
  724. mappings.push(...extractJavaImports(content));
  725. } else if (language === 'php') {
  726. mappings.push(...extractPHPImports(content));
  727. } else if (language === 'c' || language === 'cpp') {
  728. mappings.push(...extractCppImports(content));
  729. }
  730. return mappings;
  731. }
  732. /**
  733. * Extract JS/TS import mappings
  734. */
  735. function extractJSImports(content: string): ImportMapping[] {
  736. const mappings: ImportMapping[] = [];
  737. // ES6 imports
  738. const importRegex = /import\s+(?:(\w+)\s*,?\s*)?(?:\{([^}]+)\})?\s*(?:(\*)\s+as\s+(\w+))?\s*from\s*['"]([^'"]+)['"]/g;
  739. let match;
  740. while ((match = importRegex.exec(content)) !== null) {
  741. const [, defaultImport, namedImports, star, namespaceAlias, source] = match;
  742. // Default import
  743. if (defaultImport) {
  744. mappings.push({
  745. localName: defaultImport,
  746. exportedName: 'default',
  747. source: source!,
  748. isDefault: true,
  749. isNamespace: false,
  750. });
  751. }
  752. // Named imports
  753. if (namedImports) {
  754. const names = namedImports.split(',').map((s) => s.trim());
  755. for (const name of names) {
  756. const aliasMatch = name.match(/(\w+)\s+as\s+(\w+)/);
  757. if (aliasMatch) {
  758. mappings.push({
  759. localName: aliasMatch[2]!,
  760. exportedName: aliasMatch[1]!,
  761. source: source!,
  762. isDefault: false,
  763. isNamespace: false,
  764. });
  765. } else if (name) {
  766. mappings.push({
  767. localName: name,
  768. exportedName: name,
  769. source: source!,
  770. isDefault: false,
  771. isNamespace: false,
  772. });
  773. }
  774. }
  775. }
  776. // Namespace import
  777. if (star && namespaceAlias) {
  778. mappings.push({
  779. localName: namespaceAlias,
  780. exportedName: '*',
  781. source: source!,
  782. isDefault: false,
  783. isNamespace: true,
  784. });
  785. }
  786. }
  787. // Require statements
  788. const requireRegex = /(?:const|let|var)\s+(?:(\w+)|{([^}]+)})\s*=\s*require\(['"]([^'"]+)['"]\)/g;
  789. while ((match = requireRegex.exec(content)) !== null) {
  790. const [, defaultName, destructured, source] = match;
  791. if (defaultName) {
  792. mappings.push({
  793. localName: defaultName,
  794. exportedName: 'default',
  795. source: source!,
  796. isDefault: true,
  797. isNamespace: false,
  798. });
  799. }
  800. if (destructured) {
  801. const names = destructured.split(',').map((s) => s.trim());
  802. for (const name of names) {
  803. const aliasMatch = name.match(/(\w+)\s*:\s*(\w+)/);
  804. if (aliasMatch) {
  805. mappings.push({
  806. localName: aliasMatch[2]!,
  807. exportedName: aliasMatch[1]!,
  808. source: source!,
  809. isDefault: false,
  810. isNamespace: false,
  811. });
  812. } else if (name) {
  813. mappings.push({
  814. localName: name,
  815. exportedName: name,
  816. source: source!,
  817. isDefault: false,
  818. isNamespace: false,
  819. });
  820. }
  821. }
  822. }
  823. }
  824. return mappings;
  825. }
  826. /**
  827. * Extract Python import mappings
  828. */
  829. function extractPythonImports(content: string): ImportMapping[] {
  830. const mappings: ImportMapping[] = [];
  831. // from X import Y
  832. const fromImportRegex = /from\s+([\w.]+)\s+import\s+([^#\n]+)/g;
  833. let match;
  834. while ((match = fromImportRegex.exec(content)) !== null) {
  835. const [, source, imports] = match;
  836. const names = imports!.split(',').map((s) => s.trim());
  837. for (const name of names) {
  838. const aliasMatch = name.match(/(\w+)\s+as\s+(\w+)/);
  839. if (aliasMatch) {
  840. mappings.push({
  841. localName: aliasMatch[2]!,
  842. exportedName: aliasMatch[1]!,
  843. source: source!,
  844. isDefault: false,
  845. isNamespace: false,
  846. });
  847. } else if (name && name !== '*') {
  848. mappings.push({
  849. localName: name,
  850. exportedName: name,
  851. source: source!,
  852. isDefault: false,
  853. isNamespace: false,
  854. });
  855. }
  856. }
  857. }
  858. // import X
  859. const importRegex = /^import\s+([\w.]+)(?:\s+as\s+(\w+))?/gm;
  860. while ((match = importRegex.exec(content)) !== null) {
  861. const [, source, alias] = match;
  862. const localName = alias || source!.split('.').pop()!;
  863. mappings.push({
  864. localName,
  865. exportedName: '*',
  866. source: source!,
  867. isDefault: false,
  868. isNamespace: true,
  869. });
  870. }
  871. return mappings;
  872. }
  873. /**
  874. * Extract Go import mappings
  875. */
  876. function extractGoImports(content: string): ImportMapping[] {
  877. const mappings: ImportMapping[] = [];
  878. // import "path" or import alias "path"
  879. const singleImportRegex = /import\s+(?:(\w+)\s+)?["']([^"']+)["']/g;
  880. let match;
  881. while ((match = singleImportRegex.exec(content)) !== null) {
  882. const [, alias, source] = match;
  883. const packageName = source!.split('/').pop()!;
  884. mappings.push({
  885. localName: alias || packageName,
  886. exportedName: '*',
  887. source: source!,
  888. isDefault: false,
  889. isNamespace: true,
  890. });
  891. }
  892. // import ( ... ) block
  893. const blockImportRegex = /import\s*\(\s*([^)]+)\s*\)/gs;
  894. while ((match = blockImportRegex.exec(content)) !== null) {
  895. const block = match[1]!;
  896. const lineRegex = /(?:(\w+)\s+)?["']([^"']+)["']/g;
  897. let lineMatch;
  898. while ((lineMatch = lineRegex.exec(block)) !== null) {
  899. const [, alias, source] = lineMatch;
  900. const packageName = source!.split('/').pop()!;
  901. mappings.push({
  902. localName: alias || packageName,
  903. exportedName: '*',
  904. source: source!,
  905. isDefault: false,
  906. isNamespace: true,
  907. });
  908. }
  909. }
  910. return mappings;
  911. }
  912. /**
  913. * Extract Java / Kotlin import mappings.
  914. *
  915. * Java/Kotlin imports carry the full qualified name of the imported
  916. * symbol — `import com.example.dao.converter.FooConverter;` — which is
  917. * exactly the disambiguation signal we need when two packages both
  918. * declare a `FooConverter`. Pre-#314 the resolver had no Java branch
  919. * here at all, so this mapping was empty and cross-module name
  920. * collisions were resolved by file-path proximity (often wrongly).
  921. *
  922. * `import static com.example.Foo.bar;` is parsed as a local-name `bar`
  923. * pointing at FQN `com.example.Foo.bar` so static-method call sites
  924. * (`bar(...)`) can resolve through the same import lookup.
  925. */
  926. function extractJavaImports(content: string): ImportMapping[] {
  927. const mappings: ImportMapping[] = [];
  928. // Strip line and block comments so `// import foo;` doesn't false-match.
  929. const stripped = content
  930. .replace(/\/\*[\s\S]*?\*\//g, '')
  931. .replace(/\/\/[^\n]*/g, '');
  932. // `import [static] <fqn>[.*];`
  933. const re = /^\s*import\s+(static\s+)?([\w.]+(?:\.\*)?)\s*;/gm;
  934. let match: RegExpExecArray | null;
  935. while ((match = re.exec(stripped)) !== null) {
  936. const fqn = match[2]!;
  937. // `import com.example.*;` — wildcard. We can't materialize a single
  938. // local name; skip and let name-matching handle members reachable
  939. // through the wildcard. (Future enhancement: enumerate package files.)
  940. if (fqn.endsWith('.*')) continue;
  941. const parts = fqn.split('.');
  942. const localName = parts[parts.length - 1];
  943. if (!localName) continue;
  944. mappings.push({
  945. localName,
  946. exportedName: localName,
  947. source: fqn,
  948. isDefault: false,
  949. isNamespace: false,
  950. });
  951. }
  952. return mappings;
  953. }
  954. /**
  955. * Extract PHP import mappings (use statements)
  956. */
  957. function extractPHPImports(content: string): ImportMapping[] {
  958. const mappings: ImportMapping[] = [];
  959. // use Namespace\Class; or use Namespace\Class as Alias;
  960. const useRegex = /use\s+([\w\\]+)(?:\s+as\s+(\w+))?;/g;
  961. let match;
  962. while ((match = useRegex.exec(content)) !== null) {
  963. const [, fullPath, alias] = match;
  964. const className = fullPath!.split('\\').pop()!;
  965. mappings.push({
  966. localName: alias || className,
  967. exportedName: className,
  968. source: fullPath!,
  969. isDefault: false,
  970. isNamespace: false,
  971. });
  972. }
  973. return mappings;
  974. }
  975. /**
  976. * Extract C/C++ import mappings from #include directives.
  977. *
  978. * #include brings all symbols from the included header into scope
  979. * (namespace import), so each mapping uses isNamespace: true and
  980. * exportedName: '*'. The localName is set to the header's basename
  981. * without extension so that symbol references like `MyClass` can
  982. * match against any include that might provide it.
  983. */
  984. function extractCppImports(content: string): ImportMapping[] {
  985. const mappings: ImportMapping[] = [];
  986. // Match both #include <...> and #include "..."
  987. const includeRegex = /^\s*#\s*include\s+[<"]([^>"]+)[>"]/gm;
  988. let match;
  989. while ((match = includeRegex.exec(content)) !== null) {
  990. const modulePath = match[1]!;
  991. // Basename without extension for localName matching
  992. const basename = modulePath.split('/').pop()!.replace(/\.(h|hpp|hxx|hh|inl|ipp|cxx|cc|cpp)$/,'');
  993. mappings.push({
  994. localName: basename || modulePath,
  995. exportedName: '*',
  996. source: modulePath,
  997. isDefault: false,
  998. isNamespace: true,
  999. });
  1000. }
  1001. return mappings;
  1002. }
  1003. // Cache import mappings per file to avoid re-reading and re-parsing
  1004. const importMappingCache = new Map<string, ImportMapping[]>();
  1005. /**
  1006. * Clear the import mapping cache (call between indexing runs)
  1007. */
  1008. export function clearImportMappingCache(): void {
  1009. importMappingCache.clear();
  1010. cppIncludeDirCache.clear();
  1011. }
  1012. /**
  1013. * Strip JS line + block comments from `content` while preserving
  1014. * string literals (so `"//"` inside a string stays intact). Used by
  1015. * {@link extractReExports} so commented-out export-from statements
  1016. * don't generate phantom re-export edges.
  1017. *
  1018. * Scanner is deliberately small: it only tracks the three contexts
  1019. * relevant for JS/TS — single-quote string, double-quote string, and
  1020. * template literal. Comment recognition is the JS spec subset, no
  1021. * regex-literal awareness (which is fine for our use case: we don't
  1022. * apply this to function bodies, only to top-level files).
  1023. */
  1024. function stripJsComments(content: string): string {
  1025. let out = '';
  1026. let i = 0;
  1027. let str: '"' | "'" | '`' | null = null;
  1028. while (i < content.length) {
  1029. const ch = content[i]!;
  1030. if (str !== null) {
  1031. out += ch;
  1032. if (ch === '\\' && i + 1 < content.length) {
  1033. out += content[i + 1]!;
  1034. i += 2;
  1035. continue;
  1036. }
  1037. if (ch === str) str = null;
  1038. i++;
  1039. continue;
  1040. }
  1041. if (ch === '"' || ch === "'" || ch === '`') {
  1042. str = ch;
  1043. out += ch;
  1044. i++;
  1045. continue;
  1046. }
  1047. if (ch === '/' && content[i + 1] === '/') {
  1048. while (i < content.length && content[i] !== '\n') i++;
  1049. continue;
  1050. }
  1051. if (ch === '/' && content[i + 1] === '*') {
  1052. i += 2;
  1053. while (i < content.length && !(content[i] === '*' && content[i + 1] === '/')) i++;
  1054. i += 2;
  1055. continue;
  1056. }
  1057. out += ch;
  1058. i++;
  1059. }
  1060. return out;
  1061. }
  1062. /**
  1063. * Extract JS/TS re-export declarations from `content`.
  1064. *
  1065. * Recognised forms:
  1066. * export { foo } from './a';
  1067. * export { foo as bar } from './a';
  1068. * export * from './a';
  1069. * export * as ns from './a'; (treated as wildcard for chasing)
  1070. * export { default as Foo } from './a';
  1071. *
  1072. * The walker intentionally stays regex-based — the import-resolver
  1073. * elsewhere in this file already chooses regex over a fresh
  1074. * tree-sitter pass, and this function shares that trade-off. Errors
  1075. * fall through silently; resolution simply skips the broken file.
  1076. */
  1077. export function extractReExports(content: string, language: Language): ReExport[] {
  1078. if (
  1079. language !== 'typescript' &&
  1080. language !== 'javascript' &&
  1081. language !== 'tsx' &&
  1082. language !== 'jsx' &&
  1083. language !== 'arkts'
  1084. ) {
  1085. return [];
  1086. }
  1087. const out: ReExport[] = [];
  1088. // Pre-strip block comments + line comments so a commented-out
  1089. // `// export { x } from '...'` doesn't produce a phantom edge.
  1090. // (Template literals are still a possible source of false positives;
  1091. // a project that builds export statements as runtime strings is
  1092. // out of scope.)
  1093. const cleaned = stripJsComments(content);
  1094. // Wildcard: `export * from '...'` or `export * as ns from '...'`
  1095. const wildcardRe = /export\s*\*(?:\s+as\s+\w+)?\s*from\s*['"]([^'"]+)['"]/g;
  1096. let m: RegExpExecArray | null;
  1097. while ((m = wildcardRe.exec(cleaned)) !== null) {
  1098. out.push({ kind: 'wildcard', source: m[1]! });
  1099. }
  1100. // Named: `export { a, b as c } from '...'`
  1101. const namedRe = /export\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g;
  1102. while ((m = namedRe.exec(cleaned)) !== null) {
  1103. const inner = m[1]!;
  1104. const source = m[2]!;
  1105. for (const raw of inner.split(',')) {
  1106. const item = raw.trim();
  1107. if (!item) continue;
  1108. const aliasMatch = item.match(/^(\w+)\s+as\s+(\w+)$/);
  1109. if (aliasMatch) {
  1110. out.push({
  1111. kind: 'named',
  1112. exportedName: aliasMatch[2]!,
  1113. originalName: aliasMatch[1]!,
  1114. source,
  1115. });
  1116. } else if (/^\w+$/.test(item)) {
  1117. out.push({
  1118. kind: 'named',
  1119. exportedName: item,
  1120. originalName: item,
  1121. source,
  1122. });
  1123. }
  1124. }
  1125. }
  1126. return out;
  1127. }
  1128. /**
  1129. * Resolve a reference using import mappings
  1130. */
  1131. /**
  1132. * JVM (Java / Kotlin) imports use fully-qualified names (`import
  1133. * com.example.foo.Bar`) decoupled from filenames, so the JS/Python
  1134. * style filesystem path lookup misses them whenever the file isn't
  1135. * named after its primary symbol (Kotlin `Utils.kt` exporting `Bar`,
  1136. * top-level fns, extension fns). Resolve them through the
  1137. * `qualifiedName` index instead — populated by the package_header /
  1138. * package_declaration namespace wrappers in the extractor.
  1139. */
  1140. export function resolveJvmImport(
  1141. ref: UnresolvedRef,
  1142. context: ResolutionContext
  1143. ): ResolvedRef | null {
  1144. if (ref.referenceKind !== 'imports') return null;
  1145. if (ref.language !== 'java' && ref.language !== 'kotlin') return null;
  1146. const fqn = ref.referenceName;
  1147. const lastDot = fqn.lastIndexOf('.');
  1148. if (lastDot <= 0) return null;
  1149. const pkg = fqn.substring(0, lastDot);
  1150. const sym = fqn.substring(lastDot + 1);
  1151. // Wildcard imports (`com.example.*`) deliberately punt to name-matcher.
  1152. if (sym === '*') return null;
  1153. const candidates = context.getNodesByQualifiedName(`${pkg}::${sym}`);
  1154. if (candidates.length === 0) return null;
  1155. // Kotlin Multiplatform: an `expect` declaration and its `actual`s share one
  1156. // FQN across source sets (commonMain / androidMain / appleMain). Taking the
  1157. // first candidate let a single platform `actual` absorb every common-side
  1158. // import, so the `expect` (the canonical API a commonMain file imports)
  1159. // looked unused. Prefer the candidate CLOSEST to the importing file by
  1160. // directory proximity — a commonMain import resolves to the commonMain
  1161. // declaration — with the `expect` side as a tiebreak.
  1162. const best = candidates.length === 1 ? candidates[0]! : pickClosestJvmCandidate(candidates, ref.filePath);
  1163. return {
  1164. original: ref,
  1165. targetNodeId: best.id,
  1166. confidence: 0.95,
  1167. resolvedBy: 'import',
  1168. };
  1169. }
  1170. /**
  1171. * Pick the same-FQN candidate closest to `fromPath` by shared directory
  1172. * prefix, preferring an `expect` declaration on a tie. Used to keep a Kotlin
  1173. * Multiplatform `expect`/`actual` import resolving within the importer's own
  1174. * source set instead of an arbitrary platform `actual`.
  1175. */
  1176. function pickClosestJvmCandidate(candidates: Node[], fromPath: string): Node {
  1177. const fromDirs = fromPath.split('/').slice(0, -1);
  1178. const sharedPrefix = (p: string): number => {
  1179. const d = p.split('/').slice(0, -1);
  1180. let shared = 0;
  1181. for (let i = 0; i < Math.min(fromDirs.length, d.length); i++) {
  1182. if (fromDirs[i] === d[i]) shared++;
  1183. else break;
  1184. }
  1185. return shared;
  1186. };
  1187. const isExpect = (n: Node): boolean => Array.isArray(n.decorators) && n.decorators.includes('expect');
  1188. let best = candidates[0]!;
  1189. let bestProx = sharedPrefix(best.filePath);
  1190. for (let i = 1; i < candidates.length; i++) {
  1191. const c = candidates[i]!;
  1192. const prox = sharedPrefix(c.filePath);
  1193. if (prox > bestProx || (prox === bestProx && isExpect(c) && !isExpect(best))) {
  1194. best = c;
  1195. bestProx = prox;
  1196. }
  1197. }
  1198. return best;
  1199. }
  1200. export function resolveViaImport(
  1201. ref: UnresolvedRef,
  1202. context: ResolutionContext
  1203. ): ResolvedRef | null {
  1204. // C/C++ #include references — resolve directly to the included file
  1205. // (file→file edge), bypassing symbol lookup. The extractor emits these
  1206. // with `referenceKind: 'imports'` and `referenceName: <include path>`
  1207. // (e.g. "uint256.h" or "common/args.h"). Without this branch the
  1208. // include-dir scan path inside resolveImportPath never produces an
  1209. // edge — resolveViaImport's symbol lookup below would search the
  1210. // resolved file for a symbol named like the file extension and fail.
  1211. if ((ref.language === 'c' || ref.language === 'cpp') && ref.referenceKind === 'imports') {
  1212. // C/C++ quoted includes (`#include "X.h"`) resolve relative to the
  1213. // INCLUDING file's own directory first (the C standard's quoted-include
  1214. // search order). Prefer a same-directory header over an -I directory or a
  1215. // same-named header on another platform (windows/code/RNCAsyncStorage.h vs
  1216. // apple/.../RNCAsyncStorage.h) — the include-dir heuristic below would
  1217. // otherwise pick an arbitrary same-named header, leaving the real local one
  1218. // with no dependents.
  1219. const slash = ref.filePath.lastIndexOf('/');
  1220. const fromDir = slash >= 0 ? ref.filePath.slice(0, slash) : '';
  1221. const siblingPath = path.posix.normalize(fromDir ? `${fromDir}/${ref.referenceName}` : ref.referenceName);
  1222. const siblingBase = siblingPath.split('/').pop()!;
  1223. const sibling = context
  1224. .getNodesByName(siblingBase)
  1225. .find((n) => n.kind === 'file' && n.filePath === siblingPath);
  1226. if (sibling) {
  1227. return { original: ref, targetNodeId: sibling.id, confidence: 0.92, resolvedBy: 'import' };
  1228. }
  1229. const resolvedPath = resolveImportPath(ref.referenceName, ref.filePath, ref.language, context);
  1230. if (!resolvedPath) return null;
  1231. const basename = resolvedPath.split('/').pop()!;
  1232. const fileNodes = context.getNodesByName(basename).filter((n) => n.kind === 'file');
  1233. const fileNode = fileNodes.find((n) => n.filePath === resolvedPath);
  1234. if (fileNode) {
  1235. return {
  1236. original: ref,
  1237. targetNodeId: fileNode.id,
  1238. confidence: 0.9,
  1239. resolvedBy: 'import',
  1240. };
  1241. }
  1242. return null;
  1243. }
  1244. // COBOL COPY / EXEC SQL INCLUDE — resolve the copybook member to a
  1245. // file→file edge, mirroring the C/C++ include branch above. A member that
  1246. // matches no indexed file (compiler-supplied copybooks like SQLCA/DFHAID)
  1247. // stays unresolved — callers must not fall back to the symbol name-matcher,
  1248. // which would connect it to a same-named import symbol elsewhere.
  1249. if (isCobolCopybookRef(ref)) {
  1250. const resolvedPath = resolveImportPath(ref.referenceName, ref.filePath, ref.language!, context);
  1251. if (!resolvedPath) return null;
  1252. const basename = resolvedPath.split('/').pop()!;
  1253. const fileNode = context
  1254. .getNodesByName(basename)
  1255. .find((n) => n.kind === 'file' && n.filePath === resolvedPath);
  1256. if (fileNode) {
  1257. return {
  1258. original: ref,
  1259. targetNodeId: fileNode.id,
  1260. confidence: 0.9,
  1261. resolvedBy: 'import',
  1262. };
  1263. }
  1264. return null;
  1265. }
  1266. // PHP include/require — resolve the static string path to a file→file
  1267. // edge, mirroring the C/C++ branch above. Distinguish include PATHS from
  1268. // namespace `use` symbols by shape: an include path contains a slash or a
  1269. // file extension ("lib.php", "inc/db.php", "../x.php"), whereas a namespace
  1270. // use is an FQN (App\Foo\Bar) or a bare class symbol (Closure) — PHP
  1271. // identifiers contain neither '/' nor '.'. Only path-shaped references are
  1272. // includes; symbol references fall through to the namespace resolution.
  1273. if (isPhpIncludePathRef(ref)) {
  1274. const resolvedPath = resolvePhpIncludePath(ref.referenceName, ref.filePath, context);
  1275. if (resolvedPath) {
  1276. const basename = resolvedPath.split('/').pop()!;
  1277. const fileNode = context
  1278. .getNodesByName(basename)
  1279. .find((n) => n.kind === 'file' && n.filePath === resolvedPath);
  1280. if (fileNode) {
  1281. return {
  1282. original: ref,
  1283. targetNodeId: fileNode.id,
  1284. confidence: 0.9,
  1285. resolvedBy: 'import',
  1286. };
  1287. }
  1288. }
  1289. // A path-shaped include that doesn't resolve to a known project file is a
  1290. // dead end. Return unresolved rather than falling through to the symbol
  1291. // name-matcher, which would mis-connect e.g. "inc/db.php" to an unrelated
  1292. // db.php elsewhere in the tree — a wrong edge is worse than a missing one.
  1293. return null;
  1294. }
  1295. // Nix static project-path imports (`import ./x.nix`, `builtins.import ./dir`,
  1296. // `import ./x.nix {}`) resolve to file nodes only. Do not resolve
  1297. // angle-bracket channels, attribute expressions, variables, or other dynamic
  1298. // expressions as project files.
  1299. if (isNixPathImportRef(ref)) {
  1300. const resolvedPath = resolveImportPath(ref.referenceName, ref.filePath, ref.language, context);
  1301. if (!resolvedPath) return null;
  1302. const basename = resolvedPath.split('/').pop()!;
  1303. const fileNode = context
  1304. .getNodesByName(basename)
  1305. .find((n) => n.kind === 'file' && n.filePath === resolvedPath);
  1306. if (fileNode) {
  1307. return {
  1308. original: ref,
  1309. targetNodeId: fileNode.id,
  1310. confidence: 0.9,
  1311. resolvedBy: 'import',
  1312. };
  1313. }
  1314. return null;
  1315. }
  1316. // Use cached import mappings (avoids re-reading and re-parsing per ref)
  1317. const imports = context.getImportMappings(ref.filePath, ref.language);
  1318. if (imports.length === 0 && !context.readFile(ref.filePath)) {
  1319. return null;
  1320. }
  1321. // Go cross-package calls: `pkga.FuncX(...)` extracts to referenceName
  1322. // `pkga.FuncX` and the import `github.com/example/myproject/pkga`
  1323. // maps to a *package directory* containing one or more .go files.
  1324. // The generic file-based lookup below can't follow that — issue #388.
  1325. if (ref.language === 'go') {
  1326. const goResult = resolveGoCrossPackageReference(ref, imports, context);
  1327. if (goResult) return goResult;
  1328. }
  1329. // Java / Kotlin: imports are FQNs (`import com.example.Foo;`) — no
  1330. // resolvable file path the JS/TS-style chain below could follow. Look
  1331. // up the symbol by name and filter to the candidate whose file path
  1332. // matches the imported FQN. This is the disambiguation signal that
  1333. // breaks the same-name class collision the path-proximity matcher
  1334. // can't resolve (issue #314).
  1335. if (ref.language === 'java' || ref.language === 'kotlin') {
  1336. const javaResult = resolveJavaImportedReference(ref, imports, context);
  1337. if (javaResult) return javaResult;
  1338. }
  1339. // Python qualified access through an imported MODULE: `certs.where()` after
  1340. // `from . import certs`, `mod.func()` after `import mod`. The receiver names a
  1341. // submodule (a file), not a symbol, so the generic symbol lookup below would
  1342. // search the *package* for `certs` instead of looking inside the module.
  1343. if (ref.language === 'python') {
  1344. const pyResult = resolvePythonModuleMember(ref, imports, context);
  1345. if (pyResult) return pyResult;
  1346. // Absolute dotted module import: `import conduit.apps.articles.signals`
  1347. // (the standard Django AppConfig.ready() signal-registration pattern, and
  1348. // any side-effect `import pkg.mod`). Map the dotted path to its file.
  1349. const pyModResult = resolvePythonAbsoluteModule(ref, context);
  1350. if (pyModResult) return pyModResult;
  1351. }
  1352. // Rust qualified path: resolve the module prefix of `crate::m::Item` /
  1353. // `self::sub::Item` / `super::m::func` to a file, then find the leaf symbol in
  1354. // it. Disambiguates common-name `pub use self::read::read` re-exports that
  1355. // name-matching would land on the wrong same-named symbol.
  1356. if (ref.language === 'rust' && ref.referenceName.includes('::')) {
  1357. const rustResult = resolveRustPathReference(ref, context);
  1358. if (rustResult) return rustResult;
  1359. }
  1360. // Lua / Luau `require(...)`: a dotted module path (`a.b.c` from
  1361. // `require("a.b.c")`) or an instance-path leaf (`Signal` from
  1362. // `require(script.Parent.Signal)`) — map it to a module file. There's no static
  1363. // import statement, so the generic path-matcher can't bridge the dot↔slash /
  1364. // leaf↔basename gap; resolve it explicitly to the module file.
  1365. if ((ref.language === 'lua' || ref.language === 'luau') && ref.referenceKind === 'imports') {
  1366. const luaResult = resolveLuaRequire(ref, context);
  1367. if (luaResult) return luaResult;
  1368. }
  1369. // Whole-module / namespace imports → link the importing file to the module
  1370. // file. Python `from . import certs` / `import mod`, and TS/JS `import * as ns
  1371. // from './x'` (so a namespace touched only via a value-member read still
  1372. // records the dependency). A named TS/JS import returns null here and falls
  1373. // through to symbol resolution below.
  1374. if (
  1375. ref.language === 'python' ||
  1376. ref.language === 'typescript' ||
  1377. ref.language === 'tsx' ||
  1378. ref.language === 'javascript' ||
  1379. ref.language === 'jsx' ||
  1380. ref.language === 'arkts'
  1381. ) {
  1382. const moduleFile = resolveModuleImportToFile(ref, imports, context);
  1383. if (moduleFile) return moduleFile;
  1384. }
  1385. // Check if the reference name matches any import
  1386. for (const imp of imports) {
  1387. if (imp.localName === ref.referenceName || ref.referenceName.startsWith(imp.localName + '.')) {
  1388. // Resolve the import path
  1389. const resolvedPath = resolveImportPath(
  1390. imp.source,
  1391. ref.filePath,
  1392. ref.language,
  1393. context
  1394. );
  1395. if (resolvedPath) {
  1396. const exportedName = imp.isDefault ? 'default' : imp.exportedName;
  1397. const memberName = imp.isNamespace
  1398. ? ref.referenceName.replace(imp.localName + '.', '')
  1399. : null;
  1400. const targetNode = findExportedSymbol(
  1401. resolvedPath,
  1402. { isDefault: imp.isDefault, isNamespace: imp.isNamespace, exportedName, memberName },
  1403. ref.language,
  1404. context,
  1405. new Set()
  1406. );
  1407. if (targetNode) {
  1408. // `Foo.bar()` / `Foo.CONST` — a NAMED (non-namespace) class import
  1409. // accessed through a member. `findExportedSymbol` resolved `Foo` to
  1410. // the class itself; descend into it so the reference links to the
  1411. // member `bar`, not the class. Without this the edge points at the
  1412. // class and `createEdges` then mis-promotes the call to an
  1413. // `instantiates` edge, so the static method shows zero callers and a
  1414. // hollow impact radius. (#825)
  1415. if (!imp.isNamespace && ref.referenceName.startsWith(imp.localName + '.')) {
  1416. const memberNode = resolveStaticMember(targetNode, ref, imp.localName, context);
  1417. if (memberNode) {
  1418. return {
  1419. original: ref,
  1420. targetNodeId: memberNode.id,
  1421. confidence: 0.9,
  1422. resolvedBy: 'import',
  1423. };
  1424. }
  1425. // An imported VALUE (singleton constant / shared instance) called
  1426. // through a member: `reproStore.notifyJoinGuildStatus()` after
  1427. // `import { reproStore } from './store'`. findExportedSymbol
  1428. // resolved the CONSTANT itself; linking the CALL there hides the
  1429. // real callee — callers of the method miss every cross-file use
  1430. // and the method can look unused (#1292). Infer the value's type
  1431. // from its own declaration in the exporting file and resolve the
  1432. // member on that type. resolveMethodOnType VALIDATES the type
  1433. // declares the method, so a mis-inference falls through to the
  1434. // constant edge below rather than fabricating a wrong one.
  1435. const instanceMember = resolveImportedInstanceMember(targetNode, ref, imp.localName, context);
  1436. if (instanceMember) return instanceMember;
  1437. }
  1438. return {
  1439. original: ref,
  1440. targetNodeId: targetNode.id,
  1441. confidence: 0.9,
  1442. resolvedBy: 'import',
  1443. };
  1444. }
  1445. }
  1446. }
  1447. }
  1448. return null;
  1449. }
  1450. /**
  1451. * Resolve a Python qualified reference whose receiver is an imported MODULE:
  1452. * `certs.where()` after `from . import certs`, `mod.func()` after `import mod`
  1453. * or `from pkg import mod`. The receiver names a submodule (a file), not a
  1454. * symbol, so the generic symbol lookup in `resolveViaImport` can't follow it —
  1455. * it would search the *package* for `certs`/`mod` instead of looking inside the
  1456. * module. This is the Python half of the cross-package qualified-call problem
  1457. * (cf. `resolveGoCrossPackageReference` for Go's `pkg.Func`, issue #388).
  1458. *
  1459. * Builds the module's dotted import path from the binding — `from . import
  1460. * certs` → `.certs`; `from pkg import mod` → `pkg.mod`; `import mod` → `mod` —
  1461. * resolves it to the module file, and finds the member defined there. Returns
  1462. * null when no module file exists at that path, so attribute access on an
  1463. * imported *value* (`helper.attr` where `helper` is a function) falls through
  1464. * to the other strategies untouched.
  1465. */
  1466. function resolvePythonModuleMember(
  1467. ref: UnresolvedRef,
  1468. imports: ImportMapping[],
  1469. context: ResolutionContext
  1470. ): ResolvedRef | null {
  1471. const dotIdx = ref.referenceName.indexOf('.');
  1472. if (dotIdx <= 0) return null;
  1473. const receiver = ref.referenceName.substring(0, dotIdx);
  1474. // The immediate member of the module (first segment after the receiver).
  1475. const member = ref.referenceName.substring(dotIdx + 1).split('.')[0];
  1476. if (!member) return null;
  1477. for (const imp of imports) {
  1478. if (imp.localName !== receiver) continue;
  1479. // `import mod` / `import numpy as np` bind the module at `source` itself;
  1480. // `from . import certs` / `from pkg import mod` bind a SUBMODULE whose
  1481. // dotted path is the source joined with the imported name.
  1482. const modulePath = imp.isNamespace
  1483. ? imp.source
  1484. : imp.source.endsWith('.')
  1485. ? imp.source + imp.localName
  1486. : imp.source + '.' + imp.localName;
  1487. // resolveImportPath only maps RELATIVE dotted paths (`.mod`, `..pkg.mod`); an
  1488. // ABSOLUTE package path (`pkg.module` from `from pkg import module`, or a bare
  1489. // `import pkg.mod`) resolves to null there, so fall back to the dotted-module
  1490. // file lookup — the same asymmetry resolveModuleImportToFile already handles
  1491. // for the file→file import edge. Without this, a `module.func()` call after
  1492. // `from pkg import module` dropped its `calls` edge even though the import
  1493. // edge resolved (#578).
  1494. let resolvedPath = resolveImportPath(modulePath, ref.filePath, ref.language, context);
  1495. if (!resolvedPath) {
  1496. resolvedPath = findPythonModuleFile(modulePath, context, ref.filePath)?.filePath ?? null;
  1497. }
  1498. if (!resolvedPath || resolvedPath === ref.filePath) continue;
  1499. // Find the member as a top-level definition in the module file. Exclude
  1500. // `method` so `mod.foo` never lands on a same-named class method.
  1501. const target = context.getNodesInFile(resolvedPath).find(
  1502. (n) =>
  1503. n.name === member &&
  1504. (n.kind === 'function' ||
  1505. n.kind === 'class' ||
  1506. n.kind === 'variable' ||
  1507. n.kind === 'constant')
  1508. );
  1509. if (target) {
  1510. return { original: ref, targetNodeId: target.id, confidence: 0.85, resolvedBy: 'import' };
  1511. }
  1512. }
  1513. return null;
  1514. }
  1515. /**
  1516. * Resolve a whole-MODULE import to that module's file (a file→file dependency).
  1517. * The imported name is a module, not a symbol, so there's nothing to resolve to
  1518. * — but importing a module IS a dependency on it. Covers:
  1519. * - Python submodule imports — `from . import certs`, `from pkg import sub`;
  1520. * - namespace imports — Python `import mod` / `import numpy as np`, and
  1521. * TS/JS `import * as ns from './x'`.
  1522. *
  1523. * It is also the robust backstop for {@link resolvePythonModuleMember} and for
  1524. * TS namespace usage: it records the dependency even when the used member is
  1525. * re-exported elsewhere (requests' `certs.where`, re-exported from `certifi`),
  1526. * the usage is module-level code that isn't extracted as a call, or a TS
  1527. * namespace is touched only via a value-member read (`ns.SOME_CONST`).
  1528. *
  1529. * Only fires for dot-free `imports`-kind refs whose module path resolves to a
  1530. * real file. A NAMED TS/JS import (`import { widget }`) is not a module, so it
  1531. * returns null and normal symbol resolution handles it.
  1532. */
  1533. /**
  1534. * Resolve a Lua/Luau `require(...)` to its module file. The reference name is
  1535. * either a dotted module path (`telescope.config` → `telescope/config.lua`) or a
  1536. * Roblox instance-path leaf (`Signal` from `require(script.Parent.Signal)` →
  1537. * `Signal.luau`). We try `<path>.lua|.luau` and `<path>/init.lua|.luau`, matched
  1538. * by path suffix (the module root — `lua/`, `src/`, … — is project-specific).
  1539. * Among suffix matches, the one sharing the longest directory prefix with the
  1540. * requiring file wins (instance-path requires resolve within the same package).
  1541. */
  1542. function resolveLuaRequire(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null {
  1543. const name = ref.referenceName;
  1544. if (!name) return null;
  1545. const base = name.includes('.') ? name.replace(/\./g, '/') : name;
  1546. const suffixes = [`${base}.lua`, `${base}.luau`, `${base}/init.lua`, `${base}/init.luau`];
  1547. const byBasename = luaBasenameIndex(context);
  1548. const shared = (a: string, b: string): number => {
  1549. let i = 0;
  1550. while (i < a.length && i < b.length && a[i] === b[i]) i++;
  1551. return i;
  1552. };
  1553. for (const suffix of suffixes) {
  1554. // Only files sharing the suffix's basename can match — the bucket is in
  1555. // getAllFiles() order, so this filter yields exactly what the full-list
  1556. // scan did.
  1557. const candidates = byBasename.get(suffix.split('/').pop() ?? '') ?? [];
  1558. const matches = candidates.filter((f) => f === suffix || f.endsWith('/' + suffix));
  1559. if (matches.length === 0) continue;
  1560. matches.sort((x, y) => shared(y, ref.filePath) - shared(x, ref.filePath));
  1561. const best = matches[0]!;
  1562. if (best === ref.filePath) continue;
  1563. const fileNode = context.getNodesInFile(best).find((n) => n.kind === 'file');
  1564. if (fileNode) {
  1565. // Confidence ≥ 0.9 so this deterministic path/suffix match wins over
  1566. // name-matching, which otherwise resolves the require to the import node
  1567. // itself (a same-name self-match).
  1568. return { original: ref, targetNodeId: fileNode.id, confidence: 0.9, resolvedBy: 'import' };
  1569. }
  1570. }
  1571. return null;
  1572. }
  1573. function resolveModuleImportToFile(
  1574. ref: UnresolvedRef,
  1575. imports: ImportMapping[],
  1576. context: ResolutionContext
  1577. ): ResolvedRef | null {
  1578. if (ref.referenceKind !== 'imports') return null;
  1579. if (ref.referenceName.includes('.')) return null;
  1580. for (const imp of imports) {
  1581. if (imp.localName !== ref.referenceName) continue;
  1582. let modulePath: string;
  1583. if (imp.isNamespace || imp.isDefault) {
  1584. // `import * as ns from './x'` (namespace) or `import x from './x'`
  1585. // (default) — the dependency is on the MODULE FILE. A default import binds
  1586. // a (possibly renamed) local to whatever the module's default export is
  1587. // (`import articlesController from './article.controller'` ← `export
  1588. // default router`), so the binding name can't be found as a symbol — link
  1589. // the file the import resolves to instead. External modules don't resolve
  1590. // (no file), so `import React from 'react'` creates no edge.
  1591. modulePath = imp.source;
  1592. } else if (ref.language === 'python') {
  1593. // `from . import certs` — the imported NAME is a submodule of the source.
  1594. modulePath = imp.source.endsWith('.')
  1595. ? imp.source + imp.localName
  1596. : imp.source + '.' + imp.localName;
  1597. } else {
  1598. // A named TS/JS import binds a symbol, not a module — leave it alone.
  1599. continue;
  1600. }
  1601. const resolvedPath = resolveImportPath(modulePath, ref.filePath, ref.language, context);
  1602. if (resolvedPath && resolvedPath !== ref.filePath) {
  1603. const fileNode = context.getNodesInFile(resolvedPath).find((n) => n.kind === 'file');
  1604. if (fileNode) {
  1605. return { original: ref, targetNodeId: fileNode.id, confidence: 0.9, resolvedBy: 'import' };
  1606. }
  1607. }
  1608. // Python absolute `from a.b import submodule` (a FastAPI router aggregator's
  1609. // `from app.api.routes import authentication`): resolveImportPath only maps
  1610. // RELATIVE dotted paths to a file, so resolve the absolute dotted module
  1611. // directly to its file node.
  1612. if (ref.language === 'python') {
  1613. const modFile = findPythonModuleFile(modulePath, context, ref.filePath);
  1614. if (modFile) {
  1615. return { original: ref, targetNodeId: modFile.id, confidence: 0.9, resolvedBy: 'import' };
  1616. }
  1617. }
  1618. }
  1619. return null;
  1620. }
  1621. /**
  1622. * Find the file node for a Python dotted module path `a.b.c` — a module file
  1623. * ending in `a/b/c.py`, or a package `a/b/c/__init__.py` (suffix-matched, so a
  1624. * package rooted under `src/` etc. still resolves). Returns null for
  1625. * stdlib/external modules (no matching repo file node), so `import os` creates
  1626. * no edge. Shared by absolute `import a.b.c` and absolute `from a.b import c`
  1627. * (where `c` is a submodule) resolution.
  1628. */
  1629. function findPythonModuleFile(
  1630. mod: string,
  1631. context: ResolutionContext,
  1632. excludeFilePath: string
  1633. ): Node | null {
  1634. if (!mod || mod.startsWith('.')) return null; // relative imports handled elsewhere
  1635. const rel = mod.replace(/\./g, '/');
  1636. const lastSeg = mod.split('.').pop()!;
  1637. const endsWith = (p: string, want: string): boolean => p === want || p.endsWith('/' + want);
  1638. const moduleFile = context
  1639. .getNodesByName(`${lastSeg}.py`)
  1640. .find((n) => n.kind === 'file' && n.filePath !== excludeFilePath && endsWith(n.filePath, `${rel}.py`));
  1641. if (moduleFile) return moduleFile;
  1642. const pkgFile = context
  1643. .getNodesByName('__init__.py')
  1644. .find((n) => n.kind === 'file' && n.filePath !== excludeFilePath && endsWith(n.filePath, `${rel}/__init__.py`));
  1645. return pkgFile ?? null;
  1646. }
  1647. /**
  1648. * Resolve a Python ABSOLUTE dotted module import (`import a.b.c`) to its file —
  1649. * the Django `AppConfig.ready(): import myapp.signals` pattern and any
  1650. * side-effect module import.
  1651. */
  1652. function resolvePythonAbsoluteModule(
  1653. ref: UnresolvedRef,
  1654. context: ResolutionContext
  1655. ): ResolvedRef | null {
  1656. if (ref.referenceKind !== 'imports') return null;
  1657. // Only a DOTTED `import a.b.c` ref carries its full module path. A bare leaf
  1658. // (`from app.api.routes import authentication`) is ambiguous on its own — three
  1659. // `authentication.py` files may exist — so leave it to resolveModuleImportToFile,
  1660. // which uses the import's source (`app.api.routes`) to build the full path.
  1661. if (!ref.referenceName.includes('.')) return null;
  1662. const hit = findPythonModuleFile(ref.referenceName, context, ref.filePath);
  1663. return hit ? { original: ref, targetNodeId: hit.id, confidence: 0.9, resolvedBy: 'import' } : null;
  1664. }
  1665. /**
  1666. * Resolve a Rust qualified reference `A::B::C` by mapping the MODULE prefix
  1667. * (`A::B`) to a file and finding the leaf symbol (`C`) in it. This is the Rust
  1668. * analog of {@link resolvePythonModuleMember} / {@link resolveGoCrossPackageReference}
  1669. * and the precise answer to common-name re-exports (`pub use self::read::read`)
  1670. * that name-matching can't disambiguate. Returns null when the prefix isn't a
  1671. * real module path (e.g. `Widget::new` — `Widget` is a struct, not a module),
  1672. * so associated-function calls and enum-variant paths fall through untouched.
  1673. */
  1674. function resolveRustPathReference(
  1675. ref: UnresolvedRef,
  1676. context: ResolutionContext
  1677. ): ResolvedRef | null {
  1678. const segments = ref.referenceName.split('::').filter((s) => s.length > 0);
  1679. if (segments.length < 2) return null;
  1680. const leaf = segments[segments.length - 1]!;
  1681. const modSegs = segments.slice(0, -1);
  1682. const file = resolveRustModuleFile(modSegs, ref.filePath, context);
  1683. if (!file || file === ref.filePath) return null;
  1684. const target = context.getNodesInFile(file).find(
  1685. (n) =>
  1686. n.name === leaf &&
  1687. (n.kind === 'function' ||
  1688. n.kind === 'struct' ||
  1689. n.kind === 'enum' ||
  1690. n.kind === 'trait' ||
  1691. n.kind === 'type_alias' ||
  1692. n.kind === 'constant' ||
  1693. n.kind === 'method' ||
  1694. n.kind === 'class' ||
  1695. n.kind === 'interface')
  1696. );
  1697. if (target) {
  1698. return { original: ref, targetNodeId: target.id, confidence: 0.9, resolvedBy: 'import' };
  1699. }
  1700. return null;
  1701. }
  1702. /** The crate-root directory (holds `lib.rs`/`main.rs`), walking up from a file. */
  1703. function rustCrateRootDir(fromFileAbs: string, context: ResolutionContext): string | null {
  1704. const projectRoot = context.getProjectRoot();
  1705. const toRel = (p: string) => path.relative(projectRoot, p).replace(/\\/g, '/');
  1706. let dir = path.dirname(fromFileAbs);
  1707. for (let i = 0; i < 64; i++) {
  1708. if (context.fileExists(toRel(path.join(dir, 'lib.rs'))) ||
  1709. context.fileExists(toRel(path.join(dir, 'main.rs')))) {
  1710. return dir;
  1711. }
  1712. const parent = path.dirname(dir);
  1713. if (parent === dir) return null;
  1714. dir = parent;
  1715. }
  1716. return null;
  1717. }
  1718. /** Directory under which the current file's module declares its SUBMODULES. */
  1719. function rustSelfModuleDir(fromFileAbs: string): string {
  1720. const base = path.basename(fromFileAbs);
  1721. const dir = path.dirname(fromFileAbs);
  1722. // mod.rs / lib.rs / main.rs own their directory; `foo.rs`'s submodules live in `foo/`.
  1723. if (base === 'mod.rs' || base === 'lib.rs' || base === 'main.rs') return dir;
  1724. return path.join(dir, base.replace(/\.rs$/, ''));
  1725. }
  1726. /**
  1727. * Resolve a Rust module path (segments WITHOUT the leaf symbol) to the file of
  1728. * the last module segment — `crate::a::b` → `<crate>/a/b.rs` (or `.../b/mod.rs`).
  1729. * Anchors on `crate` / `self` / `super`; a bare path is tried crate-relative.
  1730. */
  1731. function resolveRustModuleFile(
  1732. segments: string[],
  1733. fromFile: string,
  1734. context: ResolutionContext
  1735. ): string | null {
  1736. if (segments.length === 0) return null;
  1737. const projectRoot = context.getProjectRoot();
  1738. const fromAbs = path.join(projectRoot, fromFile);
  1739. const toRel = (p: string) => path.relative(projectRoot, p).replace(/\\/g, '/');
  1740. // Walk a sequence of module segments down from `startDir`, mapping each to a
  1741. // `<seg>.rs` or `<seg>/mod.rs` file. Returns the leaf module's file, or null
  1742. // if `startDir` is null or any segment has no file on disk.
  1743. const resolveUnder = (startDir: string | null, rest: string[]): string | null => {
  1744. if (!startDir) return null;
  1745. let dir = startDir;
  1746. let targetFile: string | null = null;
  1747. for (const seg of rest) {
  1748. if (seg === 'self' || seg === 'crate' || seg === 'super') continue;
  1749. const asFile = toRel(path.join(dir, seg + '.rs'));
  1750. const asMod = toRel(path.join(dir, seg, 'mod.rs'));
  1751. if (context.fileExists(asFile)) targetFile = asFile;
  1752. else if (context.fileExists(asMod)) targetFile = asMod;
  1753. else return null;
  1754. dir = path.join(dir, seg);
  1755. }
  1756. return targetFile;
  1757. };
  1758. const first = segments[0]!;
  1759. if (first === 'crate') {
  1760. return resolveUnder(rustCrateRootDir(fromAbs, context), segments.slice(1));
  1761. }
  1762. if (first === 'self') {
  1763. return resolveUnder(rustSelfModuleDir(fromAbs), segments.slice(1));
  1764. }
  1765. if (first === 'super') {
  1766. let supers = 0;
  1767. while (segments[supers] === 'super') supers++;
  1768. let dir: string | null = rustSelfModuleDir(fromAbs);
  1769. for (let s = 0; s < supers && dir; s++) dir = path.dirname(dir);
  1770. return resolveUnder(dir, segments.slice(supers));
  1771. }
  1772. // Bare path. In expression position (`submodule::item()` — the router-assembly
  1773. // and general cross-module-call pattern) the prefix is a SUBMODULE of the
  1774. // current module, i.e. 2018 `self::`-relative — so try self-relative FIRST.
  1775. // Fall back to crate-relative for 2015-edition / crate-root items. External
  1776. // crate paths (`serde::de::Error`) miss both and fall through to name-matching.
  1777. return (
  1778. resolveUnder(rustSelfModuleDir(fromAbs), segments) ??
  1779. resolveUnder(rustCrateRootDir(fromAbs, context), segments)
  1780. );
  1781. }
  1782. /**
  1783. * Resolve a Java/Kotlin reference whose receiver is the simple name of
  1784. * an imported FQN: `Foo.bar(...)` where `import com.example.Foo;`. The
  1785. * imported FQN converts to a file-path suffix (`com/example/Foo.java`
  1786. * or `.kt`) which uniquely identifies the right symbol when multiple
  1787. * classes share the same simple name.
  1788. *
  1789. * Also handles bare references to the imported class itself
  1790. * (`new Foo()` extraction emits `Foo` as a `references`/`instantiates`
  1791. * ref) and `import static <Foo>.bar` style imports of a single member.
  1792. */
  1793. function resolveJavaImportedReference(
  1794. ref: UnresolvedRef,
  1795. imports: ImportMapping[],
  1796. context: ResolutionContext
  1797. ): ResolvedRef | null {
  1798. if (imports.length === 0) return null;
  1799. const ext = ref.language === 'kotlin' ? '.kt' : '.java';
  1800. for (const imp of imports) {
  1801. const matchesBare = imp.localName === ref.referenceName;
  1802. const matchesQualified = ref.referenceName.startsWith(imp.localName + '.');
  1803. if (!matchesBare && !matchesQualified) continue;
  1804. // Convert FQN to a file-path suffix. `com.example.Foo` ->
  1805. // `com/example/Foo.java` (or `.kt`). The actual file may live
  1806. // under any source root (`src/main/java/`, `src/`, etc.), so match
  1807. // by suffix rather than exact path.
  1808. const fqnPath = imp.source.replace(/\./g, '/') + ext;
  1809. // Which symbol name to look up: the class itself, or a member.
  1810. const memberName = matchesBare
  1811. ? imp.localName
  1812. : ref.referenceName.substring(imp.localName.length + 1);
  1813. const candidates = context.getNodesByName(memberName);
  1814. for (const node of candidates) {
  1815. if (node.language !== ref.language) continue;
  1816. const fp = node.filePath.replace(/\\/g, '/');
  1817. if (fp.endsWith(fqnPath) || fp.endsWith('/' + fqnPath)) {
  1818. return {
  1819. original: ref,
  1820. targetNodeId: node.id,
  1821. confidence: 0.9,
  1822. resolvedBy: 'import',
  1823. };
  1824. }
  1825. }
  1826. // `import static com.example.Foo.bar;` — the FQN's tail is the
  1827. // member name, the part before is the owner class. Look up the
  1828. // member named `<imp.localName>` (e.g. `bar`) and prefer the
  1829. // candidate whose file matches the parent FQN's path.
  1830. if (matchesBare) {
  1831. const dot = imp.source.lastIndexOf('.');
  1832. if (dot > 0) {
  1833. const ownerFqn = imp.source.substring(0, dot);
  1834. const ownerPath = ownerFqn.replace(/\./g, '/') + ext;
  1835. for (const node of candidates) {
  1836. if (node.language !== ref.language) continue;
  1837. const fp = node.filePath.replace(/\\/g, '/');
  1838. if (fp.endsWith(ownerPath) || fp.endsWith('/' + ownerPath)) {
  1839. return {
  1840. original: ref,
  1841. targetNodeId: node.id,
  1842. confidence: 0.9,
  1843. resolvedBy: 'import',
  1844. };
  1845. }
  1846. }
  1847. }
  1848. }
  1849. }
  1850. return null;
  1851. }
  1852. /**
  1853. * Resolve a Go cross-package qualified reference (`pkga.FuncX`) by matching
  1854. * the package alias against an in-module import, stripping the module prefix
  1855. * to a project-relative directory, and locating the exported symbol in any
  1856. * `.go` file under that directory. Returns `null` for stdlib / third-party
  1857. * imports (no `go.mod`-relative match) so the rest of `resolveViaImport`
  1858. * can still try the file-based path.
  1859. */
  1860. function resolveGoCrossPackageReference(
  1861. ref: UnresolvedRef,
  1862. imports: ImportMapping[],
  1863. context: ResolutionContext
  1864. ): ResolvedRef | null {
  1865. const mod = context.getGoModule?.();
  1866. if (!mod) return null;
  1867. // Qualified call: receiver before `.`, member after. A bare reference
  1868. // (no dot) is a same-file/in-package call — handled elsewhere.
  1869. const dotIdx = ref.referenceName.indexOf('.');
  1870. if (dotIdx <= 0) return null;
  1871. const receiver = ref.referenceName.substring(0, dotIdx);
  1872. const memberName = ref.referenceName.substring(dotIdx + 1);
  1873. if (!memberName) return null;
  1874. for (const imp of imports) {
  1875. if (imp.localName !== receiver) continue;
  1876. // Only in-module imports map to a known directory.
  1877. if (imp.source !== mod.modulePath && !imp.source.startsWith(mod.modulePath + '/')) {
  1878. continue;
  1879. }
  1880. const pkgDir = imp.source === mod.modulePath
  1881. ? ''
  1882. : imp.source.substring(mod.modulePath.length + 1);
  1883. // Look up the member by name and pick the candidate whose file lives
  1884. // directly in the package directory. Match the immediate parent dir
  1885. // exactly so a call to `pkga.FuncX` doesn't accidentally land on a
  1886. // `FuncX` declared in `pkga/subpkg/`.
  1887. const candidates = context.getNodesByName(memberName);
  1888. for (const node of candidates) {
  1889. if (node.language !== 'go') continue;
  1890. if (!node.isExported) continue;
  1891. const fp = node.filePath.replace(/\\/g, '/');
  1892. const lastSlash = fp.lastIndexOf('/');
  1893. const fileDir = lastSlash >= 0 ? fp.substring(0, lastSlash) : '';
  1894. if (fileDir === pkgDir) {
  1895. return {
  1896. original: ref,
  1897. targetNodeId: node.id,
  1898. confidence: 0.9,
  1899. resolvedBy: 'import',
  1900. };
  1901. }
  1902. }
  1903. }
  1904. return null;
  1905. }
  1906. /** Recursive depth cap for re-export chain following. Real codebases
  1907. * rarely chain barrels more than 2–3 deep; 8 is a generous safety
  1908. * net that still bounds worst-case work. */
  1909. const REEXPORT_MAX_DEPTH = 8;
  1910. /**
  1911. * Find an exported symbol in `filePath`, following `export { x } from
  1912. * './other'` and `export * from './other'` chains until the original
  1913. * declaration is reached. Cycle-safe via the `visited` set.
  1914. *
  1915. * Without this, every barrel-style import (`import { Foo } from
  1916. * './index'` where `index.ts` only re-exports) used to resolve to
  1917. * nothing — the existing code only looked for declarations IN the
  1918. * resolved file, not declarations the file forwarded.
  1919. */
  1920. function findExportedSymbol(
  1921. filePath: string,
  1922. want: {
  1923. isDefault: boolean;
  1924. isNamespace: boolean;
  1925. exportedName: string;
  1926. memberName: string | null;
  1927. },
  1928. language: Language,
  1929. context: ResolutionContext,
  1930. visited: Set<string>,
  1931. depth = 0
  1932. ): Node | undefined {
  1933. // Memoize fresh (top-level) lookups only: recursive re-export steps carry a
  1934. // populated `visited` set, whose contents change the reachable answer.
  1935. // Every ref to the same imported symbol repeats this exact walk, so the
  1936. // top-level memo removes the re-export chase + per-file linear scans from
  1937. // all but the first occurrence.
  1938. if (depth === 0 && visited.size === 0) {
  1939. let memo = exportedSymbolMemos.get(context);
  1940. if (!memo) {
  1941. memo = new Map();
  1942. exportedSymbolMemos.set(context, memo);
  1943. }
  1944. const key = `${filePath}\0${want.isDefault ? 1 : 0}${want.isNamespace ? 1 : 0}\0${want.exportedName}\0${want.memberName ?? ''}\0${language}`;
  1945. if (memo.has(key)) return memo.get(key);
  1946. const result = findExportedSymbolWalk(filePath, want, language, context, visited, depth);
  1947. memo.set(key, result);
  1948. return result;
  1949. }
  1950. return findExportedSymbolWalk(filePath, want, language, context, visited, depth);
  1951. }
  1952. function findExportedSymbolWalk(
  1953. filePath: string,
  1954. want: {
  1955. isDefault: boolean;
  1956. isNamespace: boolean;
  1957. exportedName: string;
  1958. memberName: string | null;
  1959. },
  1960. language: Language,
  1961. context: ResolutionContext,
  1962. visited: Set<string>,
  1963. depth: number
  1964. ): Node | undefined {
  1965. if (depth > REEXPORT_MAX_DEPTH) return undefined;
  1966. if (visited.has(filePath)) return undefined;
  1967. visited.add(filePath);
  1968. const exportIndex = getFileExportIndex(filePath, context);
  1969. // 1. Direct hit: the symbol is declared in this file.
  1970. if (want.isDefault) {
  1971. // Svelte/Vue single-file components ARE the module's default export,
  1972. // but are extracted as kind 'component' (not function/class). Prefer
  1973. // the component node; fall back to an exported function/class for the
  1974. // `.ts`/`.tsx` `export default fn`/`class` case. Without the component
  1975. // branch, an `export { default as X } from './X.svelte'` barrel never
  1976. // resolves and the component shows a false 0 callers (#629).
  1977. const direct = exportIndex.defaultComponent ?? exportIndex.defaultFnClass;
  1978. if (direct) return direct;
  1979. } else if (want.isNamespace && want.memberName) {
  1980. const direct = exportIndex.byName.get(want.memberName);
  1981. if (direct) return direct;
  1982. } else {
  1983. const direct = exportIndex.byName.get(want.exportedName);
  1984. if (direct) return direct;
  1985. }
  1986. // 2. Re-export hit: the file forwards the symbol to another module.
  1987. const reExports = context.getReExports?.(filePath, language) ?? [];
  1988. if (reExports.length === 0) return undefined;
  1989. // Look for explicit `export { want } from './other'` (with optional rename).
  1990. const targetName = want.isDefault ? 'default' : want.exportedName;
  1991. for (const rex of reExports) {
  1992. if (rex.kind === 'named' && rex.exportedName === targetName) {
  1993. const next = resolveImportPath(rex.source, filePath, language, context);
  1994. if (!next) continue;
  1995. // After rename: `export { foo as bar } from './x'` — to chase
  1996. // `bar`, we look for `foo` in `./x`.
  1997. const chained = findExportedSymbol(
  1998. next,
  1999. {
  2000. isDefault: rex.originalName === 'default',
  2001. isNamespace: false,
  2002. exportedName: rex.originalName,
  2003. memberName: null,
  2004. },
  2005. language,
  2006. context,
  2007. visited,
  2008. depth + 1
  2009. );
  2010. if (chained) return chained;
  2011. }
  2012. }
  2013. // 3. Wildcard re-export: `export * from './other'` — try every
  2014. // forwarding source. This is the barrel-of-barrels case.
  2015. for (const rex of reExports) {
  2016. if (rex.kind === 'wildcard') {
  2017. const next = resolveImportPath(rex.source, filePath, language, context);
  2018. if (!next) continue;
  2019. const chained = findExportedSymbol(next, want, language, context, visited, depth + 1);
  2020. if (chained) return chained;
  2021. }
  2022. }
  2023. return undefined;
  2024. }
  2025. /** Node kinds that own static members reachable as `Container.member`. */
  2026. const STATIC_MEMBER_CONTAINERS = new Set<Node['kind']>([
  2027. 'class', 'struct', 'interface', 'enum', 'trait', 'protocol',
  2028. ]);
  2029. /**
  2030. * Resolve `Container.member` — a static method/property access on a NAMED class
  2031. * import (`import { Foo } …; Foo.bar()`) — to the member node, given the
  2032. * already-resolved container class.
  2033. *
  2034. * Members carry a `Container::member` qualifiedName, so we look up
  2035. * `${container.qualifiedName}::${member}` within the container's own file (the
  2036. * file filter disambiguates same-named classes in other modules). Returns
  2037. * undefined when the container isn't a member-owning kind or the member isn't
  2038. * found, so the caller falls back to the container itself (prior behavior) —
  2039. * languages whose members aren't `::`-qualified, and genuine class references,
  2040. * are unaffected. See #825.
  2041. */
  2042. /**
  2043. * Resolve a CALL through an imported value to the method on the value's own
  2044. * type: `reproStore.notifyJoinGuildStatus()` where `reproStore` is
  2045. * `export const reproStore = new ReproStore()` in the imported file (#1292).
  2046. * The same-file form of this call already resolves via local-variable
  2047. * receiver inference (#1108); this is the cross-file/import half. The type is
  2048. * recovered from the VALUE'S OWN declaration lines in the exporting file
  2049. * (initializer `= new T(...)` or a type annotation, per the shared #1108
  2050. * pattern table), then the member is resolved AND VALIDATED on that type by
  2051. * resolveMethodOnType — a failed inference or validation returns null so the
  2052. * caller keeps its existing constant-edge behavior.
  2053. */
  2054. function resolveImportedInstanceMember(
  2055. value: Node,
  2056. ref: UnresolvedRef,
  2057. localName: string,
  2058. context: ResolutionContext
  2059. ): ResolvedRef | null {
  2060. if (ref.referenceKind !== 'calls') return null;
  2061. if (value.kind !== 'constant' && value.kind !== 'variable') return null;
  2062. const member = ref.referenceName.slice(localName.length + 1).split('.')[0];
  2063. if (!member) return null;
  2064. const source = context.readFile(value.filePath);
  2065. if (!source) return null;
  2066. // Only the value's own declaration lines — never the whole file, so a
  2067. // same-named identifier elsewhere can't donate a type.
  2068. const lines = source.split('\n');
  2069. const declSlice = lines.slice(Math.max(0, value.startLine - 1), value.endLine).join('\n');
  2070. const receiver = value.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  2071. for (const pattern of localReceiverTypePatterns(value.language as Language, receiver)) {
  2072. const m = declSlice.match(pattern);
  2073. if (!m || !m[1]) continue;
  2074. const typeName = normalizeInferredTypeName(m[1]);
  2075. if (!typeName) continue;
  2076. const resolved = resolveMethodOnType(typeName, member, ref, context, 0.85, 'instance-method');
  2077. if (resolved) return resolved;
  2078. }
  2079. return null;
  2080. }
  2081. function resolveStaticMember(
  2082. container: Node,
  2083. ref: UnresolvedRef,
  2084. localName: string,
  2085. context: ResolutionContext
  2086. ): Node | undefined {
  2087. if (!STATIC_MEMBER_CONTAINERS.has(container.kind)) return undefined;
  2088. // First segment after the receiver: `Foo.bar.baz` → `bar`.
  2089. const member = ref.referenceName.slice(localName.length + 1).split('.')[0];
  2090. if (!member) return undefined;
  2091. const candidates = context
  2092. .getNodesByQualifiedName(`${container.qualifiedName}::${member}`)
  2093. .filter((n) => n.filePath === container.filePath);
  2094. if (candidates.length === 0) return undefined;
  2095. // When the reference is a call, prefer a callable member if several nodes
  2096. // share the qualifiedName (e.g. a static property and a method).
  2097. if (ref.referenceKind === 'calls') {
  2098. const callable = candidates.find((n) => n.kind === 'method' || n.kind === 'function');
  2099. if (callable) return callable;
  2100. }
  2101. return candidates[0];
  2102. }