Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix(ingest): resolve JS and TS calls across parse batches (#375)

Hiro-Chibad9b692a22e80
diff --git a/core-ingestion/src/__tests__/resolveEdges.test.ts b/core-ingestion/src/__tests__/resolveEdges.test.ts
index 92979463..8d1fb05f 100644
--- a/core-ingestion/src/__tests__/resolveEdges.test.ts
+++ b/core-ingestion/src/__tests__/resolveEdges.test.ts
@@ -256,6 +256,78 @@ describe('resolveEdges', () => {
});
});
+ it('resolves a TypeScript call when the imported definition is outside the parse batch', () => {
+ const caller = fileResult(
+ '/repo/consumer.ts',
+ SupportedLanguages.TypeScript,
+ [entity('runCrossBatchTarget', SupportedLanguages.TypeScript)],
+ [
+ { srcName: 'consumer.ts', dstName: 'target', predicate: 'IMPORTS', importRaw: './target' },
+ { srcName: 'runCrossBatchTarget', dstName: 'crossBatchTarget', predicate: 'CALLS' },
+ ],
+ );
+ caller.importBindings = [
+ { pkg: './target', local: 'crossBatchTarget', imported: 'crossBatchTarget' },
+ ];
+
+ const targetPath = '/repo/target.ts';
+ const globalIndex = buildGlobalResolutionIndex(
+ ['/repo/consumer.ts', targetPath],
+ new Map([[targetPath, 'export function crossBatchTarget() {}\n']]),
+ );
+
+ expect(resolveEdges([caller], undefined, globalIndex)).toContainEqual({
+ srcFilePath: '/repo/consumer.ts',
+ srcName: 'runCrossBatchTarget',
+ dstFilePath: targetPath,
+ dstName: 'crossBatchTarget',
+ dstQualifiedKey: 'crossBatchTarget',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ });
+
+ it('uses caller-supplied parse results instead of re-parsing', () => {
+ // The CLI parses prescan sources on its worker pool and hands the results
+ // in, so the index costs no main-thread parsing. Proven by supplying a
+ // parse result whose entity does not appear in the source text: if the
+ // index re-parsed, `fromPool` could not be resolved.
+ const targetPath = '/repo/target.ts';
+ const caller = fileResult(
+ '/repo/consumer.ts',
+ SupportedLanguages.TypeScript,
+ [entity('run', SupportedLanguages.TypeScript)],
+ [
+ { srcName: 'consumer.ts', dstName: 'target', predicate: 'IMPORTS', importRaw: './target' },
+ { srcName: 'run', dstName: 'fromPool', predicate: 'CALLS' },
+ ],
+ );
+ caller.importBindings = [{ pkg: './target', local: 'fromPool', imported: 'fromPool' }];
+
+ const poolResult = fileResult(
+ targetPath,
+ SupportedLanguages.TypeScript,
+ [entity('fromPool', SupportedLanguages.TypeScript)],
+ [],
+ );
+
+ const globalIndex = buildGlobalResolutionIndex(
+ ['/repo/consumer.ts', targetPath],
+ new Map([[targetPath, '// the pool result is authoritative, not this text\n']]),
+ new Map([[targetPath, poolResult]]),
+ );
+
+ expect(resolveEdges([caller], undefined, globalIndex)).toContainEqual({
+ srcFilePath: '/repo/consumer.ts',
+ srcName: 'run',
+ dstFilePath: targetPath,
+ dstName: 'fromPool',
+ dstQualifiedKey: 'fromPool',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ });
+ });
+
it('resolves Elixir alias-qualified calls through the implicit short alias', () => {
const caller = fileResult(
'/repo/lib/my_app/accounts.ex',
diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.ts
index 295230b7..b4e17505 100644
--- a/core-ingestion/src/index.ts
+++ b/core-ingestion/src/index.ts
@@ -2641,6 +2641,14 @@ export interface GlobalResolutionIndex {
export function buildGlobalResolutionIndex(
filePaths: string[],
sources?: Map<string, string>,
+ // Parse results the caller already has. The parser-derived language blocks
+ // below (PHP, JS/TS, R, SAS) call parseFile synchronously on the main thread,
+ // which is fine for a handful of files and not fine for a whole repository's
+ // worth of TypeScript. The CLI owns a worker pool; letting it parse in
+ // parallel and hand the results in keeps the work off this thread entirely.
+ // Absent an entry, each block falls back to parsing here, so callers that do
+ // not have a pool (tests, library use) behave exactly as before.
+ preParsed?: Map<string, FileParseResult>,
): GlobalResolutionIndex {
const stemToFiles = new Map<string, string[]>();
const dirToIndexFiles = new Map<string, string[]>();
@@ -2747,6 +2755,28 @@ export function buildGlobalResolutionIndex(
}
}
+ // JavaScript/TypeScript: index definitions for cross-batch resolution from
+ // the same parser output used by the normal ingest path. A path-only index
+ // can find an imported file outside the current streaming batch, but without
+ // its symbols resolveEdges cannot verify the destination and drops the edge.
+ const jsTsExtensions = new Set(['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx']);
+ for (const [fp, src] of sources) {
+ if (!jsTsExtensions.has(nodePath.extname(fp).toLowerCase())) continue;
+ const parsed = preParsed?.get(fp) ?? parseFile(fp, src);
+ if (!parsed) continue;
+ const qkMap = new Map<string, string[]>();
+ for (const e of parsed.entities) {
+ if (e.kind === 'file' || e.kind === 'module') continue;
+ const list = qkMap.get(e.name) ?? [];
+ list.push(qualifiedKey(e));
+ qkMap.set(e.name, list);
+ }
+ if (qkMap.size > 0) {
+ fileQKeys.set(fp, qkMap);
+ fileHasSymbol.set(fp, new Set(qkMap.keys()));
+ }
+ }
+
// R: index function definitions for cross-batch Tier-3 resolution. Derive
// them from the parser's definition.function entities (not a regex) so this
// never drifts from what the in-batch path extracts in resolveEdges — the
@@ -2755,7 +2785,7 @@ export function buildGlobalResolutionIndex(
// resolveEdges (key by name, value qkey). Same pattern as the SAS index.
for (const [fp, src] of sources) {
if (nodePath.extname(fp).toLowerCase() !== '.r') continue;
- const parsed = parseFile(fp, src);
+ const parsed = preParsed?.get(fp) ?? parseFile(fp, src);
if (!parsed) continue;
const qkMap = new Map<string, string[]>();
for (const e of parsed.entities) {
@@ -2774,7 +2804,7 @@ export function buildGlobalResolutionIndex(
// calls to classes and interfaces in unchanged files.
for (const [fp, src] of sources) {
if (nodePath.extname(fp).toLowerCase() !== '.php') continue;
- const parsed = parseFile(fp, src);
+ const parsed = preParsed?.get(fp) ?? parseFile(fp, src);
if (!parsed) continue;
const qkMap = new Map<string, string[]>();
for (const e of parsed.entities) {
@@ -2796,7 +2826,7 @@ export function buildGlobalResolutionIndex(
// Mirrors the qkMap construction at resolveEdges (key by name, value qkey).
for (const [fp, src] of sources) {
if (nodePath.extname(fp).toLowerCase() !== '.sas') continue;
- const parsed = parseFile(fp, src);
+ const parsed = preParsed?.get(fp) ?? parseFile(fp, src);
if (!parsed) continue;
const qkMap = new Map<string, string[]>();
for (const e of parsed.entities) {
diff --git a/ix-cli/src/cli/__tests__/ingest-discovery.test.ts b/ix-cli/src/cli/__tests__/ingest-discovery.test.ts
index d4bcc19a..e6b85b0e 100644
--- a/ix-cli/src/cli/__tests__/ingest-discovery.test.ts
+++ b/ix-cli/src/cli/__tests__/ingest-discovery.test.ts
@@ -55,8 +55,14 @@ describe('dedupeDiscoveredFilePaths', () => {
}
});
- it('pre-scans PHP definitions for incremental call resolution', () => {
- expect(needsIndexPrescan('src/Service.php')).toBe(true);
+ it('pre-scans every language whose index is parser-derived', () => {
+ for (const filePath of [
+ 'src/Service.php',
+ 'src/helper.js', 'src/helper.jsx', 'src/helper.mjs', 'src/helper.cjs',
+ 'src/helper.ts', 'src/helper.tsx',
+ ]) {
+ expect(needsIndexPrescan(filePath)).toBe(true);
+ }
expect(needsIndexPrescan('src/service.py')).toBe(false);
});
});
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 123ecefd..02400ae7 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -43,9 +43,13 @@ export function isSupportedSourceFile(filePath: string): boolean {
// Extensions whose source text must be pre-read so buildGlobalResolutionIndex can
// extract cross-batch symbols before the streaming parse loop. Go uses a fast
-// regex scan; PHP, SAS, and R are parsed (their cross-batch indexes are derived
-// from the parser's definition entities).
-const INDEX_PRESCAN_EXTENSIONS = new Set(['.go', '.php', '.r', '.sas']);
+// regex scan; PHP, JavaScript, TypeScript, SAS and R are parsed, so their
+// cross-batch indexes are derived from the parser's definition entities and
+// cannot drift from what the in-batch path extracts.
+const INDEX_PRESCAN_EXTENSIONS = new Set([
+ '.go', '.php', '.r', '.sas',
+ '.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx',
+]);
export function needsIndexPrescan(filePath: string): boolean {
return INDEX_PRESCAN_EXTENSIONS.has(nodePath.extname(filePath).toLowerCase());
@@ -687,6 +691,42 @@ export async function ingestFiles(
};
+
+ /**
+ * Parse the prescan sources on the worker pool.
+ *
+ * buildGlobalResolutionIndex derives PHP/JS/TS/R/SAS indexes from real parse
+ * results rather than a regex, so they cannot drift from what the in-batch
+ * path extracts — the right call, but it means the index costs one parse per
+ * prescanned file. Done inside the index that is a synchronous main-thread
+ * loop, and .ts is not a rare extension: on a TypeScript repo it is most of
+ * the files, and an incremental map pays it for every unchanged file too.
+ *
+ * The pool is already running for the streaming loop below, so parse there
+ * instead and hand the results over. Only extensions whose index is
+ * parser-derived are worth the round trip; Go is a regex scan inside the
+ * index and needs nothing here.
+ */
+ const PARSER_DERIVED_PRESCAN = new Set(['.php', '.r', '.sas', '.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx']);
+ const preParsePrescanSources = async (relSources: Map<string, string>): Promise<Map<string, any>> => {
+ const targets = [...relSources.keys()].filter(
+ fp => PARSER_DERIVED_PRESCAN.has(nodePath.extname(fp).toLowerCase()),
+ );
+ const preParsed = new Map<string, any>();
+ if (targets.length === 0) return preParsed;
+ const PRESCAN_PARSE_CHUNK = 500;
+ for (let i = 0; i < targets.length; i += PRESCAN_PARSE_CHUNK) {
+ const chunk = targets.slice(i, i + PRESCAN_PARSE_CHUNK);
+ const parsed = await Promise.all(
+ chunk.map(fp => ensureParsePool().parse(fp, relSources.get(fp)!).catch(() => null)),
+ );
+ for (let j = 0; j < chunk.length; j++) {
+ if (parsed[j]) preParsed.set(chunk[j], parsed[j]);
+ }
+ }
+ return preParsed;
+ };
+
let progressPhase = 'Scanning';
let progressCurrent = 0;
let progressTotal = 0;
@@ -1219,9 +1259,11 @@ export async function ingestFiles(
const relSources = new Map<string, string>();
for (const [abs, text] of sources) relSources.set(toWorkspaceRelative(abs), text);
const relFilePaths = filePaths.map(toWorkspaceRelative);
- globalIndex = (ingestion.buildGlobalResolutionIndex as Function)(relFilePaths, relSources);
+ const preParsed = await preParsePrescanSources(relSources);
+ globalIndex = (ingestion.buildGlobalResolutionIndex as Function)(relFilePaths, relSources, preParsed);
sources.clear();
relSources.clear();
+ preParsed.clear();
}
let pendingFlush: Promise<void> = Promise.resolve();
@@ -1273,8 +1315,10 @@ export async function ingestFiles(
}
}
const relFilePaths = filePaths.map(toWorkspaceRelative);
- globalIndex = ingestion.buildGlobalResolutionIndex(relFilePaths, sources);
+ const preParsed = await preParsePrescanSources(sources);
+ globalIndex = ingestion.buildGlobalResolutionIndex(relFilePaths, sources, preParsed);
sources.clear();
+ preParsed.clear();
timings.goIndexMs = Math.round(performance.now() - goIndexStart);
}
diff --git a/ix-cli/src/cli/commands/ingestion-loader.ts b/ix-cli/src/cli/commands/ingestion-loader.ts
index f68e831c..b448f8f2 100644
--- a/ix-cli/src/cli/commands/ingestion-loader.ts
+++ b/ix-cli/src/cli/commands/ingestion-loader.ts
@@ -5,7 +5,7 @@ type IngestionModule = {
parseFile: (filePath: string, source: string) => any;
resolveEdges: (results: any[], stats?: any, globalIndex?: any) => any[];
isGrammarSupported: (filePath: string) => boolean;
- buildGlobalResolutionIndex: (filePaths: string[], sources?: Map<string, string>) => any;
+ buildGlobalResolutionIndex: (filePaths: string[], sources?: Map<string, string>, preParsed?: Map<string, any>) => any;
};
type PatchBuilderModule = {