From 9e729910de6295f4fae5d8153b07b28c0531bdad Mon Sep 17 00:00:00 2001 From: Jonjo McKay Date: Thu, 26 Nov 2026 16:36:57 +0000 Subject: [PATCH 01/61] fix(cli): take the index lock before replacing the database Hold codegraph.lock through database recreation and indexing so a refused rebuild cannot remove the database a running build is using. Refs #3494 --- CHANGELOG.md | 1 + __tests__/index-command.test.ts | 38 ++++++++++++++- __tests__/watcher-replaced-db.test.ts | 20 ++++---- src/bin/codegraph.ts | 7 +++ src/index.ts | 67 +++++++++++++++++---------- 5 files changed, 95 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 87ba42da05..ba35e039eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - In Pascal, a call to a routine with overloads in several units, like mORMot's `FormatUtf8`, now links to the overload its arguments fit, and a call from another unit no longer links to a routine that a unit declares only in its implementation section. (#3476) - In Pascal, an `inherited` call, like `inherited Create(AOwner)` or a bare `inherited;`, now links to the method of the nearest ancestor class that declares it, so a flow through an overriding method goes on into the method it overrides; re-index Pascal projects after upgrading. (#3477) - In Pascal, a routine whose `{$IFDEF}` branches each open a block for one shared `end`, like a `case` on one platform and a `begin` on another, or a Pascal body beside assembler versions, now ends at its own `end`, so the routines after it keep their own nodes and calls instead of being read as part of it; re-index Pascal projects after upgrading. (#3478) +- Running `codegraph index` while `codegraph init` is still building that project's index no longer breaks the first build: `index` reports the lock and stops before it touches the database, so `init` finishes with a complete index instead of failing and leaving an empty one. ## [1.6.4] - 2026-11-20 diff --git a/__tests__/index-command.test.ts b/__tests__/index-command.test.ts index 92d57d6378..bb6127c4d2 100644 --- a/__tests__/index-command.test.ts +++ b/__tests__/index-command.test.ts @@ -14,12 +14,12 @@ */ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { execFileSync } from 'child_process'; +import { execFileSync, spawnSync } from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; import { CodeGraph } from '../src'; -import { DatabaseConnection } from '../src/db'; +import { DatabaseConnection, getDatabasePath } from '../src/db'; import { encodeLockInfo, getDaemonPidPath } from '../src/mcp/daemon-paths'; const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js'); @@ -141,6 +141,40 @@ describe('codegraph index — full re-index keeps the graph populated (#874)', ( expect(afterIndex.edges).toBe(afterInit.edges); }); + it('refuses a rebuild without interrupting a running initial index', async () => { + const builder = CodeGraph.initSync(tempDir); + const dbPath = getDatabasePath(tempDir); + let attempted = false; + try { + const built = await builder.indexAll({ + onProgress: ({ phase }) => { + if (phase !== 'parsing' || attempted) return; + attempted = true; + // The first build already holds the write lock. Pause it here while + // the CLI tries to rebuild, without relying on the size of the project. + const before = fs.readFileSync(dbPath); + const { status, stdout, stderr, error } = spawnSync(process.execPath, [BIN, 'index'], { + cwd: tempDir, + encoding: 'utf8', + timeout: 15_000, + env: { ...process.env, CODEGRAPH_NO_DAEMON: '1' }, + }); + expect(error).toBeUndefined(); + expect(status).toBe(1); + expect(stdout + stderr).toContain('Could not acquire file lock - another process may be indexing'); + expect(fs.readFileSync(dbPath).equals(before), 'the running build’s database was changed').toBe(true); + }, + }); + expect(attempted).toBe(true); + expect(built).toMatchObject({ success: true, filesIndexed: 2 }); + } finally { + builder.close(); + } + const after = graphCounts(tempDir); + expect(after.nodes).toBeGreaterThan(0); + expect(after.edges).toBeGreaterThan(0); + }); + it('refuses to recreate while a live daemon cannot be verified (#1325)', () => { runCodegraph(['init'], tempDir); const daemonPid = startDetachedProcess(); diff --git a/__tests__/watcher-replaced-db.test.ts b/__tests__/watcher-replaced-db.test.ts index a81220f3d9..fab5adae97 100644 --- a/__tests__/watcher-replaced-db.test.ts +++ b/__tests__/watcher-replaced-db.test.ts @@ -16,7 +16,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import CodeGraph, { LockUnavailableError } from '../src/index'; +import CodeGraph from '../src/index'; import type { MCPEngine } from '../src/mcp/engine'; const posixOnly = it.runIf(process.platform !== 'win32'); @@ -83,17 +83,15 @@ describe('live sync after the index is rebuilt by another process (#1902)', () = } }); - posixOnly('a sync in the gap between recreate and indexAll steps aside, then reconciles in full', async () => { + posixOnly('a sync steps aside while recreate holds the write lock, then reconciles in full', async () => { const server = CodeGraph.initSync(root); await server.indexAll(); try { - // `codegraph index`: the file is recreated first, the write lock is taken later by indexAll. + // The rebuild already holds the lock before indexAll starts. const rebuilder = await CodeGraph.recreate(root); fs.appendFileSync(path.join(root, 'src', 'a.ts'), 'export function gamma() { return 3; }\n'); - // The server's sync lands in the gap: it must not claim the lock for a - // full reconcile of the empty file, and reports contention instead of success. - await expect(server.sync({ paths: ['src/a.ts'] })).rejects.toBeInstanceOf(LockUnavailableError); - // So the rebuild still gets its lock and completes. + await expect(server.sync({ paths: ['src/a.ts'] })).rejects.toThrow(/^Sync could not acquire the file lock/); + // The rebuild uses the same lock to complete the index. const built = await rebuilder.indexAll(); expect(built.success).toBe(true); rebuilder.close(); @@ -115,10 +113,10 @@ describe('live sync after the index is rebuilt by another process (#1902)', () = } }); - posixOnly('a watcher sync that lands in the rebuild gap keeps its pending files until the rebuild is reconciled', async () => { + posixOnly('a watcher blocked by the rebuild lock keeps its pending files until the rebuild is reconciled', async () => { const server = CodeGraph.initSync(root); await server.indexAll(); - // Record every sync the watcher starts, so the test can wait for the one in the gap. + // Record every sync the watcher starts, so the test can wait for the blocked attempt. const attempts: Array> = []; const realSync = server.sync.bind(server); (server as any).sync = (options?: Parameters[0]) => { @@ -131,11 +129,11 @@ describe('live sync after the index is rebuilt by another process (#1902)', () = // must outlast the rebuild below; 200 ms leaves several seconds. expect(server.watch({ debounceMs: 200, onSyncComplete: () => { synced++; } })).toBe(true); try { - // `codegraph index` has recreated the file but not taken the write lock yet. + // The rebuilt file is empty, but already locked. const rebuilder = await CodeGraph.recreate(root); fs.appendFileSync(path.join(root, 'src', 'a.ts'), 'export function gamma() { return 3; }\n'); await waitFor(() => attempts.length > 0); - await expect(attempts[0]).rejects.toBeInstanceOf(LockUnavailableError); + await expect(attempts[0]).rejects.toThrow(/^Sync could not acquire the file lock/); // Stepping aside is not a sync: the edit stays pending, nothing is reported as synced. expect(synced).toBe(0); expect(server.getPendingFiles().map((f) => f.path)).toContain('src/a.ts'); diff --git a/src/bin/codegraph.ts b/src/bin/codegraph.ts index 07313961b6..8d22cc82f2 100644 --- a/src/bin/codegraph.ts +++ b/src/bin/codegraph.ts @@ -52,6 +52,7 @@ import { Command } from 'commander'; import * as path from 'path'; import * as fs from 'fs'; import { getCodeGraphDir, makeGitignoreLocalOnly, isInitialized, hasSchemalessDb, hasForeignDbFile, unsafeIndexRootReason, findNearestCodeGraphRoot, planFrontload, isTaskNotification, isAgentMessage, isCrossSessionMessage, stripSystemReminders, hasStructuralKeyword, extractCodeTokens, capPromptHookInjection, codeGraphDirName, DEFAULT_CODEGRAPH_DIR } from '../directory'; +import { LockUnavailableError } from '../errors'; import { extractProseCandidates } from '../search/identifier-segments'; import { detectWorktreeIndexMismatch, worktreeMismatchWarning } from '../sync/worktree'; import { createShimmerProgress } from '../ui/shimmer-progress'; @@ -1116,6 +1117,12 @@ program releaseWriterLock(projectPath, 'rebuild.pid'); } } catch (err) { + // The rebuild now takes the write lock before it replaces the database, + // so a busy lock is reported here instead of from indexAll's result. + if (err instanceof LockUnavailableError) { + if (!options.quiet) error(err.message); + process.exit(1); + } error(`Failed to index: ${err instanceof Error ? err.message : String(err)}`); process.exit(1); } diff --git a/src/index.ts b/src/index.ts index 95d25c3999..744a32b894 100644 --- a/src/index.ts +++ b/src/index.ts @@ -205,6 +205,8 @@ export class CodeGraph { // File lock for preventing concurrent writes across processes (CLI, MCP, git hooks) private fileLock: FileLock; + // Only recreate() hands us an acquired lock, for the first indexAll() call. + private hasRebuildLock: boolean; // File watcher for auto-sync on file changes private watcher: FileWatcher | null = null; @@ -218,14 +220,16 @@ export class CodeGraph { private constructor( db: DatabaseConnection, queries: QueryBuilder, - projectRoot: string + projectRoot: string, + rebuildLock?: FileLock ) { this.db = db; this.queries = queries; this.projectRoot = projectRoot; - this.fileLock = new FileLock( + this.fileLock = rebuildLock ?? new FileLock( path.join(getCodeGraphDir(projectRoot), 'codegraph.lock') ); + this.hasRebuildLock = rebuildLock !== undefined; this.wireLayers(); } @@ -528,6 +532,9 @@ export class CodeGraph { * full re-index could never recover the bad state (#1067). Discarding the * files is O(1) regardless of size, reclaims the disk, and sidesteps opening * (and running migrations against) the poisoned database entirely. + * + * Takes the write lock before removing any database file. The returned + * instance holds it until its first indexAll() finishes or it is closed. */ static async recreate(projectRoot: string): Promise { await initGrammars(); @@ -540,25 +547,37 @@ export class CodeGraph { } const dbPath = getDatabasePath(resolvedRoot); + const lock = new FileLock(path.join(path.dirname(dbPath), 'codegraph.lock')); try { - removeDatabaseFiles(dbPath); - } catch (err) { - // POSIX unlinks an open file fine; this fires mainly on Windows when a - // live daemon/MCP server still holds the database. Turn the raw EBUSY into - // an actionable instruction instead of a generic failure. - const reason = err instanceof Error ? err.message : String(err); - throw new Error( - `Could not rebuild the index — the database file is in use (${reason}). ` + - `Stop any running CodeGraph MCP server/daemon for this project and retry, ` + - `or remove the ${getCodeGraphDir(resolvedRoot)} directory and run "codegraph init".` - ); + lock.acquire(); + } catch { + throw new LockUnavailableError('Could not acquire file lock - another process may be indexing'); } - // Re-create an empty, freshly-schema'd database at the same path. - const db = DatabaseConnection.initialize(dbPath); - const queries = new QueryBuilder(db.getDb()); + try { + try { + removeDatabaseFiles(dbPath); + } catch (err) { + // POSIX unlinks an open file fine; this fires mainly on Windows when a + // live daemon/MCP server still holds the database. Turn the raw EBUSY into + // an actionable instruction instead of a generic failure. + const reason = err instanceof Error ? err.message : String(err); + throw new Error( + `Could not rebuild the index — the database file is in use (${reason}). ` + + `Stop any running CodeGraph MCP server/daemon for this project and retry, ` + + `or remove the ${path.dirname(dbPath)} directory and run "codegraph init".` + ); + } - return new CodeGraph(db, queries, resolvedRoot); + // Re-create an empty, freshly-schema'd database at the same path. + const db = DatabaseConnection.initialize(dbPath); + const queries = new QueryBuilder(db.getDb()); + + return new CodeGraph(db, queries, resolvedRoot, lock); + } catch (err) { + lock.release(); + throw err; + } } /** @@ -633,6 +652,7 @@ export class CodeGraph { this.deferredSynthesisTimer = null; } // Release file lock if held + this.hasRebuildLock = false; this.fileLock.release(); this.db.close(); } @@ -657,10 +677,11 @@ export class CodeGraph { return this.indexMutex.withLock(async () => { const startedAt = Date.now(); try { - this.fileLock.acquire(); + if (!this.hasRebuildLock) this.fileLock.acquire(); } catch { return { success: false, filesIndexed: 0, filesSkipped: 0, filesErrored: 0, nodesCreated: 0, edgesCreated: 0, errors: [{ message: 'Could not acquire file lock - another process may be indexing', severity: 'error' as const }], durationMs: 0 }; } + this.hasRebuildLock = false; // Defer WAL auto-checkpointing for the whole bulk run (#1231): the // default 1000-page interval re-writes hot pages into the main DB file // over and over — ~95% of all disk I/O during a bulk index, and a @@ -1192,13 +1213,9 @@ export class CodeGraph { ); } if (this.pendingFullReconcile) { - // `codegraph index` recreates the file, THEN takes the write lock in - // indexAll. A sync landing in that gap would otherwise run a full - // reconcile of the empty file and hold the lock the rebuild is about - // to ask for. A fresh file with no index_state yet is that rebuild: - // step aside (lock contention, the watcher retries) and reconcile in - // full once it is done. Bounded, so a rebuild that died before - // indexing does not park the watcher forever. + // The lock above keeps sync out of a live rebuild. If the rebuild + // stopped before indexAll set index_state, give the fresh empty file + // a bounded grace period before reconciling it. if (this.getIndexState() === null && this.isFreshlyRecreated()) { this.fileLock.release(); throw new LockUnavailableError('A rebuild of this index is in progress; retry when it finishes.'); From d1679fea359b26a50494503f031fb7eb37263332 Mon Sep 17 00:00:00 2001 From: Colby Mchenry Date: Fri, 27 Nov 2026 14:55:13 -0600 Subject: [PATCH 02/61] fix(index): say which source files were left out for their size (#3503) A source file over the size limit is tracked and never parsed, so the graph holds none of its symbols. That is on purpose. What was wrong is that nothing said so: `index` printed "Indexed 1,678 files", `status` printed "Index is up to date" with no parse errors, and the file's own symbol map read "No indexed symbols in this file", for src/resolution/name-matcher.ts in this repository, 37,000 lines of hand-written source at 1.9 MB. A search, a caller list or an impact report over such a project is missing whatever the file holds, and silence reads as "not there". - `getIndexHealth()` lists the files left out for size, with their sizes. - `status` names them and reports them in its JSON as `index.filesOverSizeLimit`, `index.oversizeFiles` and `index.sizeLimitBytes`. It still says the index is up to date, and `--strict` still passes: nothing is stale, and a sync would change nothing. - `init`, `index` and `sync` print the same line when a file is left out. - `codegraph node --file --symbols-only` says the file was not indexed and why, in place of an empty map. The smallest are named first: a generated parser of 30 MB is what the limit is for, and a file just over it is the likeliest to be written by hand. In this repository that puts name-matcher.ts ahead of four generated parser.c files of 7 to 35 MB. The limit itself is unchanged. Co-authored-by: Claude Fable 5.2 --- CHANGELOG.md | 1 + __tests__/oversize-files-reported.test.ts | 150 ++++++++++++++++++++++ src/bin/codegraph.ts | 49 +++++++ src/index.ts | 7 +- src/mcp/tools.ts | 6 +- src/types.ts | 7 + 6 files changed, 218 insertions(+), 2 deletions(-) create mode 100644 __tests__/oversize-files-reported.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index adcc3f8dbc..3b81d317ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Fixes - In Rust, a method called on a closure's parameter now links to the right type's method when the closure is handed to a standard method such as `map`, `for_each`, `is_none_or` or `map_err`, as in `rpc.as_mut().is_none_or(|r| r.stop().is_ok())`, and so does one called on what `if let Some(x) = value.as_mut()` binds. Before, such a call was left out of `callers` and `impact` whenever two types in the project had a method of that name; re-index Rust projects after upgrading. (#3497) +- `init`, `index`, `sync` and `status` now name the source files left out of the graph for being over the 1 MB size limit, smallest first, and `status --json` lists them as `index.oversizeFiles`; before, nothing said that such a file's symbols, callers and impact were missing from every answer, and the file's own symbol map read as empty. - On Windows, the `codegraph` command in Git Bash now works in a terminal that turns off path conversion with `MSYS_NO_PATHCONV=1` or `MSYS2_ARG_CONV_EXCL=*`, as some agent harnesses do, instead of failing with "Cannot find module". Thanks @BlueberryDuck for the report. (#3464) - On projects with fewer than 500 files, every tool named in `CODEGRAPH_MCP_TOOLS` is now listed to the agent, instead of only the small-repo defaults. Thanks @nchrisr for the report and the fix. (#3462) - `codegraph callers` and `codegraph_callers` list callers outside tests before tests, so a symbol called mostly from tests no longer shows only tests under the default limit while its real callers are cut. Thanks @blairjordan for the report and the fix. (#3456) diff --git a/__tests__/oversize-files-reported.test.ts b/__tests__/oversize-files-reported.test.ts new file mode 100644 index 0000000000..18d6963bc5 --- /dev/null +++ b/__tests__/oversize-files-reported.test.ts @@ -0,0 +1,150 @@ +/** + * A source file over the size limit is tracked and never parsed, so the graph + * holds none of its symbols. That is on purpose. What was wrong is that nothing + * said so: `index` printed "Indexed N files", `status` printed "Index is up to + * date", and a file's symbol map read "No indexed symbols in this file", for a + * file of 37,000 lines of hand-written source. A search, a caller list or an + * impact report over such a project is missing whatever that file holds, and + * silence reads as "not there". + * + * These pin where it is now said: the index health the engine reports, the + * `status` text and JSON, the line `index` prints, and the symbol map of the + * file itself. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { spawnSync } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import CodeGraph from '../src/index'; +import { MAX_SOURCE_FILE_SIZE_BYTES } from '../src/file-limits'; +import { ToolHandler } from '../src/mcp/tools'; + +const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js'); + +// These index a project and spawn the real CLI. +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +const SMALL = 'export function alpha(): number { return 1; }\n'; +/** Real source, with a symbol, a little over the limit. */ +const BIG = `// ${'x'.repeat(MAX_SOURCE_FILE_SIZE_BYTES)}\nexport function hidden(): number { return 2; }\n`; + +describe('files left out of the graph for their size are said to be', () => { + let dir: string; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-oversize-reported-')); + }); + + afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }); + }); + + function write(files: Record): void { + for (const [file, content] of Object.entries(files)) { + const full = path.join(dir, file); + fs.mkdirSync(path.dirname(full), { recursive: true }); + fs.writeFileSync(full, content); + } + } + + function cli(...args: string[]): { code: number | null; stdout: string; stderr: string } { + const run = spawnSync(process.execPath, [BIN, ...args], { + encoding: 'utf-8', + env: { ...process.env, CODEGRAPH_NO_DAEMON: '1', NO_COLOR: '1', CODEGRAPH_TELEMETRY: '0' }, + }); + return { code: run.status, stdout: run.stdout, stderr: run.stderr }; + } + + it('lists them in the index health, with their size, and nothing else as oversize', async () => { + write({ 'src/small.ts': SMALL, 'src/big.ts': BIG, 'data/big.json': `{"k":"${'y'.repeat(MAX_SOURCE_FILE_SIZE_BYTES)}"}` }); + const cg = await CodeGraph.init(dir); + await cg.indexAll(); + try { + const health = cg.getIndexHealth(); + expect(health.oversize).toEqual([{ path: 'src/big.ts', size: Buffer.byteLength(BIG) }]); + // Left out on purpose: not something a sync would repair, not a parse error. + expect(health.needsReindex).toEqual([]); + expect(health.parseErrors).toEqual([]); + } finally { + cg.close(); + } + }); + + it('reports none for a project whose files are all within the limit', async () => { + write({ 'src/small.ts': SMALL }); + const cg = await CodeGraph.init(dir); + await cg.indexAll(); + try { + expect(cg.getIndexHealth().oversize).toEqual([]); + } finally { + cg.close(); + } + const text = cli('status', dir).stdout; + expect(text).toContain('Index is up to date'); + expect(text).not.toContain('size limit'); + expect(JSON.parse(cli('status', dir, '--json').stdout).index.filesOverSizeLimit).toBe(0); + }); + + it('status names them and still says the index is up to date', async () => { + write({ 'src/small.ts': SMALL, 'src/big.ts': BIG }); + const cg = await CodeGraph.init(dir); + await cg.indexAll(); + cg.close(); + + const { code, stdout } = cli('status', dir); + expect(code).toBe(0); + // Nothing is stale and nothing needs a sync: the file is left out by design. + expect(stdout).toContain('Index is up to date'); + expect(stdout).toMatch(/1 source file is over the 1\.0 MB size limit and not in the graph/); + expect(stdout).toContain('src/big.ts (1.0 MB)'); + + const json = JSON.parse(cli('status', dir, '--json').stdout); + expect(json.index.filesOverSizeLimit).toBe(1); + expect(json.index.oversizeFiles).toEqual([{ path: 'src/big.ts', size: Buffer.byteLength(BIG) }]); + expect(json.index.sizeLimitBytes).toBe(MAX_SOURCE_FILE_SIZE_BYTES); + // `--strict` is about an unfinished or stale index. This is neither. + expect(cli('status', dir, '--strict').code).toBe(0); + }); + + it('index says so when it leaves a file out, the smallest first', async () => { + const bigger = `${BIG}// ${'z'.repeat(300_000)}\n`; + write({ 'src/small.ts': SMALL, 'src/big.ts': BIG, 'src/bigger.ts': bigger }); + const { code, stdout, stderr } = cli('init', dir); + expect(code).toBe(0); + const said = `${stdout}\n${stderr}`; + expect(said).toMatch(/2 source files are over the 1\.0 MB size limit and not in the graph/); + // The file nearest the limit is the likeliest to be hand-written source. + expect(said).toMatch(/src\/big\.ts \(1\.0 MB\), src\/bigger\.ts \(1\.3 MB\)/); + }); + + it('sync says so too, for a file that grew past the limit and for one already left out', async () => { + write({ 'src/small.ts': SMALL, 'src/big.ts': SMALL }); + expect(cli('init', dir).code).toBe(0); + write({ 'src/big.ts': BIG }); + const grew = cli('sync', dir); + expect(grew.code).toBe(0); + expect(`${grew.stdout}\n${grew.stderr}`).toMatch(/1 source file is over the 1\.0 MB size limit and not in the graph/); + // Nothing changed this time; the file is still left out, and sync still says so. + const again = cli('sync', dir); + expect(`${again.stdout}\n${again.stderr}`).toContain('src/big.ts (1.0 MB)'); + }); + + it('the symbol map of such a file says it was not indexed, not that it is empty', async () => { + write({ 'src/small.ts': SMALL, 'src/big.ts': BIG }); + const cg = await CodeGraph.init(dir); + await cg.indexAll(); + try { + const handler = new ToolHandler(cg); + const map = async (file: string): Promise => + (await handler.execute('codegraph_node', { file, symbolsOnly: true })).content.map((c) => c.text).join('\n'); + const big = await map('src/big.ts'); + expect(big).toContain('_Not indexed: at 1.0 MB this file is over the size limit for source files'); + expect(big).not.toContain('No indexed symbols in this file'); + expect(await map('src/small.ts')).toContain('`alpha`'); + } finally { + cg.close(); + } + }); +}); diff --git a/src/bin/codegraph.ts b/src/bin/codegraph.ts index 07313961b6..8bb3d0477c 100644 --- a/src/bin/codegraph.ts +++ b/src/bin/codegraph.ts @@ -63,6 +63,7 @@ import { installFatalHandlers } from './fatal-handler'; import { relaunchWithWasmRuntimeFlagsIfNeeded } from '../extraction/wasm-runtime-flags'; import { installCommandSupervision, watchParent } from './command-supervision'; import { EXTRACTION_VERSION } from '../extraction/extraction-version'; +import { MAX_SOURCE_FILE_SIZE_BYTES } from '../file-limits'; import { getTelemetry, TELEMETRY_DOCS, recordIndexEvent } from '../telemetry'; // Value import, but dependency-free by design so `--help` text can name the // default port without dragging node:http into every other subcommand; the @@ -509,6 +510,15 @@ function printIndexResult(clack: typeof import('@clack/prompts'), result: IndexR // failures are indexed but possibly incomplete — say so here, or the run // reads as fully clean and the index quietly disagrees with a later // re-parse of the same bytes (#1565). + // Files over the size limit are stored without being parsed. That is on + // purpose, and it used to be silent: "Indexed 1,678 files" with one of + // them, 37,000 lines of hand-written source, holding no symbol at all. + const oversize = describeOversizeFiles( + result.errors + .filter((e) => e.code === 'size_exceeded' && e.filePath) + .map((e) => ({ path: e.filePath!, size: Number(/\((\d+) > \d+\)/.exec(e.message)?.[1] ?? 0) })), + ); + if (oversize) clack.log.warn(oversize); const salvaged = result.errors.filter((e) => e.code === 'salvaged_stripped'); if (salvaged.length > 0) { const sample = salvaged.slice(0, 3).map((e) => e.filePath).filter(Boolean).join(', '); @@ -1186,6 +1196,11 @@ program clack.log.warn('This index was built by an older CodeGraph engine, and sync only re-reads changed files. Run "codegraph index" for a full rebuild.'); } + // Up to date and still not whole: the files left out for their size, + // whether or not this sync touched them. + const oversize = describeOversizeFiles(cg.getIndexHealth().oversize); + if (oversize) clack.log.warn(oversize); + clack.outro('Done'); } finally { cg.destroy(); @@ -1203,6 +1218,31 @@ function samplePaths(paths: string[]): string { return paths.slice(0, 3).join(', ') + (paths.length > 3 ? ` (+${formatNumber(paths.length - 3)} more)` : ''); } +/** A file size as people say it: "1.9 MB", "640 KB". */ +function formatFileSize(bytes: number): string { + return bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : `${Math.ceil(bytes / 1024)} KB`; +} + +/** + * One line naming the source files left out of the graph for their size, or + * null when there are none. `init`, `index`, `sync` and `status` all say it: + * a file over the limit is tracked but never parsed, and until this line the + * only sign of that was a search that came back without it. + * + * The smallest are named first. A generated parser of 30 MB is what the limit + * is for; a file just over it is the one most likely to be written by hand, + * and the one a reader needs to see. + */ +function describeOversizeFiles(files: { path: string; size: number }[]): string | null { + if (files.length === 0) return null; + const smallest = [...files].sort((a, b) => a.size - b.size); + const named = smallest.slice(0, 3).map((f) => `${f.path} (${formatFileSize(f.size)})`).join(', '); + const more = files.length > 3 ? ` (+${formatNumber(files.length - 3)} more)` : ''; + const one = files.length === 1; + return `${formatNumber(files.length)} source ${one ? 'file is' : 'files are'} over the ${formatFileSize(MAX_SOURCE_FILE_SIZE_BYTES)} size limit and not in the graph ${getGlyphs().dash} ` + + `${one ? 'its' : 'their'} symbols, callers and impact are missing from every answer: ${named}${more}`; +} + /** * The `status` warnings for indexed files whose symbols are missing although * their content is current (#2335, #2336): one line per group, saying what is @@ -1369,6 +1409,12 @@ program // Files with a recorded parse error and no symbols from it // (#2336); unchanged until the file or the parser changes. filesWithParseErrors: health.parseErrors.length, + // Source files over the size limit: tracked, never parsed, so + // nothing in them is in the graph. The smallest come first: the + // ones nearest the limit are the likeliest to be hand-written. + filesOverSizeLimit: health.oversize.length, + oversizeFiles: [...health.oversize].sort((a, b) => a.size - b.size).slice(0, 50), + sizeLimitBytes: MAX_SOURCE_FILE_SIZE_BYTES, }, })); cg.destroy(); @@ -1489,6 +1535,9 @@ program if (totalChanges === 0 && missingSymbols.length === 0) { success('Index is up to date'); } + // Up to date and still not whole: files left out for their size. + const oversize = describeOversizeFiles(health.oversize); + if (oversize) warn(oversize); console.log(); // Re-index hint: the index was built by an older engine than the one now diff --git a/src/index.ts b/src/index.ts index 95d25c3999..9184780efa 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3077,6 +3077,7 @@ export class CodeGraph { getIndexHealth(): IndexHealth { const needsReindex: string[] = []; const parseErrors: string[] = []; + const oversize: IndexHealth['oversize'] = []; for (const file of this.queries.getFilesWithoutNodesOrWithErrors()) { const errors = file.errors ?? []; if (hasGrammarLoadFailure(errors)) { @@ -3087,6 +3088,10 @@ export class CodeGraph { // wiped row (#1541) or a recorded failure — except file-level-only // languages and files over the size limit, which are empty on purpose. if (isFileLevelOnlyLanguage(file.language)) continue; + if (errors.some((e) => e.code === 'size_exceeded')) { + oversize.push({ path: file.path, size: file.size }); + continue; + } if (errors.length === 0) needsReindex.push(file.path); else if (errors.some((e) => e.severity === 'error' || e.code === 'parse_error')) parseErrors.push(file.path); } else if (errors.some((e) => e.code === 'parse_error')) { @@ -3094,7 +3099,7 @@ export class CodeGraph { parseErrors.push(file.path); } } - return { needsReindex, parseErrors }; + return { needsReindex, parseErrors, oversize }; } /** diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts index baf34b1144..40ead9610f 100644 --- a/src/mcp/tools.ts +++ b/src/mcp/tools.ts @@ -8521,7 +8521,11 @@ export class ToolHandler { if (opts.symbolsOnly) { const out = [`**${filePath}**${testLabel} — ${nodes.length} symbol${nodes.length === 1 ? '' : 's'}, ${depSummary}`, '']; if (nodes.length) out.push(...symbolMap('**Symbols**')); - else out.push('_No indexed symbols in this file._'); + // A file over the size limit is tracked but never parsed. Say that, so + // an empty map is not read as an empty file. + else if ((resolved.errors ?? []).some((e) => e.code === 'size_exceeded')) { + out.push(`_Not indexed: at ${(resolved.size / 1024 / 1024).toFixed(1)} MB this file is over the size limit for source files, so the graph holds none of its symbols and no caller of them. Read the file directly._`); + } else out.push('_No indexed symbols in this file._'); out.push('', '> Drop `symbolsOnly` (or pass `offset`/`limit`) to read the source, like Read.'); return this.textResult(this.truncateOutput(out.join('\n'))); } diff --git a/src/types.ts b/src/types.ts index b16f55c9ed..3b5b7e0440 100644 --- a/src/types.ts +++ b/src/types.ts @@ -303,6 +303,13 @@ export interface IndexHealth { * they stay this way until the file (or the parser) changes. */ parseErrors: string[]; + /** + * Source files over the size limit (`MAX_SOURCE_FILE_SIZE_BYTES`): tracked, + * never parsed, so the graph holds none of their symbols. Empty on purpose, + * and nothing to repair, but reported: a search, a caller list or an impact + * report says nothing of what is in them, and silence reads as "not there". + */ + oversize: { path: string; size: number }[]; } // ============================================================================= From 03383f9d172282e3e83d74ef02c98c995a7661b3 Mon Sep 17 00:00:00 2001 From: Colby Mchenry Date: Fri, 27 Nov 2026 20:39:03 -0600 Subject: [PATCH 03/61] perf(index): a large file indexes in the time its size asks for; index files up to 4 MB (#3504) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * perf(index): a large file indexes in the time its size asks for; index files up to 4 MB A large source file took time in the square of its size. A Python file of plain functions took 3 seconds at a third of a megabyte and 27 at nine tenths, a Ruby one twice that; a table of rows that each call a helper took 37 seconds at a third of a megabyte; one string of hex 30 KB long cost a second, which is eighteen minutes for a megabyte of it. Past about a megabyte a file was given the 180 seconds a file is allowed and then given up on, with none of its symbols indexed. That is why the size limit could not be raised. Every cause was the same shape: work done for each symbol, or each reference, that went through the whole file or everything before it. In both extractors (the native kernel and the wasm one): - A declaration's decorators were looked for after finding where it stands among its parent's children, counted from the first (seven languages). The walk now starts from the declaration. - A Ruby method's visibility walked back over every sibling before it; a C++ member read every child of its parent. Each now keeps what the last answer was, per parent. - A node's children were read by index, and tree-sitter reads the children before the one asked for when they are a flat run, as some thousand consecutive comment lines are. They are now stepped through (278 loops in the kernel; in the wasm extractor, the 97 that read every child). - Each JS/TS constant compiled a pattern and searched the whole file to see if a later statement exports it. The names are read once per file. In the kernel alone: - A column was counted character by character from its line's start, so a script minified to one line paid its length for every symbol. It is read from a table built once per file. - The C scan searched for `struct` and for `union` from its place on every turn, to the end of the file for whichever the file does not use. - A declaration's walked initializers were kept as a list and searched for every node under it: a Go `const (…)` block of some thousand names. In the resolver: - "Does the function's code, from its first line through this one, bind this name?" read that code again for each line asked about (JS/TS, Scala), and a Python reference read its whole statement, which for a table is the whole file. Each is now read once and answered for any line. - What is around a reference (its function, its class, its namespace) was found by going through every node of the file, in nearly forty places. The nodes that can hold a line now come from a per-file index (nodes-around.ts); the test each place makes is unchanged. - A file's imports were gone through for every reference at each step of import resolution. They are indexed by name and by source (import-lookup.ts). - Import statements named alike (`crate` for every `use crate::…` of a Rust project) went through each other; a file's nodes were filtered by name, or queried one name at a time, for every reference. - The line of an offset was written `text.slice(0, i).split('\n').length` in more than fifty places, a pass over the file for each match of a route or handler scan. They share one helper (lineAt). - A few checks stripped or split their whole file for each reference (object-literal aliases, store calls). One change is a change of what is read, not only of how fast: the resolver's patterns are no longer given a run of name characters longer than 1,024 (an embedded asset, a key, a table of hex). A pattern that reads a name starts one at every character of such a run and reads to its end. The run is blanked, at its length, in the text the resolver reads (withoutLongRuns); the file on disk, its symbols and its positions are untouched. With that, the limit goes from 1 MB to 4 MB. At 4 MB a file of some hundred thousand imports or references also overflowed the stack where a list was spread into a call's arguments; those lists are now added item by item. Checked against the engine as it was: the graph built from this repository's test fixtures, from its own source, from the desktop app, from parts of the Python, Ruby and Go standard libraries and five Rust crates, and from 300 generated files (one a language and shape) is the same, node for node and edge for edge, with the kernel and with the wasm extractor. At 3.9 MB, 317 generated files (17 languages, 24 shapes) index in 2.2 seconds on average, the slowest in 12 (130,000 `#include` lines). Fourteen real files of 1 to 3.8 MB found on one machine (generated Go, tree-sitter parsers, Arm headers, a bundle, icon typings, this repository's own name-matcher.ts) take 0.3 to 4.2 seconds each. Memory per megabyte is as it was, so a file four times the old limit can take four times the memory while it is indexed: 0.15 to 0.7 GB at its peak for those real files, 1.8 GB for the 3.8 MB bundle. Co-Authored-By: Claude Fable 5.2 * perf(index): large files in the other languages, in routes files and across the bridges The commit before this one measured the seventeen languages the native kernel reads. The README lists about twice that many, and the frameworks whose routes and handlers are linked; none of those had been timed. Timed now, at 1.2 MB: an Express file of inline handlers took 58 seconds, Liquid markup 41, a CodeIgniter routes file and its controller 31, ArkTS components 22, a React Native Fabric spec 20, a file of event listeners 16, and a Rails, Play, React Router or Angular routes file 8 to 12. The causes were the same shape as before, work for each symbol, reference or route that goes through the whole file, in the places that commit did not reach: In the wasm extractor and the extractors that read without a grammar: - An ArkTS declaration's decorators were looked for after finding where it stands among its parent's children, counted from the first. - Liquid read the text before each tag for its line, and split the whole source for each line's start. Both come from a table built once. - A member's qualified name looked for each id on the stack among every node extracted so far (five places). They are kept by id. - A Vue options component looked for the member around each reference among all of them. The member of each line is written down once. - The ninety loops over a node's children that leave early were still read by index (the first commit converted those that read every child). They step with a cursor (childrenOf, namedChildrenOf): a megabyte of comment lines under a VB.NET module took four seconds. In the resolver and the framework passes: - "The node of this file named X" was a pass over all of the file's nodes, once per route for a routes file and its controller (CodeIgniter, Rails, Play, Laravel, Drupal, Vue, Angular, React) and once per reference in a dozen other places. The nodes of a file are indexed by name, by name in any case, and by owner (nodesNamed, nodesNamedLower, nodesUnder). - React Router looked for the routes around each route among all of them, and for a page claiming the same path among all of them. Routes are kept by stretch of the source and by path. - The scan for the line that declares a receiver's type keeps its last answer and goes on from it when asked about a later line; asked about an earlier one, it scanned again from that line up. It now answers from what it kept. That was the Express file: each handler calls a method on a parameter nothing declares. - Event listeners, Angular templates and the enclosing-function helpers went through every node of the file for the ones around a line; the line of an offset was counted from the file's start for each Angular binding and each React Native bridge method. - A JSX file of many components searched the whole scope for each tag name written bare. The words are read once. - A React Native Fabric spec looked for each prop's name from the first line of its props interface, and for the interface itself each time: twenty seconds for an interface of 1.2 MB. Where each name first occurs is read in one pass (firstIndexOfEach). - An Objective-C message that a Swift `@objc` method might answer split the Swift file into lines, to read the three above the method's declaration: seven seconds for 0.8 MB. The file's lines are split once. - A member called on a module's default import asked whether the module's file says `module.exports`, then read the file for what it states as its default, for each call: four seconds for a megabyte of calls on one TurboModule. Each is asked once per file. - A Tauri front end tried a pattern on the code before each `invoke` call to see whether the function destructures a binding of that name. Where the first such binding ends is kept per function. Nothing here changes what is read. The graph is the same as the engine at main builds, node for node and edge for edge, over the bodies of code the first commit was checked on, over 96 more generated projects, one for each remaining language, framework and bridge, and over small projects written for what the faster paths decide, with the kernel and with the wasm extractor. One slowness is left, and it is the parser's: tree-sitter's Objective-C grammar does not parse `RCT_EXTERN_METHOD(...)` lines inside an `@interface`, and its error recovery takes the square of their number. Two thousand such lines take half a second and sixteen thousand seven; thirty-two thousand are given up on at the parse limit, with the timeout reported. A real shim has tens of them. Blanking the lines before the parse would change what the parser makes of every such shim today, which this commit does not do. Co-Authored-By: Claude Fable 5.2 * docs(index): what made large files slow, how to measure it, how to keep it out The two commits before this one removed about forty instances of one fault, and nothing in the repository said what the fault is, what to write instead, or how it was found. The next change to an extraction or resolution loop would have put it back, and the next report of a slow file, or of one with no symbols, would have started from nothing. - docs/design/large-file-performance.md: the rule (a file costs its size), the shape of the fault with each form it took and what to write instead, the rules for a lookup that keeps an index, how to measure, how to find the line, how to prove the graph unchanged, the traps that cost a run, what is known and left as it is, and what to do with an issue or a pull request. - AGENTS.md: the rule and the pointer, in the guide every session loads. - scripts/benchmarks/large-files/: the two harnesses the numbers came from (the kernel's 17 languages in about 24 shapes; the other languages, each framework's routes file and each bridge), a profiler that names the line, and compare-graphs.mjs, which indexes a project with two builds and compares what scripts/dump-graph.mjs prints for each. - CONTRIBUTING.md and docs/README.md point at the guide. - CHANGELOG.md: this pull request's entries without timings, as the rules for entries ask. compare-graphs.mjs uses the repository's own dump, which also holds the unresolved references. Run over what the earlier commits were checked on (the fixtures, this repository's src, real code in five languages, the generated projects and the small ones written for each decision, 117 projects in all), it finds every graph the same, with the kernel and with the wasm extractor. Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: Claude Fable 5.2 --- AGENTS.md | 11 + CHANGELOG.md | 8 +- CONTRIBUTING.md | 1 + README.md | 2 +- __tests__/go-indexed-receiver.test.ts | 5 +- __tests__/go-unread-file-methods.test.ts | 12 +- __tests__/kernel-large-file-parity.test.ts | 232 ++++ __tests__/large-corpus-regressions.test.ts | 8 +- __tests__/large-file-frameworks.test.ts | 307 +++++ __tests__/large-file-indexing.test.ts | 304 +++++ __tests__/large-file-lookups.test.ts | 382 ++++++ __tests__/name-matcher-memo-clears.test.ts | 2 + __tests__/oversize-file-not-read.test.ts | 17 +- __tests__/oversize-files-reported.test.ts | 14 +- __tests__/parameter-flow.test.ts | 4 +- __tests__/resolution-file-read.test.ts | 6 +- __tests__/sync.test.ts | 3 +- codegraph-kernel/src/ccpp/brace_scopes.rs | 2 +- codegraph-kernel/src/ccpp/mod.rs | 161 +-- codegraph-kernel/src/cfnptr.rs | 14 +- codegraph-kernel/src/csharp.rs | 134 +- codegraph-kernel/src/dart.rs | 62 +- codegraph-kernel/src/go.rs | 98 +- codegraph-kernel/src/java.rs | 181 +-- codegraph-kernel/src/kotlin.rs | 231 ++-- codegraph-kernel/src/lua.rs | 2 +- codegraph-kernel/src/php.rs | 108 +- codegraph-kernel/src/python.rs | 121 +- codegraph-kernel/src/rlang.rs | 2 +- codegraph-kernel/src/ruby.rs | 128 +- codegraph-kernel/src/rustlang.rs | 103 +- codegraph-kernel/src/scala.rs | 42 +- codegraph-kernel/src/swift.rs | 180 +-- codegraph-kernel/src/textutil.rs | 74 +- codegraph-kernel/src/tsjs/extractors.rs | 304 +++-- codegraph-kernel/src/tsjs/fnref.rs | 6 +- codegraph-kernel/src/tsjs/mod.rs | 79 +- docs/README.md | 1 + docs/design/large-file-performance.md | 143 +++ .../benchmarks/large-files/compare-graphs.mjs | 91 ++ .../large-files/kernel-languages.mjs | 241 ++++ .../benchmarks/large-files/kernel-shapes.mjs | 220 ++++ .../large-files/other-languages.mjs | 445 +++++++ scripts/benchmarks/large-files/profile.mjs | 57 + .../docs/getting-started/configuration.md | 2 +- src/extraction/cfml-extractor.ts | 14 +- src/extraction/commonjs-requires.ts | 3 +- src/extraction/function-ref.ts | 29 +- src/extraction/kernel/index.ts | 5 +- src/extraction/languages/arkts.ts | 32 +- src/extraction/languages/c-cpp.ts | 44 +- src/extraction/languages/cfscript.ts | 5 +- src/extraction/languages/cpp-macro-methods.ts | 5 +- src/extraction/languages/csharp.ts | 18 +- src/extraction/languages/dart.ts | 11 +- src/extraction/languages/erlang.ts | 4 +- src/extraction/languages/java.ts | 11 +- src/extraction/languages/javascript.ts | 14 +- src/extraction/languages/kotlin.ts | 67 +- src/extraction/languages/lua.ts | 3 +- src/extraction/languages/objc.ts | 17 +- src/extraction/languages/pascal.ts | 9 +- src/extraction/languages/php.ts | 8 +- src/extraction/languages/python.ts | 3 +- src/extraction/languages/r.ts | 14 +- src/extraction/languages/ruby.ts | 50 +- src/extraction/languages/rust.ts | 8 +- src/extraction/languages/scala.ts | 20 +- src/extraction/languages/solidity.ts | 20 +- src/extraction/languages/swift.ts | 17 +- src/extraction/languages/typescript.ts | 34 +- src/extraction/languages/vbnet.ts | 5 +- src/extraction/liquid-extractor.ts | 38 +- src/extraction/store-worker.ts | 3 +- src/extraction/tree-sitter-helpers.ts | 34 + src/extraction/tree-sitter.ts | 371 +++--- src/extraction/vue-extractor.ts | 28 +- src/file-limits.ts | 59 +- .../angular-template-synthesizer.ts | 29 +- src/resolution/callback-synthesizer.ts | 39 +- src/resolution/const-alias-synthesizer.ts | 3 +- src/resolution/event-emitter-synthesizer.ts | 27 +- src/resolution/expo-router-synthesizer.ts | 5 +- src/resolution/frameworks/angular-router.ts | 11 +- src/resolution/frameworks/astro.ts | 3 +- src/resolution/frameworks/codeigniter.ts | 12 +- src/resolution/frameworks/csharp.ts | 7 +- src/resolution/frameworks/drupal.ts | 10 +- src/resolution/frameworks/expo-modules.ts | 3 +- src/resolution/frameworks/expo-router.ts | 5 +- src/resolution/frameworks/express.ts | 7 +- src/resolution/frameworks/fabric.ts | 35 +- src/resolution/frameworks/go.ts | 3 +- src/resolution/frameworks/goframe.ts | 3 +- src/resolution/frameworks/java.ts | 12 +- src/resolution/frameworks/laravel.ts | 8 +- src/resolution/frameworks/nestjs.ts | 5 +- src/resolution/frameworks/next-proxy.ts | 3 +- src/resolution/frameworks/nextjs.ts | 3 +- src/resolution/frameworks/page-component.ts | 4 +- src/resolution/frameworks/play.ts | 3 +- src/resolution/frameworks/python.ts | 13 +- src/resolution/frameworks/react-native.ts | 17 +- src/resolution/frameworks/react.ts | 46 +- src/resolution/frameworks/ruby.ts | 10 +- src/resolution/frameworks/rust.ts | 13 +- src/resolution/frameworks/swift-objc.ts | 13 +- src/resolution/frameworks/swift.ts | 14 +- src/resolution/frameworks/tanstack-router.ts | 3 +- src/resolution/frameworks/vue-router.ts | 3 +- src/resolution/frameworks/vue.ts | 7 +- src/resolution/import-lookup.ts | 90 ++ src/resolution/import-resolver.ts | 47 +- src/resolution/index.ts | 87 +- src/resolution/name-matcher.ts | 1118 +++++++++++++---- src/resolution/nodes-around.ts | 150 +++ src/resolution/python-overloads.ts | 3 +- src/resolution/ruby-constant-paths.ts | 3 +- src/resolution/swift-type-visibility.ts | 13 +- src/resolution/synth-utils.ts | 172 ++- src/resolution/tauri-synthesizer.ts | 35 +- src/resolution/type-parameters.ts | 4 +- src/ui-server/api/source.ts | 2 +- src/utils.ts | 24 + 124 files changed, 5471 insertions(+), 2209 deletions(-) create mode 100644 __tests__/kernel-large-file-parity.test.ts create mode 100644 __tests__/large-file-frameworks.test.ts create mode 100644 __tests__/large-file-indexing.test.ts create mode 100644 __tests__/large-file-lookups.test.ts create mode 100644 docs/design/large-file-performance.md create mode 100644 scripts/benchmarks/large-files/compare-graphs.mjs create mode 100644 scripts/benchmarks/large-files/kernel-languages.mjs create mode 100644 scripts/benchmarks/large-files/kernel-shapes.mjs create mode 100644 scripts/benchmarks/large-files/other-languages.mjs create mode 100644 scripts/benchmarks/large-files/profile.mjs create mode 100644 src/resolution/import-lookup.ts create mode 100644 src/resolution/nodes-around.ts diff --git a/AGENTS.md b/AGENTS.md index 3185f27718..763df81daa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -190,6 +190,17 @@ Every engine test file runs in a throwaway home dir (`__tests__/setup-home-sandb Behavior that differs by platform (path resolution, drive letters, `SENSITIVE_PATHS`, `%APPDATA%` config dirs, CRLF) must be gated, not assumed. Use `it.runIf(process.platform === 'win32')(...)` for Windows-only assertions and `it.runIf(process.platform !== 'win32')(...)` for POSIX-only ones — e.g. `/etc` is sensitive on POSIX but resolves to `C:\etc` (non-existent) on Windows, so an ungated `/etc` assertion fails on Windows. Validate the Windows side for real (see below); don't merge a Windows-gated test you haven't seen run. +## Indexing cost grows with the file's size (do not regress) + +**Indexing a file costs in proportion to its size: about a second a megabyte.** Nothing done for one symbol, reference, route or match may read the whole file, all of the file's nodes, all of its imports, or everything before it. That one shape, in about forty places across the kernel, the wasm extractor, the resolver and the framework passes, made a megabyte take from half a minute to several minutes and left large files with no symbols. Each instance looks like ordinary code and is fine at 300 lines. + +**Before changing or reviewing a loop in `src/extraction/`, `src/resolution/` or `codegraph-kernel/`, and before answering an issue about slow indexing, a hang, or a file with no symbols, read `docs/design/large-file-performance.md`.** It lists what to look for in a diff and what to write instead, how to measure, and how to prove a fix. In short: + +- **Use the lookups, not a pass over the file:** `lineAt` / `linesOf` / `firstIndexOfEach` (`resolution/synth-utils.ts`), `nodesAroundLine` / `nodesNamed` (`resolution/nodes-around.ts`), `importsBoundTo` and its siblings (`resolution/import-lookup.ts`), `childrenOf` / `namedChildrenOf` or `node.namedChildren` in place of `node.child(i)` in a loop, `pushAll` / `maxOf` in place of spreading a file-sized list. +- **Measure** with `scripts/benchmarks/large-files/` at 0.3, 1.2 and 3.9 MB, with the kernel and with `CODEGRAPH_KERNEL=0`: four times the size must cost about four times the time. Start from the README's language, framework and bridge tables, not from the list of parsers; a new one gets a case. +- **A speed fix leaves the graph identical:** `scripts/benchmarks/large-files/compare-graphs.mjs `, with both parsers. A change in what is read goes in its own pull request. +- **Tests:** `__tests__/large-file-{indexing,frameworks,lookups}.test.ts` and `kernel-large-file-parity.test.ts`. Each case bounds the time and asserts something the faster path could get wrong. + ## Cross-platform validation The dev machine — and the default `npm test` target — is **macOS**, so local runs cover the macOS path. The other two platforms aren't here; when a change is platform-sensitive (file watching, sockets / named pipes, path & symlink handling, process lifecycle, inotify budget) validate them for real rather than guessing. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b81d317ed..4748894fe5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,13 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Fixes - In Rust, a method called on a closure's parameter now links to the right type's method when the closure is handed to a standard method such as `map`, `for_each`, `is_none_or` or `map_err`, as in `rpc.as_mut().is_none_or(|r| r.stop().is_ok())`, and so does one called on what `if let Some(x) = value.as_mut()` binds. Before, such a call was left out of `callers` and `impact` whenever two types in the project had a method of that name; re-index Rust projects after upgrading. (#3497) -- `init`, `index`, `sync` and `status` now name the source files left out of the graph for being over the 1 MB size limit, smallest first, and `status --json` lists them as `index.oversizeFiles`; before, nothing said that such a file's symbols, callers and impact were missing from every answer, and the file's own symbol map read as empty. +- A large source file now indexes in seconds in every supported language, where the time used to grow so fast with the file's size that a file past about a megabyte could run out its time limit and end up with no symbols. +- The same now holds for a large routes or handlers file in every supported framework and router (Express, Rails, CodeIgniter, Play, React Router, Angular and the rest), for Liquid, ArkTS and the other languages read without the native parser, and for the React Native, Expo, Tauri and Swift to Objective-C bridges. +- A file that holds one long string of hex or base64-like text, such as an embedded image, font or key, no longer stalls indexing. +- A script minified to one line now indexes in seconds instead of stalling. +- A generated file of thousands of imports, `require` lines, routes or comment lines now indexes in seconds, and a file with a very large number of imports no longer stops indexing with "Maximum call stack size exceeded". +- Source files up to 4 MB are now indexed, up from 1 MB, so a large hand-written file is no longer left out of the graph with nothing said; the next `codegraph sync` after upgrading indexes any file between the two sizes. +- `init`, `index`, `sync` and `status` now name the source files left out of the graph for being over the size limit, smallest first, and `status --json` lists them as `index.oversizeFiles`; before, nothing said that such a file's symbols, callers and impact were missing from every answer, and the file's own symbol map read as empty. - On Windows, the `codegraph` command in Git Bash now works in a terminal that turns off path conversion with `MSYS_NO_PATHCONV=1` or `MSYS2_ARG_CONV_EXCL=*`, as some agent harnesses do, instead of failing with "Cannot find module". Thanks @BlueberryDuck for the report. (#3464) - On projects with fewer than 500 files, every tool named in `CODEGRAPH_MCP_TOOLS` is now listed to the agent, instead of only the small-repo defaults. Thanks @nchrisr for the report and the fix. (#3462) - `codegraph callers` and `codegraph_callers` list callers outside tests before tests, so a symbol called mostly from tests no longer shows only tests under the default limit while its real callers are cut. Thanks @blairjordan for the report and the fix. (#3456) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5831fc77ac..b78e50272a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,6 +48,7 @@ Run the focused tests while you work, then `npm test` before opening a pull requ - **A bug fix needs a test that fails without the fix.** - **Behavior that differs by platform** gets a gated test, such as `it.runIf(process.platform === 'win32')(...)`, and needs checking on the platforms it affects. See [cross-platform validation](AGENTS.md#cross-platform-validation). - **New language or framework support** needs validating on real repositories. Start with the `/add-lang` skill in [`.claude/skills/add-lang/SKILL.md`](.claude/skills/add-lang/SKILL.md), then follow the [validation methodology](docs/AGENTS.md#validation-methodology-required-for-every-new-languageframework) and the [coverage playbook](docs/design/dynamic-dispatch-coverage-playbook.md). Before extending a router or web framework, read [framework coverage](docs/design/framework-coverage.md). +- **A change to a loop in extraction or resolution** keeps indexing time in proportion to the file's size: a megabyte in about a second. [Large-file performance](docs/design/large-file-performance.md) lists what to look for and how to measure it. - **A documentation-only change** doesn't need the test suite. Check its examples and links instead. ## Prepare a pull request diff --git a/README.md b/README.md index 76913933e5..9b9b086dbf 100644 --- a/README.md +++ b/README.md @@ -675,7 +675,7 @@ What it skips out of the box: and a Java, Kotlin or Scala package named `build` is indexed whole. - **Anything in your `.gitignore`** — honored in git repos via git, and in non-git projects by reading `.gitignore` directly (root and nested). -- **Files larger than 1 MB** — generated bundles, minified JS, vendored blobs. +- **Files larger than 4 MB** — generated bundles, minified JS, vendored blobs. `codegraph status` names any source file left out for its size. To keep something else out, add it to `.gitignore`. To pull a default-excluded directory back **in** (say you really do want a vendored dependency indexed), diff --git a/__tests__/go-indexed-receiver.test.ts b/__tests__/go-indexed-receiver.test.ts index e4ba2e3b96..6757984124 100644 --- a/__tests__/go-indexed-receiver.test.ts +++ b/__tests__/go-indexed-receiver.test.ts @@ -21,6 +21,7 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { CodeGraph } from '../src'; +import { MAX_SOURCE_FILE_SIZE_BYTES } from '../src/file-limits'; let root = ''; let cg: CodeGraph; @@ -84,12 +85,12 @@ func (m *Meta) Unmarshal(dAtA []byte) error { return nil } func (m *Meta) Describe() string { return "" } `, - // Over the index's 1 MB limit, so none of it is read: Item's own + // Over the index's size limit, so none of it is read: Item's own // Unmarshal is missing from the graph. 'model/generated.pb.go': `package model func (i *Item) Unmarshal(dAtA []byte) error { return nil } -${'// generated padding, never read by the indexer\n'.repeat(24_000)}`, +${'// generated padding, never read by the indexer\n'.repeat(Math.ceil(MAX_SOURCE_FILE_SIZE_BYTES / 40))}`, 'caller/caller.go': `package caller import ( diff --git a/__tests__/go-unread-file-methods.test.ts b/__tests__/go-unread-file-methods.test.ts index 6c859b122d..fb7db36e5d 100644 --- a/__tests__/go-unread-file-methods.test.ts +++ b/__tests__/go-unread-file-methods.test.ts @@ -1,9 +1,10 @@ /** * A Go method a type declares in a file the index couldn't read. * - * kubernetes' core/v1 generated.pb.go is 1.7 MB, over the index's 1 MB - * limit, so `Pod`'s own `String`, `Marshal` and `Unmarshal` are not in the - * graph. Resolving `pod.String()` on a `*v1.Pod`, the walk over the types + * kubernetes' core/v1 generated.pb.go was 1.7 MB against an index limit of + * 1 MB, so `Pod`'s own `String`, `Marshal` and `Unmarshal` were not in the + * graph. (The limit is 4 MB now, which takes that file in; what follows holds + * for any file over it.) Resolving `pod.String()` on a `*v1.Pod`, the walk over the types * `Pod` embeds found the `String` its `TypeMeta` has and linked that, a * method the call never runs. Every typed Go receiver took that walk: a * parameter, a local, a field, an assertion, a package-level variable. @@ -18,6 +19,7 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { CodeGraph } from '../src'; +import { MAX_SOURCE_FILE_SIZE_BYTES } from '../src/file-limits'; let root = ''; let cg: CodeGraph; @@ -52,13 +54,13 @@ type Pod struct { Spec string } `, - // Over the index's 1 MB limit, so none of it is read. + // Over the index's size limit, so none of it is read. 'api/generated.pb.go': `package api func (m *Pod) String() string { return "" } func (m *Pod) Unmarshal(dAtA []byte) error { return nil } -${'// generated padding, never read by the indexer\n'.repeat(24_000)}`, +${'// generated padding, never read by the indexer\n'.repeat(Math.ceil(MAX_SOURCE_FILE_SIZE_BYTES / 40))}`, 'caller/caller.go': `package caller import "example.com/app/api" diff --git a/__tests__/kernel-large-file-parity.test.ts b/__tests__/kernel-large-file-parity.test.ts new file mode 100644 index 0000000000..38eb99b5f4 --- /dev/null +++ b/__tests__/kernel-large-file-parity.test.ts @@ -0,0 +1,232 @@ +/** + * The native kernel and the wasm extractor agree on files of some thousand + * declarations, and both read one in the time its size asks for. + * + * Both did work for each declaration that went through its siblings: finding + * where a declaration stands among its parent's children before looking for + * the decorators above it, walking back over every sibling for a Ruby method's + * visibility, reading every child of a C++ parent for an access specifier, + * searching the whole file for a later `export` of each JS constant, and + * counting a line's characters for each column. Each is now read once, or + * from where the last answer left off, in both extractors. + * + * These pin that the two still produce the same nodes, edges and references + * on the shapes those paths decide: decorators and annotations in the eight + * languages that have them, visibility by section in Ruby and C++, exports + * written after the declaration, and columns on a long line that holds + * characters wider in bytes than in UTF-16 units. The parity suites beside + * this one pin the same on hand-written fixtures; these are the sizes where a + * slip in what is remembered from one declaration to the next would show. + */ + +import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest'; +import * as fs from 'fs'; +import * as path from 'path'; +import { extractFromSource } from '../src/extraction'; +import { initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars'; +import { tryKernelExtract, resetKernelForTests } from '../src/extraction/kernel'; +import type { ExtractionResult, Language } from '../src/types'; + +const KERNEL_PATH = path.join( + __dirname, + '..', + 'codegraph-kernel', + 'prebuilds', + `${process.platform}-${process.arch}`, + 'codegraph-kernel.node' +); +const kernelBuilt = fs.existsSync(KERNEL_PATH); + +vi.setConfig({ testTimeout: 240_000, hookTimeout: 60_000 }); + +/** What either extractor may take over one of these files. Each takes well under a second. */ +const ALLOWED_MS = 30_000; + +function canon(result: ExtractionResult): { nodes: string[]; edges: string[]; refs: string[] } { + return { + nodes: result.nodes + .map(({ updatedAt: _u, ...n }) => JSON.stringify(n, Object.keys(n).sort())) + .sort(), + edges: result.edges.map((e) => JSON.stringify(e, Object.keys(e).sort())).sort(), + refs: result.unresolvedReferences + .map((r) => JSON.stringify(r, Object.keys(r).sort())) + .sort(), + }; +} + +/** `unit(i)` for each of `count`, between a head and a tail. */ +const repeat = (count: number, unit: (i: number) => string, head = '', tail = ''): string => + head + Array.from({ length: count }, (_, i) => unit(i)).join('') + tail; + +const ENV_KEYS = ['CODEGRAPH_KERNEL', 'CODEGRAPH_KERNEL_LANGS'] as const; +let savedEnv: Record; + +const LANGUAGES: Language[] = ['python', 'typescript', 'javascript', 'java', 'kotlin', 'swift', 'scala', 'dart', 'ruby', 'cpp']; + +describe.skipIf(!kernelBuilt)('kernel and wasm extraction agree on files of some thousand declarations', () => { + beforeAll(async () => { + await initGrammars(); + await loadGrammarsForLanguages(LANGUAGES); + }); + + beforeEach(() => { + savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]])); + resetKernelForTests(); + }); + + afterEach(() => { + for (const k of ENV_KEYS) { + if (savedEnv[k] === undefined) delete process.env[k]; + else process.env[k] = savedEnv[k]; + } + resetKernelForTests(); + }); + + /** Both extractors' results for `source`, having checked they are the same and neither took long. */ + function assertParity(filePath: string, source: string, language: Language, minNodes: number): ExtractionResult { + process.env.CODEGRAPH_KERNEL_LANGS = 'all'; + delete process.env.CODEGRAPH_KERNEL; + let started = Date.now(); + const viaKernel = tryKernelExtract(filePath, source, language); + expect(Date.now() - started, `${filePath}: kernel time`).toBeLessThan(ALLOWED_MS); + expect(viaKernel, `kernel extraction failed for ${filePath}`).not.toBeNull(); + + process.env.CODEGRAPH_KERNEL = '0'; + started = Date.now(); + const viaWasm = extractFromSource(filePath, source, language); + expect(Date.now() - started, `${filePath}: wasm time`).toBeLessThan(ALLOWED_MS); + delete process.env.CODEGRAPH_KERNEL; + + const k = canon(viaKernel!); + const w = canon(viaWasm); + expect(k.nodes.length, `${filePath}: node count`).toBe(w.nodes.length); + expect(k.nodes, `${filePath}: nodes`).toEqual(w.nodes); + expect(k.edges, `${filePath}: edges`).toEqual(w.edges); + expect(k.refs, `${filePath}: refs`).toEqual(w.refs); + expect(viaWasm.nodes.length).toBeGreaterThanOrEqual(minNodes); + return viaWasm; + } + + /** How many `decorates` references each decorated name got. */ + const decorations = (result: ExtractionResult): Map => { + const counts = new Map(); + for (const ref of result.unresolvedReferences) { + if (ref.referenceKind === 'decorates') counts.set(ref.referenceName, (counts.get(ref.referenceName) ?? 0) + 1); + } + return counts; + }; + + const N = 3000; + + it('Python: a decorator, or two, on the function or the method under them', () => { + const source = repeat(N, (i) => (i % 3 === 0 + ? `@cached\n@traced(level=${i})\ndef thing${i}(name):\n return name\n\n` + : i % 3 === 1 ? `@cached\ndef thing${i}(name):\n return name\n\n` : `def thing${i}(name):\n return name\n\n`), + 'def cached(f):\n return f\n\ndef traced(level):\n return cached\n\n', + `class Big:\n${repeat(N, (i) => ` @staticmethod\n def method${i}(name):\n return name\n\n`)}`); + const result = assertParity('big.py', source, 'python', N * 2); + const counts = decorations(result); + expect(counts.get('cached')).toBe(N / 3 * 2); + // A decorator written as a call is recorded as the call it is. + expect(counts.get('traced')).toBeUndefined(); + expect(result.unresolvedReferences.filter((r) => r.referenceKind === 'calls' && r.referenceName === 'traced')).toHaveLength(N / 3); + expect(counts.get('staticmethod')).toBe(N); + }); + + it('TypeScript: decorators on a class and its methods', () => { + const source = repeat(N, (i) => (i % 2 === 0 + ? ` @cached()\n @traced\n thing${i}(name: string): string {\n return name;\n }\n\n` + : ` thing${i}(name: string): string {\n return name;\n }\n\n`), + 'declare function cached(): any;\ndeclare const traced: any;\ndeclare const component: any;\n\n@component\nexport class Big {\n', '}\n'); + const counts = decorations(assertParity('big.ts', source, 'typescript', N)); + expect(counts.get('cached')).toBe(N / 2); + expect(counts.get('traced')).toBe(N / 2); + expect(counts.get('component')).toBe(1); + }); + + it('Java: annotations on methods', () => { + const source = repeat(N, (i) => (i % 2 === 0 + ? ` @Deprecated\n @Tagged("t${i}")\n String thing${i}(String name) {\n return name;\n }\n\n` + : ` String thing${i}(String name) {\n return name;\n }\n\n`), + 'public class Big {\n', '}\n'); + const counts = decorations(assertParity('Big.java', source, 'java', N)); + expect(counts.get('Deprecated')).toBe(N / 2); + expect(counts.get('Tagged')).toBe(N / 2); + }); + + it('Kotlin, Swift, Scala and Dart: annotations on top-level functions', () => { + const cases: Array<[string, Language, (i: number) => string, string, string]> = [ + ['big.kt', 'kotlin', (i) => `${i % 2 ? '' : '@Tagged\n'}fun thing${i}(name: String): String {\n return name\n}\n\n`, '', ''], + ['big.swift', 'swift', (i) => `${i % 2 ? '' : '@discardableResult\n'}func thing${i}(name: String) -> String {\n return name\n}\n\n`, '', ''], + ['big.scala', 'scala', (i) => `${i % 2 ? '' : ' @deprecated\n'} def thing${i}(name: String): String = {\n name\n }\n\n`, 'object Big {\n', '}\n'], + // Dart lets a comment stand between an annotation and what it annotates. + ['big.dart', 'dart', (i) => `${i % 2 ? '' : `@deprecated\n${i % 4 ? '' : '// kept for callers\n'}`}String thing${i}(String name) {\n return name;\n}\n\n`, '', ''], + ]; + for (const [file, language, unit, head, tail] of cases) { + const counts = decorations(assertParity(file, repeat(N, unit, head, tail), language, N)); + expect([...counts.values()].reduce((a, b) => a + b, 0), file).toBe(N / 2); + } + }); + + it('Ruby: methods under visibility calls, in classes one after another and one inside another', () => { + // A visibility is read from a call with arguments (`private :name`); the + // bare word alone is not one to either extractor, and never was. + const section = (from: number, count: number, indent = ' ') => repeat(count, (i) => `${indent}def thing${from + i}(name)\n${indent} name\n${indent}end\n\n`); + const cls = (name: string, from: number) => + `class ${name}\n${section(from, 400)} private :thing${from}\n\n${section(from + 400, 400)} protected :thing${from}\n\n${section(from + 800, 200)} public :thing${from}\n\n${section(from + 1000, 200)}` + + ` class Inner\n${section(from + 1200, 100, ' ')} private :thing${from + 1200}\n\n${section(from + 1300, 100, ' ')} end\n\n${section(from + 1400, 100)} private\n\n${section(from + 1500, 100)}end\n\n`; + const source = `${repeat(200, (i) => `def top${i}(name)\n name\nend\n\n`)}private :top0\n\n${repeat(200, (i) => `def hidden${i}(name)\n name\nend\n\n`)}${cls('First', 0)}${cls('Second', 2000)}`; + const result = assertParity('big.rb', source, 'ruby', 3000); + const visibility = (name: string) => result.nodes.find((n) => n.name === name)?.visibility; + expect(['top0', 'top199', 'hidden0', 'hidden199'].map(visibility)).toEqual(['public', 'public', 'private', 'private']); + expect(['thing0', 'thing399', 'thing400', 'thing799', 'thing800', 'thing999', 'thing1000', 'thing1199'].map(visibility)) + .toEqual(['public', 'public', 'private', 'private', 'protected', 'protected', 'public', 'public']); + // The inner class has its own calls, and the outer one goes on as it was after it; a bare `private` changes nothing. + expect(['thing1200', 'thing1299', 'thing1300', 'thing1399', 'thing1400', 'thing1499', 'thing1500', 'thing1599'].map(visibility)) + .toEqual(['public', 'public', 'private', 'private', 'public', 'public', 'public', 'public']); + expect(['thing2000', 'thing2400', 'thing2800', 'thing3000'].map(visibility)).toEqual(['public', 'private', 'protected', 'public']); + }); + + it('C++: free functions, and classes with and without access specifiers', () => { + const source = repeat(N, (i) => `int thing${i}(int name) {\n return name + ${i};\n}\n\n`, + 'class Marked {\n int unmarked() { return 1; }\nprivate:\n int hidden() { return 2; }\npublic:\n int open() { return 3; }\n};\n\nclass Plain {\n int bare() { return 4; }\n};\n\nstruct Opened {\npublic:\n int shown() { return 5; }\n};\n\n', + `class Wide {\npublic:\n${repeat(N, (i) => ` int method${i}(int name) {\n return name + ${i};\n }\n\n`)}};\n`); + const result = assertParity('big.cpp', source, 'cpp', N * 2); + const visibility = (name: string) => result.nodes.find((n) => n.name === name)?.visibility; + // The first specifier among a parent's children decides for all of them. + expect(['unmarked', 'hidden', 'open', 'bare', 'shown', 'thing0', `thing${N - 1}`, 'method0', `method${N - 1}`].map(visibility)) + .toEqual(['private', 'private', 'private', undefined, 'public', undefined, undefined, 'public', 'public']); + }); + + it('JavaScript: stores exported where they are declared, by a later statement, or not at all', () => { + const stores = repeat(N, (i) => `${i % 10 === 0 ? 'export ' : ''}const store${i} = create((set) => ({ act${i}: () => set({ n: ${i} }) }));\n`, + "import { create } from 'zustand';\n\n"); + const exportsOf = (lines: string[]) => `${stores}\n${lines.join('\n')}\n`; + const later = ['export default store7;', 'export { store9, store11 as renamed, items$ };', ' export {\n store13,\n $store\n}', 'export default store1 ;']; + for (const [file, source] of [ + ['big.js', exportsOf(later)], + // As a Windows checkout has it. + ['crlf.js', exportsOf(later).replace(/\n/g, '\r\n')], + // Statements that export none of them: a longer name, a name in a string, an `export` that is not at a line's start. + ['none.js', exportsOf(['export default store77x;', 'const text = "export default store3;";', 'if (ok) export_default(store5);', 'export { store150x, xstore151 };'])], + ] as const) { + const result = assertParity(file, source, 'javascript', N); + const actions = result.nodes.filter((n) => /^act\d+$/.test(n.name)).map((n) => +n.name.slice(3)).sort((a, b) => a - b); + const declared = Array.from({ length: N / 10 }, (_, i) => i * 10); + const expected = file === 'none.js' ? declared : [...declared, 1, 7, 9, 11, 13].sort((a, b) => a - b); + expect(actions, file).toEqual(expected); + } + }); + + it('a long line: every column counts UTF-16 units, past characters wider in bytes', () => { + const head = 'var s="é😀日本";function h(x){return x}'; + const source = `${repeat(N, (i) => `function t${i}(n){var v=h("ü${i}");return t${i ? i - 1 : 0}(v)}`, head)}\n`; + const result = assertParity('min.js', source, 'javascript', N); + for (const i of [0, 1, N / 2, N - 1]) { + const fn = result.nodes.find((n) => n.name === `t${i}`)!; + expect(fn.startColumn, `t${i}`).toBe(source.indexOf(`function t${i}(`)); + } + const python = `${repeat(N, (i) => `v${i} = h("ü😀${i}"); `, 'def h(x): return x\ns = "é😀日本"; ')}\n`; + assertParity('long.py', python, 'python', N); + }); +}); diff --git a/__tests__/large-corpus-regressions.test.ts b/__tests__/large-corpus-regressions.test.ts index 109032cb8f..ebc061c85f 100644 --- a/__tests__/large-corpus-regressions.test.ts +++ b/__tests__/large-corpus-regressions.test.ts @@ -4,6 +4,10 @@ import * as os from 'node:os'; import * as path from 'node:path'; import CodeGraph from '../src/index'; import { QueryBuilder } from '../src/db/queries'; +import { MAX_SOURCE_FILE_SIZE_BYTES } from '../src/file-limits'; + +/** A Python file a little over the size limit. */ +const OVERSIZED = 'value = 1\n'.repeat(Math.ceil(MAX_SOURCE_FILE_SIZE_BYTES / 10) + 1); describe('large-corpus regression fixes', () => { it('collects a dense unresolved-reference chunk without spreading it onto the V8 stack (#1558)', () => { @@ -29,7 +33,7 @@ describe('large-corpus regression fixes', () => { it('records an oversized file during a fresh index so sync does not retry it (#1557)', async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-skipped-file-')); try { - fs.writeFileSync(path.join(dir, 'oversized.py'), 'value = 1\n'.repeat(120_000)); + fs.writeFileSync(path.join(dir, 'oversized.py'), OVERSIZED); const cg = await CodeGraph.init(dir, { silent: true }); const indexed = await cg.indexAll(); expect(indexed.filesSkipped).toBe(1); @@ -45,7 +49,7 @@ describe('large-corpus regression fixes', () => { it('records an oversized file through the single-file indexing path (#1557)', async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-single-skipped-file-')); try { - fs.writeFileSync(path.join(dir, 'oversized.py'), 'value = 1\n'.repeat(120_000)); + fs.writeFileSync(path.join(dir, 'oversized.py'), OVERSIZED); const cg = await CodeGraph.init(dir, { silent: true }); const indexed = await cg.indexFiles(['oversized.py']); expect(indexed.filesSkipped).toBe(1); diff --git a/__tests__/large-file-frameworks.test.ts b/__tests__/large-file-frameworks.test.ts new file mode 100644 index 0000000000..1e7730c4db --- /dev/null +++ b/__tests__/large-file-frameworks.test.ts @@ -0,0 +1,307 @@ +/** + * A large file indexes in the time its size asks for in the languages the + * native kernel does not read, and when it is a framework's routes file. + * + * large-file-indexing.test.ts covers the languages the kernel reads. The + * same shape of slowness, work for each symbol or route that goes through + * the whole file, was in what it does not cover: the wasm extractor's own + * language modules, the extractors that read a file without a grammar, and + * the framework passes that turn a routes file into routes and link each to + * its handler. At 1.2 MB an Express file of inline handlers took 58 seconds, + * Liquid markup 41, a CodeIgniter routes file 31, ArkTS 21, a React Native + * Fabric spec 20, a file of event listeners 16, and React Router, Angular and + * Play route tables about 12. + * + * Each case here is one such file at 2 MB or more, where the square was + * minutes. They pin that it is indexed in seconds, and that what the faster + * path decides is what the slow one decided: a decorator on the declaration + * under it, a tag on its own line and column, a route linked to its own + * handler and no other, a nested route's path joined to its parent's, a + * call that a local binding hides left unlinked. + * + * The time allowed is generous, for a loaded machine: every case takes a few + * seconds. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import CodeGraph from '../src/index'; +import type { Node } from '../src/types'; + +vi.setConfig({ testTimeout: 240_000, hookTimeout: 60_000 }); + +/** What a case may take. Each took minutes at this size, where it was indexed at all. */ +const ALLOWED_MS = 60_000; + +const MB = 1024 * 1024; + +/** `unit(i)` repeated until the text is `bytes` long, between a head and a tail. */ +function fill(bytes: number, unit: (i: number) => string, head = '', tail = ''): { text: string; count: number } { + const parts = [head]; + let length = head.length + tail.length; + let count = 0; + for (; length < bytes; count++) { + const part = unit(count); + parts.push(part); + length += part.length; + } + parts.push(tail); + return { text: parts.join(''), count }; +} +/** `unit(i)` for each of `count`. */ +const each = (count: number, unit: (i: number) => string): string => Array.from({ length: count }, (_, i) => unit(i)).join(''); + +describe('a large file indexes in the time its size asks for, beyond the kernel\'s languages', () => { + let dir: string; + let cg: CodeGraph | null = null; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-large-framework-')); + }); + + afterEach(() => { + cg?.close(); + cg = null; + fs.rmSync(dir, { recursive: true, force: true }); + }); + + async function index(files: Record): Promise { + for (const [file, content] of Object.entries(files)) { + const full = path.join(dir, file); + fs.mkdirSync(path.dirname(full), { recursive: true }); + fs.writeFileSync(full, content); + } + cg = await CodeGraph.init(dir); + const started = Date.now(); + await cg.indexAll(); + return Date.now() - started; + } + + const inFile = (file: string, kind: Node['kind']): Node[] => cg!.getNodesInFile(file).filter((n) => n.kind === kind); + const named = (file: string, name: string, kind?: Node['kind']): Node => { + const found = cg!.getNodesInFile(file).filter((n) => n.name === name && (!kind || n.kind === kind)); + expect(found.map((n) => n.kind), `${name} in ${file}`).toHaveLength(1); + return found[0]!; + }; + /** What points at a node, as `kind from name`, in order. */ + const into = (node: Node, ...kinds: string[]): string[] => + cg!.getIncomingEdges(node.id) + .filter((e) => kinds.includes(e.kind)) + .map((e) => `${e.kind} from ${cg!.getNode(e.source)?.name}`) + .sort(); + + it('ArkTS components: each decorator on the struct under it', async () => { + const { text, count } = fill(2 * MB, (i) => `@Component\nstruct View${i} {\n @State count: number = ${i}\n build() {\n Column() {\n Text('x${i}')\n View${i ? i - 1 : 0}()\n }\n }\n}\n\n`); + expect(await index({ 'src/big.ets': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/big.ets', 'struct')).toHaveLength(count); + for (const i of [0, 5, count - 1]) expect(named('src/big.ets', `View${i}`).decorators, `View${i}`).toEqual(['Component']); + expect(into(named('src/big.ets', 'View5'), 'instantiates')).toEqual(['instantiates from build']); + }); + + it('Liquid markup: each tag on its own line and column', async () => { + const { text, count } = fill(2 * MB, (i) => `{% render 'snippet${i % 50}', value: product.title %}\n{{ product.title | append: '${i}' }}\n{% assign v${i} = product.price | times: ${i} %}\n`); + expect(await index({ 'sections/big.liquid': text })).toBeLessThan(ALLOWED_MS); + const renders = inFile('sections/big.liquid', 'component'); + expect(renders).toHaveLength(count); + // The k-th `render` opens line 3k + 1. + for (const k of [0, 7, Math.floor(count / 2), count - 1]) { + const at = renders.filter((n) => n.startLine === 3 * k + 1); + expect(at.map((n) => [n.name, n.startColumn]), `render ${k}`).toEqual([[`snippet${k % 50}`, 0]]); + } + expect(named('sections/big.liquid', `v${count - 1}`, 'variable').startLine).toBe(3 * (count - 1) + 3); + }); + + it('a VB.NET module followed by nothing but comment lines', async () => { + const comments = fill(2.5 * MB, (i) => `' a line of commentary, number ${i}\n`).text; + const text = `Public Module Big\n Public Function Helper(x As Integer) As Integer\n Return x\n End Function\n\n Public Function Use() As Integer\n Return Helper(1)\n End Function\nEnd Module\n${comments}`; + expect(await index({ 'src/Big.vb': text })).toBeLessThan(ALLOWED_MS); + expect(into(named('src/Big.vb', 'Helper'), 'calls')).toEqual(['calls from Use']); + }); + + it('an Objective-C class whose methods send each other messages', async () => { + const { text, count } = fill(2.5 * MB, (i) => `- (NSString *)thing${i}:(NSString *)name {\n NSString *value = [self helper:name];\n return [self thing${i ? i - 1 : 0}:value];\n}\n\n`, + '#import \n\n@interface Big : NSObject\n- (NSString *)helper:(NSString *)x;\n@end\n\n@implementation Big\n- (NSString *)helper:(NSString *)x { return x; }\n\n', '@end\n'); + expect(await index({ 'src/Big.m': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/Big.m', 'method').length).toBeGreaterThanOrEqual(count); + expect(into(named('src/Big.m', 'thing5:'), 'calls')).toEqual(['calls from thing6:']); + }); + + it('a Vue component of many options-API methods: each call from the method it is in', async () => { + const { text, count } = fill(2 * MB, (i) => ` thing${i}(name) {\n const value = this.helper(name);\n return this.thing${i ? i - 1 : 0}(value);\n },\n`, + '\n\n\n'); + expect(await index({ 'src/Big.vue': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/Big.vue', 'method')).toHaveLength(count + 1); + expect(into(named('src/Big.vue', 'thing5'), 'calls')).toEqual(['calls from thing6']); + expect(into(named('src/Big.vue', `thing${count - 2}`), 'calls')).toEqual([`calls from thing${count - 1}`]); + }); + + it('an Express file of inline route handlers', async () => { + const { text, count } = fill(2.5 * MB, (i) => `app.get('/x${i}', (req, res) => {\n res.json(helper(${i}));\n});\n\n`, + "const express = require('express');\nconst app = express();\nfunction helper(x) { return x; }\n\n", 'module.exports = app;\n'); + expect(await index({ 'package.json': '{"name":"big","dependencies":{"express":"^4.0.0"}}\n', 'server.js': text })).toBeLessThan(ALLOWED_MS); + const routes = inFile('server.js', 'route'); + expect(routes).toHaveLength(count); + expect(routes.filter((r) => r.name.endsWith(' /x5') || r.name === '/x5')).toHaveLength(1); + }); + + it('a routes file and its controller, in CodeIgniter, Rails and Play: each route to its own action', async () => { + const n = 30_000; + expect(await index({ + 'index.php': " ` public function x${i}() { return ${i}; }\n`)}}\n`, + 'application/config/routes.php': ` `$route['x${i}'] = 'big/x${i}';\n`)}`, + })).toBeLessThan(ALLOWED_MS); + expect(into(named('application/controllers/Big.php', 'x5'), 'references')).toEqual(['references from ANY /big/x5', 'references from ANY /x5']); + expect(into(named('application/controllers/Big.php', `x${n - 1}`), 'references')).toContain(`references from ANY /x${n - 1}`); + cg!.close(); + cg = null; + fs.rmSync(dir, { recursive: true, force: true }); + fs.mkdirSync(dir); + + expect(await index({ + 'Gemfile': "source 'https://rubygems.org'\ngem 'rails'\n", + 'config/application.rb': "require 'rails/all'\n", + 'app/controllers/big_controller.rb': `class BigController < ApplicationController\n${each(n, (i) => ` def x${i}\n end\n\n`)}end\n`, + 'config/routes.rb': `Rails.application.routes.draw do\n${each(n, (i) => ` get '/x${i}', to: 'big#x${i}'\n`)}end\n`, + })).toBeLessThan(ALLOWED_MS); + expect(into(named('app/controllers/big_controller.rb', 'x5'), 'references')).toEqual(['references from GET /x5']); + expect(into(named('app/controllers/big_controller.rb', `x${n - 1}`), 'references')).toEqual([`references from GET /x${n - 1}`]); + cg!.close(); + cg = null; + fs.rmSync(dir, { recursive: true, force: true }); + fs.mkdirSync(dir); + + expect(await index({ + 'build.sbt': 'lazy val root = (project in file(".")).enablePlugins(PlayScala)\n', + 'app/controllers/Big.scala': `package controllers\n\nimport play.api.mvc._\n\nclass Big extends BaseController {\n${each(n, (i) => ` def x${i} = Action { Ok("${i}") }\n`)}}\n`, + 'conf/routes': each(n, (i) => `GET /x${i} controllers.Big.x${i}\n`), + })).toBeLessThan(ALLOWED_MS); + expect(into(named('app/controllers/Big.scala', 'x5'), 'references')).toEqual(['references from GET /x5']); + expect(into(named('app/controllers/Big.scala', `x${n - 1}`), 'references')).toEqual([`references from GET /x${n - 1}`]); + }); + + it('a Spring controller of request mappings', async () => { + const { text, count } = fill(2.5 * MB, (i) => ` @RequestMapping(value = "/x${i}", method = RequestMethod.POST)\n public ResponseEntity x${i}(@RequestBody String body) {\n return ResponseEntity.ok(service.handle(body));\n }\n\n`, + 'package x;\n\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\n\n@RestController\npublic class BigController {\n private final BigService service = new BigService();\n\n', + '}\n\nclass BigService {\n String handle(String body) { return body; }\n}\n'); + expect(await index({ + 'pom.xml': 'org.springframework.bootspring-boot-starter-web\n', + 'src/main/java/x/BigController.java': text, + })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/main/java/x/BigController.java', 'route')).toHaveLength(count); + expect(into(named('src/main/java/x/BigController.java', 'x5'), 'references')).toEqual(['references from POST /x5']); + expect(cg!.getCallers(named('src/main/java/x/BigController.java', 'handle').id)).toHaveLength(count); + }); + + it('a React Router table: each route to its page, a nested route under its parent\'s path', async () => { + const n = 18_000; + const text = `import React from 'react';\nimport { Routes, Route, useNavigate } from 'react-router-dom';\n\n${each(n, (i) => `function Page${i}() { return
${i}
; }\n`)}\n` + + `export function Nav() {\n const navigate = useNavigate();\n${each(500, (i) => ` const go${i} = () => navigate('/x${i}');\n`)} return null;\n}\n\n` + + `export function App() {\n return (\n \n${each(n, (i) => ` } />\n`)}` + + ` \n } />\n \n \n );\n}\n`; + expect(Buffer.byteLength(text)).toBeGreaterThan(1.5 * MB); + expect(await index({ 'package.json': '{"name":"big","dependencies":{"react":"^18.0.0","react-router-dom":"^6.0.0"}}\n', 'src/routes.tsx': text })).toBeLessThan(ALLOWED_MS); + const routes = inFile('src/routes.tsx', 'route').map((r) => r.name); + // The parent is a route of its own; its child's path is joined to it. + expect(routes).toHaveLength(n + 2); + expect(routes).toContain('/shop'); + expect(routes).toContain('/shop/cart'); + expect(into(named('src/routes.tsx', 'Page5'), 'references')).toEqual(['references from /x5']); + expect(into(named('src/routes.tsx', '/x5'), 'navigates')).toEqual(['navigates from go5']); + expect(into(named('src/routes.tsx', `Page${n - 1}`), 'references')).toEqual([`references from /x${n - 1}`]); + }); + + it('an Angular routes file of components', async () => { + const n = 16_000; + const text = `import { Component } from '@angular/core';\nimport { Routes } from '@angular/router';\n\n${each(n, (i) => `@Component({ selector: 'p-${i}', template: '' })\nexport class Page${i}Component {}\n`)}\n` + + `export const routes: Routes = [\n${each(n, (i) => ` { path: 'x${i}', component: Page${i}Component },\n`)}];\n`; + expect(Buffer.byteLength(text)).toBeGreaterThan(1.5 * MB); + expect(await index({ 'package.json': '{"name":"big","dependencies":{"@angular/core":"^17.0.0","@angular/router":"^17.0.0"}}\n', 'src/app/app.routes.ts': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/app/app.routes.ts', 'route')).toHaveLength(n); + expect(into(named('src/app/app.routes.ts', 'Page5Component'), 'references')).toEqual(['references from /x5']); + expect(into(named('src/app/app.routes.ts', `Page${n - 1}Component`), 'references')).toEqual([`references from /x${n - 1}`]); + }); + + it('a file of event listeners: each emit to the listener of its event', async () => { + const { text, count } = fill(2 * MB, (i) => `function on${i}(x) { return x; }\nemitter.on('e${i}', on${i});\nfunction fire${i}() { emitter.emit('e${i}', ${i}); }\n`, + "const { EventEmitter } = require('events');\nconst emitter = new EventEmitter();\n\n"); + expect(await index({ 'package.json': '{"name":"big"}\n', 'src/events.js': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/events.js', 'function')).toHaveLength(count * 2); + expect(into(named('src/events.js', 'on5'), 'calls')).toEqual(['calls from fire5']); + expect(into(named('src/events.js', `on${count - 1}`), 'calls')).toEqual([`calls from fire${count - 1}`]); + }); + + it('a React Native Fabric spec of many props: each where its name first stands', async () => { + const { text, count } = fill(2 * MB, (i) => ` prop${i}?: string;\n onEvent${i}?: CT.DirectEventHandler>;\n`, + "import { codegenNativeComponent } from 'react-native';\nimport type { ViewProps, CodegenTypes as CT } from 'react-native';\n\nexport interface NativeProps extends ViewProps {\n" + + // Named in a type before it is declared: a prop is placed where its name first occurs. + ' first?: Wrapper;\n', + " late?: string;\n}\n\nexport default codegenNativeComponent('Big');\n"); + expect(await index({ + 'package.json': '{"name":"big","dependencies":{"react-native":"^0.74.0"}}\n', + 'ios/BigView.mm': '#import \n\n@interface BigView : RCTViewComponentView\n@end\n\n@implementation BigView\n@end\n', + 'src/BigNativeComponent.ts': text, + })).toBeLessThan(ALLOWED_MS); + const props = cg!.getNodesInFile('src/BigNativeComponent.ts').filter((n) => n.id.startsWith('fabric-prop:')); + expect(props).toHaveLength(count * 2 + 2); + const lineOf = (name: string): number[] => props.filter((n) => n.name === name).map((n) => n.startLine); + // Four lines above the interface's first prop; then two lines to each pair. + for (const k of [0, 1, 10, Math.floor(count / 2), count - 1]) { + expect(lineOf(`prop${k}`), `prop${k}`).toEqual([6 + 2 * k]); + expect(lineOf(`onEvent${k}`), `onEvent${k}`).toEqual([7 + 2 * k]); + } + expect(lineOf('first')).toEqual([5]); + expect(lineOf('late')).toEqual([5]); + expect(inFile('src/BigNativeComponent.ts', 'component').map((n) => n.name)).toEqual(['Big']); + }); + + it('an Objective-C file of messages to a Swift class: each to the `@objc` method it names, and to no other', async () => { + const n = 14_000; + // Windows line endings, which the lines above a declaration are read through. + const swift = `import Foundation\n\n@objc class Big: NSObject {\n${each(n, (i) => ` @objc func thing${i}(name: String) -> String {\n return name\n }\n\n`)}` + + ' func hidden(name: String) -> String {\n return name\n }\n\n @objc\n func above(name: String) -> String {\n return name\n }\n}\n'; + const objc = `#import "Big-Swift.h"\n\n@interface Use : NSObject\n@end\n\n@implementation Use\n- (void)use:(Big *)big {\n${each(n, (i) => ` [big thing${i}WithName:@"x"];\n`)}` + + ' [big hiddenWithName:@"x"];\n [big aboveWithName:@"x"];\n}\n@end\n'; + expect(await index({ 'Sources/Big.swift': swift.replace(/\n/g, '\r\n'), 'Sources/Use.m': objc })).toBeLessThan(ALLOWED_MS); + expect(inFile('Sources/Big.swift', 'method')).toHaveLength(n + 2); + for (const i of [0, 5, n - 1]) expect(into(named('Sources/Big.swift', `thing${i}`), 'calls'), `thing${i}`).toEqual(['calls from use:']); + // `@objc` on the line above counts; a method with none is not Objective-C's to call. + expect(into(named('Sources/Big.swift', 'above'), 'calls')).toEqual(['calls from use:']); + expect(into(named('Sources/Big.swift', 'hidden'), 'calls')).toEqual([]); + }); + + it('a file of calls on a React Native TurboModule: each to the native method of its name', async () => { + const n = 14_000; + expect(await index({ + 'package.json': '{"name":"big","dependencies":{"react-native":"^0.74.0"}}\n', + 'src/NativeBig.ts': `import type { TurboModule } from 'react-native';\nimport { TurboModuleRegistry } from 'react-native';\n\nexport interface Spec extends TurboModule {\n${each(n, (i) => ` thing${i}(name: string): string;\n`)}}\n\nexport default TurboModuleRegistry.getEnforcing('Big');\n`, + 'ios/Big.mm': `#import "Big.h"\n\n@implementation Big\nRCT_EXPORT_MODULE()\n\n${each(n, (i) => `- (NSString *)thing${i}:(NSString *)name {\n return name;\n}\n\n`)}@end\n`, + 'src/use.ts': `import Big from './NativeBig';\n\nexport function use() {\n${each(n, (i) => ` Big.thing${i}('x');\n`)}}\n`, + })).toBeLessThan(ALLOWED_MS); + for (const i of [0, 5, n - 1]) expect(into(named('ios/Big.mm', `thing${i}:`), 'calls'), `thing${i}:`).toEqual(['calls from use']); + expect(cg!.getCallees(named('src/use.ts', 'use').id).length).toBeGreaterThanOrEqual(n); + }); + + it('a Tauri front end of many invokes: each to its command, but not one a local binding hides', async () => { + const n = 25_000; + const core = `${each(n, (i) => `#[tauri::command]\nfn cmd${i}(x: i32) -> i32 {\n x\n}\n\n`)}fn main() {\n tauri::Builder::default().invoke_handler(tauri::generate_handler![${Array.from({ length: n }, (_, i) => `cmd${i}`).join(', ')}]).run();\n}\n`; + const front = `import { invoke } from '@tauri-apps/api/core';\n\nexport async function use() {\n${each(n, (i) => ` await invoke('cmd${i}', { x: 1 });\n`)}}\n\n` + + // Its own \`invoke\`, taken from what it is handed, some thousand lines into a function of other calls. + `export async function local(api: { invoke: (name: string) => Promise }) {\n${each(3000, (i) => ` await api.invoke('other${i}');\n`)} const { invoke } = api;\n await invoke('cmd7');\n}\n\n` + + 'export async function before(api: { invoke: (name: string) => Promise }) {\n await invoke(\'cmd8\');\n const { invoke: mine } = api;\n await mine(\'cmd9\');\n}\n'; + expect(await index({ + 'package.json': '{"name":"big","dependencies":{"@tauri-apps/api":"^2.0.0"}}\n', + 'src-tauri/Cargo.toml': '[package]\nname = "big"\nversion = "0.1.0"\n\n[dependencies]\ntauri = "2"\n', + 'src-tauri/src/main.rs': core, + 'src/use.ts': front, + })).toBeLessThan(ALLOWED_MS); + expect(into(named('src-tauri/src/main.rs', 'cmd5'), 'calls')).toEqual(['calls from use']); + expect(into(named('src-tauri/src/main.rs', `cmd${n - 1}`), 'calls')).toEqual(['calls from use']); + // Hidden by the function's own binding where it is called; not where it is called above the binding. + expect(into(named('src-tauri/src/main.rs', 'cmd7'), 'calls')).toEqual(['calls from use']); + expect(into(named('src-tauri/src/main.rs', 'cmd8'), 'calls')).toEqual(['calls from before', 'calls from use']); + }); +}); diff --git a/__tests__/large-file-indexing.test.ts b/__tests__/large-file-indexing.test.ts new file mode 100644 index 0000000000..f5147dc9f2 --- /dev/null +++ b/__tests__/large-file-indexing.test.ts @@ -0,0 +1,304 @@ +/** + * A large source file indexes in about the time its size asks for. + * + * It did not. Work was done for each symbol, or for each reference, that went + * through the whole file, or through everything before it, so the time grew + * with the square of the file: a Python file of plain functions took 3 seconds + * at a third of a megabyte and 27 at nine tenths, a Ruby one twice that, a + * table of rows that each call a helper 37 seconds at a third of a megabyte, + * and one string of hex 30 KB long a second, which is eighteen minutes for a + * megabyte of it. Past about a megabyte a file was given the 180 seconds a + * file is allowed and then given up on, with no symbols. + * + * Each case here is a shape real large files take, at a size where the square + * was minutes. They pin two things: that the file is indexed in seconds, and + * that what the faster paths decide is what the slow ones decided — a + * decorator belongs to the declaration under it, a Ruby method is as visible + * as the last `private` above it says, a call is the local's once the function + * has declared the name and the module's before, a column counts UTF-16 units. + * + * The time allowed is generous, for a loaded machine: every case takes a + * second or two, and took from one minute to never. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import CodeGraph from '../src/index'; +import { LONGEST_NAME_RUN, MAX_SOURCE_FILE_SIZE_BYTES, withoutLongRuns } from '../src/file-limits'; +import type { Node } from '../src/types'; + +vi.setConfig({ testTimeout: 240_000, hookTimeout: 60_000 }); + +/** What a case may take. Each took from a minute to never. */ +const ALLOWED_MS = 60_000; + +const MB = 1024 * 1024; + +/** `unit(i)` repeated until the text is `bytes` long, between a head and a tail. */ +function fill(bytes: number, unit: (i: number) => string, head = '', tail = ''): { text: string; count: number } { + const parts = [head]; + let length = head.length + tail.length; + let count = 0; + for (; length < bytes; count++) { + const part = unit(count); + parts.push(part); + length += part.length; + } + parts.push(tail); + return { text: parts.join(''), count }; +} + +describe('a large file indexes in the time its size asks for', () => { + let dir: string; + let cg: CodeGraph | null = null; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-large-file-')); + }); + + afterEach(() => { + cg?.close(); + cg = null; + fs.rmSync(dir, { recursive: true, force: true }); + }); + + /** Writes the files, indexes them, and returns how long indexing took. */ + async function index(files: Record): Promise { + for (const [file, content] of Object.entries(files)) { + const full = path.join(dir, file); + fs.mkdirSync(path.dirname(full), { recursive: true }); + fs.writeFileSync(full, content); + } + cg = await CodeGraph.init(dir); + const started = Date.now(); + await cg.indexAll(); + return Date.now() - started; + } + + const inFile = (file: string, kind?: Node['kind']): Node[] => + cg!.getNodesInFile(file).filter((n) => n.kind !== 'file' && (!kind || n.kind === kind)); + const named = (file: string, name: string): Node => { + const found = cg!.getNodesInFile(file).filter((n) => n.name === name); + expect(found.map((n) => n.kind), `${name} in ${file}`).toHaveLength(1); + return found[0]!; + }; + const callersOf = (node: Node): string[] => cg!.getCallers(node.id).map((c) => c.node.name).sort(); + + it('is no longer held to one megabyte', () => { + expect(MAX_SOURCE_FILE_SIZE_BYTES).toBeGreaterThanOrEqual(4 * MB); + }); + + it('a Python file of decorated functions: each decorator on the function under it', async () => { + const { text, count } = fill(1.2 * MB, (i) => `@cached\ndef thing${i}(name):\n return name + "${i}"\n\n`, 'def cached(f):\n return f\n\n'); + expect(await index({ 'src/big.py': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/big.py', 'function')).toHaveLength(count + 1); + const decorated = cg!.getIncomingEdges(named('src/big.py', 'cached').id).filter((e) => e.kind === 'decorates'); + expect(decorated).toHaveLength(count); + // The one under the last decorator, and no other. + const last = named('src/big.py', `thing${count - 1}`); + expect(cg!.getOutgoingEdges(last.id).filter((e) => e.kind === 'decorates')).toHaveLength(1); + }); + + it('a Python table of rows, one statement: a lambda or a comprehension binds its own name on the row it is on', async () => { + const rows = fill(0.6 * MB, (i) => ` ("name${i}", ${i}, helper(${i})),\n`).text; + const text = [ + 'from pkg import tool as other', + '', + 'def helper(x):', + ' return x', + '', + 'ROWS = [', + rows.trimEnd(), + // The lambda's own parameter, to the comma that ends its body; the module after it. + ' (lambda other: other.in_lambda(), other.after_lambda()),', + // The comprehension's own target, inside its brackets; the module outside them. + ' [other.in_loop() for other in range(3)],', + ' other.plain(),', + ']', + '', + ].join('\n'); + const tool = ['in_lambda', 'after_lambda', 'in_loop', 'plain'].map((n) => `def ${n}():\n return 1\n`).join('\n'); + expect(await index({ 'src/big.py': text, 'pkg/__init__.py': '', 'pkg/tool.py': tool })).toBeLessThan(ALLOWED_MS); + expect(cg!.getCallers(named('src/big.py', 'helper').id).length).toBeGreaterThan(0); + expect(cg!.getCallers(named('pkg/tool.py', 'plain').id)).toHaveLength(1); + expect(cg!.getCallers(named('pkg/tool.py', 'after_lambda').id)).toHaveLength(1); + expect(cg!.getCallers(named('pkg/tool.py', 'in_lambda').id)).toHaveLength(0); + expect(cg!.getCallers(named('pkg/tool.py', 'in_loop').id)).toHaveLength(0); + }); + + it('a Ruby class of methods: each as visible as the last visibility call above it says', async () => { + const methods = (from: number, bytes: number) => fill(bytes, (i) => ` def thing${from + i}(name)\n name.to_s + "${i}"\n end\n\n`); + const open = methods(0, 0.4 * MB); + const hidden = methods(open.count, 0.4 * MB); + const guarded = methods(open.count + hidden.count, 0.4 * MB); + // Read from a call with arguments; the bare word alone is not one, and never was. + const text = `class Big\n${open.text} private :thing0\n\n${hidden.text} protected :thing0\n\n${guarded.text} public :thing0\n\n def last(name)\n name\n end\nend\n`; + expect(await index({ 'src/big.rb': text })).toBeLessThan(ALLOWED_MS); + const total = open.count + hidden.count + guarded.count; + expect(inFile('src/big.rb', 'method')).toHaveLength(total + 1); + const visibility = (i: number) => named('src/big.rb', `thing${i}`).visibility; + expect([visibility(0), visibility(open.count - 1)]).toEqual(['public', 'public']); + expect([visibility(open.count), visibility(open.count + hidden.count - 1)]).toEqual(['private', 'private']); + expect([visibility(open.count + hidden.count), visibility(total - 1)]).toEqual(['protected', 'protected']); + expect(named('src/big.rb', 'last').visibility).toBe('public'); + }); + + it('a C++ file of free functions and a class with sections', async () => { + const { text, count } = fill(1.2 * MB, (i) => `int thing${i}(int name) {\n return name + ${i};\n}\n\n`, + 'class Box {\n int unmarked() { return 1; }\nprivate:\n int hidden() { return 2; }\npublic:\n int open() { return 3; }\n};\n\n'); + expect(await index({ 'src/big.cpp': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/big.cpp', 'function')).toHaveLength(count); + // The class's first specifier decides for all of its members, as it did. + expect(['unmarked', 'hidden', 'open'].map((n) => named('src/big.cpp', n).visibility)).toEqual(['private', 'private', 'private']); + }); + + it('a TypeScript function of many calls: a name is the local\'s once the function has declared it, the module\'s before', async () => { + const calls = (bytes: number) => fill(bytes, (i) => ` helper(${i}, "name${i}");\n`).text; + const text = [ + 'function helper(x: number, y: string) { return x; }', + 'function shadowed(x: number) { return x; }', + // Calls it before declaring the name: the module's function. + `export function before() {\n shadowed(1);\n${calls(0.3 * MB)} const shadowed = (x: number) => x;\n return shadowed;\n}`, + // Declares the name, then calls it a few thousand lines down: its own. + `export function after() {\n const shadowed = (x: number) => x;\n${calls(0.3 * MB)} shadowed(2);\n}`, + // Takes the name as a parameter. + `export function given(shadowed: (x: number) => number) {\n${calls(0.3 * MB)} shadowed(3);\n}`, + '', + ].join('\n'); + expect(await index({ 'src/big.ts': text })).toBeLessThan(ALLOWED_MS); + expect(callersOf(named('src/big.ts', 'helper'))).toEqual(['after', 'before', 'given']); + const module = cg!.getNodesInFile('src/big.ts').find((n) => n.name === 'shadowed' && n.startLine === 2)!; + expect(callersOf(module)).toEqual(['before']); + }); + + it('a script minified to one line: every function, each at its UTF-16 column', async () => { + // What stands before the functions is wider in bytes than in UTF-16 units. + const head = 'var s="é😀日本";function h(x){return x}'; + const { text, count } = fill(1.2 * MB, (i) => `function t${i}(n){var v=h(n);return t${i ? i - 1 : 0}(v)}`, head, '\n'); + expect(await index({ 'src/big.js': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/big.js', 'function')).toHaveLength(count + 1); + for (const i of [0, 1, Math.floor(count / 2), count - 1]) { + const fn = named('src/big.js', `t${i}`); + expect(fn.startLine).toBe(1); + expect(fn.startColumn, `t${i}`).toBe(text.indexOf(`function t${i}(`)); + } + expect(callersOf(named('src/big.js', 'h')).length).toBe(count); + }); + + it('a file that holds one long string of hex', async () => { + const blob = '0f3a'.repeat((1.5 * MB) / 4); + const text = `function helper(x: string) { return x.length; }\nexport const BLOB = "${blob}";\nexport function use() { return helper(BLOB); }\n`; + expect(await index({ 'src/big.ts': text })).toBeLessThan(ALLOWED_MS); + expect(callersOf(named('src/big.ts', 'helper'))).toEqual(['use']); + expect(named('src/big.ts', 'BLOB').kind).toBe('constant'); + }); + + it('a Rust file of `use crate::…` lines, each an import named `crate`', async () => { + const { text, count } = fill(0.9 * MB, (i) => `use crate::mod${i}::Name${i};\n`, '', '\nfn helper() -> i32 { 1 }\n\nfn run() -> i32 { helper() }\n'); + expect(await index({ 'src/big.rs': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/big.rs', 'import')).toHaveLength(count); + expect(callersOf(named('src/big.rs', 'helper'))).toEqual(['run']); + }); + + it('a C# class whose methods call each other through the object', async () => { + const { text, count } = fill(1.2 * MB, (i) => ` string Thing${i}(string name) {\n var value = this.Helper(name);\n return this.Thing${i ? i - 1 : 0}(value);\n }\n\n`, + 'public class Big {\n string Helper(string x) { return x; }\n\n', '}\n'); + expect(await index({ 'src/Big.cs': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/Big.cs', 'method')).toHaveLength(count + 1); + expect(callersOf(named('src/Big.cs', 'Thing5'))).toEqual(['Thing6']); + expect(cg!.getCallers(named('src/Big.cs', 'Helper').id)).toHaveLength(count); + }); + + it('a Kotlin test class of many small tests', async () => { + const { text, count } = fill(1.2 * MB, (i) => ` @Test\n fun thing${i}() {\n val value = helper(${i})\n assertEquals(${i}, value)\n }\n\n`, + 'import kotlin.test.Test\nimport kotlin.test.assertEquals\n\nfun helper(x: Int): Int { return x }\n\nclass BigTest {\n', '}\n'); + expect(await index({ 'src/BigTest.kt': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/BigTest.kt', 'method')).toHaveLength(count); + expect(cg!.getCallers(named('src/BigTest.kt', 'helper').id)).toHaveLength(count); + }); + + it('a Java file of some hundred thousand imports, which overflowed the stack', async () => { + const { text, count } = fill(3.9 * MB, (i) => `import pkg.mod${i}.Name${i};\n`, '', '\npublic class Big {\n static int helper() { return 1; }\n int run() { return helper(); }\n}\n'); + expect(count).toBeGreaterThan(125_000); + expect(await index({ 'src/Big.java': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/Big.java', 'import')).toHaveLength(count); + expect(callersOf(named('src/Big.java', 'helper'))).toEqual(['run']); + }); + + it('a Ruby class near the size limit, its methods calling each other', async () => { + const { text, count } = fill(3.5 * MB, (i) => ` def thing${i}(name)\n value = self.helper(name)\n self.thing${i ? i - 1 : 0}(value)\n end\n\n`, + 'class Big\n def helper(x)\n x\n end\n\n', 'end\n'); + expect(await index({ 'src/big.rb': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/big.rb', 'method')).toHaveLength(count + 1); + expect(callersOf(named('src/big.rb', 'thing5'))).toEqual(['thing6']); + }); + + it('a Java class near the size limit, its methods calling each other', async () => { + const { text, count } = fill(3.5 * MB, (i) => ` String thing${i}(String name) {\n String value = helper(name);\n return thing${i ? i - 1 : 0}(value);\n }\n\n`, + 'public class Big {\n static String helper(String x) { return x; }\n\n', '}\n'); + expect(await index({ 'src/Big.java': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/Big.java', 'method')).toHaveLength(count + 1); + expect(callersOf(named('src/Big.java', 'thing5'))).toEqual(['thing6']); + expect(cg!.getCallers(named('src/Big.java', 'helper').id)).toHaveLength(count); + }); + + it('a Go constant block of some hundred thousand names', async () => { + const { text, count } = fill(3 * MB, (i) => `\tMember${i} = ${i}\n`, 'package big\n\nconst (\n', ')\n'); + expect(await index({ 'src/big.go': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/big.go', 'constant')).toHaveLength(count); + }); + + it('a file that is mostly comment lines', async () => { + const comments = fill(3.5 * MB, (i) => `# a line of commentary, number ${i}\n`).text; + const text = `class Big\n def run(name)\n helper(name)\n end\n\n def helper(name)\n name\n end\nend\n${comments}`; + expect(await index({ 'src/big.rb': text })).toBeLessThan(ALLOWED_MS / 2); + expect(callersOf(named('src/big.rb', 'helper'))).toEqual(['run']); + }); + + it('a JavaScript file of stores, two of them exported by a later statement', async () => { + const { text, count } = fill(0.9 * MB, (i) => `const store${i} = create((set) => ({ act${i}: () => set({ n: ${i} }) }));\n`, + "import { create } from 'zustand';\n\n", '\nexport default store7;\nexport { store9, store11 as renamed };\n'); + expect(await index({ 'src/big.js': text })).toBeLessThan(ALLOWED_MS); + expect(inFile('src/big.js').filter((n) => /^store\d+$/.test(n.name))).toHaveLength(count); + // Only a store the file exports has its actions as functions of their own. + const actions = inFile('src/big.js').filter((n) => /^act\d+$/.test(n.name)).map((n) => n.name).sort(); + expect(actions).toEqual(['act11', 'act7', 'act9']); + }); +}); + +describe('the runs of name characters a pattern is not given', () => { + const run = (length: number) => 'a1.b2'.repeat(Math.ceil(length / 5)).slice(0, length); + + it('leaves a text with no run longer than a name as it is, the same string', () => { + const text = `const key = "${run(LONGEST_NAME_RUN)}";\nfunction use() { return key; }\n`; + expect(withoutLongRuns(text)).toBe(text); + }); + + it('blanks a longer run at its length, and nothing around it', () => { + const long = run(LONGEST_NAME_RUN + 1); + const text = `const a = "${long}"; const b = "${run(40)}";\nconst c = "${long}";`; + const read = withoutLongRuns(text); + expect(read).toHaveLength(text.length); + expect(read).toBe(text.split(long).join('\u0001'.repeat(long.length))); + expect(read).toContain(`const b = "${run(40)}";\nconst c = "`); + }); + + it('takes a run to end at a blank, a quote, a bracket, or a character past ASCII', () => { + const half = run(LONGEST_NAME_RUN / 2 + 1); + for (const between of [' ', '"', '(', ',', '\n', 'é']) { + const text = `${half}${between}${half}`; + expect(withoutLongRuns(text), JSON.stringify(between)).toBe(text); + } + // What joins names into one run does not end it. + for (const between of ['.', ':', '/', '+', '=', '-', '_', '$']) { + expect(withoutLongRuns(`${half}${between}${half}`), between).toBe('\u0001'.repeat(half.length * 2 + 1)); + } + }); + + it('blanks a run that reaches the end of the text', () => { + const long = run(LONGEST_NAME_RUN * 3); + expect(withoutLongRuns(`x = ${long}`)).toBe(`x = ${'\u0001'.repeat(long.length)}`); + }); +}); diff --git a/__tests__/large-file-lookups.test.ts b/__tests__/large-file-lookups.test.ts new file mode 100644 index 0000000000..4371830846 --- /dev/null +++ b/__tests__/large-file-lookups.test.ts @@ -0,0 +1,382 @@ +/** + * The lookups that replaced a pass over a whole file for each match or each + * reference answer exactly as the pass did. + * + * Three of them are small enough to pin against what they replaced, input by + * input: the line of an offset in a text, which every route and handler scan + * wrote as `text.slice(0, i).split('\n').length`; the imports of a file that + * a reference's name reads, which every step of import resolution found by + * going through all of them; and the nodes of a file that hold a line, which + * every question about what is around a reference found by going through all + * of the file's nodes. Each is checked here against that original expression + * over generated inputs, on both sides of the size at which the lookup + * starts to keep an index. + * + * The same goes for the nodes of a file by name, which a routes file asked + * its controller for once per route, for a node's children stepped through + * with a cursor where they were read by index, and for where each of many + * names first occurs in a text, which was an `indexOf` from the text's start + * for each name. + * + * And a list as long as a large file has imports or symbols is added to + * another without being spread into a call's arguments, which overflowed the + * stack. + */ + +import { describe, it, expect } from 'vitest'; +import { firstIndexOfEach, lineAt } from '../src/resolution/synth-utils'; +import { importsBoundTo, importsFrom, importsReadBy, pythonMemberImports } from '../src/resolution/import-lookup'; +import { nodesAroundLine, nodesAroundLineIn, nodesNamed, nodesNamedIn, nodesNamedLower, nodesUnder } from '../src/resolution/nodes-around'; +import { childrenOf, namedChildrenOf } from '../src/extraction/tree-sitter-helpers'; +import { getParser, initGrammars, loadGrammarsForLanguages } from '../src/extraction/grammars'; +import { maxOf, minOf, pushAll } from '../src/utils'; +import type { ImportMapping, ResolutionContext } from '../src/resolution/types'; +import type { Node } from '../src/types'; + +/** A small repeatable generator, so a failure names inputs that can be run again. */ +function random(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (Math.imul(state, 1664525) + 1013904223) >>> 0; + return state / 0x100000000; + }; +} + +describe('the line of an offset', () => { + const written = (text: string, idx: number): number => text.slice(0, idx).split('\n').length; + + it('is what counting the lines before it gives, in a short text and a long one', () => { + const next = random(7); + for (const lines of [0, 1, 3, 40, 400, 4000]) { + const text = Array.from({ length: lines }, (_, i) => 'x'.repeat(Math.floor(next() * 12)) + (i % 7 === 0 ? '\r' : '')).join('\n'); + const offsets = [0, 1, text.length - 1, text.length, text.length + 5, ...Array.from({ length: 60 }, () => Math.floor(next() * (text.length + 1)))]; + for (const idx of offsets) expect(lineAt(text, idx), `${lines} lines, offset ${idx}`).toBe(written(text, idx)); + } + }); + + it('is so at a newline, just before one and just after', () => { + const text = `${'a'.repeat(3000)}\n${'b'.repeat(10)}\n\n${'c'.repeat(3000)}\n`; + for (let idx = 2995; idx < 3020; idx++) expect(lineAt(text, idx), `offset ${idx}`).toBe(written(text, idx)); + for (let idx = text.length - 4; idx <= text.length + 1; idx++) expect(lineAt(text, idx), `offset ${idx}`).toBe(written(text, idx)); + }); + + it('reads an offset below zero, or none, as the expression it replaced did', () => { + const text = Array.from({ length: 500 }, (_, i) => `line ${i}`).join('\n'); + for (const idx of [-1, -40, -text.length - 3, NaN, undefined as unknown as number]) { + expect(lineAt(text, idx), `offset ${idx}`).toBe(written(text, idx)); + } + }); + + it('keeps apart the texts it is asked about in turn', () => { + const texts = Array.from({ length: 7 }, (_, t) => Array.from({ length: 300 + t * 50 }, (_, i) => `text ${t} line ${i}`).join('\n')); + const next = random(11); + for (let round = 0; round < 400; round++) { + const text = texts[Math.floor(next() * texts.length)]!; + const idx = Math.floor(next() * text.length); + expect(lineAt(text, idx)).toBe(written(text, idx)); + } + }); +}); + +describe('the imports of a file a name reads', () => { + /** A file's imports: some sharing a local name, some a source, some bound to a dotted or an empty name. */ + function imports(count: number, seed: number): ImportMapping[] { + const next = random(seed); + const names = ['a', 'b', 'a.b', 'pkg', 'pkg.mod', 'mod', '', 'x1', 'x10', 'React', '$']; + const sources = ['pkg', 'pkg.mod', './a', './b', 'react', 'pkg.mod.deep', 'a']; + return Array.from({ length: count }, (_, i) => { + const local = next() < 0.5 ? names[Math.floor(next() * names.length)]! : `name${i}`; + const source = next() < 0.5 ? sources[Math.floor(next() * sources.length)]! : `./mod${i}`; + return { localName: local, exportedName: next() < 0.3 ? 'default' : local, source, isDefault: next() < 0.2, isNamespace: next() < 0.3 } as ImportMapping; + }); + } + const asked = ['a', 'b', 'a.b', 'a.b.c', 'pkg.mod.func', 'pkg.mod.deep.x', 'mod', '.hidden', '', 'x1', 'x10.y', 'name3', 'name3.field', 'name30', 'React.useState', '$.get', 'nothing', 'pkg']; + + // Five imports are read through; forty and four hundred are indexed. + for (const count of [0, 5, 15, 16, 40, 400]) { + it(`answers as a pass over all of them does, in their order (${count} imports)`, () => { + const all = imports(count, count + 1); + for (const name of asked) { + expect(importsReadBy(all, name), `read by ${JSON.stringify(name)}`) + .toEqual(all.filter((imp) => imp.localName === name || name.startsWith(imp.localName + '.'))); + expect(importsBoundTo(all, name), `bound to ${JSON.stringify(name)}`).toEqual(all.filter((imp) => imp.localName === name)); + expect(importsFrom(all, name), `from ${JSON.stringify(name)}`).toEqual(all.filter((imp) => imp.source === name)); + } + for (const source of ['pkg', 'pkg.mod', './a', 'react', './mod3', 'none']) { + expect(importsFrom(all, source), `from ${source}`).toEqual(all.filter((imp) => imp.source === source)); + } + }); + + it(`gives a Python member reference every import its resolver acts on (${count} imports)`, () => { + const all = imports(count, count + 2); + for (const name of asked) { + const receiver = name.includes('.') ? name.slice(0, name.lastIndexOf('.')) : name; + // What resolvePythonModuleMember does not pass over. + const acted = all.filter((imp) => { + const spelledOut = imp.isNamespace && imp.localName === imp.source.split('.').pop() + && imp.source.includes('.') && name.startsWith(`${imp.source}.`); + return imp.localName === receiver || spelledOut; + }); + const given = pythonMemberImports(all, receiver, name); + // In the file's order, and none the resolver acts on left out. + expect(given.map((imp) => all.indexOf(imp))).toEqual(given.map((imp) => all.indexOf(imp)).slice().sort((x, y) => x - y)); + for (const imp of acted) expect(given, `${JSON.stringify(name)} on ${JSON.stringify(receiver)}`).toContain(imp); + } + }); + } + + it('reads the array it is handed, not one it was handed before', () => { + const first = imports(40, 1); + const second = first.map((imp) => ({ ...imp, localName: `${imp.localName}2` })); + expect(importsBoundTo(first, 'a')).toEqual(first.filter((imp) => imp.localName === 'a')); + expect(importsBoundTo(second, 'a')).toEqual([]); + expect(importsBoundTo(second, 'a2')).toEqual(second.filter((imp) => imp.localName === 'a2')); + }); +}); + +describe('the nodes of a file that hold a line', () => { + const node = (id: number, startLine: number, endLine: number, kind = 'function'): Node => + ({ id: `n${id}`, kind, name: `n${id}`, startLine, endLine } as unknown as Node); + const contextOf = (nodes: Node[]): ResolutionContext => ({ getNodesInFile: () => nodes } as unknown as ResolutionContext); + + /** A file's nodes as a parser leaves them: one around all, types around methods, some on one line, some ending where the next starts. */ + function fileNodes(count: number, seed: number): Node[] { + const next = random(seed); + const nodes: Node[] = [node(0, 1, count * 4 + 10, 'file')]; + let line = 2; + for (let i = 1; nodes.length < count; i++) { + const span = Math.floor(next() * 400); + nodes.push(node(nodes.length, line, line + span, 'class')); + let inner = line + 1; + while (inner < line + span && nodes.length < count) { + const length = Math.floor(next() * 6); + nodes.push(node(nodes.length, inner, Math.min(line + span, inner + length))); + if (next() < 0.2) nodes.push(node(nodes.length, inner, inner, 'variable')); + inner += next() < 0.3 ? length : length + 1 + Math.floor(next() * 3); + } + line += span + (next() < 0.5 ? 0 : 1 + Math.floor(next() * 80)); + } + return nodes; + } + + for (const count of [10, 63, 64, 500, 5000]) { + it(`are among those it gives, in the file's order (${count} nodes)`, () => { + const nodes = fileNodes(count, count); + const context = contextOf(nodes); + const lastLine = nodes[0]!.endLine; + const next = random(count + 1); + const lines = [0, 1, 2, 63, 64, 65, 127, 128, lastLine - 1, lastLine, lastLine + 1, lastLine + 500, + ...Array.from({ length: 300 }, () => Math.floor(next() * (lastLine + 20)))]; + for (const line of lines) { + const holds = (n: Node): boolean => n.startLine <= line && n.endLine >= line; + expect(nodesAroundLine(context, 'f', line).filter(holds).map((n) => n.id), `line ${line}`).toEqual(nodes.filter(holds).map((n) => n.id)); + } + }); + } + + it('are fewer than all of them, in a file large enough to be worth it', () => { + const nodes = fileNodes(5000, 3); + const around = nodesAroundLine(contextOf(nodes), 'f', Math.floor(nodes[0]!.endLine / 2)); + expect(around.length).toBeLessThan(nodes.length / 10); + }); + + it('gives every node when one has no lines to go by, or the line is none', () => { + const nodes = fileNodes(200, 5); + for (const odd of [node(900, 40, 12), node(901, NaN, 50), node(902, 30, undefined as unknown as number)]) { + const withOdd = [...nodes.slice(0, 100), odd, ...nodes.slice(100)]; + expect(nodesAroundLine(contextOf(withOdd), 'f', 45)).toBe(withOdd); + } + for (const line of [-1, NaN, undefined as unknown as number]) expect(nodesAroundLine(contextOf(nodes), 'f', line)).toBe(nodes); + }); + + it('reads the array the context hands out now, not the one it handed out before', () => { + const first = fileNodes(300, 8); + const second = first.map((n, i) => node(i + 10_000, n.startLine + 5, n.endLine + 5, n.kind)); + const holds = (n: Node): boolean => n.startLine <= 70 && n.endLine >= 70; + expect(nodesAroundLine(contextOf(first), 'f', 70).filter(holds).map((n) => n.id)).toEqual(first.filter(holds).map((n) => n.id)); + expect(nodesAroundLine(contextOf(second), 'f', 70).filter(holds).map((n) => n.id)).toEqual(second.filter(holds).map((n) => n.id)); + }); +}); + +describe('the nodes of a file by name', () => { + const contextOf = (nodes: Node[]): ResolutionContext => ({ getNodesInFile: () => nodes } as unknown as ResolutionContext); + + /** A file's nodes: names shared across kinds and owners, some differing only in case, members under types under namespaces. */ + function fileNodes(count: number, seed: number): Node[] { + const next = random(seed); + const names = ['index', 'Index', 'INDEX', 'show', 'x1', 'x10', 'constructor', '__proto__', 'toString', '']; + const owners = ['App', 'App::Users', 'App::Users::Admin', 'Other', 'app', 'App::User']; + return Array.from({ length: count }, (_, i) => { + const name = next() < 0.6 ? names[Math.floor(next() * names.length)]! : `x${i}`; + const owner = next() < 0.8 ? owners[Math.floor(next() * owners.length)]! : ''; + return { id: `n${i}`, kind: next() < 0.5 ? 'method' : 'class', name, qualifiedName: owner ? `${owner}::${name}` : name, startLine: i + 1, endLine: i + 1 } as unknown as Node; + }); + } + const asked = ['index', 'Index', 'show', 'x1', 'x10', 'x3', 'x30', 'constructor', '__proto__', 'toString', 'hasOwnProperty', '', 'nothing']; + const ids = (nodes: readonly Node[]): string[] => nodes.map((n) => n.id); + + // Ten and sixty-three nodes are read through; sixty-four and more are indexed. + for (const count of [0, 10, 63, 64, 500, 5000]) { + it(`are what a pass over all of them finds, in the file's order (${count} nodes)`, () => { + const nodes = fileNodes(count, count + 2); + const context = contextOf(nodes); + for (const name of asked) { + const same = (n: Node): boolean => n.name === name; + expect(ids(nodesNamed(context, 'f', name).filter(same)), `named ${JSON.stringify(name)}`).toEqual(ids(nodes.filter(same))); + expect(ids(nodesNamedIn(nodes, name).filter(same)), `named ${JSON.stringify(name)}, in hand`).toEqual(ids(nodes.filter(same))); + const lower = name.toLowerCase(); + expect(ids(nodesNamedLower(context, 'f', lower)), `named ${JSON.stringify(lower)} in any case`).toEqual(ids(nodes.filter((n) => n.name.toLowerCase() === lower))); + } + for (const owner of ['App', 'App::Users', 'App::Users::Admin', 'App::User', 'Other', 'app', 'App::', '', 'Nothing']) { + expect(ids(nodesUnder(context, 'f', owner)), `under ${JSON.stringify(owner)}`).toEqual(ids(nodes.filter((n) => n.qualifiedName.startsWith(`${owner}::`)))); + } + }); + } + + it('are fewer than all of them, in a file large enough to be worth it', () => { + const nodes = fileNodes(5000, 4); + expect(nodesNamed(contextOf(nodes), 'f', 'x4999').length).toBeLessThan(3); + expect(nodesNamed(contextOf(nodes), 'f', 'nothing')).toHaveLength(0); + }); + + it('gives every node when there is no name to go by', () => { + const nodes = fileNodes(300, 6); + for (const name of [undefined, null]) expect(nodesNamed(contextOf(nodes), 'f', name)).toBe(nodes); + }); + + it('reads the array the context hands out now, not the one it handed out before', () => { + const first = fileNodes(300, 8); + const second = fileNodes(300, 9); + for (const nodes of [first, second, first]) { + const context = contextOf(nodes); + expect(ids(nodesNamed(context, 'f', 'show'))).toEqual(ids(nodes.filter((n) => n.name === 'show'))); + expect(ids(nodesNamedLower(context, 'f', 'index'))).toEqual(ids(nodes.filter((n) => n.name.toLowerCase() === 'index'))); + expect(ids(nodesUnder(context, 'f', 'App'))).toEqual(ids(nodes.filter((n) => n.qualifiedName.startsWith('App::')))); + const holds = (n: Node): boolean => n.startLine <= 70 && n.endLine >= 70; + expect(ids(nodesAroundLineIn(nodes, 70).filter(holds))).toEqual(ids(nodes.filter(holds))); + } + }); +}); + +describe('a node\'s children, stepped through', () => { + // A run of comment lines under one parent is what reading by index was slow on. + const SOURCES: Array<[string, 'javascript' | 'python', string]> = [ + ['a file of comments and declarations', 'javascript', `${Array.from({ length: 300 }, (_, i) => `// comment ${i}`).join('\n')}\nfunction a(x, y) { return [x, y, { z: 1 }]; }\nclass B { m() {} /* c */ n() {} }\n`], + ['a file with nothing in it', 'javascript', ''], + ['a file of one expression', 'javascript', 'f(1, 2, 3);'], + ['a Python class of methods and comments', 'python', `class A:\n${Array.from({ length: 200 }, (_, i) => ` # note ${i}\n def m${i}(self, a, b=1):\n return [a, b]\n`).join('')}`], + ]; + + for (const [what, language, source] of SOURCES) { + it(`are the ones child(i) and namedChild(i) give, in order: ${what}`, async () => { + await initGrammars(); + await loadGrammarsForLanguages([language]); + const tree = getParser(language)!.parse(source)!; + try { + let seen = 0; + const visit = (node: Parameters[0]): void => { + const all = [...childrenOf(node)]; + const named = [...namedChildrenOf(node)]; + expect(all.map((c) => c.id)).toEqual(Array.from({ length: node.childCount }, (_, i) => node.child(i)!.id)); + expect(named.map((c) => c.id)).toEqual(Array.from({ length: node.namedChildCount }, (_, i) => node.namedChild(i)!.id)); + seen += all.length; + for (const c of all) visit(c); + }; + visit(tree.rootNode); + if (source) expect(seen).toBeGreaterThan(3); + } finally { + tree.delete(); + } + }); + } + + it('can be left before the last of them', async () => { + await initGrammars(); + await loadGrammarsForLanguages(['javascript']); + const tree = getParser('javascript')!.parse('a; b; c; d;')!; + try { + for (let round = 0; round < 2000; round++) { + let first: string | undefined; + for (const c of namedChildrenOf(tree.rootNode)) { + first = c.text; + break; + } + expect(first).toBe('a;'); + } + } finally { + tree.delete(); + } + }); +}); + +describe('where each of many names first occurs in a text', () => { + it('is where indexOf finds each, for names that are starts, ends and middles of one another', () => { + const text = ' disabledOnPress?: boolean;\n onPress?: () => void;\n on: string;\n press: Press;\n'; + const names = ['on', 'onPress', 'Press', 'ress', 'nP', 'disabledOnPress', 'o', 'press', 'string', 'missing', 'OnPresses', ';\n', '']; + const found = firstIndexOfEach(text, names); + for (const name of names) expect(found.get(name), JSON.stringify(name)).toBe(text.indexOf(name)); + expect(found.get('on')).toBeGreaterThan(text.indexOf('disabled')); + expect(found.get('missing')).toBe(-1); + expect(found.size).toBe(names.length); + }); + + it('is so over generated names and texts, few and many', () => { + const next = random(13); + const alphabet = 'ab_o1nP'; + const word = (longest: number): string => + Array.from({ length: 1 + Math.floor(next() * longest) }, () => alphabet[Math.floor(next() * alphabet.length)]).join(''); + for (const [nameCount, words] of [[0, 50], [1, 50], [40, 400], [600, 6000], [3000, 300]] as const) { + const names = Array.from({ length: nameCount }, () => word(7)); + let text = ''; + for (let i = 0; i < words; i++) text += word(9) + (next() < 0.5 ? ' ' : ';\n'); + const found = firstIndexOfEach(text, names); + for (const name of names) expect(found.get(name), `${JSON.stringify(name)} among ${nameCount} names`).toBe(text.indexOf(name)); + expect(found.size).toBe(new Set(names).size); + } + }); + + it('is so for a name the text ends in, one it starts with, and characters outside ASCII', () => { + const text = 'größe: 日本語 😀 naïve größer 😀😀 end'; + const names = ['größe', 'größer', 'ö', '日本', '本語', '😀', '😀😀', '\ud83d', 'end', 'nd', 'g', 'ende', ' ']; + const found = firstIndexOfEach(text, names); + for (const name of names) expect(found.get(name), JSON.stringify(name)).toBe(text.indexOf(name)); + }); + + it('is so in a text as long as a large file, for every name it declares', () => { + const lines = Array.from({ length: 40_000 }, (_, i) => ` prop${i}?: string;\n onEvent${i}?: Handler;\n`); + const text = lines.join(''); + const names = lines.flatMap((_, i) => [`prop${i}`, `onEvent${i}`]); + const started = Date.now(); + const found = firstIndexOfEach(text, names); + expect(Date.now() - started).toBeLessThan(20_000); + const next = random(17); + for (const i of [0, 1, 7, 10, 39_999, ...Array.from({ length: 300 }, () => Math.floor(next() * 40_000))]) { + expect(found.get(`prop${i}`), `prop${i}`).toBe(text.indexOf(`prop${i}`)); + expect(found.get(`onEvent${i}`), `onEvent${i}`).toBe(text.indexOf(`onEvent${i}`)); + } + }); +}); + +describe('a list too long to spread into a call', () => { + // More arguments than a call takes: `target.push(...items)` throws a RangeError at about this many. + const many = Array.from({ length: 400_000 }, (_, i) => (i * 7919) % 100_003); + + it('is added to another, item by item', () => { + const target = [1, 2]; + pushAll(target, many); + expect(target).toHaveLength(many.length + 2); + expect(target.slice(0, 4)).toEqual([1, 2, many[0], many[1]]); + expect(target[target.length - 1]).toBe(many[many.length - 1]); + pushAll(target, []); + expect(target).toHaveLength(many.length + 2); + }); + + it('has its largest and its smallest found as Math.max and Math.min find them', () => { + expect(maxOf(many)).toBe(100_002); + expect(minOf(many)).toBe(0); + for (const values of [[3, -1, 7], [-5], [2, NaN, 9], [Infinity, 1], []]) { + expect(maxOf(values)).toBe(Math.max(...values)); + expect(minOf(values)).toBe(Math.min(...values)); + } + }); +}); diff --git a/__tests__/name-matcher-memo-clears.test.ts b/__tests__/name-matcher-memo-clears.test.ts index 76e5e72e24..f1b7359f77 100644 --- a/__tests__/name-matcher-memo-clears.test.ts +++ b/__tests__/name-matcher-memo-clears.test.ts @@ -19,6 +19,8 @@ const HOLDS_NO_PROJECT_STATE: ReadonlyMap = new Map([ ['RUST_CHAINED_CALLS', 'keyed by the reference object, which a sync makes anew'], ['PY_CHAIN_GUESSING', 'keyed by the reference object, for the length of one lookup'], ['CPP_ARGUMENT_CHOICES_IN_FLIGHT', 'a recursion guard, empty between lookups'], + ['NOT_IMPORT_NODES', 'keyed by the array of nodes the context handed out, and dropped with it'], + ['CALLABLE_NODES', 'keyed by the array of nodes the context handed out, and dropped with it'], ]); /** A module-level collection that starts empty; one built from a literal (`new Map([`) is a constant. */ diff --git a/__tests__/oversize-file-not-read.test.ts b/__tests__/oversize-file-not-read.test.ts index fad014c375..5275d21fa4 100644 --- a/__tests__/oversize-file-not-read.test.ts +++ b/__tests__/oversize-file-not-read.test.ts @@ -4,6 +4,7 @@ import * as os from 'os'; import * as path from 'path'; import { CodeGraph } from '../src'; import { oversizeStamp, hashContent } from '../src/extraction'; +import { MAX_SOURCE_FILE_SIZE_BYTES } from '../src/file-limits'; import { hasDriftedOnDisk, readFileShape } from '../src/ui-server/api/source'; import { ToolHandler } from '../src/mcp/tools'; import { validateAnswerFiles } from '../src/mcp/answer-freshness'; @@ -22,20 +23,20 @@ describe('oversize files are stat-gated, never read (#1910)', () => { it('indexes the neighbours, records the oversize file as skipped with a size-stamp hash, and does not decode it', async () => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-oversize-')); fs.writeFileSync(path.join(dir, 'app.ts'), 'export function alpha() { return beta(); }\nexport function beta() { return 1; }\n'); - // 1 MB + 1: over the limit; invalid UTF-8 (0xFF) so any decode would be visible as replacement chars. - fs.writeFileSync(path.join(dir, 'blob.ts'), big(1024 * 1024 + 1, 0xff)); + // One byte over the limit; invalid UTF-8 (0xFF) so any decode would be visible as replacement chars. + fs.writeFileSync(path.join(dir, 'blob.ts'), big(MAX_SOURCE_FILE_SIZE_BYTES + 1, 0xff)); const cg = await CodeGraph.init(dir, { index: true }); try { expect(cg.getNodesByKind('function').map(n => n.name).sort()).toEqual(['alpha', 'beta']); const rec = cg.getFiles().find(f => f.path === 'blob.ts'); expect(rec).toBeDefined(); - expect(rec!.contentHash).toBe(hashContent(oversizeStamp(1024 * 1024 + 1))); + expect(rec!.contentHash).toBe(hashContent(oversizeStamp(MAX_SOURCE_FILE_SIZE_BYTES + 1))); // Nothing from the blob reached the graph. expect(cg.getNodesInFile('blob.ts').filter(n => n.kind !== 'file')).toEqual([]); // Change detection agrees with what was stored: nothing pending. expect(cg.getChangedFiles()).toEqual({ added: [], modified: [], removed: [] }); // A same-size rewrite is not a change (nothing about it is indexed)... - fs.writeFileSync(path.join(dir, 'blob.ts'), big(1024 * 1024 + 1, 0xfe)); + fs.writeFileSync(path.join(dir, 'blob.ts'), big(MAX_SOURCE_FILE_SIZE_BYTES + 1, 0xfe)); expect(cg.getChangedFiles().modified).toEqual([]); // ...crossing the limit is: the file becomes ordinary source. fs.writeFileSync(path.join(dir, 'blob.ts'), 'export const gamma = 3;\n'); @@ -43,10 +44,10 @@ describe('oversize files are stat-gated, never read (#1910)', () => { await cg.sync(); expect(cg.getNodesInFile('blob.ts').some(n => n.name === 'gamma')).toBe(true); // ...and growing back over it is a change too, stored as the stamp again. - fs.writeFileSync(path.join(dir, 'blob.ts'), big(2 * 1024 * 1024, 0xff)); + fs.writeFileSync(path.join(dir, 'blob.ts'), big(2 * MAX_SOURCE_FILE_SIZE_BYTES, 0xff)); expect(cg.getChangedFiles().modified).toEqual(['blob.ts']); await cg.sync(); - expect(cg.getFiles().find(f => f.path === 'blob.ts')!.contentHash).toBe(hashContent(oversizeStamp(2 * 1024 * 1024))); + expect(cg.getFiles().find(f => f.path === 'blob.ts')!.contentHash).toBe(hashContent(oversizeStamp(2 * MAX_SOURCE_FILE_SIZE_BYTES))); expect(cg.getNodesInFile('blob.ts').some(n => n.name === 'gamma')).toBe(false); } finally { cg.close(); @@ -88,14 +89,14 @@ describe('an unchanged file over the size limit is not reported as drifted (#191 it('reads as current in the viewer and in MCP until its size changes', async () => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-oversize-drift-')); fs.writeFileSync(path.join(dir, 'app.ts'), 'export function alpha() { return 1; }\n'); - // 1.4 MB of ordinary text: over the index limit, under the viewer's 8 MB read cap. + // Ordinary text 1.4 times the index limit (5.6 MB): over it, under the viewer's 8 MB read cap. // Each line differs: Windows Defender's script scan of a freshly written `.js` // made of one statement repeated 110k times takes close to a minute on the // first read, so the viewer's read below blew the test timeout there. Real // code of the same size is scanned in milliseconds. const line = 'const last = 0;\n'; const lines: string[] = []; - for (let size = 0, i = 0; size < 1.4 * 1024 * 1024; i++) { + for (let size = 0, i = 0; size < 1.4 * MAX_SOURCE_FILE_SIZE_BYTES; i++) { lines.push(`const x${i} = ${i};\n`); size += lines[i]!.length; } diff --git a/__tests__/oversize-files-reported.test.ts b/__tests__/oversize-files-reported.test.ts index 18d6963bc5..030a62c183 100644 --- a/__tests__/oversize-files-reported.test.ts +++ b/__tests__/oversize-files-reported.test.ts @@ -97,8 +97,8 @@ describe('files left out of the graph for their size are said to be', () => { expect(code).toBe(0); // Nothing is stale and nothing needs a sync: the file is left out by design. expect(stdout).toContain('Index is up to date'); - expect(stdout).toMatch(/1 source file is over the 1\.0 MB size limit and not in the graph/); - expect(stdout).toContain('src/big.ts (1.0 MB)'); + expect(stdout).toMatch(/1 source file is over the 4\.0 MB size limit and not in the graph/); + expect(stdout).toContain('src/big.ts (4.0 MB)'); const json = JSON.parse(cli('status', dir, '--json').stdout); expect(json.index.filesOverSizeLimit).toBe(1); @@ -114,9 +114,9 @@ describe('files left out of the graph for their size are said to be', () => { const { code, stdout, stderr } = cli('init', dir); expect(code).toBe(0); const said = `${stdout}\n${stderr}`; - expect(said).toMatch(/2 source files are over the 1\.0 MB size limit and not in the graph/); + expect(said).toMatch(/2 source files are over the 4\.0 MB size limit and not in the graph/); // The file nearest the limit is the likeliest to be hand-written source. - expect(said).toMatch(/src\/big\.ts \(1\.0 MB\), src\/bigger\.ts \(1\.3 MB\)/); + expect(said).toMatch(/src\/big\.ts \(4\.0 MB\), src\/bigger\.ts \(4\.3 MB\)/); }); it('sync says so too, for a file that grew past the limit and for one already left out', async () => { @@ -125,10 +125,10 @@ describe('files left out of the graph for their size are said to be', () => { write({ 'src/big.ts': BIG }); const grew = cli('sync', dir); expect(grew.code).toBe(0); - expect(`${grew.stdout}\n${grew.stderr}`).toMatch(/1 source file is over the 1\.0 MB size limit and not in the graph/); + expect(`${grew.stdout}\n${grew.stderr}`).toMatch(/1 source file is over the 4\.0 MB size limit and not in the graph/); // Nothing changed this time; the file is still left out, and sync still says so. const again = cli('sync', dir); - expect(`${again.stdout}\n${again.stderr}`).toContain('src/big.ts (1.0 MB)'); + expect(`${again.stdout}\n${again.stderr}`).toContain('src/big.ts (4.0 MB)'); }); it('the symbol map of such a file says it was not indexed, not that it is empty', async () => { @@ -140,7 +140,7 @@ describe('files left out of the graph for their size are said to be', () => { const map = async (file: string): Promise => (await handler.execute('codegraph_node', { file, symbolsOnly: true })).content.map((c) => c.text).join('\n'); const big = await map('src/big.ts'); - expect(big).toContain('_Not indexed: at 1.0 MB this file is over the size limit for source files'); + expect(big).toContain('_Not indexed: at 4.0 MB this file is over the size limit for source files'); expect(big).not.toContain('No indexed symbols in this file'); expect(await map('src/small.ts')).toContain('`alpha`'); } finally { diff --git a/__tests__/parameter-flow.test.ts b/__tests__/parameter-flow.test.ts index bb6111b848..6f1cc05d2d 100644 --- a/__tests__/parameter-flow.test.ts +++ b/__tests__/parameter-flow.test.ts @@ -436,7 +436,7 @@ describe('what the pass reads of a file', () => { it('takes a file over the size limit for nothing, as the index does', async () => { // A mention it could read would cost the flow, and reading it costs the heap. const mention = 'class Huge\n def run(name)\n name.send(:add_to, name)\n end\nend\n'; - const huge = `${mention}${'# a line of padding, to go over the limit\n'.repeat(30_000)}`; + const huge = `${mention}${'# a line of padding, to go over the limit\n'.repeat(Math.ceil(MAX_SOURCE_FILE_SIZE_BYTES / 40))}`; expect(Buffer.byteLength(huge)).toBeGreaterThan(MAX_SOURCE_FILE_SIZE_BYTES); const { cg } = await indexed({ ...BASE, 'lib/huge.rb': huge }); expect(addToCalls(cg)).toEqual(FLOWED); @@ -444,7 +444,7 @@ describe('what the pass reads of a file', () => { it('counts a mention in a file just under the limit', async () => { const mention = 'class Big\n def run(name)\n name.send(:add_to, name)\n end\nend\n'; - const big = `${mention}${'# a line of padding, to go near the limit\n'.repeat(20_000)}`; + const big = `${mention}${'# a line of padding, to go near the limit\n'.repeat(Math.floor((MAX_SOURCE_FILE_SIZE_BYTES * 0.8) / 42))}`; expect(Buffer.byteLength(big)).toBeLessThan(MAX_SOURCE_FILE_SIZE_BYTES); const { cg } = await indexed({ ...BASE, 'lib/big.rb': big }); expect(addToCalls(cg)).toEqual(GUESSED); diff --git a/__tests__/resolution-file-read.test.ts b/__tests__/resolution-file-read.test.ts index 3711c876e8..61d8d821f3 100644 --- a/__tests__/resolution-file-read.test.ts +++ b/__tests__/resolution-file-read.test.ts @@ -38,7 +38,7 @@ describe('resolution file reads', () => { const fd = fs.openSync(archive, 'w'); try { fs.writeSync(fd, Buffer.from([0x1f, 0x8b])); - fs.ftruncateSync(fd, 2 * 1024 * 1024); + fs.ftruncateSync(fd, 2 * MAX_SOURCE_FILE_SIZE_BYTES); } finally { fs.closeSync(fd); } @@ -64,7 +64,9 @@ describe('resolution file reads', () => { }); it('accepts exactly the byte limit and rejects one byte more', () => { - const content = 'a'.repeat(MAX_SOURCE_FILE_SIZE_BYTES); + // Lines, not one run of a letter: a run longer than any name is read blanked (withoutLongRuns). + const content = 'a\n'.repeat(MAX_SOURCE_FILE_SIZE_BYTES / 2); + expect(Buffer.byteLength(content)).toBe(MAX_SOURCE_FILE_SIZE_BYTES); fs.writeFileSync(path.join(root, 'boundary.ts'), content); expect(context.readFile('boundary.ts')).toBe(content); fs.appendFileSync(path.join(root, 'boundary.ts'), 'a'); diff --git a/__tests__/sync.test.ts b/__tests__/sync.test.ts index 5729756a21..5632260b21 100644 --- a/__tests__/sync.test.ts +++ b/__tests__/sync.test.ts @@ -13,6 +13,7 @@ import * as os from 'os'; import { execFileSync } from 'child_process'; import CodeGraph, { LockUnavailableError } from '../src/index'; import { QueryBuilder } from '../src/db/queries'; +import { MAX_SOURCE_FILE_SIZE_BYTES } from '../src/file-limits'; import { __emitWatchEventForTests } from '../src/sync/watcher'; /** @@ -239,7 +240,7 @@ describe('Sync Module', () => { it('persists an oversized skipped file so later syncs do not retry it (#1557)', async () => { const filePath = path.join(testDir, 'src', 'oversized.ts'); - fs.writeFileSync(filePath, 'const value = 1;\n'.repeat(70_000)); + fs.writeFileSync(filePath, 'const value = 1;\n'.repeat(Math.ceil(MAX_SOURCE_FILE_SIZE_BYTES / 17) + 1)); const first = await cg.sync(); expect(first.filesAdded).toBe(1); diff --git a/codegraph-kernel/src/ccpp/brace_scopes.rs b/codegraph-kernel/src/ccpp/brace_scopes.rs index 072c14113e..dacc50de38 100644 --- a/codegraph-kernel/src/ccpp/brace_scopes.rs +++ b/codegraph-kernel/src/ccpp/brace_scopes.rs @@ -85,7 +85,7 @@ impl BraceScopes { } /// The 1-based line and the UTF-16 column of `offset`. - pub fn position_of(src: &str, line_starts: &[usize], offset: usize) -> (u32, u32) { + pub fn position_of(src: &str, line_starts: &util::LineStarts, offset: usize) -> (u32, u32) { let row = line_starts.partition_point(|&s| s <= offset).saturating_sub(1); (row as u32 + 1, util::col16(src, line_starts, row, offset)) } diff --git a/codegraph-kernel/src/ccpp/mod.rs b/codegraph-kernel/src/ccpp/mod.rs index dfa4715f06..d9f16db9fa 100644 --- a/codegraph-kernel/src/ccpp/mod.rs +++ b/codegraph-kernel/src/ccpp/mod.rs @@ -86,6 +86,7 @@ use crate::docstring::preceding_docstring; use crate::ids; use crate::textutil as util; use regex::Regex; +use std::cell::RefCell; use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::OnceLock; use tree_sitter::{Node, Parser}; @@ -369,7 +370,7 @@ pub struct Walker<'t> { src: &'t str, file_path: &'t str, variant: Variant, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -396,6 +397,8 @@ pub struct Walker<'t> { /// declaration is walked in C, and in C++ unless the tree has errors and /// its braces don't balance (no brace scopes; only under the hatch). walk_declared_types: bool, + /// What `visibility_of` found for each parent it was asked about, by the parent's id. + visibility_seen: RefCell>>, } pub fn extract(file_path: &str, source: &str, language: &str) -> Result { @@ -449,6 +452,7 @@ pub fn extract(file_path: &str, source: &str, language: &str) -> Result Walker<'t> { } return self.text(resolved).to_string(); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { - return self.text(c).to_string(); - } + for c in node.named_children(&mut node.walk()) { + if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { + return self.text(c).to_string(); } } "".to_string() @@ -988,24 +990,34 @@ impl<'t> Walker<'t> { /// cppExtractor.getVisibility: the FIRST access_specifier among the /// parent's children decides (document order, not nearest-preceding — /// bug-for-bug with the TS loop). + /// + /// The answer is the parent's, so it is read once for each parent and + /// kept: read again for every member, a file of twenty thousand functions + /// spent a minute on it, each one reading every sibling it has. fn visibility_of(&self, node: Node) -> Option { let parent = node.parent()?; - for i in 0..parent.child_count() { - let Some(child) = parent.child(i) else { continue }; + if let Some(known) = self.visibility_seen.borrow().get(&parent.id()) { + return *known; + } + let mut found = None; + let mut cursor = parent.walk(); + for child in parent.children(&mut cursor) { if child.kind() == "access_specifier" { let text = self.text(child); if text.contains("public") { - return Some(1); + found = Some(1); + } else if text.contains("private") { + found = Some(2); + } else if text.contains("protected") { + found = Some(3); } - if text.contains("private") { - return Some(2); - } - if text.contains("protected") { - return Some(3); + if found.is_some() { + break; } } } - None + self.visibility_seen.borrow_mut().insert(parent.id(), found); + found } /// cExtractor.isConst: any named `type_qualifier` child reading "const". @@ -1159,10 +1171,8 @@ impl<'t> Walker<'t> { .unwrap_or_default(); if !ns_name.is_empty() { self.namespace_prefix.push(ns_name); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } self.namespace_prefix.pop(); return; @@ -1217,11 +1227,9 @@ impl<'t> Walker<'t> { match defined_type { Some(t) => { self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if c.id() != t.id() { - self.scan_fn_ref_subtree(c, 1); - } + for c in node.named_children(&mut node.walk()) { + if c.id() != t.id() { + self.scan_fn_ref_subtree(c, 1); } } } @@ -1251,10 +1259,8 @@ impl<'t> Walker<'t> { } if !skip_children { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } } } @@ -1398,10 +1404,8 @@ impl<'t> Walker<'t> { self.extract_inheritance(node, row); self.push_member_type_refs(node, row, &scope.name); self.stack.push(scope); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -1425,10 +1429,8 @@ impl<'t> Walker<'t> { self.extract_inheritance(node, row); self.push_member_type_refs(node, row, &scope.name); self.stack.push(scope); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -1445,8 +1447,7 @@ impl<'t> Walker<'t> { let Some(row) = self.create_node("enum", &name, node, extra) else { return }; self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "enum", name, qualified: None }); - for i in 0..body.named_child_count() { - let Some(child) = body.named_child(i) else { continue }; + for child in body.named_children(&mut body.walk()) { if child.kind() == "enumerator" { self.extract_enum_members(child); } else { @@ -1479,8 +1480,7 @@ impl<'t> Walker<'t> { // WITH a body decides the node kind (anon inner specifier takes the // typedef's name). let mut resolved: Option<&'static str> = None; - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "enum_specifier" && child.child_by_field_name("body").is_some() { resolved = Some("enum"); break; @@ -1516,10 +1516,8 @@ impl<'t> Walker<'t> { self.stack.push(Scope { row, kind, name, qualified: None }); if let Some(tc) = type_child { let body = tc.child_by_field_name("body").unwrap_or(tc); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } } self.stack.pop(); @@ -1539,8 +1537,7 @@ impl<'t> Walker<'t> { if let Some(inner) = self.find_child_by_kind(node, "enum_specifier") { self.extract_inheritance(inner, row); if let Some(body) = inner.child_by_field_name("body") { - for i in 0..body.named_child_count() { - let Some(child) = body.named_child(i) else { continue }; + for child in body.named_children(&mut body.walk()) { if child.kind() == "enumerator" { self.extract_enum_members(child); } else { @@ -1580,8 +1577,7 @@ impl<'t> Walker<'t> { if has_function_ancestor(node) { return; } - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if !matches!( child.kind(), "init_declarator" | "pointer_declarator" | "array_declarator" @@ -1614,8 +1610,7 @@ impl<'t> Walker<'t> { } else { // Generic fallback: direct identifier children only (`int x;` // extracts; `int x = 5;` nests in an init_declarator and does not). - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() != "identifier" { continue; } @@ -1683,12 +1678,10 @@ impl<'t> Walker<'t> { if child.kind() != "ERROR" { continue; } - for j in 0..child.named_child_count() { - if let Some(op) = child.named_child(j) { - if op.kind() == "operator_name" { - operator_name = self.text(op).to_string(); - break 'err; - } + for op in child.named_children(&mut child.walk()) { + if op.kind() == "operator_name" { + operator_name = self.text(op).to_string(); + break 'err; } } } @@ -1883,8 +1876,7 @@ impl<'t> Walker<'t> { } let mut instantiates = false; let mut arities = Vec::new(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "storage_class_specifier" && self.text(child) == "extern" { return none; } @@ -2083,8 +2075,7 @@ impl<'t> Walker<'t> { // C++ local fn-pointer bindings: declarations and branch reassignments. if self.variant == Variant::Cpp && !self.stack.is_empty() { if kind == "declaration" { - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() != "init_declarator" { continue; } @@ -2135,10 +2126,8 @@ impl<'t> Walker<'t> { return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_for_calls_and_structure(c); } } @@ -2152,12 +2141,10 @@ impl<'t> Walker<'t> { fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) { stack_guard!(); let extends_kind = edge_kind_index("extends").unwrap(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { match child.kind() { "base_class_clause" => { - for j in 0..child.named_child_count() { - let Some(t) = child.named_child(j) else { continue }; + for t in child.named_children(&mut child.walk()) { if matches!( t.kind(), "type_identifier" | "qualified_identifier" | "template_type" @@ -2334,10 +2321,8 @@ impl<'t> Walker<'t> { let mut values: Vec> = Vec::new(); match mode { Mode::Args | Mode::List => { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - values.push(c); - } + for c in node.named_children(&mut node.walk()) { + values.push(c); } } Mode::Rhs => { @@ -2446,10 +2431,8 @@ impl<'t> Walker<'t> { return; } self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.scan_fn_ref_subtree(c, depth + 1); - } + for c in node.named_children(&mut node.walk()) { + self.scan_fn_ref_subtree(c, depth + 1); } } @@ -2533,10 +2516,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -2586,10 +2567,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } @@ -2620,14 +2599,12 @@ fn find_declarator_qualified_id(declarator: Node) -> Option { if current.kind() == "qualified_identifier" { return Some(current); } - for i in 0..current.named_child_count() { - if let Some(child) = current.named_child(i) { - if !matches!( - child.kind(), - "parameter_list" | "trailing_return_type" | "noexcept" | "throw_specifier" | "requires_clause" - ) { - queue.push_back(child); - } + for child in current.named_children(&mut current.walk()) { + if !matches!( + child.kind(), + "parameter_list" | "trailing_return_type" | "noexcept" | "throw_specifier" | "requires_clause" + ) { + queue.push_back(child); } } } diff --git a/codegraph-kernel/src/cfnptr.rs b/codegraph-kernel/src/cfnptr.rs index 2ba81d1300..8ba3723359 100644 --- a/codegraph-kernel/src/cfnptr.rs +++ b/codegraph-kernel/src/cfnptr.rs @@ -432,9 +432,19 @@ struct InlineScan { fn scan_inline_structs(s: &[u8]) -> InlineScan { let mut out = InlineScan { ptr: false, types: Vec::new(), tags: Vec::new() }; let mut last = 0; + // Where each keyword next stands, looked for again only once the scan has + // passed it. Looked for from `last` on every turn, the one a file does not + // use was searched for to the end of the file for each of the other: a + // header of twenty thousand structs and no union read itself that many times. + let mut next_struct = find_word(s, b"struct", 0); + let mut next_union = find_word(s, b"union", 0); loop { - let next_struct = find_word(s, b"struct", last); - let next_union = find_word(s, b"union", last); + if next_struct.is_some_and(|at| at < last) { + next_struct = find_word(s, b"struct", last); + } + if next_union.is_some_and(|at| at < last) { + next_union = find_word(s, b"union", last); + } let Some((t, keyword_len)) = (match (next_struct, next_union) { (Some(st), Some(un)) if st < un => Some((st, 6)), (Some(_), Some(un)) => Some((un, 5)), diff --git a/codegraph-kernel/src/csharp.rs b/codegraph-kernel/src/csharp.rs index 0558bd407c..2a3eccc3eb 100644 --- a/codegraph-kernel/src/csharp.rs +++ b/codegraph-kernel/src/csharp.rs @@ -139,7 +139,7 @@ struct Cand { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -220,8 +220,7 @@ pub fn extract(file_path: &str, source: &str) -> Result { // scopes only its own body — visit_node. let root = tree.root_node(); let mut pkg_pushed = false; - for i in 0..root.named_child_count() { - let Some(child) = root.named_child(i) else { continue }; + for child in root.named_children(&mut root.walk()) { if child.kind() != "file_scoped_namespace_declaration" { continue; } @@ -429,8 +428,7 @@ impl<'t> Walker<'t> { /// levels wins; none → public in an interface, internal in a namespace /// or the file, private in a class or struct (the C# defaults). fn visibility_of(&self, node: Node) -> u8 { - for i in 0..node.child_count() { - let Some(child) = node.child(i) else { continue }; + for child in node.children(&mut node.walk()) { if child.kind() == "modifier" { match self.text(child) { "public" => return 1, @@ -470,8 +468,7 @@ impl<'t> Walker<'t> { fn is_const(&self, node: Node) -> bool { let mut has_static = false; let mut has_readonly = false; - for i in 0..node.child_count() { - let Some(child) = node.child(i) else { continue }; + for child in node.children(&mut node.walk()) { if child.kind() != "modifier" { continue; } @@ -509,11 +506,9 @@ impl<'t> Walker<'t> { if let Some(name_node) = node.child_by_field_name("name") { return self.text(name_node).to_string(); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { - return self.text(c).to_string(); - } + for c in node.named_children(&mut node.walk()) { + if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { + return self.text(c).to_string(); } } "".to_string() @@ -543,10 +538,8 @@ impl<'t> Walker<'t> { if let Some(row) = row { self.stack.push(Scope { row, kind: "namespace", name: full }); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } if row.is_some() { self.stack.pop(); @@ -601,21 +594,21 @@ impl<'t> Walker<'t> { } None => Vec::new(), }; - self.scan_fn_ref_subtree(node, 0, &walked); + self.scan_fn_ref_subtree(node, 0, &walked.into_iter().collect()); skip_children = true; } else if kind == "field_declaration" && self.inside_class_like() { // Each declarator, `= initializer` included, is walked with its // field on the stack (extract_field); the candidates-only scan // covers the rest, skipping the declarators that walk captured. let walked = self.extract_field(node); - self.scan_fn_ref_subtree(node, 0, &walked); + self.scan_fn_ref_subtree(node, 0, &walked.into_iter().collect()); skip_children = true; } else if kind == "local_declaration_statement" && !self.inside_class_like() { // Top-level statements: extractVariable's generic fallback finds no // direct identifier/variable_declarator children (C# nests them in // variable_declaration) → ZERO nodes, zero refs. Candidates only. self.extract_variable(node); - self.scan_fn_ref_subtree(node, 0, &[]); + self.scan_fn_ref_subtree(node, 0, &HashSet::new()); skip_children = true; } else if kind == "using_directive" { self.extract_import(node); @@ -635,10 +628,8 @@ impl<'t> Walker<'t> { // attribute to the enclosing scope (checklist §dispatch). if !skip_children { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } } } @@ -693,10 +684,8 @@ impl<'t> Walker<'t> { return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_for_calls_and_structure(c); } } @@ -724,10 +713,8 @@ impl<'t> Walker<'t> { // children falls through (base-arg identifiers still feed fn-ref // capture, mirroring the TS walk). let body = node.child_by_field_name("body").unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } // no synthesizeMembers for C# self.stack.pop(); @@ -754,10 +741,8 @@ impl<'t> Walker<'t> { // NOTE: extractStruct does NOT call extractDecoratorsFor (TS parity). if let Some(body) = body { self.stack.push(Scope { row, kind: "struct", name }); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -774,10 +759,8 @@ impl<'t> Walker<'t> { self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "interface", name }); let body = node.child_by_field_name("body").unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -796,8 +779,7 @@ impl<'t> Walker<'t> { // an `extends` ref named `byte` (garbage, PRESERVE). self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "enum", name }); - for i in 0..body.named_child_count() { - let Some(child) = body.named_child(i) else { continue }; + for child in body.named_children(&mut body.walk()) { if child.kind() == "enum_member_declaration" { self.extract_enum_members(child); } else { @@ -1087,8 +1069,7 @@ impl<'t> Walker<'t> { // level produces no node, no calls ref, no instantiates — preserve). let kind: &'static str = if self.is_const(node) { "constant" } else { "variable" }; let docstring = preceding_docstring(node, self.src); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { let name = match child.kind() { "identifier" => self.text(child).to_string(), "variable_declarator" => self.extract_name(child), @@ -1253,10 +1234,8 @@ impl<'t> Walker<'t> { self.push_ref(row, &type_name, edge_kind_index("extends").unwrap(), line, column); self.stack.push(Scope { row, kind: "class", name: anon_name }); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -1307,13 +1286,11 @@ impl<'t> Walker<'t> { /// `(repo)` argument-list / `BaseDto(Name)` / `: byte` shapes preserved). fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) { let extends_kind = edge_kind_index("extends").unwrap(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() != "base_list" { continue; } - for j in 0..child.named_child_count() { - let Some(base) = child.named_child(j) else { continue }; + for base in child.named_children(&mut child.walk()) { let name = if base.kind() == "generic_name" { // `ClientBase` → head identifier; position = generic_name. let ident = (0..base.named_child_count()) @@ -1352,8 +1329,7 @@ impl<'t> Walker<'t> { } // Method/constructor parameters: ONLY each `parameter`'s `type` field. if let Some(params) = node.child_by_field_name("parameters") { - for i in 0..params.named_child_count() { - let Some(p) = params.named_child(i) else { continue }; + for p in params.named_children(&mut params.walk()) { if p.kind() != "parameter" { continue; } @@ -1371,8 +1347,7 @@ impl<'t> Walker<'t> { .filter_map(|i| node.named_child(i)) .find(|c| c.kind() == "parameter_list"); let Some(param_list) = param_list else { return }; - for i in 0..param_list.named_child_count() { - let Some(p) = param_list.named_child(i) else { continue }; + for p in param_list.named_children(&mut param_list.walk()) { if p.kind() != "parameter" { continue; } @@ -1408,10 +1383,8 @@ impl<'t> Walker<'t> { } } _ => { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.walk_type_position(c, from_row); - } + for c in node.named_children(&mut node.walk()) { + self.walk_type_position(c, from_row); } } } @@ -1442,10 +1415,8 @@ impl<'t> Walker<'t> { let mut values: Vec = Vec::new(); match mode { Mode::Args | Mode::List => { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - values.push(c); - } + for c in node.named_children(&mut node.walk()) { + values.push(c); } } Mode::Rhs => { @@ -1515,10 +1486,8 @@ impl<'t> Walker<'t> { } "argument" => { // Transparent layer (field=null) → recurse all named children. - for i in 0..v.named_child_count() { - if let Some(c) = v.named_child(i) { - self.normalize_fn_ref_value(c, from, depth + 1); - } + for c in v.named_children(&mut v.walk()) { + self.normalize_fn_ref_value(c, from, depth + 1); } } "member_access_expression" => { @@ -1563,7 +1532,7 @@ impl<'t> Walker<'t> { }); } - fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &[usize]) { + fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &HashSet) { stack_guard!(); if depth > 12 { return; @@ -1585,10 +1554,8 @@ impl<'t> Walker<'t> { return; } self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.scan_fn_ref_subtree(c, depth + 1, walked); - } + for c in node.named_children(&mut node.walk()) { + self.scan_fn_ref_subtree(c, depth + 1, walked); } } @@ -1664,10 +1631,8 @@ impl<'t> Walker<'t> { } } // (property_declaration's bump is structurally null for C# — not ported.) - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -1717,10 +1682,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } @@ -1734,8 +1697,7 @@ impl<'t> Walker<'t> { fn property_bodies(node: Node) -> Vec { let mut bodies = Vec::new(); if let Some(accessors) = node.child_by_field_name("accessors") { - for i in 0..accessors.named_child_count() { - let Some(accessor) = accessors.named_child(i) else { continue }; + for accessor in accessors.named_children(&mut accessors.walk()) { if accessor.kind() != "accessor_declaration" { continue; } @@ -1755,11 +1717,9 @@ fn last_named_child(node: Node) -> Option { } fn find_anonymous_class_body(node: Node) -> Option { - for i in 0..node.named_child_count() { - if let Some(child) = node.named_child(i) { - if matches!(child.kind(), "class_body" | "declaration_list") { - return Some(child); - } + for child in node.named_children(&mut node.walk()) { + if matches!(child.kind(), "class_body" | "declaration_list") { + return Some(child); } } None diff --git a/codegraph-kernel/src/dart.rs b/codegraph-kernel/src/dart.rs index e9ffad6a38..98c75af8f3 100644 --- a/codegraph-kernel/src/dart.rs +++ b/codegraph-kernel/src/dart.rs @@ -256,7 +256,7 @@ struct Extra { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -686,11 +686,9 @@ impl<'t> Walker<'t> { fn is_async_of(&self, node: Node<'t>) -> bool { if let Some(next) = node.next_named_sibling() { if next.kind() == "function_body" { - for i in 0..next.child_count() { - if let Some(c) = next.child(i) { - if c.kind() == "async" { - return true; - } + for c in next.children(&mut next.walk()) { + if c.kind() == "async" { + return true; } } } @@ -701,11 +699,9 @@ impl<'t> Walker<'t> { /// isStatic (dart.ts:234-243). fn is_static_of(&self, node: Node<'t>) -> bool { if node.kind() == "method_signature" { - for i in 0..node.child_count() { - if let Some(c) = node.child(i) { - if c.kind() == "static" { - return true; - } + for c in node.children(&mut node.walk()) { + if c.kind() == "static" { + return true; } } } @@ -1962,29 +1958,19 @@ impl<'t> Walker<'t> { // A `declaration`-wrapped member's annotations precede the wrapper, // and the comments between annotations and declaration are stepped over. let anchor = self.declaration_wrapper(decl).unwrap_or(decl); - if let Some(parent) = anchor.parent() { - let decl_start = anchor.start_byte(); - let mut decl_idx: Option = None; - for i in 0..parent.named_child_count() { - if let Some(sib) = parent.named_child(i) { - if sib.start_byte() == decl_start { - decl_idx = Some(i); - break; - } - } + // Walked back from the declaration itself. Finding its place first, by counting the + // parent's children from the start, cost each declaration as much as it has + // siblings before it: a file of twenty thousand took minutes. + let mut sibling = anchor.prev_named_sibling(); + while let Some(sib) = sibling { + sibling = sib.prev_named_sibling(); + if DECORATOR_STEP_OVER.contains(&sib.kind()) { + continue; } - if let Some(di) = decl_idx { - for j in (0..di).rev() { - let Some(sib) = parent.named_child(j) else { continue }; - if DECORATOR_STEP_OVER.contains(&sib.kind()) { - continue; - } - if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { - break; - } - self.consider_decorator(sib, decorated_row); - } + if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { + break; } + self.consider_decorator(sib, decorated_row); } } @@ -2524,10 +2510,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -2584,10 +2568,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } diff --git a/codegraph-kernel/src/go.rs b/codegraph-kernel/src/go.rs index 3b8a2bd234..9d2d9bb6d2 100644 --- a/codegraph-kernel/src/go.rs +++ b/codegraph-kernel/src/go.rs @@ -89,7 +89,7 @@ struct NodeMeta { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -318,11 +318,9 @@ impl<'t> Walker<'t> { if let Some(name_node) = node.child_by_field_name("name") { return self.text(name_node).to_string(); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { - return self.text(c).to_string(); - } + for c in node.named_children(&mut node.walk()) { + if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { + return self.text(c).to_string(); } } "".to_string() @@ -433,7 +431,7 @@ impl<'t> Walker<'t> { // The initializers extract_variable walked under their specs' // symbols took their own candidates; the scan covers the rest. let walked = self.extract_variable(node); - self.scan_fn_ref_subtree(node, 0, &walked); + self.scan_fn_ref_subtree(node, 0, &walked.into_iter().collect()); skip_children = true; } else if kind == "import_declaration" { self.extract_import(node); @@ -444,10 +442,8 @@ impl<'t> Walker<'t> { } if !skip_children { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } } } @@ -476,10 +472,8 @@ impl<'t> Walker<'t> { } } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_for_calls_and_structure(c); } } @@ -599,10 +593,8 @@ impl<'t> Walker<'t> { self.push_ref_at(row, &text, references, ty); } let body = type_child.child_by_field_name("body").unwrap_or(type_child); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } } self.stack.pop(); @@ -650,8 +642,7 @@ impl<'t> Walker<'t> { fn extract_go_interface_methods(&mut self, interface_type: Node<'t>, iface_row: u32, iface_name: &str, decl: Node<'t>) { self.stack.push(Scope { row: iface_row, kind: "interface", name: iface_name.to_string() }); let references = edge_kind_index("references").unwrap(); - for i in 0..interface_type.named_child_count() { - let Some(m) = interface_type.named_child(i) else { continue }; + for m in interface_type.named_children(&mut interface_type.walk()) { if !matches!(m.kind(), "method_elem" | "method_spec") { continue; } @@ -695,8 +686,7 @@ impl<'t> Walker<'t> { // A `var ( … )` group wraps its specs in a `var_spec_list`; a // `const ( … )` group holds them directly. let mut specs: Vec> = Vec::new(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "var_spec_list" { specs.extend((0..child.named_child_count()).filter_map(|j| child.named_child(j))); } else { @@ -804,11 +794,9 @@ impl<'t> Walker<'t> { .filter_map(|i| node.named_child(i)) .find(|c| c.kind() == "import_spec_list"); if let Some(list) = spec_list { - for i in 0..list.named_child_count() { - if let Some(spec) = list.named_child(i) { - if spec.kind() == "import_spec" { - handle_spec(self, spec); - } + for spec in list.named_children(&mut list.walk()) { + if spec.kind() == "import_spec" { + handle_spec(self, spec); } } } else { @@ -1079,10 +1067,8 @@ impl<'t> Walker<'t> { return; } let qualified = node.kind() == "qualified_type"; - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.collect_type_names(c, declared, qualified, out); - } + for c in node.named_children(&mut node.walk()) { + self.collect_type_names(c, declared, qualified, out); } } @@ -1093,8 +1079,7 @@ impl<'t> Walker<'t> { fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) { stack_guard!(); let extends_kind = edge_kind_index("extends").unwrap(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { match child.kind() { "type_elem" => { let mut terms = (0..child.named_child_count()) @@ -1153,10 +1138,8 @@ impl<'t> Walker<'t> { } return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.extract_type_refs_from_subtree(c, from_row); - } + for c in node.named_children(&mut node.walk()) { + self.extract_type_refs_from_subtree(c, from_row); } } @@ -1180,10 +1163,8 @@ impl<'t> Walker<'t> { let mut values: Vec = Vec::new(); match mode { "args" | "list" => { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - values.push(c); - } + for c in node.named_children(&mut node.walk()) { + values.push(c); } } "rhs" => { @@ -1281,22 +1262,22 @@ impl<'t> Walker<'t> { }); } "literal_element" | "expression_list" => { - for i in 0..v.named_child_count() { - if let Some(c) = v.named_child(i) { - self.normalize_fn_ref_value(c, from, depth + 1, container); - } + for c in v.named_children(&mut v.walk()) { + self.normalize_fn_ref_value(c, from, depth + 1, container); } } _ => {} } } - fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &[usize]) { + fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &HashSet) { stack_guard!(); if depth > 12 { return; } - // Subtrees the body walker has already been through. + // Subtrees the body walker has already been through. A set: looked up + // for every node of the subtree, the list of a `const (…)` block of some + // thousand names was read through each time. if walked.contains(&node.id()) { return; } @@ -1310,10 +1291,8 @@ impl<'t> Walker<'t> { return; } self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.scan_fn_ref_subtree(c, depth + 1, walked); - } + for c in node.named_children(&mut node.walk()) { + self.scan_fn_ref_subtree(c, depth + 1, walked); } } @@ -1408,10 +1387,8 @@ impl<'t> Walker<'t> { } _ => {} } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -1460,10 +1437,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } @@ -1620,8 +1595,7 @@ fn go_local_bindings<'t>(units: &[Node<'t>], names: &HashSet<&str>, src: &str) - if list.kind() != "parameter_list" { continue; } - for i in 0..list.named_child_count() { - let Some(p) = list.named_child(i) else { continue }; + for p in list.named_children(&mut list.walk()) { if !matches!(p.kind(), "parameter_declaration" | "variadic_parameter_declaration") { continue; } diff --git a/codegraph-kernel/src/java.rs b/codegraph-kernel/src/java.rs index 9e03a066af..f2c6e26b3a 100644 --- a/codegraph-kernel/src/java.rs +++ b/codegraph-kernel/src/java.rs @@ -126,7 +126,7 @@ struct Cand { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -211,8 +211,7 @@ pub fn extract(file_path: &str, source: &str) -> Result { // carrying the package FQN. let root = tree.root_node(); let mut pkg_pushed = false; - for i in 0..root.named_child_count() { - let Some(child) = root.named_child(i) else { continue }; + for child in root.named_children(&mut root.walk()) { if child.kind() != "package_declaration" { continue; } @@ -431,11 +430,9 @@ impl<'t> Walker<'t> { if node.kind() == "constant_declaration" { return true; } - for i in 0..node.child_count() { - if let Some(child) = node.child(i) { - if child.kind() == "modifiers" && self.text(child).contains("static") { - return true; - } + for child in node.children(&mut node.walk()) { + if child.kind() == "modifiers" && self.text(child).contains("static") { + return true; } } false @@ -446,12 +443,10 @@ impl<'t> Walker<'t> { if node.kind() == "constant_declaration" { return true; } - for i in 0..node.child_count() { - if let Some(child) = node.child(i) { - if child.kind() == "modifiers" { - let text = self.text(child); - return word_re("static").is_match(text) && word_re("final").is_match(text); - } + for child in node.children(&mut node.walk()) { + if child.kind() == "modifiers" { + let text = self.text(child); + return word_re("static").is_match(text) && word_re("final").is_match(text); } } false @@ -484,11 +479,9 @@ impl<'t> Walker<'t> { if let Some(name_node) = node.child_by_field_name("name") { return self.text(name_node).to_string(); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { - return self.text(c).to_string(); - } + for c in node.named_children(&mut node.walk()) { + if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { + return self.text(c).to_string(); } } "".to_string() @@ -519,11 +512,11 @@ impl<'t> Walker<'t> { // The initializers extract_field walked under their fields took // their own candidates; the scan covers the rest. let walked = self.extract_field(node); - self.scan_fn_ref_subtree(node, 0, &walked); + self.scan_fn_ref_subtree(node, 0, &walked.into_iter().collect()); skip_children = true; } else if kind == "local_variable_declaration" && !self.inside_class_like() { self.extract_variable(node); - self.scan_fn_ref_subtree(node, 0, &[]); + self.scan_fn_ref_subtree(node, 0, &HashSet::new()); skip_children = true; } else if kind == "import_declaration" { self.extract_import(node); @@ -538,10 +531,8 @@ impl<'t> Walker<'t> { } if !skip_children { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } } } @@ -584,10 +575,8 @@ impl<'t> Walker<'t> { return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_for_calls_and_structure(c); } } @@ -607,10 +596,8 @@ impl<'t> Walker<'t> { self.stack.push(Scope { row, kind: "class", name }); let body = node.child_by_field_name("body").unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } // synthesizeJavaMembers — class still on the stack: record // components first, then Lombok (#912). @@ -687,10 +674,8 @@ impl<'t> Walker<'t> { self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "interface", name }); let body = node.child_by_field_name("body").unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -707,8 +692,7 @@ impl<'t> Walker<'t> { let Some(row) = self.create_node("enum", &name, node, extra) else { return }; self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "enum", name }); - for i in 0..body.named_child_count() { - let Some(child) = body.named_child(i) else { continue }; + for child in body.named_children(&mut body.walk()) { if child.kind() == "enum_constant" { let member = self.extract_enum_members(child); self.visit_enum_constant_body(child, member); @@ -733,10 +717,8 @@ impl<'t> Walker<'t> { let Some((row, name)) = member else { return }; let Some(body) = (0..node.named_child_count()).filter_map(|i| node.named_child(i)).find(|c| c.kind() == "class_body") else { return }; self.stack.push(Scope { row, kind: "enum_member", name }); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -831,8 +813,7 @@ impl<'t> Walker<'t> { fn extract_variable(&mut self, node: Node<'t>) { let kind: &'static str = if self.is_const(node) { "constant" } else { "variable" }; let docstring = preceding_docstring(node, self.src); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { let name = match child.kind() { "identifier" => self.text(child).to_string(), "variable_declarator" => self.extract_name(child), @@ -996,10 +977,8 @@ impl<'t> Walker<'t> { self.push_ref(row, &written, edge_kind_index("extends").unwrap(), line, column); self.stack.push(Scope { row, kind: "class", name: anon_name }); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -1048,8 +1027,7 @@ impl<'t> Walker<'t> { fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) { let extends_kind = edge_kind_index("extends").unwrap(); let implements_kind = edge_kind_index("implements").unwrap(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { match child.kind() { "superclass" | "extends_interfaces" => { let type_list = (0..child.named_child_count()) @@ -1098,43 +1076,26 @@ impl<'t> Walker<'t> { /// extractDecoratorsFor — Java annotations live inside `modifiers`. fn extract_decorators_for(&mut self, decl: Node<'t>, decorated_row: u32) { - for i in 0..decl.named_child_count() { - let Some(child) = decl.named_child(i) else { continue }; + for child in decl.named_children(&mut decl.walk()) { self.consider_decorator(child, decorated_row); if child.kind() == "modifiers" { - for j in 0..child.named_child_count() { - if let Some(m) = child.named_child(j) { - self.consider_decorator(m, decorated_row); - } + for m in child.named_children(&mut child.walk()) { + self.consider_decorator(m, decorated_row); } } } // Preceding-sibling scan (TS-style class decorators) — Java annotations // are inside modifiers, so this is inert here; kept for parity of shape. - let Some(parent) = decl.parent() else { return }; - let decl_start = decl.start_byte(); - let mut decl_idx: isize = -1; - for i in 0..parent.named_child_count() { - if let Some(sib) = parent.named_child(i) { - if sib.start_byte() == decl_start { - decl_idx = i as isize; - break; - } - } - } - if decl_idx > 0 { - let mut j = decl_idx - 1; - while j >= 0 { - let Some(sib) = parent.named_child(j as usize) else { - j -= 1; - continue; - }; - if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { - break; - } - self.consider_decorator(sib, decorated_row); - j -= 1; + // Walked back from the declaration itself. Finding its place first, by counting the + // parent's children from the start, cost each declaration as much as it has + // siblings before it: a file of twenty thousand took minutes. + let mut sibling = decl.prev_named_sibling(); + while let Some(sib) = sibling { + if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { + break; } + self.consider_decorator(sib, decorated_row); + sibling = sib.prev_named_sibling(); } } @@ -1143,8 +1104,7 @@ impl<'t> Walker<'t> { return; } let mut target: Option = None; - for i in 0..n.named_child_count() { - let Some(child) = n.named_child(i) else { continue }; + for child in n.named_children(&mut n.walk()) { if child.kind() == "call_expression" { target = child.child_by_field_name("function").or_else(|| child.named_child(0)); if target.is_some() { @@ -1193,10 +1153,8 @@ impl<'t> Walker<'t> { } return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.extract_type_refs_from_subtree(c, from_row); - } + for c in node.named_children(&mut node.walk()) { + self.extract_type_refs_from_subtree(c, from_row); } } @@ -1217,10 +1175,8 @@ impl<'t> Walker<'t> { let mut values: Vec = Vec::new(); if field.is_empty() { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - values.push(c); - } + for c in node.named_children(&mut node.walk()) { + values.push(c); } } else if field == "right" { if let Some(rhs) = node.child_by_field_name("right") { @@ -1246,11 +1202,9 @@ impl<'t> Walker<'t> { continue; // idTypes is EMPTY for Java — only method references } let mut last_ident: Option = None; - for i in 0..v.named_child_count() { - if let Some(c) = v.named_child(i) { - if c.kind() == "identifier" { - last_ident = Some(c); - } + for c in v.named_children(&mut v.walk()) { + if c.kind() == "identifier" { + last_ident = Some(c); } } let Some(last) = last_ident else { continue }; @@ -1277,7 +1231,7 @@ impl<'t> Walker<'t> { } } - fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &[usize]) { + fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &HashSet) { stack_guard!(); if depth > 12 { return; @@ -1291,10 +1245,8 @@ impl<'t> Walker<'t> { return; } self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.scan_fn_ref_subtree(c, depth + 1, walked); - } + for c in node.named_children(&mut node.walk()) { + self.scan_fn_ref_subtree(c, depth + 1, walked); } } @@ -1382,10 +1334,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -1436,10 +1386,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } @@ -1450,8 +1398,7 @@ impl<'t> Walker<'t> { fn lombok_annotation_names(&self, node: Node<'t>) -> HashSet { let mut names = HashSet::new(); let Some(modifiers) = self.modifiers_child(node) else { return names }; - for i in 0..modifiers.named_child_count() { - let Some(child) = modifiers.named_child(i) else { continue }; + for child in modifiers.named_children(&mut modifiers.walk()) { if matches!(child.kind(), "marker_annotation" | "annotation") { if let Some(name_node) = child.child_by_field_name("name") { if let Some(simple) = self.text(name_node).trim().rsplit('.').next() { @@ -1492,8 +1439,7 @@ impl<'t> Walker<'t> { fn synthesize_record_components(&mut self, record_node: Node<'t>, record_row: u32) { let Some(params) = record_node.child_by_field_name("parameters") else { return }; let (mut taken_methods, mut taken_fields) = self.declared_member_names(record_row); - for i in 0..params.named_child_count() { - let Some(param) = params.named_child(i) else { continue }; + for param in params.named_children(&mut params.walk()) { if param.kind() != "formal_parameter" { continue; } @@ -1625,8 +1571,7 @@ impl<'t> Walker<'t> { let is_boolean_primitive = type_node.map(|t| t.kind() == "boolean_type").unwrap_or(false); let return_type = self.normalize_java_type(type_node); - for i in 0..fd.named_child_count() { - let Some(vd) = fd.named_child(i) else { continue }; + for vd in fd.named_children(&mut fd.walk()) { if vd.kind() != "variable_declarator" { continue; } @@ -1720,11 +1665,9 @@ impl<'t> Walker<'t> { } fn find_anonymous_class_body(node: Node) -> Option { - for i in 0..node.named_child_count() { - if let Some(child) = node.named_child(i) { - if matches!(child.kind(), "class_body" | "declaration_list") { - return Some(child); - } + for child in node.named_children(&mut node.walk()) { + if matches!(child.kind(), "class_body" | "declaration_list") { + return Some(child); } } None diff --git a/codegraph-kernel/src/kotlin.rs b/codegraph-kernel/src/kotlin.rs index b5cdf68717..70c6685fe0 100644 --- a/codegraph-kernel/src/kotlin.rs +++ b/codegraph-kernel/src/kotlin.rs @@ -123,8 +123,7 @@ fn kotlin_receiver_chain(text: &str) -> Option { fn property_initializers<'t>(node: Node<'t>) -> Vec> { let mut out: Vec> = Vec::new(); let mut after_eq = false; - for i in 0..node.child_count() { - let Some(c) = node.child(i) else { continue }; + for c in node.children(&mut node.walk()) { if !c.is_named() { if c.kind() == "=" { after_eq = true; @@ -160,8 +159,7 @@ fn accessor_owner<'t>(node: Node<'t>) -> Option> { /// The named child right after the first `token` child of `node`, if any. fn named_child_after<'t>(node: Node<'t>, token: &str) -> Option> { let mut seen = false; - for i in 0..node.child_count() { - let Some(c) = node.child(i) else { continue }; + for c in node.children(&mut node.walk()) { if !c.is_named() { if c.kind() == token { seen = true; @@ -183,12 +181,10 @@ fn named_child_after<'t>(node: Node<'t>, token: &str) -> Option> { /// before the body; the types and annotations around it are left alone. fn class_header_code<'t>(node: Node<'t>) -> Vec> { let mut out: Vec> = Vec::new(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { match child.kind() { "primary_constructor" => { - for j in 0..child.named_child_count() { - let Some(param) = child.named_child(j) else { continue }; + for param in child.named_children(&mut child.walk()) { if param.kind() != "class_parameter" { continue; } @@ -275,7 +271,7 @@ struct Cand { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -356,8 +352,7 @@ pub fn extract(file_path: &str, source: &str) -> Result { // the whole walk. let root = tree.root_node(); let mut pkg_pushed = false; - for i in 0..root.named_child_count() { - let Some(child) = root.named_child(i) else { continue }; + for child in root.named_children(&mut root.walk()) { if child.kind() != "package_header" { continue; } @@ -446,8 +441,7 @@ impl<'t> Walker<'t> { /// (fun-interface parent body — unreachable post-defer, kept for /// contract), else first function_body | class_body | enum_class_body. fn resolve_body(&self, node: Node<'t>) -> Option> { - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "ERROR" { if let Some(first) = child.child(0) { if first.kind() == "{" { @@ -593,11 +587,9 @@ impl<'t> Walker<'t> { // (mirrored for shape; the grammar has zero fields). return self.text(name_node).to_string(); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { - return self.text(c).to_string(); - } + for c in node.named_children(&mut node.walk()) { + if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { + return self.text(c).to_string(); } } "".to_string() @@ -607,8 +599,7 @@ impl<'t> Walker<'t> { /// internal in that order; default PUBLIC. Text-includes semantics — /// annotation text inside modifiers can flip it (bug-for-bug). fn visibility_of(&self, node: Node) -> u8 { - for i in 0..node.child_count() { - let Some(child) = node.child(i) else { continue }; + for child in node.children(&mut node.walk()) { if child.kind() == "modifiers" { let text = self.text(child); if text.contains("public") { @@ -643,8 +634,7 @@ impl<'t> Walker<'t> { fn signature_of(&self, node: Node) -> Option { let mut params: Option = None; let mut return_type: Option = None; - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "function_value_parameters" { params = Some(child); continue; @@ -674,8 +664,7 @@ impl<'t> Walker<'t> { /// None; Unit/Nothing → None; `: T` generic params leak (preserve). fn return_type_of(&self, node: Node) -> Option { let mut seen_params = false; - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "function_value_parameters" { seen_params = true; continue; @@ -716,8 +705,7 @@ impl<'t> Walker<'t> { /// type_identifier's text (qualified receivers take the FIRST segment — /// the `com::qext` bug, preserve). fn receiver_type_of(&self, node: Node<'t>) -> Option { - for i in 0..node.child_count() { - let Some(child) = node.child(i) else { continue }; + for child in node.children(&mut node.walk()) { match child.kind() { "receiver_type" => { let ut = (0..child.named_child_count()) @@ -739,18 +727,15 @@ impl<'t> Walker<'t> { /// TYPE (never text), in order. Runs inside create_node for every node. fn extract_modifiers(&self, node: Node) -> Option> { let mut mods: Vec = Vec::new(); - for i in 0..node.child_count() { - let Some(child) = node.child(i) else { continue }; + for child in node.children(&mut node.walk()) { if child.kind() != "modifiers" { continue; } - for j in 0..child.child_count() { - let Some(pm) = child.child(j) else { continue }; + for pm in child.children(&mut child.walk()) { if pm.kind() != "platform_modifier" { continue; } - for k in 0..pm.child_count() { - let Some(kw) = pm.child(k) else { continue }; + for kw in pm.children(&mut pm.walk()) { if matches!(kw.kind(), "expect" | "actual") { mods.push(kw.kind().to_string()); } @@ -902,7 +887,7 @@ impl<'t> Walker<'t> { fn visit_node(&mut self, node: Node<'t>) { stack_guard!(); if let Some(walked) = self.try_visit_hook(node) { - self.scan_fn_ref_subtree(node, 0, &walked); + self.scan_fn_ref_subtree(node, 0, &walked.into_iter().collect()); return; } @@ -921,16 +906,14 @@ impl<'t> Walker<'t> { } else if kind == "class_declaration" { // classifyClassNode: `interface`/`enum` keyword children. let mut classified = "class"; - for i in 0..node.child_count() { - if let Some(c) = node.child(i) { - if c.kind() == "interface" { - classified = "interface"; - break; - } - if c.kind() == "enum" { - classified = "enum"; - break; - } + for c in node.children(&mut node.walk()) { + if c.kind() == "interface" { + classified = "interface"; + break; + } + if c.kind() == "enum" { + classified = "enum"; + break; } } match classified { @@ -949,7 +932,7 @@ impl<'t> Walker<'t> { // Hook-declined destructuring: extractField/extractVariable both // find no matching children for kotlin — NOTHING minted, RHS // invisible; candidates-only scan. - self.scan_fn_ref_subtree(node, 0, &[]); + self.scan_fn_ref_subtree(node, 0, &HashSet::new()); skip_children = true; } else if kind == "import_header" { self.extract_import(node); @@ -968,10 +951,8 @@ impl<'t> Walker<'t> { // branch — recursed (calls attribute to the stack top). if !skip_children { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } } } @@ -1014,16 +995,14 @@ impl<'t> Walker<'t> { } if kind == "class_declaration" { let mut classified = "class"; - for i in 0..node.child_count() { - if let Some(c) = node.child(i) { - if c.kind() == "interface" { - classified = "interface"; - break; - } - if c.kind() == "enum" { - classified = "enum"; - break; - } + for c in node.children(&mut node.walk()) { + if c.kind() == "interface" { + classified = "interface"; + break; + } + if c.kind() == "enum" { + classified = "enum"; + break; } } match classified { @@ -1037,10 +1016,8 @@ impl<'t> Walker<'t> { // `fun`s hit the function branch above and leak out as FUNCTIONS // under the enclosing fn; its properties mint nothing (quirk). - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_for_calls_and_structure(c); } } @@ -1157,10 +1134,8 @@ impl<'t> Walker<'t> { } } let body = resolved_body.unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -1176,10 +1151,8 @@ impl<'t> Walker<'t> { self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "interface", name }); let body = self.resolve_body(node).unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -1200,8 +1173,7 @@ impl<'t> Walker<'t> { for code in class_header_code(node) { self.visit_node(code); } - for i in 0..body.named_child_count() { - let Some(child) = body.named_child(i) else { continue }; + for child in body.named_children(&mut body.walk()) { if child.kind() == "enum_entry" { let member = self.extract_enum_members(child); self.visit_enum_entry_body(child, member); @@ -1217,8 +1189,7 @@ impl<'t> Walker<'t> { // enum_member per direct simple_identifier, positioned AT the // identifier. Entry value_arguments are never visited. let mut first: Option<(u32, String)> = None; - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if matches!(child.kind(), "simple_identifier" | "identifier" | "property_identifier") { let name = self.text(child).to_string(); let row = self.create_node("enum_member", &name, child, Extra::default()); @@ -1236,10 +1207,8 @@ impl<'t> Walker<'t> { let Some((row, name)) = member else { return }; let Some(body) = (0..node.named_child_count()).filter_map(|i| node.named_child(i)).find(|c| c.kind() == "class_body") else { return }; self.stack.push(Scope { row, kind: "enum_member", name }); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -1450,8 +1419,7 @@ impl<'t> Walker<'t> { /// delegation names no class and emits nothing). fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) { let extends_kind = edge_kind_index("extends").unwrap(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() != "delegation_specifier" { continue; } @@ -1564,13 +1532,11 @@ impl<'t> Walker<'t> { } let anon_name = format!("<{short_name}$anon@{}>", node.start_position().row + 1); let Some(row) = self.create_node("class", &anon_name, node, Extra::default()) else { - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - if body_walker { - self.visit_for_calls_and_structure(c); - } else { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + if body_walker { + self.visit_for_calls_and_structure(c); + } else { + self.visit_node(c); } } return true; @@ -1581,10 +1547,8 @@ impl<'t> Walker<'t> { self.push_ref_at(row, name, extends_kind, at); } self.stack.push(Scope { row, kind: "class", name: anon_name }); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); true @@ -1595,41 +1559,24 @@ impl<'t> Walker<'t> { /// (constructor_invocation) → NOTHING. Runs for functions/methods/classes /// only (hook properties never call it). fn extract_decorators_for(&mut self, decl: Node<'t>, decorated_row: u32) { - for i in 0..decl.named_child_count() { - let Some(child) = decl.named_child(i) else { continue }; + for child in decl.named_children(&mut decl.walk()) { self.consider_decorator(child, decorated_row); if child.kind() == "modifiers" { - for j in 0..child.named_child_count() { - if let Some(m) = child.named_child(j) { - self.consider_decorator(m, decorated_row); - } - } - } - } - let Some(parent) = decl.parent() else { return }; - let decl_start = decl.start_byte(); - let mut decl_idx: isize = -1; - for i in 0..parent.named_child_count() { - if let Some(sib) = parent.named_child(i) { - if sib.start_byte() == decl_start { - decl_idx = i as isize; - break; + for m in child.named_children(&mut child.walk()) { + self.consider_decorator(m, decorated_row); } } } - if decl_idx > 0 { - let mut j = decl_idx - 1; - while j >= 0 { - let Some(sib) = parent.named_child(j as usize) else { - j -= 1; - continue; - }; - if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { - break; - } - self.consider_decorator(sib, decorated_row); - j -= 1; + // Walked back from the declaration itself. Finding its place first, by counting the + // parent's children from the start, cost each declaration as much as it has + // siblings before it: a file of twenty thousand took minutes. + let mut sibling = decl.prev_named_sibling(); + while let Some(sib) = sibling { + if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { + break; } + self.consider_decorator(sib, decorated_row); + sibling = sib.prev_named_sibling(); } } @@ -1638,8 +1585,7 @@ impl<'t> Walker<'t> { return; } let mut target: Option = None; - for i in 0..n.named_child_count() { - let Some(child) = n.named_child(i) else { continue }; + for child in n.named_children(&mut n.walk()) { if child.kind() == "call_expression" { target = child.child_by_field_name("function").or_else(|| child.named_child(0)); if target.is_some() { @@ -1683,10 +1629,8 @@ impl<'t> Walker<'t> { let mut values: Vec = Vec::new(); match mode { Mode::Args => { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - values.push(c); - } + for c in node.named_children(&mut node.walk()) { + values.push(c); } } Mode::Rhs => { @@ -1730,10 +1674,8 @@ impl<'t> Walker<'t> { // value_argument layer with NO field resolution (zero fields) — // the label-forward skip is DEAD for kotlin; fan out namedChildren. "value_argument" => { - for i in 0..v.named_child_count() { - if let Some(c) = v.named_child(i) { - self.normalize_fn_ref_value(c, from, depth + 1); - } + for c in v.named_children(&mut v.walk()) { + self.normalize_fn_ref_value(c, from, depth + 1); } } // `::topLevel` / `OtherClass::handle` — receiver = LAST @@ -1743,8 +1685,7 @@ impl<'t> Walker<'t> { "callable_reference" => { let mut receiver: Option = None; let mut member: Option = None; - for i in 0..v.named_child_count() { - let Some(child) = v.named_child(i) else { continue }; + for child in v.named_children(&mut v.walk()) { if child.kind() == "type_identifier" { receiver = Some(child); } @@ -1770,8 +1711,7 @@ impl<'t> Walker<'t> { if !self.text(v).starts_with("this::") { return; } - for i in 0..v.named_child_count() { - let Some(child) = v.named_child(i) else { continue }; + for child in v.named_children(&mut v.walk()) { if child.kind() == "navigation_suffix" && self.text(child).starts_with("::") { if child.named_child_count() > 0 { if let Some(id) = child.named_child(child.named_child_count() - 1) { @@ -1801,7 +1741,7 @@ impl<'t> Walker<'t> { }); } - fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &[usize]) { + fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &HashSet) { stack_guard!(); if depth > 12 { return; @@ -1823,10 +1763,8 @@ impl<'t> Walker<'t> { return; } self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.scan_fn_ref_subtree(c, depth + 1, walked); - } + for c in node.named_children(&mut node.walk()) { + self.scan_fn_ref_subtree(c, depth + 1, walked); } } @@ -1898,8 +1836,7 @@ impl<'t> Walker<'t> { *decl_counts.entry(nm).or_insert(0) += 1; } } else { - for i in 0..left.named_child_count() { - let Some(c) = left.named_child(i) else { continue }; + for c in left.named_children(&mut left.walk()) { if matches!(c.kind(), "identifier" | "simple_identifier") { let nm = self.text(c); if targets.contains_key(nm) { @@ -1928,10 +1865,8 @@ impl<'t> Walker<'t> { // (the Swift name-field half of the shared case is a null // path for kotlin — variable_declaration always present) } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -1983,10 +1918,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } diff --git a/codegraph-kernel/src/lua.rs b/codegraph-kernel/src/lua.rs index 186fafef29..6ea9bf4f47 100644 --- a/codegraph-kernel/src/lua.rs +++ b/codegraph-kernel/src/lua.rs @@ -73,7 +73,7 @@ pub struct Walker<'t> { src: &'t str, file_path: &'t str, is_luau: bool, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, diff --git a/codegraph-kernel/src/php.rs b/codegraph-kernel/src/php.rs index 807f5b8ad1..c9ccad5a87 100644 --- a/codegraph-kernel/src/php.rs +++ b/codegraph-kernel/src/php.rs @@ -140,7 +140,7 @@ struct Cand { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -224,8 +224,7 @@ pub fn extract(file_path: &str, source: &str) -> Result { // pushed for the whole walk — QNs become `App\Services::Name` and import // nodes/refs hang off it. let mut pkg_pushed = false; - for i in 0..root.named_child_count() { - let Some(child) = root.named_child(i) else { continue }; + for child in root.named_children(&mut root.walk()) { if child.kind() != "namespace_definition" { continue; } @@ -415,11 +414,9 @@ impl<'t> Walker<'t> { if let Some(name_node) = node.child_by_field_name("name") { return self.text(name_node).to_string(); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { - return self.text(c).to_string(); - } + for c in node.named_children(&mut node.walk()) { + if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { + return self.text(c).to_string(); } } "".to_string() @@ -430,8 +427,7 @@ impl<'t> Walker<'t> { /// getVisibility: any `visibility_modifier` child with one of the three /// texts; none → public (the php default). fn visibility_of(&self, node: Node) -> u8 { - for i in 0..node.child_count() { - let Some(child) = node.child(i) else { continue }; + for child in node.children(&mut node.walk()) { if child.kind() == "visibility_modifier" { match self.text(child) { "public" => return 1, @@ -606,10 +602,8 @@ impl<'t> Walker<'t> { // match / attributes: no branch — children visited. if !skip_children { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } } } @@ -682,10 +676,8 @@ impl<'t> Walker<'t> { return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_for_calls_and_structure(c); } } @@ -751,10 +743,8 @@ impl<'t> Walker<'t> { // decorators: none. self.stack.push(Scope { row, kind, name }); let body = node.child_by_field_name("body").unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -770,10 +760,8 @@ impl<'t> Walker<'t> { self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "interface", name }); let body = node.child_by_field_name("body").unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -792,8 +780,7 @@ impl<'t> Walker<'t> { // read (it's not in a base_clause). self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "enum", name }); - for i in 0..body.named_child_count() { - let Some(child) = body.named_child(i) else { continue }; + for child in body.named_children(&mut body.walk()) { if child.kind() == "enum_case" { self.extract_enum_members(child); } else { @@ -1014,8 +1001,7 @@ impl<'t> Walker<'t> { return None; } let mut content: Option = None; - for i in 0..arg.named_child_count() { - let Some(c) = arg.named_child(i) else { continue }; + for c in arg.named_children(&mut arg.walk()) { if c.kind() != "string_content" { return None; } @@ -1270,10 +1256,8 @@ impl<'t> Walker<'t> { }; self.push_ref(row, &type_name, edge_kind_index("extends").unwrap(), line, column); self.stack.push(Scope { row, kind: "class", name: anon_name }); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -1332,16 +1316,14 @@ impl<'t> Walker<'t> { fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) { let extends_kind = edge_kind_index("extends").unwrap(); let implements_kind = edge_kind_index("implements").unwrap(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "base_clause" { if let Some(target) = child.named_child(0) { let name = self.text(target).to_string(); self.push_ref_at(class_row, &name, extends_kind, target); } } else if child.kind() == "class_interface_clause" { - for j in 0..child.named_child_count() { - let Some(iface) = child.named_child(j) else { continue }; + for iface in child.named_children(&mut child.walk()) { let name = self.text(iface).to_string(); self.push_ref_at(class_row, &name, implements_kind, iface); } @@ -1356,18 +1338,15 @@ impl<'t> Walker<'t> { .filter_map(|i| node.named_child(i)) .find(|c| c.kind() == "formal_parameters"); if let Some(params) = params { - for i in 0..params.named_child_count() { - let Some(p) = params.named_child(i) else { continue }; - for j in 0..p.named_child_count() { - let Some(c) = p.named_child(j) else { continue }; + for p in params.named_children(&mut params.walk()) { + for c in p.named_children(&mut p.walk()) { if is_php_type_node(c.kind()) { self.walk_php_type_position(c, from_row); } } } } - for i in 0..node.named_child_count() { - let Some(c) = node.named_child(i) else { continue }; + for c in node.named_children(&mut node.walk()) { if is_php_type_node(c.kind()) { self.walk_php_type_position(c, from_row); } @@ -1392,10 +1371,8 @@ impl<'t> Walker<'t> { } } _ => { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.walk_php_type_position(c, from_row); - } + for c in node.named_children(&mut node.walk()) { + self.walk_php_type_position(c, from_row); } } } @@ -1411,10 +1388,8 @@ impl<'t> Walker<'t> { return; } let from = self.top_row(); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.normalize_fn_ref_value(c, from, 0); - } + for c in node.named_children(&mut node.walk()) { + self.normalize_fn_ref_value(c, from, 0); } } @@ -1425,10 +1400,8 @@ impl<'t> Walker<'t> { } match v.kind() { "argument" => { - for i in 0..v.named_child_count() { - if let Some(c) = v.named_child(i) { - self.normalize_fn_ref_value(c, from, depth + 1); - } + for c in v.named_children(&mut v.walk()) { + self.normalize_fn_ref_value(c, from, depth + 1); } } // String callable — trustworthy ONLY as an argument to a known @@ -1483,8 +1456,7 @@ impl<'t> Walker<'t> { /// phpStringContent: the string's first string_content child, trimmed. fn php_string_content(&self, node: Node) -> Option { - for i in 0..node.named_child_count() { - let Some(c) = node.named_child(i) else { continue }; + for c in node.named_children(&mut node.walk()) { if c.kind() == "string_content" { return Some(self.text(c).trim().to_string()); } @@ -1525,10 +1497,8 @@ impl<'t> Walker<'t> { return; } self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.scan_fn_ref_subtree(c, depth + 1); - } + for c in node.named_children(&mut node.walk()) { + self.scan_fn_ref_subtree(c, depth + 1); } } @@ -1624,10 +1594,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } @@ -1790,11 +1758,9 @@ fn php_use_shadows_dirname(raw: &str) -> bool { } fn find_anonymous_class_body(node: Node) -> Option { - for i in 0..node.named_child_count() { - if let Some(child) = node.named_child(i) { - if matches!(child.kind(), "class_body" | "declaration_list") { - return Some(child); - } + for child in node.named_children(&mut node.walk()) { + if matches!(child.kind(), "class_body" | "declaration_list") { + return Some(child); } } None diff --git a/codegraph-kernel/src/python.rs b/codegraph-kernel/src/python.rs index 0275927f11..1570a689dd 100644 --- a/codegraph-kernel/src/python.rs +++ b/codegraph-kernel/src/python.rs @@ -140,7 +140,7 @@ struct Cand { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -372,11 +372,9 @@ impl<'t> Walker<'t> { if let Some(name_node) = node.child_by_field_name("name") { return self.text(name_node).to_string(); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { - return self.text(c).to_string(); - } + for c in node.named_children(&mut node.walk()) { + if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { + return self.text(c).to_string(); } } "".to_string() @@ -432,7 +430,7 @@ impl<'t> Walker<'t> { // The right-hand side extract_variable walked under the assigned // name took its own candidates; the scan covers the rest. let walked = self.extract_variable(node); - self.scan_fn_ref_subtree(node, 0, &walked); + self.scan_fn_ref_subtree(node, 0, &walked.into_iter().collect()); skip_children = true; } else if kind == "import_statement" || kind == "import_from_statement" { self.extract_import(node); @@ -441,10 +439,8 @@ impl<'t> Walker<'t> { } if !skip_children { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } } } @@ -476,10 +472,8 @@ impl<'t> Walker<'t> { return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_for_calls_and_structure(c); } } @@ -541,11 +535,9 @@ impl<'t> Walker<'t> { // A parameterized base, `class Leaf(Base[str])`, is a `subscript` // whose value names the class. let extends_kind = edge_kind_index("extends").unwrap(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "argument_list" { - for j in 0..child.named_child_count() { - let Some(base) = child.named_child(j) else { continue }; + for base in child.named_children(&mut child.walk()) { let arg = if base.kind() == "subscript" { let Some(value) = base.child_by_field_name("value") else { continue }; value @@ -563,10 +555,8 @@ impl<'t> Walker<'t> { self.stack.push(Scope { row, kind: "class", name }); let body = node.child_by_field_name("body").unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -636,8 +626,7 @@ impl<'t> Walker<'t> { self.push_ref_at(parent, &module_name.clone(), imports_kind, node); // emitPyFromImportRefs: one `imports` ref per imported name. - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.start_byte() == module_node.start_byte() && child.end_byte() == module_node.end_byte() { @@ -668,8 +657,7 @@ impl<'t> Walker<'t> { // import_statement: `import a.b, x as y` — one import node + module ref // per dotted name (the python multi-import branch). let parent = self.top_row(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "dotted_name" { let name = self.text(child).to_string(); self.create_node( @@ -807,35 +795,19 @@ impl<'t> Walker<'t> { /// (python's `call` kind isn't `call_expression`, and `attribute` isn't in /// the target-kind list — mirrored exactly). fn extract_decorators_for(&mut self, decl: Node<'t>, decorated_row: u32) { - for i in 0..decl.named_child_count() { - if let Some(child) = decl.named_child(i) { - self.consider_decorator(child, decorated_row); - } - } - let Some(parent) = decl.parent() else { return }; - let decl_start = decl.start_byte(); - let mut decl_idx: isize = -1; - for i in 0..parent.named_child_count() { - if let Some(sib) = parent.named_child(i) { - if sib.start_byte() == decl_start { - decl_idx = i as isize; - break; - } - } + for child in decl.named_children(&mut decl.walk()) { + self.consider_decorator(child, decorated_row); } - if decl_idx > 0 { - let mut j = decl_idx - 1; - while j >= 0 { - let Some(sib) = parent.named_child(j as usize) else { - j -= 1; - continue; - }; - if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { - break; - } - self.consider_decorator(sib, decorated_row); - j -= 1; + // Walked back from the declaration itself. Finding its place first, by counting the + // parent's children from the start, cost each declaration as much as it has + // siblings before it: a file of twenty thousand took minutes. + let mut sibling = decl.prev_named_sibling(); + while let Some(sib) = sibling { + if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { + break; } + self.consider_decorator(sib, decorated_row); + sibling = sib.prev_named_sibling(); } } @@ -844,8 +816,7 @@ impl<'t> Walker<'t> { return; } let mut target: Option = None; - for i in 0..n.named_child_count() { - let Some(child) = n.named_child(i) else { continue }; + for child in n.named_children(&mut n.walk()) { if child.kind() == "call_expression" { target = child.child_by_field_name("function").or_else(|| child.named_child(0)); if target.is_some() { @@ -910,10 +881,8 @@ impl<'t> Walker<'t> { let mut values: Vec = Vec::new(); match mode { "args" | "list" => { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - values.push(c); - } + for c in node.named_children(&mut node.walk()) { + values.push(c); } } "rhs" => { @@ -968,7 +937,7 @@ impl<'t> Walker<'t> { } } - fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &[usize]) { + fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &HashSet) { stack_guard!(); if depth > 12 { return; @@ -989,10 +958,8 @@ impl<'t> Walker<'t> { return; } self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.scan_fn_ref_subtree(c, depth + 1, walked); - } + for c in node.named_children(&mut node.walk()) { + self.scan_fn_ref_subtree(c, depth + 1, walked); } } @@ -1062,23 +1029,19 @@ impl<'t> Walker<'t> { *decl_counts.entry(nm).or_insert(0) += 1; } } else { - for i in 0..left.named_child_count() { - if let Some(c) = left.named_child(i) { - if c.kind() == "identifier" { - let nm = self.text(c); - if targets.contains_key(nm) { - *decl_counts.entry(nm).or_insert(0) += 1; - } + for c in left.named_children(&mut left.walk()) { + if c.kind() == "identifier" { + let nm = self.text(c); + if targets.contains_key(nm) { + *decl_counts.entry(nm).or_insert(0) += 1; } } } } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -1127,10 +1090,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } diff --git a/codegraph-kernel/src/rlang.rs b/codegraph-kernel/src/rlang.rs index 13a24f6247..047f63527e 100644 --- a/codegraph-kernel/src/rlang.rs +++ b/codegraph-kernel/src/rlang.rs @@ -67,7 +67,7 @@ struct Scope { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, diff --git a/codegraph-kernel/src/ruby.rs b/codegraph-kernel/src/ruby.rs index af3daafe70..22dcc81c1c 100644 --- a/codegraph-kernel/src/ruby.rs +++ b/codegraph-kernel/src/ruby.rs @@ -24,6 +24,7 @@ use crate::docstring::preceding_docstring; use crate::ids; use crate::textutil as util; use regex::Regex; +use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::sync::OnceLock; use tree_sitter::{Node, Parser}; @@ -119,7 +120,7 @@ struct Cand { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -131,6 +132,9 @@ pub struct Walker<'t> { fs_values: HashMap, fs_value_counts: HashMap, value_scopes: Vec>, + /// For each parent, the last method whose visibility was worked out and what it was: + /// (parent's id) -> (that method's start byte, its visibility). See `visibility_of`. + visibility_seen: RefCell>, } pub fn extract(file_path: &str, source: &str) -> Result { @@ -160,6 +164,7 @@ pub fn extract(file_path: &str, source: &str) -> Result { fs_values: HashMap::new(), fs_value_counts: HashMap::new(), value_scopes: Vec::new(), + visibility_seen: RefCell::new(HashMap::new()), }; let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1; @@ -366,11 +371,9 @@ impl<'t> Walker<'t> { if let Some(name_node) = node.child_by_field_name("name") { return self.text(name_node).to_string(); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { - return self.text(c).to_string(); - } + for c in node.named_children(&mut node.walk()) { + if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { + return self.text(c).to_string(); } } "".to_string() @@ -382,22 +385,51 @@ impl<'t> Walker<'t> { /// Bug-for-bug: a BARE `private` line parses as identifier (invisible), /// and a matching call poisons every later sibling def regardless of /// ruby's actual arg-scoped semantics. + /// + /// The walk stops at the method it last answered for under the same parent + /// and takes that answer: nothing between the two changed it. Without that, + /// every method walked back over every sibling before it, and a class or a + /// file of seven thousand methods took twelve seconds over this alone. fn visibility_of(&self, node: Node) -> u8 { + let parent = node.parent().map_or(0, |p| p.id()); + let start = node.start_byte(); + // Only a method further down than the remembered one may lean on it. + let seen = self + .visibility_seen + .borrow() + .get(&parent) + .copied() + .filter(|(at, _)| *at < start); + let mut visibility = 1; // public let mut sibling = node.prev_named_sibling(); while let Some(s) = sibling { + if let Some((at, known)) = seen { + if s.start_byte() <= at { + visibility = known; + break; + } + } if s.kind() == "call" { if let Some(method) = s.child_by_field_name("method") { - match self.text(method) { - "private" => return 2, - "protected" => return 3, - "public" => return 1, - _ => {} + let decided = match self.text(method) { + "private" => Some(2), + "protected" => Some(3), + "public" => Some(1), + _ => None, + }; + if let Some(decided) = decided { + visibility = decided; + break; } } } sibling = s.prev_named_sibling(); } - 1 // public + let mut memo = self.visibility_seen.borrow_mut(); + if memo.get(&parent).is_none_or(|(at, _)| *at < start) { + memo.insert(parent, (start, visibility)); + } + visibility } // --- the visitNode hook (languages/ruby.ts:19-76) --------------------------- @@ -423,8 +455,7 @@ impl<'t> Walker<'t> { let implements = edge_kind_index("implements").unwrap(); let line = self.line_of(node); let col = self.col_of(node); - for i in 0..args.named_child_count() { - let Some(arg) = args.named_child(i) else { continue }; + for arg in args.named_children(&mut args.walk()) { // `Mod` is constant, `Foo::Bar` is scope_resolution; // `extend self` / dynamic args are skipped. Unlike // every other extraction ref, the hook sets @@ -463,10 +494,8 @@ impl<'t> Walker<'t> { }; self.stack.push(Scope { row, kind: "module", name }); if let Some(body) = node.child_by_field_name("body") { - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } } self.stack.pop(); @@ -531,10 +560,8 @@ impl<'t> Walker<'t> { // `uninterpreted`, operator_assignment: no branch — recursed. if !skip_children { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } } } @@ -587,10 +614,8 @@ impl<'t> Walker<'t> { return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_for_calls_and_structure(c); } } @@ -680,8 +705,7 @@ impl<'t> Walker<'t> { // text (scope_resolution / even `Struct.new(:a)` expressions verbatim), // positioned at the type child. let extends_kind = edge_kind_index("extends").unwrap(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "superclass" { if let Some(target) = child.named_child(0) { let tname = self.text(target).to_string(); @@ -694,10 +718,8 @@ impl<'t> Walker<'t> { // Bodiless `class X; end` has no body field → the class node itself // is walked (name/superclass children revisit harmlessly). let body = node.child_by_field_name("body").unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -883,10 +905,8 @@ impl<'t> Walker<'t> { let mut values: Vec = Vec::new(); match mode { Mode::Args => { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - values.push(c); - } + for c in node.named_children(&mut node.walk()) { + values.push(c); } } Mode::PairValue => { @@ -918,10 +938,8 @@ impl<'t> Walker<'t> { } match v.kind() { "block_argument" => { - for i in 0..v.named_child_count() { - if let Some(c) = v.named_child(i) { - self.normalize_fn_ref_value(c, from, depth + 1); - } + for c in v.named_children(&mut v.walk()) { + self.normalize_fn_ref_value(c, from, depth + 1); } } "call" => { @@ -995,10 +1013,8 @@ impl<'t> Walker<'t> { return; } self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.scan_fn_ref_subtree(c, depth + 1); - } + for c in node.named_children(&mut node.walk()) { + self.scan_fn_ref_subtree(c, depth + 1); } } @@ -1074,23 +1090,19 @@ impl<'t> Walker<'t> { *decl_counts.entry(nm).or_insert(0) += 1; } } else { - for i in 0..left.named_child_count() { - if let Some(c) = left.named_child(i) { - if c.kind() == "identifier" { - let nm = self.text(c); - if targets.contains_key(nm) { - *decl_counts.entry(nm).or_insert(0) += 1; - } + for c in left.named_children(&mut left.walk()) { + if c.kind() == "identifier" { + let nm = self.text(c); + if targets.contains_key(nm) { + *decl_counts.entry(nm).or_insert(0) += 1; } } } } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -1141,10 +1153,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } diff --git a/codegraph-kernel/src/rustlang.rs b/codegraph-kernel/src/rustlang.rs index 32b21f138d..da2c4eda1a 100644 --- a/codegraph-kernel/src/rustlang.rs +++ b/codegraph-kernel/src/rustlang.rs @@ -118,7 +118,7 @@ struct NodeMeta { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -357,11 +357,9 @@ impl<'t> Walker<'t> { if let Some(name_node) = node.child_by_field_name("name") { return self.text(name_node).to_string(); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { - return self.text(c).to_string(); - } + for c in node.named_children(&mut node.walk()) { + if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { + return self.text(c).to_string(); } } "".to_string() @@ -381,11 +379,9 @@ impl<'t> Walker<'t> { /// rustExtractor.getVisibility: direct `visibility_modifier` child whose /// text contains `pub` → public, else private; none → private. fn visibility_of(&self, node: Node) -> u8 { - for i in 0..node.child_count() { - if let Some(c) = node.child(i) { - if c.kind() == "visibility_modifier" { - return if self.text(c).contains("pub") { 1 } else { 2 }; - } + for c in node.children(&mut node.walk()) { + if c.kind() == "visibility_modifier" { + return if self.text(c).contains("pub") { 1 } else { 2 }; } } 2 // private — Rust defaults to private @@ -504,7 +500,7 @@ impl<'t> Walker<'t> { // The initializer extract_variable walked under the declared // symbol took its own candidates; the scan covers the rest. let walked = self.extract_variable(node); - self.scan_fn_ref_subtree(node, 0, &walked); + self.scan_fn_ref_subtree(node, 0, &walked.into_iter().collect()); skip_children = true; } else if kind == "use_declaration" { self.extract_import(node); @@ -521,10 +517,8 @@ impl<'t> Walker<'t> { } if !skip_children { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } } } @@ -636,10 +630,8 @@ impl<'t> Walker<'t> { self.stack.push(Scope { row, kind: "trait", name }); let body = node.child_by_field_name("body").unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -664,10 +656,8 @@ impl<'t> Walker<'t> { let Some(body) = node.child_by_field_name("body") else { return }; self.stack.push(Scope { row, kind, name }); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -687,8 +677,7 @@ impl<'t> Walker<'t> { self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "enum", name }); - for i in 0..body.named_child_count() { - let Some(c) = body.named_child(i) else { continue }; + for c in body.named_children(&mut body.walk()) { if c.kind() == "enum_variant" { if let Some(name_node) = c.child_by_field_name("name") { let vname = self.text(name_node).to_string(); @@ -733,8 +722,7 @@ impl<'t> Walker<'t> { // An impl's associated const is its type's (`Limits::MAX`), as its methods are. let owner = self.impl_item_owner(node); let mut declared: Option<(u32, String)> = None; - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() != "identifier" { continue; } @@ -851,10 +839,8 @@ impl<'t> Walker<'t> { } } "use_list" => { - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - collect(w, c, prefix, paths); - } + for c in n.named_children(&mut n.walk()) { + collect(w, c, prefix, paths); } } "use_as_clause" => { @@ -866,10 +852,8 @@ impl<'t> Walker<'t> { _ => {} // visibility_modifier, use_wildcard, bare crate/self/super } } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - collect(self, c, "", &mut paths); - } + for c in node.named_children(&mut node.walk()) { + collect(self, c, "", &mut paths); } let imports_kind = edge_kind_index("imports").unwrap(); for (text, n) in paths { @@ -1118,8 +1102,7 @@ impl<'t> Walker<'t> { } }; } - for i in 0..token_tree.child_count() { - let Some(t) = token_tree.child(i) else { continue }; + for t in token_tree.children(&mut token_tree.walk()) { if t.kind() == "identifier" { if parts.is_empty() { line = t.start_position().row as u32 + 1; @@ -1142,12 +1125,10 @@ impl<'t> Walker<'t> { fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) { stack_guard!(); let extends_kind = edge_kind_index("extends").unwrap(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { match child.kind() { "trait_bounds" => { - for j in 0..child.named_child_count() { - let Some(bound) = child.named_child(j) else { continue }; + for bound in child.named_children(&mut child.walk()) { let type_node: Option = match bound.kind() { "type_identifier" => Some(bound), "generic_type" => (0..bound.named_child_count()) @@ -1238,10 +1219,8 @@ impl<'t> Walker<'t> { } return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.extract_type_refs_from_subtree(c, from_row); - } + for c in node.named_children(&mut node.walk()) { + self.extract_type_refs_from_subtree(c, from_row); } } @@ -1300,10 +1279,8 @@ impl<'t> Walker<'t> { return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c, Some(node)); - } + for c in node.named_children(&mut node.walk()) { + self.visit_for_calls_and_structure(c, Some(node)); } } @@ -1396,10 +1373,8 @@ impl<'t> Walker<'t> { let mut values: Vec = Vec::new(); match mode { Mode::Args | Mode::List => { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - values.push(c); - } + for c in node.named_children(&mut node.walk()) { + values.push(c); } } Mode::Rhs => { @@ -1498,7 +1473,7 @@ impl<'t> Walker<'t> { } } - fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &[usize]) { + fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32, walked: &HashSet) { stack_guard!(); if depth > 12 { return; @@ -1517,10 +1492,8 @@ impl<'t> Walker<'t> { return; } self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.scan_fn_ref_subtree(c, depth + 1, walked); - } + for c in node.named_children(&mut node.walk()) { + self.scan_fn_ref_subtree(c, depth + 1, walked); } } @@ -1610,10 +1583,8 @@ impl<'t> Walker<'t> { } _ => {} } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -1662,10 +1633,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } diff --git a/codegraph-kernel/src/scala.rs b/codegraph-kernel/src/scala.rs index b2fc7429b9..eb7f2f9bad 100644 --- a/codegraph-kernel/src/scala.rs +++ b/codegraph-kernel/src/scala.rs @@ -153,7 +153,7 @@ struct Extra { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -1038,26 +1038,16 @@ impl<'t> Walker<'t> { } // Scan 2: preceding siblings (TS class style — inert for scala where // annotations are children, ported for fidelity). - if let Some(parent) = decl.parent() { - let decl_start = decl.start_byte(); - let mut decl_idx: Option = None; - for i in 0..parent.named_child_count() { - if let Some(sib) = parent.named_child(i) { - if sib.start_byte() == decl_start { - decl_idx = Some(i); - break; - } - } - } - if let Some(di) = decl_idx { - for j in (0..di).rev() { - let Some(sib) = parent.named_child(j) else { continue }; - if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { - break; - } - self.consider_decorator(sib, decorated_row); - } + // Walked back from the declaration itself. Finding its place first, by counting the + // parent's children from the start, cost each declaration as much as it has + // siblings before it: a file of twenty thousand took minutes. + let mut sibling = decl.prev_named_sibling(); + while let Some(sib) = sibling { + if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { + break; } + self.consider_decorator(sib, decorated_row); + sibling = sib.prev_named_sibling(); } } @@ -1414,10 +1404,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -1474,10 +1462,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } diff --git a/codegraph-kernel/src/swift.rs b/codegraph-kernel/src/swift.rs index 73cf0caa65..2948117da5 100644 --- a/codegraph-kernel/src/swift.rs +++ b/codegraph-kernel/src/swift.rs @@ -220,7 +220,7 @@ struct SwiftPropInfo<'t> { pub struct Walker<'t> { src: &'t str, file_path: &'t str, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -322,10 +322,8 @@ fn first_simple_identifier<'t>(node: Option>) -> Option> { if n.kind() == "simple_identifier" { return Some(n); } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - q.push_back(c); - } + for c in n.named_children(&mut n.walk()) { + q.push_back(c); } } None @@ -336,8 +334,7 @@ fn first_simple_identifier<'t>(node: Option>) -> Option> { fn last_simple_identifier<'t>(node: Node<'t>) -> Option> { stack_guard!(); let mut found: Option> = None; - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "simple_identifier" { found = Some(child); } @@ -517,11 +514,9 @@ impl<'t> Walker<'t> { if let Some(name_node) = node.child_by_field_name("name") { return self.text(name_node).to_string(); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { - return self.text(c).to_string(); - } + for c in node.named_children(&mut node.walk()) { + if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { + return self.text(c).to_string(); } } "".to_string() @@ -531,8 +526,7 @@ impl<'t> Walker<'t> { /// default INTERNAL. `open` → internal, `fileprivate` → private (via the /// 'private' substring), `public private(set)` → public (first match). fn visibility_of(&self, node: Node) -> u8 { - for i in 0..node.child_count() { - let Some(child) = node.child(i) else { continue }; + for child in node.children(&mut node.walk()) { if child.kind() == "modifiers" { let text = self.text(child); if text.contains("public") { @@ -576,8 +570,7 @@ impl<'t> Walker<'t> { /// generics stripped non-nesting; Void → None. fn return_type_of(&self, node: Node) -> Option { let mut seen_name = false; - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() == "simple_identifier" && !seen_name { seen_name = true; continue; @@ -649,16 +642,14 @@ impl<'t> Walker<'t> { // classifyClassNode: `struct`/`enum` keyword children; actor and // extension fall through to 'class'. let mut classified = "class"; - for i in 0..node.child_count() { - if let Some(c) = node.child(i) { - if c.kind() == "struct" { - classified = "struct"; - break; - } - if c.kind() == "enum" { - classified = "enum"; - break; - } + for c in node.children(&mut node.walk()) { + if c.kind() == "struct" { + classified = "struct"; + break; + } + if c.kind() == "enum" { + classified = "enum"; + break; } } match classified { @@ -694,10 +685,8 @@ impl<'t> Walker<'t> { // emit NOTHING (the pass is body-walker-only). if !skip_children { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } } } @@ -783,10 +772,8 @@ impl<'t> Walker<'t> { fn walk_attr_args(&mut self, n: Node<'t>) { stack_guard!(); self.extract_static_member_ref(n); - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - self.walk_attr_args(c); - } + for c in n.named_children(&mut n.walk()) { + self.walk_attr_args(c); } } @@ -818,16 +805,14 @@ impl<'t> Walker<'t> { } if kind == "class_declaration" { let mut classified = "class"; - for i in 0..node.child_count() { - if let Some(c) = node.child(i) { - if c.kind() == "struct" { - classified = "struct"; - break; - } - if c.kind() == "enum" { - classified = "enum"; - break; - } + for c in node.children(&mut node.walk()) { + if c.kind() == "struct" { + classified = "struct"; + break; + } + if c.kind() == "enum" { + classified = "enum"; + break; } } match classified { @@ -842,10 +827,8 @@ impl<'t> Walker<'t> { return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_for_calls_and_structure(c); } } @@ -916,10 +899,8 @@ impl<'t> Walker<'t> { self.extract_decorators_for(node, row); self.stack.push(Scope { row, kind: "class", name }); let body = node.child_by_field_name("body").unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -938,10 +919,8 @@ impl<'t> Walker<'t> { self.extract_inheritance(node, row); // NO extractDecoratorsFor for structs (`@main struct` emits nothing). self.stack.push(Scope { row, kind: "struct", name }); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -960,8 +939,7 @@ impl<'t> Walker<'t> { // String — extends refs have NO builtin filter). NO decorates. self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "enum", name }); - for i in 0..body.named_child_count() { - let Some(child) = body.named_child(i) else { continue }; + for child in body.named_children(&mut body.walk()) { if child.kind() == "enum_entry" { self.extract_enum_members(child); } else { @@ -992,10 +970,8 @@ impl<'t> Walker<'t> { self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "interface", name }); let body = node.child_by_field_name("body").unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -1220,8 +1196,7 @@ impl<'t> Walker<'t> { /// (conformances included; `: Module.Base` takes `Module`). fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) { let extends_kind = edge_kind_index("extends").unwrap(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() != "inheritance_specifier" { continue; } @@ -1266,53 +1241,34 @@ impl<'t> Walker<'t> { } return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.extract_type_refs_from_subtree(c, from_row); - } + for c in node.named_children(&mut node.walk()) { + self.extract_type_refs_from_subtree(c, from_row); } } /// extractDecoratorsFor — swift `attribute` nodes inside `modifiers`. /// Coverage: functions/methods/classes/dedicated-branch properties only. fn extract_decorators_for(&mut self, decl: Node<'t>, decorated_row: u32) { - for i in 0..decl.named_child_count() { - let Some(child) = decl.named_child(i) else { continue }; + for child in decl.named_children(&mut decl.walk()) { self.consider_decorator(child, decorated_row); if child.kind() == "modifiers" { - for j in 0..child.named_child_count() { - if let Some(m) = child.named_child(j) { - self.consider_decorator(m, decorated_row); - } + for m in child.named_children(&mut child.walk()) { + self.consider_decorator(m, decorated_row); } } } // Preceding-sibling scan — swift attributes are never siblings; the // scan stops at the first non-decorator sibling immediately. - let Some(parent) = decl.parent() else { return }; - let decl_start = decl.start_byte(); - let mut decl_idx: isize = -1; - for i in 0..parent.named_child_count() { - if let Some(sib) = parent.named_child(i) { - if sib.start_byte() == decl_start { - decl_idx = i as isize; - break; - } - } - } - if decl_idx > 0 { - let mut j = decl_idx - 1; - while j >= 0 { - let Some(sib) = parent.named_child(j as usize) else { - j -= 1; - continue; - }; - if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { - break; - } - self.consider_decorator(sib, decorated_row); - j -= 1; + // Walked back from the declaration itself. Finding its place first, by counting the + // parent's children from the start, cost each declaration as much as it has + // siblings before it: a file of twenty thousand took minutes. + let mut sibling = decl.prev_named_sibling(); + while let Some(sib) = sibling { + if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { + break; } + self.consider_decorator(sib, decorated_row); + sibling = sib.prev_named_sibling(); } } @@ -1321,8 +1277,7 @@ impl<'t> Walker<'t> { return; } let mut target: Option = None; - for i in 0..n.named_child_count() { - let Some(child) = n.named_child(i) else { continue }; + for child in n.named_children(&mut n.walk()) { if child.kind() == "call_expression" { target = child.child_by_field_name("function").or_else(|| child.named_child(0)); if target.is_some() { @@ -1370,10 +1325,8 @@ impl<'t> Walker<'t> { let mut values: Vec = Vec::new(); match mode { Mode::Args | Mode::List => { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - values.push(c); - } + for c in node.named_children(&mut node.walk()) { + values.push(c); } } Mode::Rhs => { @@ -1506,10 +1459,8 @@ impl<'t> Walker<'t> { return; } self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.scan_fn_ref_subtree(c, depth + 1); - } + for c in node.named_children(&mut node.walk()) { + self.scan_fn_ref_subtree(c, depth + 1); } } @@ -1584,8 +1535,7 @@ impl<'t> Walker<'t> { *decl_counts.entry(nm).or_insert(0) += 1; } } else { - for i in 0..left.named_child_count() { - let Some(c) = left.named_child(i) else { continue }; + for c in left.named_children(&mut left.walk()) { if matches!(c.kind(), "identifier" | "simple_identifier") { let nm = self.text(c); if targets.contains_key(nm) { @@ -1619,10 +1569,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -1671,10 +1619,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } diff --git a/codegraph-kernel/src/textutil.rs b/codegraph-kernel/src/textutil.rs index 40163ad749..65972fcb27 100644 --- a/codegraph-kernel/src/textutil.rs +++ b/codegraph-kernel/src/textutil.rs @@ -130,15 +130,53 @@ pub fn is_minified_content(file_path: &str, content: &str) -> bool { long as f64 >= total as f64 * 0.5 && punctuation as f64 >= long as f64 * 0.03 } +/// Where each line of a source starts, and what turns a byte offset on a +/// line into its UTF-16 column without reading the line: see `col16`. Reads +/// as the slice of line starts. +pub struct LineStarts { + starts: Vec, + /// Each character of more than one byte, in order: where it starts, and + /// the bytes the source spends up to and including it beyond the UTF-16 + /// units it counts for. Empty for a source that is all ASCII. + wide: Vec<(usize, usize)>, +} + +impl LineStarts { + /// The bytes before `pos` that count for no UTF-16 unit. + fn spare_before(&self, pos: usize) -> usize { + match self.wide.partition_point(|&(at, _)| at < pos) { + 0 => 0, + n => self.wide[n - 1].1, + } + } +} + +impl std::ops::Deref for LineStarts { + type Target = [usize]; + fn deref(&self) -> &[usize] { + &self.starts + } +} + /// Byte offsets of each line start, for UTF-16 column conversion. -pub fn line_starts(src: &str) -> Vec { - let mut out = vec![0usize]; +pub fn line_starts(src: &str) -> LineStarts { + let mut starts = vec![0usize]; for (i, b) in src.bytes().enumerate() { if b == b'\n' { - out.push(i + 1); + starts.push(i + 1); } } - out + let mut wide = Vec::new(); + if !src.is_ascii() { + let mut spare = 0usize; + for (at, c) in src.char_indices() { + if c.len_utf8() > 1 { + spare += c.len_utf8() - c.len_utf16(); + wide.push((at, spare)); + } + } + } + LineStarts { starts, wide } } /// UTF-16 code units in `s` — what web-tree-sitter (and JS string ops) @@ -148,12 +186,18 @@ pub fn utf16_len(s: &str) -> usize { } /// Column (UTF-16 units) of `byte_pos` on line `row`, given `line_starts`. -pub fn col16(src: &str, starts: &[usize], row: usize, byte_pos: usize) -> u32 { +/// +/// Read from the table: the bytes from the line's start, less those that +/// count for no unit. Counted character by character from the line's start +/// for every symbol and reference, a script minified to one line took the +/// square of its length: a megabyte, a minute. +/// The source is no longer read; the parameter stays so every caller is as it was. +pub fn col16(_src: &str, starts: &LineStarts, row: usize, byte_pos: usize) -> u32 { let ls = starts.get(row).copied().unwrap_or(0); if byte_pos <= ls { return 0; } - utf16_len(&src[ls..byte_pos]) as u32 + (byte_pos - ls - (starts.spare_before(byte_pos) - starts.spare_before(ls))) as u32 } /// JS `String.prototype.slice(0, n)` in UTF-16 units, without splitting a @@ -223,6 +267,24 @@ mod tests { assert_eq!(col16(src, &starts, 0, 7), 4); // after '😀' } + /// The table gives, at every character of every line, the column that + /// counting the line's characters gives. + #[test] + fn utf16_cols_match_counting() { + let src = "plain ascii\naé😀b — ü\n\n日本語 x 😀😀\nlast"; + let starts = line_starts(src); + for (row, &start) in starts.iter().enumerate() { + let end = starts.get(row + 1).map_or(src.len(), |next| next - 1); + for (offset, _) in src[start..end].char_indices().chain([(end - start, ' ')]) { + let counted = utf16_len(&src[start..start + offset]) as u32; + assert_eq!(col16(src, &starts, row, start + offset), counted, "row {row} offset {offset}"); + } + } + // Before a line's start, or on a row the source does not have: 0, and the offset itself. + assert_eq!(col16(src, &starts, 1, 3), 0); + assert_eq!(col16("abc", &line_starts("abc"), 9, 2), 2); + } + #[test] fn init_sig_short_and_long() { assert_eq!(init_signature("[1, 2]"), "= [1, 2]"); diff --git a/codegraph-kernel/src/tsjs/extractors.rs b/codegraph-kernel/src/tsjs/extractors.rs index f3a62be6ce..01f22cb7f7 100644 --- a/codegraph-kernel/src/tsjs/extractors.rs +++ b/codegraph-kernel/src/tsjs/extractors.rs @@ -126,10 +126,8 @@ impl<'t> Walker<'t> { stack_guard!(); match node.kind() { "formal_parameters" | "object_pattern" | "array_pattern" | "rest_pattern" => { - for i in 0..node.named_child_count() { - if let Some(child) = node.named_child(i) { - self.visit_pattern_defaults(child); - } + for child in node.named_children(&mut node.walk()) { + self.visit_pattern_defaults(child); } } "required_parameter" | "optional_parameter" => { @@ -309,12 +307,10 @@ impl<'t> Walker<'t> { } let mut inner: Option = None; if let Some(args) = value.child_by_field_name("arguments") { - for i in 0..args.named_child_count() { - if let Some(a) = args.named_child(i) { - if matches!(a.kind(), "arrow_function" | "function_expression") { - inner = Some(a); - break; - } + for a in args.named_children(&mut args.walk()) { + if matches!(a.kind(), "arrow_function" | "function_expression") { + inner = Some(a); + break; } } } @@ -427,8 +423,7 @@ impl<'t> Walker<'t> { let base = args .named_child(0) .filter(|f| root && matches!(f.kind(), "identifier" | "member_expression")); - for i in 0..args.named_child_count() { - let Some(arg) = args.named_child(i) else { continue }; + for (i, arg) in args.named_children(&mut args.walk()).enumerate() { if base.map(|b| b.start_byte() == arg.start_byte()).unwrap_or(false) { continue; } @@ -514,10 +509,8 @@ impl<'t> Walker<'t> { self.stack.push(Scope { row, kind: "class", name }); let body = resolved_body.unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -581,10 +574,8 @@ impl<'t> Walker<'t> { self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "interface", name }); let body = body_of(node).unwrap_or(node); - for i in 0..body.named_child_count() { - if let Some(c) = body.named_child(i) { - self.visit_node(c); - } + for c in body.named_children(&mut body.walk()) { + self.visit_node(c); } self.stack.pop(); } @@ -603,8 +594,7 @@ impl<'t> Walker<'t> { }; self.extract_inheritance(node, row); self.stack.push(Scope { row, kind: "enum", name }); - for i in 0..body.named_child_count() { - let Some(child) = body.named_child(i) else { continue }; + for child in body.named_children(&mut body.walk()) { if matches!(child.kind(), "property_identifier" | "enum_assignment") { self.extract_enum_members(child); } else { @@ -621,13 +611,11 @@ impl<'t> Walker<'t> { return; } let mut found = false; - for i in 0..node.named_child_count() { - if let Some(child) = node.named_child(i) { - if matches!(child.kind(), "simple_identifier" | "identifier" | "property_identifier") { - let name = self.text(child).to_string(); - self.create_node("enum_member", &name, child, Extra::default()); - found = true; - } + for child in node.named_children(&mut node.walk()) { + if matches!(child.kind(), "simple_identifier" | "identifier" | "property_identifier") { + let name = self.text(child).to_string(); + self.create_node("enum_member", &name, child, Extra::default()); + found = true; } } if !found && node.named_child_count() == 0 { @@ -705,8 +693,7 @@ impl<'t> Walker<'t> { /// A top-level binding exported by a LATER statement rather than at its /// declaration: `export default NAME`, `export { NAME }`, `export { NAME as /// default }`. The declaration's own `is_exported` (an `export_statement` - /// ancestor) cannot see these. One anchored regex over the file source. - /// Mirrors TreeSitterExtractor.isExportedLater. + /// ancestor) cannot see these. Mirrors TreeSitterExtractor.isExportedLater. pub(super) fn is_exported_later(&self, name: &str) -> bool { if name.is_empty() || !name.chars().next().map(|c| c.is_ascii_alphabetic() || c == '_' || c == '$').unwrap_or(false) @@ -714,22 +701,82 @@ impl<'t> Walker<'t> { { return false; } - let n = regex::escape(name); - // `R` (CRLF mode): JS's multiline `^`/`$` treat `\r` as a line end as - // well as `\n`; `(?m)` alone sees only `\n`, and would miss `export - // default NAME;\r\n` on every Windows autocrlf checkout. - // Inside `{ … }` the name is bounded by a character that can't - // continue an identifier, not by `\b`, which takes a `$` for a - // separator. The crate has no look-around, so the bounds consume. - // ASCII classes, not `\w`: this crate's `\w` is Unicode, JS's is not. - let pattern = format!( - r"(?mR)^[ \t]*export\s+(?:default\s+{n}\s*;?[ \t]*$|\{{(?:[^}}]*[^0-9A-Za-z_$}}])?{n}(?:[^0-9A-Za-z_$}}][^}}]*)?\}})", - n = n - ); - match regex::Regex::new(&pattern) { - Ok(re) => re.is_match(self.src), - Err(_) => false, - } + self.later_exports().contains(name) + } + + /// Every name a statement of the file exports after it was declared: the + /// one `export default NAME` names, and each word between the braces of an + /// `export { … }`. Read once for the file. Asking the source again for each + /// name, with a pattern compiled for it, cost a file of twenty thousand + /// unexported constants a second for every megabyte, and four times that + /// for each doubling. + fn later_exports(&self) -> &HashSet<&'t str> { + self.later_exports.get_or_init(|| { + // One statement, tried where a line starts. `R` (CRLF mode): JS's + // multiline `$` treats `\r` as a line end as well as `\n`; `(?m)` + // alone sees only `\n`, and would miss `export default NAME;\r\n` + // on every Windows autocrlf checkout. ASCII classes, not `\w`: this + // crate's `\w` is Unicode, JS's is not. + static STATEMENT: std::sync::OnceLock = std::sync::OnceLock::new(); + let statement = STATEMENT.get_or_init(|| { + regex::Regex::new( + r"\A[ \t]*export\s+(?:default\s+([A-Za-z_$][0-9A-Za-z_$]*)\s*;?[ \t]*(?mR:$)|\{([^}]*)\})", + ) + .expect("the later-export pattern compiles") + }); + let src: &'t str = self.src; + let bytes = src.as_bytes(); + let mut names: HashSet<&'t str> = HashSet::new(); + let mut line = 0usize; + loop { + // Only a line that opens with `export` can hold one. + let mut word = line; + while word < bytes.len() && (bytes[word] == b' ' || bytes[word] == b'\t') { + word += 1; + } + if bytes[word..].starts_with(b"export") { + if let Some(found) = statement.captures(&src[line..]) { + if let Some(default) = found.get(1) { + names.insert(&src[line + default.start()..line + default.end()]); + } else if let Some(braces) = found.get(2) { + // Inside `{ … }` a name is bounded by a character that + // can't continue an identifier, not by `\b`, which + // takes a `$` for a separator. + let from = line + braces.start(); + let inner = &src[from..line + braces.end()]; + let mut start: Option = None; + for (at, b) in inner.bytes().enumerate() { + let part = b.is_ascii_alphanumeric() || b == b'_' || b == b'$'; + match (part, start) { + (true, None) => start = Some(at), + (false, Some(s)) => { + names.insert(&src[from + s..from + at]); + start = None; + } + _ => {} + } + } + if let Some(s) = start { + names.insert(&src[from + s..from + inner.len()]); + } + } + } + } + // The next line starts after a `\n`, or after a `\r` no `\n` follows. + let mut next = word; + while next < bytes.len() && bytes[next] != b'\n' && bytes[next] != b'\r' { + next += 1; + } + if next >= bytes.len() { + break; + } + if bytes[next] == b'\r' && bytes.get(next + 1) == Some(&b'\n') { + next += 1; + } + line = next + 1; + } + names + }) } /// Returns the initializers it walked under the symbol they declare — a @@ -744,8 +791,7 @@ impl<'t> Walker<'t> { let docstring = crate::docstring::preceding_docstring(node, self.src); let is_exported = self.is_exported(node); // `?? false` — always present - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if child.kind() != "variable_declarator" { continue; } @@ -910,8 +956,7 @@ impl<'t> Walker<'t> { /// extractRtkHookBindings — `export const { useGetXQuery } = api`. fn extract_rtk_hook_bindings(&mut self, pattern: Node<'t>, is_exported: bool) { - for i in 0..pattern.named_child_count() { - let Some(binding) = pattern.named_child(i) else { continue }; + for binding in pattern.named_children(&mut pattern.walk()) { if binding.kind() != "shorthand_property_identifier_pattern" { continue; } @@ -971,11 +1016,9 @@ impl<'t> Walker<'t> { if !matches!(value.kind(), "object" | "object_expression") || !self.owns_object_literals() { return None; } - for i in 0..value.named_child_count() { - if let Some(member) = value.named_child(i) { - if self.owned_member_function(member).is_some() { - return Some(value); - } + for member in value.named_children(&mut value.walk()) { + if self.owned_member_function(member).is_some() { + return Some(value); } } None @@ -1003,8 +1046,7 @@ impl<'t> Walker<'t> { fn extract_owned_object_members(&mut self, obj: Node<'t>, row: u32, kind: &'static str, name: &str, values_under_owner: bool, global: bool, exported: bool) { let held = values_under_owner.then(|| self.enter_owner(row, kind, name, global)); self.maybe_capture_fn_refs(obj); - for i in 0..obj.named_child_count() { - let Some(member) = obj.named_child(i) else { continue }; + for member in obj.named_children(&mut obj.walk()) { if let Some((func, member_name)) = self.owned_member_function(member) { // The members of the module's export object are exported (#2966). self.exported_member_fn = exported.then(|| func.id()); @@ -1125,8 +1167,7 @@ impl<'t> Walker<'t> { // --- object-literal / store helpers ------------------------------------------------- pub(super) fn extract_object_literal_functions(&mut self, obj: Node<'t>) { - for i in 0..obj.named_child_count() { - let Some(member) = obj.named_child(i) else { continue }; + for member in obj.named_children(&mut obj.walk()) { if member.kind() == "pair" { let key = member.child_by_field_name("key"); let value = member.child_by_field_name("value"); @@ -1162,8 +1203,7 @@ impl<'t> Walker<'t> { return None; } let args = call.child_by_field_name("arguments")?; - for i in 0..args.named_child_count() { - let Some(arg) = args.named_child(i) else { continue }; + for arg in args.named_children(&mut args.walk()) { if matches!(arg.kind(), "arrow_function" | "function_expression") { if let Some(obj) = self.function_returned_object(arg) { return Some(obj); @@ -1198,8 +1238,7 @@ impl<'t> Walker<'t> { return Some(direct); } if body.kind() == "statement_block" { - for i in 0..body.named_child_count() { - let Some(stmt) = body.named_child(i) else { continue }; + for stmt in body.named_children(&mut body.walk()) { if stmt.kind() != "return_statement" { continue; } @@ -1214,8 +1253,7 @@ impl<'t> Walker<'t> { } pub(super) fn object_has_inline_functions(&self, obj: Node) -> bool { - for i in 0..obj.named_child_count() { - let Some(member) = obj.named_child(i) else { continue }; + for member in obj.named_children(&mut obj.walk()) { if member.kind() == "method_definition" { return true; } @@ -1244,13 +1282,11 @@ impl<'t> Walker<'t> { return None; } let args = call.child_by_field_name("arguments")?; - for i in 0..args.named_child_count() { - let Some(arg) = args.named_child(i) else { continue }; + for arg in args.named_children(&mut args.walk()) { if !matches!(arg.kind(), "object" | "object_expression") { continue; } - for j in 0..arg.named_child_count() { - let Some(member) = arg.named_child(j) else { continue }; + for member in arg.named_children(&mut arg.walk()) { if member.kind() == "pair" { let Some(key) = member.child_by_field_name("key") else { continue }; if self.text(key) != "endpoints" { @@ -1274,8 +1310,7 @@ impl<'t> Walker<'t> { } fn extract_rtk_endpoints(&mut self, obj: Node<'t>) { - for i in 0..obj.named_child_count() { - let Some(member) = obj.named_child(i) else { continue }; + for member in obj.named_children(&mut obj.walk()) { if member.kind() != "pair" { continue; } @@ -1316,16 +1351,14 @@ impl<'t> Walker<'t> { fn rtk_endpoint_handler(&self, call: Node<'t>) -> Option> { let args = call.child_by_field_name("arguments")?; - for i in 0..args.named_child_count() { - let Some(arg) = args.named_child(i) else { continue }; + for arg in args.named_children(&mut args.walk()) { if !matches!(arg.kind(), "object" | "object_expression") { continue; } let mut query_fn: Option = None; let mut query: Option = None; let mut first_fn: Option = None; - for j in 0..arg.named_child_count() { - let Some(member) = arg.named_child(j) else { continue }; + for member in arg.named_children(&mut arg.walk()) { let mut fn_node: Option = None; let mut key_name = ""; if member.kind() == "pair" { @@ -1391,13 +1424,11 @@ impl<'t> Walker<'t> { } let Some(args) = call.child_by_field_name("arguments") else { return vec![] }; let mut objects = Vec::new(); - for i in 0..args.named_child_count() { - let Some(arg) = args.named_child(i) else { continue }; + for arg in args.named_children(&mut args.walk()) { if !matches!(arg.kind(), "object" | "object_expression") { continue; } - for j in 0..arg.named_child_count() { - let Some(member) = arg.named_child(j) else { continue }; + for member in arg.named_children(&mut arg.walk()) { if member.kind() != "pair" { continue; } @@ -1419,8 +1450,7 @@ impl<'t> Walker<'t> { /// actions/mutations/getters collection, whose methods are extracted. fn extract_store_collection_methods(&mut self, config: Node<'t>) -> bool { let mut found = false; - for i in 0..config.named_child_count() { - let Some(member) = config.named_child(i) else { continue }; + for member in config.named_children(&mut config.walk()) { if member.kind() != "pair" { continue; } @@ -1474,8 +1504,7 @@ impl<'t> Walker<'t> { return None; } let args = call.child_by_field_name("arguments")?; - for i in 0..args.named_child_count() { - let Some(arg) = args.named_child(i) else { continue }; + for arg in args.named_children(&mut args.walk()) { if !matches!(arg.kind(), "arrow_function" | "function_expression") { continue; } @@ -1493,13 +1522,11 @@ impl<'t> Walker<'t> { if body.kind() != "statement_block" { return; } - for i in 0..body.named_child_count() { - let Some(stmt) = body.named_child(i) else { continue }; + for stmt in body.named_children(&mut body.walk()) { if stmt.kind() == "function_declaration" { self.extract_function(stmt, None); } else if is_variable_type(stmt.kind()) { - for j in 0..stmt.named_child_count() { - let Some(decl) = stmt.named_child(j) else { continue }; + for decl in stmt.named_children(&mut stmt.walk()) { if decl.kind() != "variable_declarator" { continue; } @@ -1543,11 +1570,9 @@ impl<'t> Walker<'t> { if value.kind() == "object_type" { object_types.push(value); } else if value.kind() == "intersection_type" { - for i in 0..value.named_child_count() { - if let Some(op) = value.named_child(i) { - if op.kind() == "object_type" { - object_types.push(op); - } + for op in value.named_children(&mut value.walk()) { + if op.kind() == "object_type" { + object_types.push(op); } } } else { @@ -1556,8 +1581,7 @@ impl<'t> Walker<'t> { self.stack.push(Scope { row: alias_row, kind: "type_alias", name: alias_name.to_string() }); for obj_type in object_types { - for i in 0..obj_type.named_child_count() { - let Some(child) = obj_type.named_child(i) else { continue }; + for child in obj_type.named_children(&mut obj_type.walk()) { if !matches!(child.kind(), "property_signature" | "method_signature") { continue; } @@ -1596,10 +1620,8 @@ impl<'t> Walker<'t> { if n.kind() == "tuple_type" { out.push(n); } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - collect(c, depth + 1, out); - } + for c in n.named_children(&mut n.walk()) { + collect(c, depth + 1, out); } } collect(value, 0, &mut tuples); @@ -1609,14 +1631,12 @@ impl<'t> Walker<'t> { self.stack.push(Scope { row: alias_row, kind: "type_alias", name: alias_name.to_string() }); for tuple in tuples { - for i in 0..tuple.named_child_count() { - let Some(entry) = tuple.named_child(i) else { continue }; + for entry in tuple.named_children(&mut tuple.walk()) { if entry.kind() != "generic_type" { continue; } let Some(type_args) = entry.child_by_field_name("type_arguments") else { continue }; - for j in 0..type_args.named_child_count() { - let Some(arg) = type_args.named_child(j) else { continue }; + for arg in type_args.named_children(&mut type_args.walk()) { if arg.kind() != "literal_type" { continue; } @@ -1646,11 +1666,9 @@ impl<'t> Walker<'t> { let Some(type_anno) = property_signature.child_by_field_name("type") else { return false; }; - for i in 0..type_anno.named_child_count() { - if let Some(inner) = type_anno.named_child(i) { - if inner.kind() == "function_type" { - return true; - } + for inner in type_anno.named_children(&mut type_anno.walk()) { + if inner.kind() == "function_type" { + return true; } } false @@ -1698,13 +1716,11 @@ impl<'t> Walker<'t> { w.push_ref(from_row, &name, imports_kind, n); }; - for i in 0..clause.named_child_count() { - let Some(child) = clause.named_child(i) else { continue }; + for child in clause.named_children(&mut clause.walk()) { match child.kind() { "identifier" => push(self, Some(child)), "named_imports" => { - for j in 0..child.named_child_count() { - let Some(spec) = child.named_child(j) else { continue }; + for spec in child.named_children(&mut child.walk()) { if spec.kind() != "import_specifier" { continue; } @@ -1734,8 +1750,7 @@ impl<'t> Walker<'t> { .find(|c| c.kind() == "export_clause"); let Some(clause) = clause else { return }; // `export * from './y'` let imports_kind = edge_kind_index("imports").unwrap(); - for i in 0..clause.named_child_count() { - let Some(spec) = clause.named_child(i) else { continue }; + for spec in clause.named_children(&mut clause.walk()) { if spec.kind() != "export_specifier" { continue; } @@ -2037,44 +2052,27 @@ impl<'t> Walker<'t> { pub(super) fn extract_decorators_for(&mut self, decl: Node<'t>, decorated_row: u32) { // 1. Direct children (method/property style). - for i in 0..decl.named_child_count() { - let Some(child) = decl.named_child(i) else { continue }; + for child in decl.named_children(&mut decl.walk()) { self.consider_decorator(child, decorated_row); if child.kind() == "modifiers" { - for j in 0..child.named_child_count() { - if let Some(m) = child.named_child(j) { - self.consider_decorator(m, decorated_row); - } + for m in child.named_children(&mut child.walk()) { + self.consider_decorator(m, decorated_row); } } } // 2. Preceding siblings (TypeScript class style), stopping at the // first non-decorator so an earlier declaration's decorators never // leak in. Matching by startIndex, not object identity. - let Some(parent) = decl.parent() else { return }; - let decl_start = decl.start_byte(); - let mut decl_idx: isize = -1; - for i in 0..parent.named_child_count() { - if let Some(sib) = parent.named_child(i) { - if sib.start_byte() == decl_start { - decl_idx = i as isize; - break; - } - } - } - if decl_idx > 0 { - let mut j = decl_idx - 1; - while j >= 0 { - let Some(sib) = parent.named_child(j as usize) else { - j -= 1; - continue; - }; - if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { - break; - } - self.consider_decorator(sib, decorated_row); - j -= 1; + // Walked back from the declaration itself. Finding its place first, by counting the + // parent's children from the start, cost each declaration as much as it has + // siblings before it: a file of twenty thousand took minutes. + let mut sibling = decl.prev_named_sibling(); + while let Some(sib) = sibling { + if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") { + break; } + self.consider_decorator(sib, decorated_row); + sibling = sib.prev_named_sibling(); } } @@ -2083,8 +2081,7 @@ impl<'t> Walker<'t> { return; } let mut target: Option = None; - for i in 0..n.named_child_count() { - let Some(child) = n.named_child(i) else { continue }; + for child in n.named_children(&mut n.walk()) { if child.kind() == "call_expression" { target = child.child_by_field_name("function").or_else(|| child.named_child(0)); if target.is_some() { @@ -2131,8 +2128,7 @@ impl<'t> Walker<'t> { stack_guard!(); let extends_kind = edge_kind_index("extends").unwrap(); let implements_kind = edge_kind_index("implements").unwrap(); - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { match child.kind() { // TS `extends_clause` (the other spellings are other grammars'). "extends_clause" | "superclass" | "base_clause" | "extends_interfaces" => { @@ -2142,11 +2138,9 @@ impl<'t> Walker<'t> { } } "implements_clause" | "class_interface_clause" | "super_interfaces" | "interfaces" => { - for j in 0..child.named_child_count() { - if let Some(iface) = child.named_child(j) { - let name = self.supertype_name(iface); - self.push_ref(class_row, &name, implements_kind, iface); - } + for iface in child.named_children(&mut child.walk()) { + let name = self.supertype_name(iface); + self.push_ref(class_row, &name, implements_kind, iface); } } // TS `interface Repo extends Base, ns.Shape, Store` — each @@ -2235,10 +2229,8 @@ impl<'t> Walker<'t> { } return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.extract_type_refs_from_subtree(c, from_row); - } + for c in node.named_children(&mut node.walk()) { + self.extract_type_refs_from_subtree(c, from_row); } } } diff --git a/codegraph-kernel/src/tsjs/fnref.rs b/codegraph-kernel/src/tsjs/fnref.rs index f568027c69..67e069f9f9 100644 --- a/codegraph-kernel/src/tsjs/fnref.rs +++ b/codegraph-kernel/src/tsjs/fnref.rs @@ -54,10 +54,8 @@ pub fn capture(container: Node, mode: Mode, src: &str) -> Vec<(Candidate, Mode)> match mode { Mode::Args | Mode::List => { - for i in 0..container.named_child_count() { - if let Some(c) = container.named_child(i) { - value_nodes.push(c); - } + for c in container.named_children(&mut container.walk()) { + value_nodes.push(c); } } Mode::Rhs => { diff --git a/codegraph-kernel/src/tsjs/mod.rs b/codegraph-kernel/src/tsjs/mod.rs index 57544f07ae..c087be4d8f 100644 --- a/codegraph-kernel/src/tsjs/mod.rs +++ b/codegraph-kernel/src/tsjs/mod.rs @@ -199,7 +199,7 @@ pub struct Walker<'t> { src: &'t str, file_path: &'t str, variant: Variant, - line_starts: Vec, + line_starts: util::LineStarts, arena: Arena, node_id_allocator: ids::NodeIdAllocator, tables: Tables, @@ -233,6 +233,9 @@ pub struct Walker<'t> { /// The function of a `module.exports = {…}` member being extracted: the /// module exports it (#2966). Mirrors TreeSitterExtractor.exportedMemberFn. exported_member_fn: Option, + /// The names a later statement exports, read from the source the first + /// time one is asked for. See `is_exported_later`. + later_exports: std::cell::OnceCell>, } const MAX_VALUE_REF_NODES: usize = 20_000; @@ -284,6 +287,7 @@ pub fn extract(file_path: &str, source: &str, language: &str) -> Result`, endLine = @@ -558,10 +562,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - dstack.push(c); - } + for c in n.named_children(&mut n.walk()) { + dstack.push(c); } } let shadowed: Vec = decl_counts @@ -612,10 +614,8 @@ impl<'t> Walker<'t> { } } } - for i in 0..n.named_child_count() { - if let Some(c) = n.named_child(i) { - stack.push(c); - } + for c in n.named_children(&mut n.walk()) { + stack.push(c); } } } @@ -651,10 +651,8 @@ impl<'t> Walker<'t> { return; } self.maybe_capture_fn_refs(node); - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.scan_fn_ref_subtree(c, depth + 1, walked); - } + for c in node.named_children(&mut node.walk()) { + self.scan_fn_ref_subtree(c, depth + 1, walked); } } @@ -792,10 +790,8 @@ impl<'t> Walker<'t> { } if !skip_children { - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_node(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_node(c); } } } @@ -887,10 +883,8 @@ impl<'t> Walker<'t> { return; } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - self.visit_for_calls_and_structure(c); - } + for c in node.named_children(&mut node.walk()) { + self.visit_for_calls_and_structure(c); } } @@ -1035,11 +1029,9 @@ impl<'t> Walker<'t> { if matches!(node.kind(), "arrow_function" | "function_expression" | "generator_function") { return "".to_string(); } - for i in 0..node.named_child_count() { - if let Some(c) = node.named_child(i) { - if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { - return self.text(c).to_string(); - } + for c in node.named_children(&mut node.walk()) { + if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") { + return self.text(c).to_string(); } } "".to_string() @@ -1093,11 +1085,9 @@ impl<'t> Walker<'t> { } fn has_keyword_child(&self, node: Node, kw: &str) -> bool { - for i in 0..node.child_count() { - if let Some(c) = node.child(i) { - if c.kind() == kw { - return true; - } + for c in node.children(&mut node.walk()) { + if c.kind() == kw { + return true; } } false @@ -1132,18 +1122,15 @@ fn classify_ts_class_member(node: Node) -> Member { if !matches!(node.kind(), "public_field_definition" | "field_definition") { return Member::Method; } - for i in 0..node.named_child_count() { - let Some(child) = node.named_child(i) else { continue }; + for child in node.named_children(&mut node.walk()) { if matches!(child.kind(), "arrow_function" | "function_expression") { return Member::Method; } if child.kind() == "call_expression" { if let Some(args) = child.child_by_field_name("arguments") { - for j in 0..args.named_child_count() { - if let Some(arg) = args.named_child(j) { - if matches!(arg.kind(), "arrow_function" | "function_expression") { - return Member::Method; - } + for arg in args.named_children(&mut args.walk()) { + if matches!(arg.kind(), "arrow_function" | "function_expression") { + return Member::Method; } } } @@ -1165,11 +1152,9 @@ fn resolve_field_body(node: Node) -> Option { } if child.kind() == "call_expression" { if let Some(args) = child.child_by_field_name("arguments") { - for j in 0..args.named_child_count() { - if let Some(arg) = args.named_child(j) { - if matches!(arg.kind(), "arrow_function" | "function_expression") { - return arg.child_by_field_name("body"); - } + for arg in args.named_children(&mut args.walk()) { + if matches!(arg.kind(), "arrow_function" | "function_expression") { + return arg.child_by_field_name("body"); } } } @@ -1246,11 +1231,9 @@ fn is_ambient_function_signature(node: Node, file_path: &str) -> bool { /// hasExportDeclaration: a statement that exports by name or by assignment /// (`export {…}`, `export =`, `export default x`), not by declaring. fn has_export_declaration(block: Node) -> bool { - for i in 0..block.named_child_count() { - if let Some(statement) = block.named_child(i) { - if statement.kind() == "export_statement" && statement.child_by_field_name("declaration").is_none() { - return true; - } + for statement in block.named_children(&mut block.walk()) { + if statement.kind() == "export_statement" && statement.child_by_field_name("declaration").is_none() { + return true; } } false diff --git a/docs/README.md b/docs/README.md index f4ee493e23..cec7c924d5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,7 @@ To install and use CodeGraph, start with the [project README](../README.md). To | Checking a language by hand | [Language verification guide](SEARCH_QUALITY_LOOP.md) | | The browser viewer's design | [Viewer design spec](design/codegraph-ui-design-spec.md) | | The native extraction kernel | [Kernel design](design/native-extraction-kernel.md) | +| Keeping indexing time in proportion to a file's size | [Large-file performance](design/large-file-performance.md) | ## Supporting material diff --git a/docs/design/large-file-performance.md b/docs/design/large-file-performance.md new file mode 100644 index 0000000000..a0e14c4ef3 --- /dev/null +++ b/docs/design/large-file-performance.md @@ -0,0 +1,143 @@ +# Large-file indexing performance + +Read this before changing a loop in `src/extraction/`, `src/resolution/` or `codegraph-kernel/`, before reviewing a pull request that does, and before answering an issue that says indexing hangs, is slow, or left a file with no symbols. + +## The rule + +**Indexing a file costs in proportion to its size.** One megabyte of ordinary code takes about a second. Nothing done for a symbol, a reference, a route or a match may read the whole file, all of the file's nodes, all of its imports, or everything before it. + +Until November 2026 that was false in every language. Time grew with the square of the file: a 0.9 MB Python file took 27 seconds and a Ruby one 54, a 1.2 MB Express file of inline handlers 58, 1.2 MB of Liquid 41. A file is given a time limit (the parse budget in `src/extraction/parse-budget.ts`, 10 to 20 seconds a parse, and the limits above it), and past it the file is given up on. So the cost was not only time: a large file ended with no symbols, and nothing a user asked about it (callers, impact, its own symbol map) had an answer. The size limit could not be raised from 1 MB to 4 MB until this was fixed (`MAX_SOURCE_FILE_SIZE_BYTES` in `src/file-limits.ts`). + +About forty causes were removed, and every one was the same shape. No single one is obvious in review, because each looks like ordinary code that is fine on a 300-line file. + +## The shape, and what to write instead + +Each row is something that was in the code. The left column is what to look for in a diff. + +| What it looks like | Why it grows with the square | Write this | +|---|---|---| +| `text.slice(0, i).split('\n').length`, `(text.substring(0, i).match(/\n/g) \|\| []).length`, or a loop counting newlines up to an offset | A pass over the text for each match. It was in more than fifty route and handler scans. | `lineAt(text, i)` in `src/resolution/synth-utils.ts`. In an extractor class, a table of line starts built once (see `LiquidExtractor.lineStarts`). | +| `content.split('\n')` or `split(/\r?\n/)` inside something called for each reference | The file is split again for each call. | `linesOf(text)` in `synth-utils.ts`. | +| `context.getNodesInFile(f).filter(n => n.startLine <= line && n.endLine >= line …)`, also with `find`, `some` or a `for` loop | Every node of the file, for each reference, and a reference asks several such questions. Nearly forty places. | `nodesAroundLine(context, f, line)` in `src/resolution/nodes-around.ts`, then the same test as before. With the nodes already in hand, `nodesAroundLineIn(nodes, line)`. | +| `getNodesInFile(f).find(n => n.name === x …)` | The same, by name. A routes file did it to its controller once per route. | `nodesNamed(context, f, x)` then the same test. Also `nodesNamedIn`, `nodesNamedLower`, `nodesUnder`, and `context.getNodesInFileNamed`. | +| `imports.find(m => m.localName === name)` or `imports.filter(m => m.source === s)` for each reference | Every import of the file, for each reference. | `importsBoundTo`, `importsFrom`, `importsReadBy`, `pythonMemberImports` in `src/resolution/import-lookup.ts`. | +| `this.nodes.find(n => n.id === id)` in the extractor | Every node extracted so far, for each member. | The extractor's `nodesById` map. | +| `for (let i = 0; i < node.childCount; i++) node.child(i)` and the `namedChild(i)` form; in the kernel `node.child(i)` and `named_child(i)` | Tree-sitter reaches child `i` by stepping from the first child when the children are a flat run, as a thousand comment lines or a thousand statements are. The loop is the square of the run. | Reading every child: `for (const c of node.namedChildren)`. Leaving early: `childrenOf(node)` or `namedChildrenOf(node)` in `src/extraction/tree-sitter-helpers.ts`. Kernel: `for c in node.named_children(&mut node.walk())`. | +| Finding where a declaration stands among its parent's children, to look at the siblings before it (decorators, a visibility marker) | Counted from the first child for each declaration. | Walk back from the node: `previousNamedSibling`, `prev_named_sibling()`. Where the answer depends on everything before (Ruby visibility, C++ access), keep the last answer per parent. | +| A column counted character by character from the start of its line (kernel) | A script minified to one line pays the line's length for each symbol. | `textutil::LineStarts` and `col16` in `codegraph-kernel/src/textutil.rs`. | +| `new RegExp(…name…)` built and run over the file for each symbol | The file, for each symbol. | Read the names once per file into a set and look each up (`laterExports`, `jsCodeWordSites`, `wordsWrittenBare`). | +| `source.indexOf(name, start)` or `source.includes(needle)` for each item | A scan for each item. A name declared late is found late. | Many names in one text: `firstIndexOfEach(text, names)` in `synth-utils.ts`. One fact about a file: ask once per file and keep it (`fileContains` in `src/resolution/index.ts`, `moduleDefaultStated` in `name-matcher.ts`). | +| `pattern.test(code.slice(functionStart, callOffset))` for each call in a function | The function is read from its top for each call. | Find where the first match in the function ends, once, and compare offsets (`shadowed` in `tauri-synthesizer.ts`). | +| "Does this function bind this name by this line?" answered by reading the function from its first line | The same, for each reference. | Read the function once and answer for any line (`JsNameBinding`, `pythonStatementBinders`, `pythonScopesAround`). A scan that keeps its place must answer an earlier line from what it kept, not start again. | +| `scopes.filter(outer => holds(outer, start, end))` for each route | Every route, for each route. | Keep them by stretch of the source and by path (`scanRoutes` in `frameworks/react.ts`). | +| A pattern such as `[\w.]+` given a megabyte of base64 or hex | The pattern starts a name at every character of the run and reads to its end: 30 KB cost a second. | The resolver reads files through `withoutLongRuns` (`src/file-limits.ts`). Read through `context.readFile`, never around it. | +| `target.push(...items)`, `Math.max(...values)` on a list as long as a file's imports or symbols | Not slow. It throws "Maximum call stack size exceeded" past about 125,000 items. | `pushAll`, `maxOf`, `minOf` in `src/utils.ts`. | + +Two more things that are not a line of code: + +- **The same code exists twice.** The native kernel (`codegraph-kernel/`) and the wasm extractor (`src/extraction/tree-sitter.ts`, `src/extraction/languages/`) extract the same languages. A fault fixed in one is usually in the other. The kernel reads 17 languages; the wasm extractor reads the rest, and all of them when the kernel is absent or `CODEGRAPH_KERNEL=0`. +- **Frameworks and bridges are their own passes.** `src/resolution/frameworks/*.ts` and the synthesizers read a routes file or a bridge with patterns, and link each route to its handler. They had the fault as much as the extractors, and a benchmark of plain functions never reaches them. + +## Rules for a lookup that keeps an index + +The helpers above keep an index per file. A new one follows the same rules, and `__tests__/large-file-lookups.test.ts` is where it is pinned against the expression it replaces. + +1. **Same answer, same order.** The helper returns what the old expression returned, or a superset in the file's own order that the caller filters exactly as before. `nodesAroundLine` and `nodesNamed` are supersets on purpose: the caller's test is unchanged, so its answer is. +2. **Keyed by what the context hands out.** A `WeakMap` on the array `getNodesInFile` or `getImportMappings` returned, or a map by context and file. Never a module-level map by file path alone: a resolver outlives one sync. +3. **Dropped with the caches.** A memo in `name-matcher.ts` is deleted in `clearNameMatcherMemos`, and `__tests__/name-matcher-memo-clears.test.ts` fails if it is not. A memo in `ReferenceResolver` is cleared in `clearCaches`. +4. **Small inputs take the old path.** Under a few dozen items the plain pass is as quick, and it keeps ordinary files on the code that has always run. Test both sides of the threshold. +5. **It changes nothing else.** One of these fixes changed what is read (`withoutLongRuns`); every other is the same answer reached without reading again. Keep a speed fix and a behaviour change in separate pull requests. + +## Measuring + +The benchmarks are in `scripts/benchmarks/large-files/`. Each takes a built engine and a size in megabytes, writes one generated project a case, indexes it, and marks what is over 2 seconds a megabyte. + +```bash +npm run build:kernel && npm run build + +# The 17 languages the kernel reads, about 24 shapes each (317 cases) +node scripts/benchmarks/large-files/kernel-languages.mjs dist 1.2 +node scripts/benchmarks/large-files/kernel-languages.mjs dist 3.9 python,ruby mixed,imports + +# Everything else the README lists: the other languages, each framework's +# routes file, each bridge (96 cases) +node scripts/benchmarks/large-files/other-languages.mjs dist 1.2 +node scripts/benchmarks/large-files/other-languages.mjs dist 3.9 express,rails + +# The wasm extractor, which is what a machine without the kernel runs +CODEGRAPH_KERNEL=0 node scripts/benchmarks/large-files/other-languages.mjs dist 1.2 +``` + +How to read them: + +- **Run three sizes: 0.3, 1.2 and 3.9.** A linear case takes four times as long for four times the size. One that takes ten to sixteen times as long has the fault, even when the small size looks fast. Under about half a megabyte the fixed cost of starting hides everything. +- **Read the counts, not only the seconds.** A case that yields no symbols, routes or edges gave the engine nothing to link and measured nothing. A file over the size limit is left out by the engine and looks very fast; the harness marks it `NOT MEASURED`. +- **The shape decides.** A benchmark of only functions, or only calls, hid most of the faults. The shapes that found them: functions that each declare a local and call a helper and the function before them (`mixed`), methods calling each other through the object (`members`), a table of rows, one statement that is the whole file (`object`, `switch`, `enum`), a script on one line (`minified`), one long string (`blob`, `hex`, `dots`), some thousand imports (`imports`), a long run of comment lines (`commentrun`), and for a framework its routes file together with the controller it names. +- **Start from the README's tables, not from the list of parsers.** The first pass measured the kernel's 17 languages and called it every language. The other 18 language rows, the frameworks, the routers and the bridges had the same fault. A new language, framework or bridge gets a case in `other-languages.mjs` in the same change. + +Where things stood when this was written (November 2026, one Mac): the 317 kernel cases at 3.9 MB average 2.1 seconds, the slowest 12 (a C++ file of 130,000 `#include` lines). The 96 other cases average 3.9 seconds with the largest file of each just under 4 MB. Cases around 2 seconds a megabyte that are linear, with 120,000 or more symbols in one file: Nix bindings, Elysia chains, NestJS controllers. + +## Finding the cause + +```bash +node scripts/benchmarks/large-files/profile.mjs other-languages dist 1.2 express/inline +node scripts/benchmarks/large-files/profile.mjs kernel-languages dist 1.2 python mixed +``` + +It prints the lines with the most CPU samples over every thread, with each line's text from the build. Profile at a size where the case takes several seconds: the faulty line is then most of the samples, and it is nearly always one line. Fix it, run again, and the next one surfaces; a case often has three or four behind each other. + +A line named `tree-sitter.wasm` is time inside the wasm parser, and the kernel's time shows on the one line that calls `kernel.extractFile`: neither is in the engine's TypeScript loops. For the kernel, build it with symbols and sample the process with the system's profiler to see which Rust function it is. + +## Proving nothing else changed + +A speed fix must leave the graph as it was, and the check is mechanical. Build the engine before the change (a `git worktree` of `main`, built) and after it, index the same projects with both, and compare what `scripts/dump-graph.mjs` prints: every node, edge, unresolved reference and file. + +```bash +node scripts/benchmarks/large-files/compare-graphs.mjs ../main/dist dist __tests__/fixtures src +CODEGRAPH_KERNEL=0 node scripts/benchmarks/large-files/compare-graphs.mjs ../main/dist dist __tests__/fixtures src + +# The benchmark's own projects, small, one a case +BENCH_WRITE=/tmp/cases node scripts/benchmarks/large-files/other-languages.mjs dist 0.06 +node scripts/benchmarks/large-files/compare-graphs.mjs ../main/dist dist --each /tmp/cases +``` + +Compare over, at least: `__tests__/fixtures`, this repository's `src`, real projects in the languages the change touches, the benchmark's projects written with `BENCH_WRITE`, and a small project written for each decision the faster path makes (a nested route, a name that is part of another name, Windows line endings, a file with no newline at its end). Run it with the kernel and with `CODEGRAPH_KERNEL=0`. A difference is a bug in the fix until shown otherwise. + +Then the tests. Four files pin this, and a fix adds to the one that fits: + +| Test file | What it pins | +|---|---| +| `__tests__/large-file-indexing.test.ts` | The kernel's languages: shapes of real large files at 1 to 3.9 MB, each bounded in time and checked for what the faster path decides. | +| `__tests__/large-file-frameworks.test.ts` | The other languages, routes files and bridges, the same way. | +| `__tests__/kernel-large-file-parity.test.ts` | The kernel and the wasm extractor agree on files of some thousand declarations. | +| `__tests__/large-file-lookups.test.ts` | Each lookup against the expression it replaced, on both sides of the size where it starts keeping an index. | + +A test that only bounds the time is half a test. Each case also asserts something the faster path could get wrong: the decorator on the right declaration, the route on its own handler and no other, the call a local binding hides left unlinked. + +## Traps that cost a run + +- **Run the suite without `CODEGRAPH_NO_DAEMON`.** The benchmark scripts set it for themselves. In the environment of `npm test` it fails exactly the daemon tests (38 tests in 7 files), which looks like a regression and is not. +- **The test setup rebuilds `dist` when `src` is newer.** Do not run tests while a benchmark is reading `dist`, and do not edit `src` while the suite runs: the tests that start the built CLI fail. +- **The first case pays for loading the engine.** The harnesses index a small project first; a timing script of your own must too. +- **A hand-written expectation is often wrong.** Ask the unchanged engine what it yields for a small input before asserting it. Things that surprised: a bare Ruby `private` is not read as a visibility (only `private :name`), a Kotlin `@Deprecated("x")` yields no `decorates` reference, a Python decorator written as a call is a `calls` reference. + +## Known and left as it is + +- **Tree-sitter's own error recovery.** Where a grammar cannot parse a long run of lines, the parser's recovery takes the square of the run, inside the parser. The known case is an Objective-C `@interface` holding `RCT_EXTERN_METHOD(...)` lines: 2,000 take half a second, 16,000 take 7 seconds, and about 32,000 are given up on at the parse limit, with the timeout reported. A real file has tens. The cure is a `preParse` rewrite (see `blankLoneMacroLines`), which changes what the parser makes of every such file, so it is a behaviour change with its own comparison, not a speed fix. +- **Memory.** Memory per megabyte did not change, so a 4 MB file can take four times what a 1 MB file did while it is indexed. Fourteen real files of 1 to 3.8 MB peaked between 0.15 and 0.7 GB; a 3.8 MB bundle peaked at 1.8 GB. +- **Linear, and heavy.** A file of 120,000 symbols takes 8 seconds at 3.9 MB. That is its size. + +## When an issue says indexing is slow, hangs, or a file has no symbols + +1. Get the file's language, its size, and what it mostly holds (see the shapes above). Ask for `codegraph status`: it names files left out for their size, and an index run reports a parse that timed out. +2. Check the report's date against the release that carries these fixes (see the house rule on anchoring reports in `AGENTS.md`). Before that release, every large file was slow. +3. Reproduce with a generated file of that shape at that size. If no case in the harnesses has the shape, add one: that is the first half of the fix. +4. Time it at three sizes. Four times the size for four times the time is not this fault: look at the parser (profile) or at the project (many files, not one large one). +5. Profile, fix the line, compare the graphs, add the test. + +## When a pull request touches extraction or resolution + +- Look in the diff for the left column of the table. A new `getNodesInFile(...).find`, a new `split('\n')`, a new index loop over children, a new pattern built from a name: each is fine at 300 lines and seconds at a megabyte. +- Ask what the new code does for each symbol, reference or match, and whether that depends on the file's size. +- A new language, framework or bridge comes with a case in `other-languages.mjs`, timed at 1.2 and 3.9 MB. +- Run both harnesses on the branch and on `main` for the languages it touches, and `compare-graphs.mjs` if it claims to change nothing. diff --git a/scripts/benchmarks/large-files/compare-graphs.mjs b/scripts/benchmarks/large-files/compare-graphs.mjs new file mode 100644 index 0000000000..50926ed81e --- /dev/null +++ b/scripts/benchmarks/large-files/compare-graphs.mjs @@ -0,0 +1,91 @@ +#!/usr/bin/env node +// The "same graph" check for a change meant to make indexing faster and nothing else: index +// each project with two builds of the engine and compare what scripts/dump-graph.mjs prints +// for each, every node, edge, unresolved reference and file. See +// docs/design/large-file-performance.md. +// +// node scripts/benchmarks/large-files/compare-graphs.mjs [project…] +// node scripts/benchmarks/large-files/compare-graphs.mjs --each +// +// A project is copied (without .codegraph, node_modules, .git) and indexed in a process of +// its own for each build, so neither build sees the other. Set CODEGRAPH_KERNEL=0 to compare +// the wasm extractor; run it both ways. Exits 1 when a graph differs, and prints the first +// lines only one build has. +import { spawnSync } from 'node:child_process'; +import { cpSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { basename, dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const args = process.argv.slice(2); +if (args.length < 3) { + console.error('usage: compare-graphs.mjs [project…] | --each '); + process.exit(2); +} +const [before, after] = args.slice(0, 2).map((d) => resolve(d)); +const projects = []; +for (let i = 2; i < args.length; i++) { + if (args[i] === '--each') { + const folder = resolve(args[++i]); + for (const name of readdirSync(folder).sort()) { + if (statSync(join(folder, name)).isDirectory()) projects.push(join(folder, name)); + } + } else { + projects.push(resolve(args[i])); + } +} + +const dumpScript = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'dump-graph.mjs'); +const env = { ...process.env, CODEGRAPH_TELEMETRY: '0', DO_NOT_TRACK: '1', CODEGRAPH_NO_DAEMON: '1' }; +const INDEX = ` +const { CodeGraph } = require(require('node:path').join(process.argv[1], 'index.js')); +(async () => { const cg = await CodeGraph.init(process.argv[2], { index: true }); cg.close(); })() + .catch((error) => { console.error(error); process.exit(1); }); +`; +const SKIPPED = /[\\/](?:\.codegraph|node_modules|\.git)(?:[\\/]|$)/; + +/** Index a copy of `project` with the build at `dist`; the dump of its graph and the seconds it took. */ +function graphOf(dist, project) { + const dir = mkdtempSync(join(tmpdir(), 'cg-compare-')); + try { + cpSync(project, dir, { recursive: true, filter: (source) => !SKIPPED.test(source.slice(project.length)) }); + const started = Date.now(); + const indexed = spawnSync(process.execPath, ['-e', INDEX, dist, dir], { env, encoding: 'utf8' }); + const seconds = (Date.now() - started) / 1000; + if (indexed.status !== 0) throw new Error(`indexing with ${dist} failed:\n${indexed.stderr}`); + // To a file: the dump of a large project is longer than a string can be. + const out = join(dir, '.codegraph', 'graph.dump'); + const dumped = spawnSync(process.execPath, [dumpScript, dir], { env, stdio: ['ignore', 'pipe', 'inherit'], maxBuffer: 2 ** 31 - 1 }); + if (dumped.status !== 0 || !dumped.stdout) throw new Error(`dump-graph.mjs failed for ${project}`); + writeFileSync(out, dumped.stdout); + return { dump: readFileSync(out), seconds }; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +/** The lines of one dump that the other does not have. */ +function onlyIn(a, b) { + const other = new Set(b.toString('utf8').split('\n')); + return a.toString('utf8').split('\n').filter((line) => !other.has(line)); +} + +let differing = 0; +for (const project of projects) { + const a = graphOf(before, project); + const b = graphOf(after, project); + const lines = a.dump.toString('utf8').split('\n').length; + const times = `${a.seconds.toFixed(1)} s before, ${b.seconds.toFixed(1)} s after`; + if (a.dump.equals(b.dump)) { + console.log(`same ${basename(project)}: ${lines} lines, ${times}`); + continue; + } + differing++; + const gone = onlyIn(a.dump, b.dump); + const added = onlyIn(b.dump, a.dump); + console.log(`DIFFER ${basename(project)}: ${gone.length} lines only before, ${added.length} only after, ${times}`); + for (const line of gone.slice(0, 4)) console.log(` - ${line.slice(0, 300)}`); + for (const line of added.slice(0, 4)) console.log(` + ${line.slice(0, 300)}`); +} +console.log(`\n${projects.length - differing} the same, ${differing} differ`); +process.exit(differing ? 1 : 0); diff --git a/scripts/benchmarks/large-files/kernel-languages.mjs b/scripts/benchmarks/large-files/kernel-languages.mjs new file mode 100644 index 0000000000..fc643d9f1f --- /dev/null +++ b/scripts/benchmarks/large-files/kernel-languages.mjs @@ -0,0 +1,241 @@ +// How long the engine takes to index one large file, for each language its native kernel +// reads and each of several shapes a large file takes. An extractor and resolver that are +// linear index any of these in about a second a megabyte; work that grows with the square of +// the file shows as tens of seconds. See docs/design/large-file-performance.md. +// +// node scripts/benchmarks/large-files/kernel-languages.mjs [language,language…] [shape,shape…] +// +// Prints one line a case: seconds to index, and the symbols the large file yielded (0 means +// the file was given up on, or the shape has none to yield). Cases over 2 seconds a megabyte +// are marked and listed at the end. Set CODEGRAPH_KERNEL=0 to time the wasm extractor. +// BENCH_WRITE= writes the files out instead of timing them (for compare-graphs.mjs). +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { createRequire } from 'node:module'; +import { more } from './kernel-shapes.mjs'; + +const [distArg, megabytes = '0.5', onlyLanguages = '', onlyShapes = ''] = process.argv.slice(2); +if (!distArg) { + console.error('usage: kernel-languages.mjs [languages] [shapes]'); + process.exit(2); +} +const dist = resolve(distArg); +// The benchmark times the index, not telemetry or a shared daemon. +Object.assign(process.env, { CODEGRAPH_TELEMETRY: '0', DO_NOT_TRACK: '1', CODEGRAPH_NO_DAEMON: '1' }); +const require = createRequire(import.meta.url); +const { CodeGraph } = require(join(dist, 'index.js')); +const { MAX_SOURCE_FILE_SIZE_BYTES } = require(join(dist, 'file-limits.js')); +const bytes = +megabytes * 1024 * 1024; + +/** Repeat `unit(i)` until the text is `bytes` long, between a head and a tail. */ +const fill = (unit, head = '', tail = '', size = bytes) => { + const parts = [head]; + let length = head.length + tail.length; + for (let i = 0; length < size; i++) { + const part = unit(i); + parts.push(part); + length += part.length; + } + parts.push(tail); + return parts.join(''); +}; + +// Each language: its file extension and the shapes it has. A shape is the whole file's text. +const LANGUAGES = { + python: { + ext: 'py', + functions: () => fill((i) => `def thing${i}(name):\n return name + "${i}"\n\n`), + decorated: () => fill((i) => `@cached\ndef thing${i}(name):\n return name + "${i}"\n\n`, 'def cached(f):\n return f\n\n'), + methods: () => fill((i) => ` def thing${i}(self, name):\n return name + "${i}"\n\n`, 'class Big:\n'), + variables: () => fill((i) => `VALUE_${i} = "${i}" + str(${i})\n`), + data: () => fill((i) => ` ("name${i}", ${i}, helper(${i})),\n`, 'def helper(x):\n return x\n\nROWS = [\n', ']\n'), + calls: () => fill((i) => ` helper(${i}, "name${i}")\n`, 'def helper(x, y):\n return x\n\ndef run():\n'), + classes: () => fill((i) => `class Thing${i}:\n def run(self):\n return ${i}\n\n`), + }, + ruby: { + ext: 'rb', + functions: () => fill((i) => `def thing${i}(name)\n name.to_s + "${i}"\nend\n\n`), + methods: () => fill((i) => ` def thing${i}(name)\n name.to_s + "${i}"\n end\n\n`, 'class Big\n', 'end\n'), + variables: () => fill((i) => `VALUE_${i} = "${i}" + ${i}.to_s\n`), + data: () => fill((i) => ` ["name${i}", ${i}, helper(${i})],\n`, 'def helper(x)\n x\nend\n\nROWS = [\n', ']\n'), + calls: () => fill((i) => ` helper(${i}, "name${i}")\n`, 'def helper(x, y)\n x\nend\n\ndef run\n', 'end\n'), + classes: () => fill((i) => `class Thing${i}\n def run\n ${i}\n end\nend\n\n`), + }, + typescript: { + ext: 'ts', + functions: () => fill((i) => `function thing${i}(name: string): string {\n return name + "${i}";\n}\n\n`), + exported: () => fill((i) => `export function thing${i}(name: string): string {\n return name + "${i}";\n}\n\n`), + methods: () => fill((i) => ` thing${i}(name: string): string {\n return name + "${i}";\n }\n\n`, 'export class Big {\n', '}\n'), + decorated: () => fill((i) => ` @cached()\n thing${i}(name: string): string {\n return name + "${i}";\n }\n\n`, 'declare function cached(): any;\nexport class Big {\n', '}\n'), + variables: () => fill((i) => `export const VALUE_${i} = "${i}" + String(${i});\n`), + data: () => fill((i) => ` ["name${i}", ${i}, helper(${i})],\n`, 'function helper(x: number) { return x; }\nexport const ROWS = [\n', '];\n'), + calls: () => fill((i) => ` helper(${i}, "name${i}");\n`, 'function helper(x: number, y: string) { return x; }\nexport function run() {\n', '}\n'), + classes: () => fill((i) => `class Thing${i} {\n run() {\n return ${i};\n }\n}\n\n`), + }, + javascript: { + ext: 'js', + functions: () => fill((i) => `function thing${i}(name) {\n return name + "${i}";\n}\n\n`), + methods: () => fill((i) => ` thing${i}(name) {\n return name + "${i}";\n }\n\n`, 'class Big {\n', '}\n'), + variables: () => fill((i) => `const VALUE_${i} = "${i}" + String(${i});\n`), + data: () => fill((i) => ` ["name${i}", ${i}, helper(${i})],\n`, 'function helper(x) { return x; }\nconst ROWS = [\n', '];\n'), + calls: () => fill((i) => ` helper(${i}, "name${i}");\n`, 'function helper(x, y) { return x; }\nfunction run() {\n', '}\n'), + }, + go: { + ext: 'go', + functions: () => fill((i) => `func Thing${i}(name string) string {\n\treturn name + "${i}"\n}\n\n`, 'package big\n\n'), + methods: () => fill((i) => `func (b *Big) Thing${i}(name string) string {\n\treturn name + "${i}"\n}\n\n`, 'package big\n\ntype Big struct{}\n\n'), + variables: () => fill((i) => `var Value${i} = "${i}" + "x"\n`, 'package big\n\n'), + data: () => fill((i) => `\t{"name${i}", ${i}, helper(${i})},\n`, 'package big\n\ntype row struct {\n\tname string\n\tn int\n\th int\n}\n\nfunc helper(x int) int { return x }\n\nvar Rows = []row{\n', '}\n'), + calls: () => fill((i) => `\thelper(${i}, "name${i}")\n`, 'package big\n\nfunc helper(x int, y string) int { return x }\n\nfunc Run() {\n', '}\n'), + types: () => fill((i) => `type Thing${i} struct {\n\tName string\n}\n\n`, 'package big\n\n'), + }, + java: { + ext: 'java', + methods: () => fill((i) => ` String thing${i}(String name) {\n return name + "${i}";\n }\n\n`, 'public class Big {\n', '}\n'), + decorated: () => fill((i) => ` @Deprecated\n String thing${i}(String name) {\n return name + "${i}";\n }\n\n`, 'public class Big {\n', '}\n'), + variables: () => fill((i) => ` static final String VALUE_${i} = "${i}" + "x";\n`, 'public class Big {\n', '}\n'), + data: () => fill((i) => ` {"name${i}", "${i}", helper(${i})},\n`, 'public class Big {\n static String helper(int x) { return "" + x; }\n static final String[][] ROWS = {\n', ' };\n}\n'), + calls: () => fill((i) => ` helper(${i}, "name${i}");\n`, 'public class Big {\n static int helper(int x, String y) { return x; }\n void run() {\n', ' }\n}\n'), + classes: () => fill((i) => `class Thing${i} {\n int run() {\n return ${i};\n }\n}\n\n`), + }, + csharp: { + ext: 'cs', + methods: () => fill((i) => ` string Thing${i}(string name) {\n return name + "${i}";\n }\n\n`, 'public class Big {\n', '}\n'), + decorated: () => fill((i) => ` [Obsolete]\n string Thing${i}(string name) {\n return name + "${i}";\n }\n\n`, 'public class Big {\n', '}\n'), + variables: () => fill((i) => ` const string Value${i} = "${i}" + "x";\n`, 'public class Big {\n', '}\n'), + calls: () => fill((i) => ` Helper(${i}, "name${i}");\n`, 'public class Big {\n static int Helper(int x, string y) { return x; }\n void Run() {\n', ' }\n}\n'), + classes: () => fill((i) => `class Thing${i} {\n int Run() {\n return ${i};\n }\n}\n\n`), + }, + php: { + ext: 'php', + functions: () => fill((i) => `function thing${i}($name) {\n return $name . "${i}";\n}\n\n`, ' fill((i) => ` function thing${i}($name) {\n return $name . "${i}";\n }\n\n`, ' fill((i) => ` ["name${i}", ${i}, helper(${i})],\n`, ' fill((i) => ` helper(${i}, "name${i}");\n`, ' fill((i) => `class Thing${i} {\n function run() {\n return ${i};\n }\n}\n\n`, ' fill((i) => `fun thing${i}(name: String): String {\n return name + "${i}"\n}\n\n`), + decorated: () => fill((i) => `@Deprecated("x")\nfun thing${i}(name: String): String {\n return name + "${i}"\n}\n\n`), + methods: () => fill((i) => ` fun thing${i}(name: String): String {\n return name + "${i}"\n }\n\n`, 'class Big {\n', '}\n'), + variables: () => fill((i) => `val VALUE_${i} = "${i}" + "x"\n`), + calls: () => fill((i) => ` helper(${i}, "name${i}")\n`, 'fun helper(x: Int, y: String): Int { return x }\n\nfun run() {\n', '}\n'), + classes: () => fill((i) => `class Thing${i} {\n fun run(): Int {\n return ${i}\n }\n}\n\n`), + }, + swift: { + ext: 'swift', + functions: () => fill((i) => `func thing${i}(name: String) -> String {\n return name + "${i}"\n}\n\n`), + decorated: () => fill((i) => `@discardableResult\nfunc thing${i}(name: String) -> String {\n return name + "${i}"\n}\n\n`), + methods: () => fill((i) => ` func thing${i}(name: String) -> String {\n return name + "${i}"\n }\n\n`, 'class Big {\n', '}\n'), + variables: () => fill((i) => `let value${i} = "${i}" + "x"\n`), + calls: () => fill((i) => ` helper(${i}, "name${i}")\n`, 'func helper(_ x: Int, _ y: String) -> Int { return x }\n\nfunc run() {\n', '}\n'), + classes: () => fill((i) => `class Thing${i} {\n func run() -> Int {\n return ${i}\n }\n}\n\n`), + }, + scala: { + ext: 'scala', + functions: () => fill((i) => ` def thing${i}(name: String): String = {\n name + "${i}"\n }\n\n`, 'object Big {\n', '}\n'), + decorated: () => fill((i) => ` @deprecated\n def thing${i}(name: String): String = {\n name + "${i}"\n }\n\n`, 'object Big {\n', '}\n'), + variables: () => fill((i) => ` val value${i} = "${i}" + "x"\n`, 'object Big {\n', '}\n'), + calls: () => fill((i) => ` helper(${i}, "name${i}")\n`, 'object Big {\n def helper(x: Int, y: String): Int = x\n def run(): Unit = {\n', ' }\n}\n'), + classes: () => fill((i) => `class Thing${i} {\n def run(): Int = ${i}\n}\n\n`), + }, + dart: { + ext: 'dart', + functions: () => fill((i) => `String thing${i}(String name) {\n return name + "${i}";\n}\n\n`), + decorated: () => fill((i) => `@deprecated\nString thing${i}(String name) {\n return name + "${i}";\n}\n\n`), + methods: () => fill((i) => ` String thing${i}(String name) {\n return name + "${i}";\n }\n\n`, 'class Big {\n', '}\n'), + variables: () => fill((i) => `const value${i} = "${i}" + "x";\n`), + calls: () => fill((i) => ` helper(${i}, "name${i}");\n`, 'int helper(int x, String y) { return x; }\n\nvoid run() {\n', '}\n'), + classes: () => fill((i) => `class Thing${i} {\n int run() {\n return ${i};\n }\n}\n\n`), + }, + rust: { + ext: 'rs', + functions: () => fill((i) => `fn thing${i}(name: &str) -> String {\n format!("{}${i}", name)\n}\n\n`), + decorated: () => fill((i) => `#[inline]\nfn thing${i}(name: &str) -> String {\n format!("{}${i}", name)\n}\n\n`), + methods: () => fill((i) => ` fn thing${i}(&self, name: &str) -> String {\n format!("{}${i}", name)\n }\n\n`, 'struct Big;\n\nimpl Big {\n', '}\n'), + variables: () => fill((i) => `const VALUE_${i}: &str = "${i}";\n`), + data: () => fill((i) => ` ("name${i}", ${i}, helper(${i})),\n`, 'const fn helper(x: i32) -> i32 { x }\n\nstatic ROWS: &[(&str, i32, i32)] = &[\n', '];\n'), + calls: () => fill((i) => ` helper(${i}, "name${i}");\n`, 'fn helper(x: i32, y: &str) -> i32 { x }\n\nfn run() {\n', '}\n'), + types: () => fill((i) => `struct Thing${i} {\n name: String,\n}\n\n`), + }, + c: { + ext: 'c', + functions: () => fill((i) => `int thing${i}(int name) {\n return name + ${i};\n}\n\n`), + variables: () => fill((i) => `static const int VALUE_${i} = ${i} + 1;\n`), + data: () => fill((i) => ` {"name${i}", ${i}, ${i} * 2},\n`, 'struct row { const char *name; int n; int h; };\n\nstatic const struct row ROWS[] = {\n', '};\n'), + calls: () => fill((i) => ` helper(${i}, "name${i}");\n`, 'int helper(int x, const char *y) { return x; }\n\nvoid run(void) {\n', '}\n'), + types: () => fill((i) => `struct thing${i} {\n int name;\n};\n\n`), + }, + cpp: { + ext: 'cpp', + functions: () => fill((i) => `int thing${i}(int name) {\n return name + ${i};\n}\n\n`), + methods: () => fill((i) => ` int thing${i}(int name) {\n return name + ${i};\n }\n\n`, 'class Big {\npublic:\n', '};\n'), + calls: () => fill((i) => ` helper(${i}, "name${i}");\n`, 'int helper(int x, const char *y) { return x; }\n\nvoid run() {\n', '}\n'), + classes: () => fill((i) => `class Thing${i} {\npublic:\n int run() {\n return ${i};\n }\n};\n\n`), + }, + lua: { + ext: 'lua', + functions: () => fill((i) => `local function thing${i}(name)\n return name .. "${i}"\nend\n\n`), + methods: () => fill((i) => `function Big.thing${i}(name)\n return name .. "${i}"\nend\n\n`, 'local Big = {}\n\n', 'return Big\n'), + variables: () => fill((i) => `VALUE_${i} = "${i}" .. "x"\n`), + data: () => fill((i) => ` {"name${i}", ${i}, helper(${i})},\n`, 'local function helper(x) return x end\n\nROWS = {\n', '}\n'), + calls: () => fill((i) => ` helper(${i}, "name${i}")\n`, 'local function helper(x, y) return x end\n\nlocal function run()\n', 'end\n'), + }, + r: { + ext: 'R', + functions: () => fill((i) => `thing${i} <- function(name) {\n paste0(name, "${i}")\n}\n\n`), + variables: () => fill((i) => `value${i} <- paste0("${i}", "x")\n`), + calls: () => fill((i) => ` helper(${i}, "name${i}")\n`, 'helper <- function(x, y) x\n\nrun <- function() {\n', '}\n'), + }, +}; + +for (const [language, shapes] of Object.entries(more(fill, bytes))) Object.assign(LANGUAGES[language], shapes); + +if (process.env.BENCH_WRITE) { + for (const [language, { ext, ...shapes }] of Object.entries(LANGUAGES)) { + for (const [shape, text] of Object.entries(shapes)) { + if (onlyShapes && !onlyShapes.split(',').includes(shape)) continue; + const dir = join(process.env.BENCH_WRITE, language, shape); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, `big.${ext}`), text()); + } + } + process.exit(0); +} + +// A small first run, so the first case timed does not pay for loading the engine. +{ + const dir = mkdtempSync(join(tmpdir(), 'cg-bench-warm-')); + mkdirSync(join(dir, 'src')); + writeFileSync(join(dir, 'src', 'warm.ts'), 'export function warm() { return 1; }\n'); + (await CodeGraph.init(dir, { index: true })).close(); + rmSync(dir, { recursive: true, force: true }); +} + +const languages = onlyLanguages ? onlyLanguages.split(',') : Object.keys(LANGUAGES); +const slow = []; +for (const language of languages) { + const { ext, ...shapes } = LANGUAGES[language]; + for (const [shape, text] of Object.entries(shapes)) { + if (onlyShapes && !onlyShapes.split(',').includes(shape)) continue; + const dir = mkdtempSync(join(tmpdir(), 'cg-bench-big-')); + mkdirSync(join(dir, 'src')); + const source = text(); + writeFileSync(join(dir, 'src', `big.${ext}`), source); + const started = Date.now(); + const cg = await CodeGraph.init(dir, { index: true }); + const seconds = (Date.now() - started) / 1000; + const symbols = cg.getNodesInFile(`src/big.${ext}`).filter((n) => n.kind !== 'file').length; + cg.close(); + rmSync(dir, { recursive: true, force: true }); + const perMb = seconds / (source.length / 1024 / 1024); + // A file over the engine's limit is left out of the index, so its time says nothing. + const over = Buffer.byteLength(source) > MAX_SOURCE_FILE_SIZE_BYTES; + const mark = over ? ' <-- NOT MEASURED: over the size limit' : perMb > 2 ? ' <-- slow' : symbols === 0 ? ' (no symbols)' : ''; + if (over || perMb > 2) slow.push(`${language}/${shape}`); + console.log(`${language.padEnd(11)} ${shape.padEnd(10)} ${seconds.toFixed(1).padStart(6)} s ${String(symbols).padStart(7)} symbols${mark}`); + } +} +console.log(slow.length ? `\nslow (over 2 s a megabyte) or not measured: ${slow.join(', ')}` : '\nnothing over 2 s a megabyte'); diff --git a/scripts/benchmarks/large-files/kernel-shapes.mjs b/scripts/benchmarks/large-files/kernel-shapes.mjs new file mode 100644 index 0000000000..9c5cc47177 --- /dev/null +++ b/scripts/benchmarks/large-files/kernel-shapes.mjs @@ -0,0 +1,220 @@ +// More shapes for kernel-languages.mjs: the ones real large files take (a table of rows, one +// statement that is the whole file, one line that is the whole file, one long string, some +// thousand imports, long runs of comments). `more(fill)` returns, by language, shape -> () => text. +const p = (i) => (i ? i - 1 : 0); + +// [unit, head, tail] for a file of functions that each declare a local, call a helper and +// call the function before them. +const MIXED = { + python: [(i) => `def thing${i}(name):\n value = helper(name)\n return thing${p(i)}(value)\n\n`, 'def helper(x):\n return x\n\n'], + ruby: [(i) => `def thing${i}(name)\n value = helper(name)\n thing${p(i)}(value)\nend\n\n`, 'def helper(x)\n x\nend\n\n'], + typescript: [(i) => `export function thing${i}(name: string): string {\n const value = helper(name);\n return thing${p(i)}(value);\n}\n\n`, 'function helper(x: string) { return x; }\n\n'], + javascript: [(i) => `function thing${i}(name) {\n const value = helper(name);\n return thing${p(i)}(value);\n}\n\n`, 'function helper(x) { return x; }\n\n'], + go: [(i) => `func Thing${i}(name string) string {\n\tvalue := helper(name)\n\treturn Thing${p(i)}(value)\n}\n\n`, 'package big\n\nfunc helper(x string) string { return x }\n\n'], + java: [(i) => ` String thing${i}(String name) {\n String value = helper(name);\n return thing${p(i)}(value);\n }\n\n`, 'public class Big {\n static String helper(String x) { return x; }\n\n', '}\n'], + csharp: [(i) => ` string Thing${i}(string name) {\n var value = Helper(name);\n return Thing${p(i)}(value);\n }\n\n`, 'public class Big {\n static string Helper(string x) { return x; }\n\n', '}\n'], + php: [(i) => `function thing${i}($name) {\n $value = helper($name);\n return thing${p(i)}($value);\n}\n\n`, ' `fun thing${i}(name: String): String {\n val value = helper(name)\n return thing${p(i)}(value)\n}\n\n`, 'fun helper(x: String): String { return x }\n\n'], + swift: [(i) => `func thing${i}(name: String) -> String {\n let value = helper(name)\n return thing${p(i)}(name: value)\n}\n\n`, 'func helper(_ x: String) -> String { return x }\n\n'], + scala: [(i) => ` def thing${i}(name: String): String = {\n val value = helper(name)\n thing${p(i)}(value)\n }\n\n`, 'object Big {\n def helper(x: String): String = x\n\n', '}\n'], + dart: [(i) => `String thing${i}(String name) {\n final value = helper(name);\n return thing${p(i)}(value);\n}\n\n`, 'String helper(String x) { return x; }\n\n'], + rust: [(i) => `fn thing${i}(name: &str) -> String {\n let value = helper(name);\n thing${p(i)}(&value)\n}\n\n`, 'fn helper(x: &str) -> String { x.to_string() }\n\n'], + c: [(i) => `int thing${i}(int name) {\n int value = helper(name);\n return thing${p(i)}(value);\n}\n\n`, 'int helper(int x) { return x; }\n\n'], + cpp: [(i) => `int thing${i}(int name) {\n int value = helper(name);\n return thing${p(i)}(value);\n}\n\n`, 'int helper(int x) { return x; }\n\n'], + lua: [(i) => `local function thing${i}(name)\n local value = helper(name)\n return thing${p(i)}(value)\nend\n\n`, 'local function helper(x) return x end\n\n'], + r: [(i) => `thing${i} <- function(name) {\n value <- helper(name)\n thing${p(i)}(value)\n}\n\n`, 'helper <- function(x) x\n\n'], +}; + +// A class whose methods call each other through the object. +const MEMBERS = { + python: [(i) => ` def thing${i}(self, name):\n value = self.helper(name)\n return self.thing${p(i)}(value)\n\n`, 'class Big:\n def helper(self, x):\n return x\n\n'], + ruby: [(i) => ` def thing${i}(name)\n value = self.helper(name)\n self.thing${p(i)}(value)\n end\n\n`, 'class Big\n def helper(x)\n x\n end\n\n', 'end\n'], + typescript: [(i) => ` thing${i}(name: string): string {\n const value = this.helper(name);\n return this.thing${p(i)}(value);\n }\n\n`, 'export class Big {\n helper(x: string) { return x; }\n\n', '}\n'], + javascript: [(i) => ` thing${i}(name) {\n const value = this.helper(name);\n return this.thing${p(i)}(value);\n }\n\n`, 'class Big {\n helper(x) { return x; }\n\n', '}\n'], + go: [(i) => `func (b *Big) Thing${i}(name string) string {\n\tvalue := b.helper(name)\n\treturn b.Thing${p(i)}(value)\n}\n\n`, 'package big\n\ntype Big struct{}\n\nfunc (b *Big) helper(x string) string { return x }\n\n'], + java: [(i) => ` String thing${i}(String name) {\n String value = this.helper(name);\n return this.thing${p(i)}(value);\n }\n\n`, 'public class Big {\n String helper(String x) { return x; }\n\n', '}\n'], + csharp: [(i) => ` string Thing${i}(string name) {\n var value = this.Helper(name);\n return this.Thing${p(i)}(value);\n }\n\n`, 'public class Big {\n string Helper(string x) { return x; }\n\n', '}\n'], + php: [(i) => ` function thing${i}($name) {\n $value = $this->helper($name);\n return $this->thing${p(i)}($value);\n }\n\n`, ' ` fun thing${i}(name: String): String {\n val value = this.helper(name)\n return this.thing${p(i)}(value)\n }\n\n`, 'class Big {\n fun helper(x: String): String { return x }\n\n', '}\n'], + swift: [(i) => ` func thing${i}(name: String) -> String {\n let value = self.helper(name)\n return self.thing${p(i)}(name: value)\n }\n\n`, 'class Big {\n func helper(_ x: String) -> String { return x }\n\n', '}\n'], + scala: [(i) => ` def thing${i}(name: String): String = {\n val value = this.helper(name)\n this.thing${p(i)}(value)\n }\n\n`, 'class Big {\n def helper(x: String): String = x\n\n', '}\n'], + dart: [(i) => ` String thing${i}(String name) {\n final value = this.helper(name);\n return this.thing${p(i)}(value);\n }\n\n`, 'class Big {\n String helper(String x) { return x; }\n\n', '}\n'], + rust: [(i) => ` fn thing${i}(&self, name: &str) -> String {\n let value = self.helper(name);\n self.thing${p(i)}(&value)\n }\n\n`, 'struct Big;\n\nimpl Big {\n fn helper(&self, x: &str) -> String { x.to_string() }\n\n', '}\n'], + cpp: [(i) => ` int thing${i}(int name) {\n int value = this->helper(name);\n return this->thing${p(i)}(value);\n }\n\n`, 'class Big {\npublic:\n int helper(int x) { return x; }\n\n', '};\n'], + lua: [(i) => `function Big:thing${i}(name)\n local value = self:helper(name)\n return self:thing${p(i)}(value)\nend\n\n`, 'local Big = {}\n\nfunction Big:helper(x) return x end\n\n', 'return Big\n'], +}; + +// One large enumeration. +const ENUM = { + typescript: [(i) => ` Member${i} = ${i},\n`, 'export enum Big {\n', '}\n'], + java: [(i) => ` MEMBER_${i},\n`, 'public enum Big {\n', '}\n'], + csharp: [(i) => ` Member${i} = ${i},\n`, 'public enum Big {\n', '}\n'], + kotlin: [(i) => ` MEMBER_${i},\n`, 'enum class Big {\n', '}\n'], + swift: [(i) => ` case member${i}\n`, 'enum Big {\n', '}\n'], + rust: [(i) => ` Member${i},\n`, 'pub enum Big {\n', '}\n'], + c: [(i) => ` MEMBER_${i} = ${i},\n`, 'enum big {\n', '};\n'], + cpp: [(i) => ` Member${i} = ${i},\n`, 'enum class Big {\n', '};\n'], + dart: [(i) => ` member${i},\n`, 'enum Big {\n', '}\n'], + go: [(i) => `\tMember${i} = ${i}\n`, 'package big\n\nconst (\n', ')\n'], + php: [(i) => ` case Member${i} = ${i};\n`, ' ` MEMBER_${i} = ${i}\n`, 'import enum\n\nclass Big(enum.Enum):\n'], + scala: [(i) => ` case Member${i}\n`, 'enum Big {\n', '}\n'], +}; + +// One function that is one large switch. +const SWITCH = { + typescript: [(i) => ` case ${i}:\n return helper(${i});\n`, 'function helper(x: number) { return x; }\nexport function run(key: number): number {\n switch (key) {\n', ' default:\n return 0;\n }\n}\n'], + javascript: [(i) => ` case ${i}:\n return helper(${i});\n`, 'function helper(x) { return x; }\nfunction run(key) {\n switch (key) {\n', ' default:\n return 0;\n }\n}\n'], + java: [(i) => ` case ${i}:\n return helper(${i});\n`, 'public class Big {\n static int helper(int x) { return x; }\n int run(int key) {\n switch (key) {\n', ' default:\n return 0;\n }\n }\n}\n'], + csharp: [(i) => ` case ${i}:\n return Helper(${i});\n`, 'public class Big {\n static int Helper(int x) { return x; }\n int Run(int key) {\n switch (key) {\n', ' default:\n return 0;\n }\n }\n}\n'], + go: [(i) => `\tcase ${i}:\n\t\treturn helper(${i})\n`, 'package big\n\nfunc helper(x int) int { return x }\n\nfunc Run(key int) int {\n\tswitch key {\n', '\t}\n\treturn 0\n}\n'], + rust: [(i) => ` ${i} => helper(${i}),\n`, 'fn helper(x: i32) -> i32 { x }\n\nfn run(key: i32) -> i32 {\n match key {\n', ' _ => 0,\n }\n}\n'], + c: [(i) => ` case ${i}:\n return helper(${i});\n`, 'int helper(int x) { return x; }\n\nint run(int key) {\n switch (key) {\n', ' default:\n return 0;\n }\n}\n'], + cpp: [(i) => ` case ${i}:\n return helper(${i});\n`, 'int helper(int x) { return x; }\n\nint run(int key) {\n switch (key) {\n', ' default:\n return 0;\n }\n}\n'], + php: [(i) => ` case ${i}:\n return helper(${i});\n`, ' ` ${i} -> helper(${i})\n`, 'fun helper(x: Int): Int { return x }\n\nfun run(key: Int): Int {\n return when (key) {\n', ' else -> 0\n }\n}\n'], + swift: [(i) => ` case ${i}:\n return helper(${i})\n`, 'func helper(_ x: Int) -> Int { return x }\n\nfunc run(key: Int) -> Int {\n switch key {\n', ' default:\n return 0\n }\n}\n'], + dart: [(i) => ` case ${i}:\n return helper(${i});\n`, 'int helper(int x) { return x; }\n\nint run(int key) {\n switch (key) {\n', ' default:\n return 0;\n }\n}\n'], + scala: [(i) => ` case ${i} => helper(${i})\n`, 'object Big {\n def helper(x: Int): Int = x\n def run(key: Int): Int = {\n key match {\n', ' case _ => 0\n }\n }\n}\n'], + python: [(i) => ` elif key == ${i}:\n return helper(${i})\n`, 'def helper(x):\n return x\n\ndef run(key):\n if key == -1:\n return 0\n'], + ruby: [(i) => ` when ${i}\n helper(${i})\n`, 'def helper(x)\n x\nend\n\ndef run(key)\n case key\n', ' end\nend\n'], + lua: [(i) => ` elseif key == ${i} then\n return helper(${i})\n`, 'local function helper(x) return x end\n\nlocal function run(key)\n if key == -1 then\n return 0\n', ' end\nend\n'], +}; + +// Nothing but imports. +const IMPORTS = { + python: [(i) => `from pkg.mod${i} import name${i}\n`], + typescript: [(i) => `import { name${i} } from './mod${i}';\n`], + javascript: [(i) => `const name${i} = require('./mod${i}');\n`], + java: [(i) => `import pkg.mod${i}.Name${i};\n`, '', 'public class Big {}\n'], + go: [(i) => `\tname${i} "example.com/pkg/mod${i}"\n`, 'package big\n\nimport (\n', ')\n'], + rust: [(i) => `use crate::mod${i}::Name${i};\n`], + kotlin: [(i) => `import pkg.mod${i}.Name${i}\n`], + csharp: [(i) => `using Pkg.Mod${i};\n`], + php: [(i) => `use Pkg\\Mod${i}\\Name${i};\n`, ' `import Mod${i}\n`], + dart: [(i) => `import 'mod${i}.dart';\n`], + scala: [(i) => `import pkg.mod${i}.Name${i}\n`], + c: [(i) => `#include "mod${i}.h"\n`], + cpp: [(i) => `#include "mod${i}.h"\n`], + ruby: [(i) => `require_relative 'mod${i}'\n`], + lua: [(i) => `local name${i} = require("mod${i}")\n`], +}; + +// Each function under a comment of several lines. +const COMMENTED = { + python: [(i) => `def thing${i}(name):\n """Thing ${i}.\n\n Takes a name and returns it.\n """\n return name\n\n`], + typescript: [(i) => `/**\n * Thing ${i}.\n *\n * Takes a name and returns it.\n */\nexport function thing${i}(name: string): string {\n return name;\n}\n\n`], + javascript: [(i) => `/**\n * Thing ${i}.\n *\n * Takes a name and returns it.\n */\nfunction thing${i}(name) {\n return name;\n}\n\n`], + java: [(i) => ` /**\n * Thing ${i}.\n *\n * Takes a name and returns it.\n */\n String thing${i}(String name) {\n return name;\n }\n\n`, 'public class Big {\n', '}\n'], + go: [(i) => `// Thing${i} is thing ${i}.\n//\n// It takes a name and returns it.\nfunc Thing${i}(name string) string {\n\treturn name\n}\n\n`, 'package big\n\n'], + rust: [(i) => `/// Thing ${i}.\n///\n/// Takes a name and returns it.\nfn thing${i}(name: &str) -> &str {\n name\n}\n\n`], + c: [(i) => `/*\n * Thing ${i}.\n *\n * Takes a name and returns it.\n */\nint thing${i}(int name) {\n return name;\n}\n\n`], + cpp: [(i) => `// Thing ${i}.\n//\n// Takes a name and returns it.\nint thing${i}(int name) {\n return name;\n}\n\n`], + ruby: [(i) => `# Thing ${i}.\n#\n# Takes a name and returns it.\ndef thing${i}(name)\n name\nend\n\n`], + php: [(i) => `/**\n * Thing ${i}.\n *\n * Takes a name and returns it.\n */\nfunction thing${i}($name) {\n return $name;\n}\n\n`, ' `/**\n * Thing ${i}.\n *\n * Takes a name and returns it.\n */\nfun thing${i}(name: String): String {\n return name\n}\n\n`], + swift: [(i) => `/// Thing ${i}.\n///\n/// Takes a name and returns it.\nfunc thing${i}(name: String) -> String {\n return name\n}\n\n`], + csharp: [(i) => ` /// \n /// Thing ${i}.\n /// \n string Thing${i}(string name) {\n return name;\n }\n\n`, 'public class Big {\n', '}\n'], + dart: [(i) => `/// Thing ${i}.\n///\n/// Takes a name and returns it.\nString thing${i}(String name) {\n return name;\n}\n\n`], + scala: [(i) => ` /** Thing ${i}.\n *\n * Takes a name and returns it.\n */\n def thing${i}(name: String): String = name\n\n`, 'object Big {\n', '}\n'], + lua: [(i) => `--- Thing ${i}.\n--\n-- Takes a name and returns it.\nlocal function thing${i}(name)\n return name\nend\n\n`], +}; + +// One object or table of named entries, each a small function or a call. +const OBJECT = { + typescript: [(i) => ` thing${i}(name: string): string {\n return helper(name);\n },\n`, 'function helper(x: string) { return x; }\nexport const api = {\n', '};\n'], + javascript: [(i) => ` thing${i}: function (name) {\n return helper(name);\n },\n`, 'function helper(x) { return x; }\nmodule.exports = {\n', '};\n'], + python: [(i) => ` "thing${i}": lambda name: helper(name),\n`, 'def helper(x):\n return x\n\nTABLE = {\n', '}\n'], + ruby: [(i) => ` thing${i}: ->(name) { helper(name) },\n`, 'def helper(x)\n x\nend\n\nTABLE = {\n', '}\n'], + lua: [(i) => ` thing${i} = function(name) return helper(name) end,\n`, 'local function helper(x) return x end\n\nlocal TABLE = {\n', '}\n\nreturn TABLE\n'], + go: [(i) => `\t"thing${i}": func(name string) string { return helper(name) },\n`, 'package big\n\nfunc helper(x string) string { return x }\n\nvar Table = map[string]func(string) string{\n', '}\n'], + php: [(i) => ` 'thing${i}' => fn($name) => helper($name),\n`, ' ` ("thing${i}", |name| helper(name)),\n`, 'fn helper(x: i32) -> i32 { x }\n\nstatic TABLE: &[(&str, fn(i32) -> i32)] = &[\n', '];\n'], + kotlin: [(i) => ` "thing${i}" to { name: String -> helper(name) },\n`, 'fun helper(x: String): String { return x }\n\nval table = mapOf(\n', ')\n'], + swift: [(i) => ` "thing${i}": { name in helper(name) },\n`, 'func helper(_ x: String) -> String { return x }\n\nlet table: [String: (String) -> String] = [\n', ']\n'], + dart: [(i) => ` 'thing${i}': (String name) => helper(name),\n`, 'String helper(String x) { return x; }\n\nfinal table = {\n', '};\n'], + scala: [(i) => ` "thing${i}" -> ((name: String) => helper(name)),\n`, 'object Big {\n def helper(x: String): String = x\n val table = Map(\n', ' )\n}\n'], + csharp: [(i) => ` { "thing${i}", name => Helper(name) },\n`, 'using System;\nusing System.Collections.Generic;\npublic class Big {\n static string Helper(string x) { return x; }\n static readonly Dictionary> Table = new() {\n', ' };\n}\n'], + java: [(i) => ` TABLE.put("thing${i}", name -> helper(name));\n`, 'import java.util.*;\nimport java.util.function.*;\npublic class Big {\n static String helper(String x) { return x; }\n static final Map> TABLE = new HashMap<>();\n static {\n', ' }\n}\n'], + cpp: [(i) => ` {"thing${i}", [](int name) { return helper(name); }},\n`, '#include \n#include \n#include \nint helper(int x) { return x; }\n\nstatic std::map> table = {\n', '};\n'], + c: [(i) => ` {"thing${i}", helper},\n`, 'int helper(int x) { return x; }\n\nstruct entry { const char *name; int (*fn)(int); };\n\nstatic const struct entry table[] = {\n', '};\n'], +}; + +// A test file: one suite holding many small tests. +const TESTS = { + typescript: [(i) => ` it('does thing ${i}', () => {\n const value = helper(${i});\n expect(value).toBe(${i});\n });\n\n`, "import { describe, it, expect } from 'vitest';\nfunction helper(x: number) { return x; }\n\ndescribe('big', () => {\n", '});\n'], + javascript: [(i) => ` it('does thing ${i}', function () {\n const value = helper(${i});\n assert.equal(value, ${i});\n });\n\n`, "const assert = require('assert');\nfunction helper(x) { return x; }\n\ndescribe('big', function () {\n", '});\n'], + python: [(i) => ` def test_thing_${i}(self):\n value = helper(${i})\n self.assertEqual(value, ${i})\n\n`, 'import unittest\n\ndef helper(x):\n return x\n\nclass BigTest(unittest.TestCase):\n'], + ruby: [(i) => ` it "does thing ${i}" do\n value = helper(${i})\n expect(value).to eq(${i})\n end\n\n`, "def helper(x)\n x\nend\n\nRSpec.describe 'big' do\n", 'end\n'], + go: [(i) => `func TestThing${i}(t *testing.T) {\n\tvalue := helper(${i})\n\tif value != ${i} {\n\t\tt.Fatal(value)\n\t}\n}\n\n`, 'package big\n\nimport "testing"\n\nfunc helper(x int) int { return x }\n\n'], + rust: [(i) => ` #[test]\n fn thing_${i}() {\n let value = helper(${i});\n assert_eq!(value, ${i});\n }\n\n`, 'fn helper(x: i32) -> i32 { x }\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n', '}\n'], + java: [(i) => ` @Test\n void thing${i}() {\n int value = helper(${i});\n assertEquals(${i}, value);\n }\n\n`, 'import org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.*;\n\nclass BigTest {\n static int helper(int x) { return x; }\n\n', '}\n'], + kotlin: [(i) => ` @Test\n fun thing${i}() {\n val value = helper(${i})\n assertEquals(${i}, value)\n }\n\n`, 'import kotlin.test.Test\nimport kotlin.test.assertEquals\n\nfun helper(x: Int): Int { return x }\n\nclass BigTest {\n', '}\n'], + scala: [(i) => ` test("thing ${i}") {\n val value = helper(${i})\n assert(value == ${i})\n }\n\n`, 'class BigSuite extends munit.FunSuite {\n def helper(x: Int): Int = x\n\n', '}\n'], + swift: [(i) => ` func testThing${i}() {\n let value = helper(${i})\n XCTAssertEqual(value, ${i})\n }\n\n`, 'import XCTest\n\nfunc helper(_ x: Int) -> Int { return x }\n\nfinal class BigTests: XCTestCase {\n', '}\n'], + dart: [(i) => ` test('thing ${i}', () {\n final value = helper(${i});\n expect(value, ${i});\n });\n\n`, "import 'package:test/test.dart';\n\nint helper(int x) { return x; }\n\nvoid main() {\n", '}\n'], + csharp: [(i) => ` [Fact]\n public void Thing${i}() {\n var value = Helper(${i});\n Assert.Equal(${i}, value);\n }\n\n`, 'using Xunit;\n\npublic class BigTests {\n static int Helper(int x) { return x; }\n\n', '}\n'], + php: [(i) => ` public function testThing${i}() {\n $value = helper(${i});\n $this->assertSame(${i}, $value);\n }\n\n`, ' `TEST(Big, Thing${i}) {\n int value = helper(${i});\n EXPECT_EQ(value, ${i});\n}\n\n`, '#include \n\nint helper(int x) { return x; }\n\n'], + lua: [(i) => ` it("does thing ${i}", function()\n local value = helper(${i})\n assert.equal(value, ${i})\n end)\n\n`, 'local function helper(x) return x end\n\ndescribe("big", function()\n', 'end)\n'], +}; + +export function more(fill, bytes) { + const out = {}; + const add = (shape, table) => { + for (const [language, [unit, head = '', tail = '']] of Object.entries(table)) { + (out[language] ??= {})[shape] = () => fill(unit, head, tail); + } + }; + add('mixed', MIXED); + add('members', MEMBERS); + add('enum', ENUM); + add('switch', SWITCH); + add('imports', IMPORTS); + add('commented', COMMENTED); + add('object', OBJECT); + add('tests', TESTS); + // A script on one line, as a bundler leaves it. + out.javascript.minified = () => fill((i) => `function t${i}(n){var v=h(n);return t${p(i)}(v)}`, 'function h(x){return x}', '\n'); + // One long string, as an embedded asset is. + const blob = () => 'QUJD'.repeat(Math.floor(bytes / 4)); + out.javascript.blob = () => `const BLOB = "${blob()}";\nfunction use() { return BLOB.length; }\n`; + out.typescript.blob = () => `export const BLOB = "${blob()}";\nexport function use() { return BLOB.length; }\n`; + out.python.blob = () => `BLOB = "${blob()}"\n\ndef use():\n return len(BLOB)\n`; + out.go.blob = () => `package big\n\nconst Blob = "${blob()}"\n\nfunc Use() int { return len(Blob) }\n`; + out.c.blob = () => `static const char BLOB[] = "${blob()}";\n\nint use(void) { return sizeof BLOB; }\n`; + // The same with other long runs: hex digits, blanks, and one line of numbers. + const wrap = { + javascript: (v) => `const BLOB = ${v};\nfunction use() { return BLOB.length; }\n`, + typescript: (v) => `export const BLOB = ${v};\nexport function use() { return BLOB.length; }\n`, + python: (v) => `BLOB = ${v}\n\ndef use():\n return len(BLOB)\n`, + go: (v) => `package big\n\nvar Blob = ${v}\n\nfunc Use() int { return len(Blob) }\n`, + c: (v) => `static const char BLOB[] = ${v};\n\nint use(void) { return sizeof BLOB; }\n`, + ruby: (v) => `BLOB = ${v}\n\ndef use\n BLOB.length\nend\n`, + java: (v) => `public class Big {\n static final Object BLOB = ${v};\n static int use() { return 1; }\n}\n`, + csharp: (v) => `public class Big {\n static readonly object Blob = ${v};\n static int Use() { return 1; }\n}\n`, + php: (v) => ` `static BLOB: &str = ${v};\n\nfn use_it() -> usize { BLOB.len() }\n`, + kotlin: (v) => `val BLOB = ${v}\n\nfun use(): Int { return 1 }\n`, + swift: (v) => `let blob = ${v}\n\nfunc use() -> Int { return 1 }\n`, + scala: (v) => `object Big {\n val blob = ${v}\n def use(): Int = 1\n}\n`, + dart: (v) => `const blob = ${v};\n\nint use() { return 1; }\n`, + cpp: (v) => `static const char BLOB[] = ${v};\n\nint use() { return sizeof BLOB; }\n`, + lua: (v) => `local BLOB = ${v}\n\nlocal function use() return #BLOB end\n`, + }; + for (const [language, around] of Object.entries(wrap)) { + out[language].blob = () => around('"' + blob() + '"'); + out[language].hex = () => around('"' + '0f3a'.repeat(Math.floor(bytes / 4)) + '"'); + out[language].blanks = () => around('"' + ' '.repeat(bytes) + '"'); + out[language].dots = () => around('"' + 'a.b.'.repeat(Math.floor(bytes / 4)) + '"'); + out[language].words = () => around('"' + 'lorem ipsum dolor sit amet, '.repeat(Math.floor(bytes / 28)) + '"'); + } + // One function, then nothing but comment lines: a long run of them is a flat list of siblings. + const mark = { python: '#', ruby: '#', r: '#', lua: '--' }; + for (const [language, around] of Object.entries(wrap)) { + const comment = mark[language] ?? '//'; + out[language].commentrun = () => around('"x"') + fill((i) => `${comment} a line of commentary, number ${i}\n`); + } + return out; +} diff --git a/scripts/benchmarks/large-files/other-languages.mjs b/scripts/benchmarks/large-files/other-languages.mjs new file mode 100644 index 0000000000..4188deec08 --- /dev/null +++ b/scripts/benchmarks/large-files/other-languages.mjs @@ -0,0 +1,445 @@ +// How long the engine takes to index one large file in everything the README lists that +// kernel-languages.mjs does not cover: the languages the native kernel does not read, each +// framework's and router's routes file, and each cross-language bridge. See +// docs/design/large-file-performance.md. +// +// node scripts/benchmarks/large-files/other-languages.mjs [case,case… or a word cases start with] +// +// One line a case: seconds, the megabytes of the whole project, the large file's symbols, and +// the project's routes and edges. Read the counts as well as the time: a case with no symbols, +// routes or edges gave the engine nothing to link, so it measured nothing. A case with a file +// over the engine's size limit is marked NOT MEASURED, because the engine leaves that file out. +// Set CODEGRAPH_KERNEL=0 to time the wasm extractor. BENCH_WRITE= writes the projects +// out instead of timing them (for compare-graphs.mjs). +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { createRequire } from 'node:module'; +import { DatabaseSync } from 'node:sqlite'; + +const [distArg, megabytes = '0.3', only = ''] = process.argv.slice(2); +if (!distArg) { + console.error('usage: other-languages.mjs [cases]'); + process.exit(2); +} +const dist = resolve(distArg); +// The benchmark times the index, not telemetry or a shared daemon. +Object.assign(process.env, { CODEGRAPH_TELEMETRY: '0', DO_NOT_TRACK: '1', CODEGRAPH_NO_DAEMON: '1' }); +const require = createRequire(import.meta.url); +const { CodeGraph } = require(join(dist, 'index.js')); +const { MAX_SOURCE_FILE_SIZE_BYTES } = require(join(dist, 'file-limits.js')); +const bytes = +megabytes * 1024 * 1024; +const p = (i) => (i ? i - 1 : 0); + +const fill = (unit, head = '', tail = '', size = bytes) => { + const parts = [head]; + let length = head.length + tail.length; + for (let i = 0; length < size; i++) { + const part = unit(i); + parts.push(part); + length += part.length; + } + parts.push(tail); + return parts.join(''); +}; +/** How many units of about `each` bytes fill the size. */ +const count = (each) => Math.max(1, Math.floor(bytes / each)); +const one = (path, text) => ({ files: { [path]: text }, main: path }); +const hex = () => '0f3a'.repeat(Math.floor(bytes / 4)); + +const CASES = { + // --- languages ----------------------------------------------------------------------------- + 'arkts/mixed': () => one('src/big.ets', fill((i) => `function thing${i}(name: string): string {\n const value = helper(name);\n return thing${p(i)}(value);\n}\n\n`, 'function helper(x: string) { return x; }\n\n')), + 'arkts/components': () => one('src/big.ets', fill((i) => `@Component\nstruct View${i} {\n @State count: number = ${i}\n build() {\n Column() {\n Text('x${i}')\n View${p(i)}()\n }\n }\n}\n\n`)), + 'tsx/components': () => one('src/big.tsx', fill((i) => `export function Comp${i}(props: { name: string }) {\n const value = helper(props.name);\n return
;\n}\n\n`, "import React from 'react';\nfunction helper(x: string) { return x; }\n\n")), + 'jsx/components': () => one('src/big.jsx', fill((i) => `export function Comp${i}(props) {\n const value = helper(props.name);\n return
;\n}\n\n`, "import React from 'react';\nfunction helper(x) { return x; }\n\n")), + 'tsx/markup': () => one('src/big.tsx', fill((i) => ` helper("${i}")} />\n`, "import React from 'react';\nfunction helper(x: string) { return x; }\nfunction Row(props: any) { return
  • {props.name}
  • ; }\nexport function Big() {\n return (\n
      \n", '
    \n );\n}\n')), + 'razor/markup': () => one('Views/Big.cshtml', fill((i) => `

    @Html.DisplayFor(m => m.Name${i})

    \n@Model.Name${i}\n`, '@model App.Models.Big\n@inject App.Services.Svc Svc\n
    \n', '
    \n')), + 'blazor/markup': () => one('Pages/Big.razor', fill((i) => `\n`, '@page "/big"\n@inject App.Services.Svc Svc\n', '\n@code {\n int[] items = new int[1];\n void Pick(int i) { }\n}\n')), + 'objc/members': () => one('src/Big.m', fill((i) => `- (NSString *)thing${i}:(NSString *)name {\n NSString *value = [self helper:name];\n return [self thing${p(i)}:value];\n}\n\n`, '#import \n\n@interface Big : NSObject\n- (NSString *)helper:(NSString *)x;\n@end\n\n@implementation Big\n- (NSString *)helper:(NSString *)x { return x; }\n\n', '@end\n')), + 'metal/mixed': () => one('src/big.metal', fill((i) => `float thing${i}(float name) {\n float value = helper(name);\n return thing${p(i)}(value);\n}\n\n`, '#include \nusing namespace metal;\n\nfloat helper(float x) { return x; }\n\n')), + 'cuda/kernels': () => one('src/big.cu', fill((i) => `__global__ void kernel${i}(float *a) {\n a[0] = helper(a[0]);\n}\n\nvoid launch${i}(float *a) {\n kernel${i}<<<1, 1>>>(a);\n}\n\n`, '__device__ float helper(float x) { return x; }\n\n')), + 'svelte/script': () => one('src/Big.svelte', fill((i) => ` function thing${i}(name: string): string {\n const value = helper(name);\n return thing${p(i)}(value);\n }\n\n`, '\n\n
    {thing0('x')}
    \n")), + 'svelte/markup': () => one('src/Big.svelte', fill((i) => `

    pick(${i})}>{label(${i})}

    \n`, '\n\n
    \n', '
    \n')), + 'vue/script': () => one('src/Big.vue', fill((i) => `function thing${i}(name: string): string {\n const value = helper(name);\n return thing${p(i)}(value);\n}\n\n`, '\n\n\n")), + 'vue/markup': () => one('src/Big.vue', fill((i) => `

    {{ label(${i}) }}

    \n`, '\n\n\n')), + 'vue/options': () => one('src/Big.vue', fill((i) => ` thing${i}(name) {\n const value = this.helper(name);\n return this.thing${p(i)}(value);\n },\n`, '\n\n\n')), + 'astro/frontmatter': () => one('src/pages/big.astro', fill((i) => `function thing${i}(name: string): string {\n const value = helper(name);\n return thing${p(i)}(value);\n}\n\n`, '---\nfunction helper(x: string) { return x; }\n\n', "---\n
    {thing0('x')}
    \n")), + 'astro/markup': () => one('src/pages/big.astro', fill((i) => `

    {label(${i})}

    \n`, '---\nfunction label(i: number) { return String(i); }\n---\n
    \n', '
    \n')), + 'liquid/markup': () => one('sections/big.liquid', fill((i) => `{% render 'snippet${i % 50}', value: product.title %}\n{{ product.title | append: '${i}' }}\n{% assign v${i} = product.price | times: ${i} %}\n`)), + 'pascal/mixed': () => one('src/Big.pas', fill((i) => `function Thing${i}(Name: string): string;\nvar\n Value: string;\nbegin\n Value := Helper(Name);\n Result := Thing${p(i)}(Value);\nend;\n\n`, 'unit Big;\n\ninterface\n\nfunction Helper(X: string): string;\n\nimplementation\n\nfunction Helper(X: string): string;\nbegin\n Result := X;\nend;\n\n', 'end.\n')), + 'pascal/members': () => { + const n = count(230); + const decl = Array.from({ length: n }, (_, i) => ` function Thing${i}(Name: string): string;\n`).join(''); + const impl = Array.from({ length: n }, (_, i) => `function TBig.Thing${i}(Name: string): string;\nvar\n Value: string;\nbegin\n Value := Self.Helper(Name);\n Result := Self.Thing${p(i)}(Value);\nend;\n\n`).join(''); + return one('src/Big.pas', `unit Big;\n\ninterface\n\ntype\n TBig = class\n public\n function Helper(X: string): string;\n${decl} end;\n\nimplementation\n\nfunction TBig.Helper(X: string): string;\nbegin\n Result := X;\nend;\n\n${impl}end.\n`); + }, + 'dfm/form': () => ({ files: { + 'src/Unit1.pas': `unit Unit1;\n\ninterface\n\nuses Forms, StdCtrls;\n\ntype\n TForm1 = class(TForm)\n procedure ButtonClick(Sender: TObject);\n end;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TForm1.ButtonClick(Sender: TObject);\nbegin\nend;\n\nend.\n`, + 'src/Unit1.dfm': fill((i) => ` object Button${i}: TButton\n Left = ${i}\n Caption = 'B${i}'\n OnClick = ButtonClick\n end\n`, 'object Form1: TForm1\n Caption = \'Form1\'\n', 'end\n'), + }, main: 'src/Unit1.dfm' }), + 'luau/mixed': () => one('src/big.luau', fill((i) => `local function thing${i}(name: string): string\n local value = helper(name)\n return thing${p(i)}(value)\nend\n\n`, 'local function helper(x: string): string\n return x\nend\n\n')), + 'cfml/script': () => one('src/Big.cfc', fill((i) => ` public string function thing${i}(required string name) {\n var value = helper(name);\n return thing${p(i)}(value);\n }\n\n`, 'component {\n public string function helper(required string x) {\n return x;\n }\n\n', '}\n')), + 'cfml/tags': () => one('src/Big.cfc', fill((i) => ` \n \n \n \n \n\n`, '\n \n \n \n \n\n', '\n')), + 'cobol/paragraphs': () => one('src/BIG.cbl', fill((i) => ` PARA-${i}.\n PERFORM PARA-${p(i)}.\n DISPLAY "X${i}".\n`, ' IDENTIFICATION DIVISION.\n PROGRAM-ID. BIG.\n PROCEDURE DIVISION.\n MAIN-PARA.\n PERFORM PARA-0.\n STOP RUN.\n')), + 'cobol/data': () => one('src/BIG.cbl', fill((i) => ` 05 FIELD-${i} PIC X(10).\n`, ' IDENTIFICATION DIVISION.\n PROGRAM-ID. BIG.\n DATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 BIG-RECORD.\n', ' PROCEDURE DIVISION.\n MAIN-PARA.\n STOP RUN.\n')), + 'vbnet/members': () => one('src/Big.vb', fill((i) => ` Public Function Thing${i}(name As String) As String\n Dim value As String = Helper(name)\n Return Thing${p(i)}(value)\n End Function\n\n`, 'Public Class Big\n Public Function Helper(x As String) As String\n Return x\n End Function\n\n', 'End Class\n')), + 'erlang/mixed': () => one('src/big.erl', fill((i) => `thing${i}(Name) ->\n Value = helper(Name),\n thing${p(i)}(Value).\n\n`, '-module(big).\n-export([thing0/1]).\n\nhelper(X) -> X.\n\n')), + 'solidity/members': () => one('src/Big.sol', fill((i) => ` function thing${i}(uint name) public pure returns (uint) {\n uint value = helper(name);\n return thing${p(i)}(value);\n }\n\n`, 'pragma solidity ^0.8.0;\n\ncontract Big {\n function helper(uint x) internal pure returns (uint) { return x; }\n\n', '}\n')), + 'terraform/resources': () => one('main.tf', fill((i) => `variable "name${i}" {\n type = string\n}\n\nresource "null_resource" "thing${i}" {\n triggers = {\n value = var.name${i}\n prev = null_resource.thing${p(i)}.id\n }\n}\n\n`)), + 'nix/bindings': () => one('default.nix', fill((i) => ` thing${i} = name: let value = helper name; in thing${p(i)} value;\n`, '{ pkgs }:\nlet\n helper = x: x;\n', 'in { inherit thing0; }\n')), + 'mybatis/mapper': () => ({ files: { + 'src/main/java/x/BigMapper.java': `package x;\n\npublic interface BigMapper {\n${Array.from({ length: Math.min(2000, count(90)) }, (_, i) => ` Object find${i}(int id);\n`).join('')}}\n`, + 'src/main/resources/x/BigMapper.xml': fill((i) => ` \n`, '\n\n\n', '\n'), + }, main: 'src/main/resources/x/BigMapper.xml' }), + + // --- long runs in the languages above ---------------------------------------------------------- + 'objc/hex': () => one('src/Big.m', `#import \nstatic NSString *const BLOB = @"${hex()}";\nint use(void) { return 1; }\n`), + 'pascal/hex': () => one('src/Big.pas', `unit Big;\ninterface\nconst\n BLOB = '${hex()}';\nimplementation\nend.\n`), + 'vbnet/hex': () => one('src/Big.vb', `Public Module Big\n Public Const Blob As String = "${hex()}"\n Public Function Use() As Integer\n Return 1\n End Function\nEnd Module\n`), + 'solidity/hex': () => one('src/Big.sol', `pragma solidity ^0.8.0;\ncontract Big {\n bytes constant BLOB = hex"${hex()}";\n function use() public pure returns (uint) { return 1; }\n}\n`), + 'vue/hex': () => one('src/Big.vue', `\n\n`), + 'svelte/hex': () => one('src/Big.svelte', `\n
    {use()}
    \n`), + 'erlang/hex': () => one('src/big.erl', `-module(big).\n-export([use/0]).\n\nblob() -> "${hex()}".\n\nuse() -> length(blob()).\n`), + 'terraform/hex': () => one('main.tf', `locals {\n blob = "${hex()}"\n}\n\noutput "n" {\n value = length(local.blob)\n}\n`), + 'nix/hex': () => one('default.nix', `{ pkgs }:\nlet\n blob = "${hex()}";\nin { inherit blob; }\n`), + 'cobol/comments': () => one('src/BIG.cbl', ' IDENTIFICATION DIVISION.\n PROGRAM-ID. BIG.\n PROCEDURE DIVISION.\n MAIN-PARA.\n STOP RUN.\n' + fill((i) => ` * a line of commentary, number ${i}\n`)), + 'pascal/comments': () => one('src/Big.pas', 'unit Big;\ninterface\nfunction Helper(X: string): string;\nimplementation\nfunction Helper(X: string): string;\nbegin\n Result := X;\nend;\n' + fill((i) => `// a line of commentary, number ${i}\n`) + 'end.\n'), + 'vbnet/comments': () => one('src/Big.vb', 'Public Module Big\n Public Function Use() As Integer\n Return 1\n End Function\nEnd Module\n' + fill((i) => `' a line of commentary, number ${i}\n`)), + 'objc/comments': () => one('src/Big.m', '#import \nint use(void) { return 1; }\n' + fill((i) => `// a line of commentary, number ${i}\n`)), + 'erlang/comments': () => one('src/big.erl', '-module(big).\n-export([use/0]).\n\nuse() -> 1.\n' + fill((i) => `% a line of commentary, number ${i}\n`)), + 'solidity/comments': () => one('src/Big.sol', 'pragma solidity ^0.8.0;\ncontract Big {\n function use() public pure returns (uint) { return 1; }\n}\n' + fill((i) => `// a line of commentary, number ${i}\n`)), + 'terraform/comments': () => one('main.tf', 'variable "name" {\n type = string\n}\n' + fill((i) => `# a line of commentary, number ${i}\n`)), + 'nix/comments': () => one('default.nix', '{ pkgs }:\n' + fill((i) => `# a line of commentary, number ${i}\n`) + '{ x = 1; }\n'), + + // --- frameworks: one large routes file each ----------------------------------------------------- + 'django/urls': () => { + const n = count(95); + return { files: { + 'requirements.txt': 'django\n', + 'manage.py': "import django\n", + 'app/__init__.py': '', + 'app/views.py': Array.from({ length: n }, (_, i) => `def view${i}(request):\n return None\n\n`).join(''), + 'app/urls.py': `from django.urls import path\nfrom . import views\n\nurlpatterns = [\n${Array.from({ length: n }, (_, i) => ` path('x${i}/', views.view${i}, name='x${i}'),\n`).join('')}]\n`, + }, main: 'app/urls.py' }; + }, + 'flask/routes': () => ({ files: { 'requirements.txt': 'flask\n', 'app.py': fill((i) => `@app.route('/x${i}', methods=['GET'])\ndef view${i}():\n return helper(${i})\n\n`, 'from flask import Flask\n\napp = Flask(__name__)\n\ndef helper(x):\n return x\n\n') }, main: 'app.py' }), + 'fastapi/routes': () => ({ files: { 'requirements.txt': 'fastapi\n', 'main.py': fill((i) => `@app.get('/x${i}')\nasync def view${i}():\n return helper(${i})\n\n`, 'from fastapi import FastAPI\n\napp = FastAPI()\n\ndef helper(x):\n return x\n\n') }, main: 'main.py' }), + 'express/inline': () => ({ files: { 'package.json': '{"name":"big","dependencies":{"express":"^4.0.0"}}\n', 'server.js': fill((i) => `app.get('/x${i}', (req, res) => {\n res.json(helper(${i}));\n});\n\n`, "const express = require('express');\nconst app = express();\nfunction helper(x) { return x; }\n\n", 'module.exports = app;\n') }, main: 'server.js' }), + 'express/named': () => ({ files: { 'package.json': '{"name":"big","dependencies":{"express":"^4.0.0"}}\n', 'server.js': fill((i) => `function h${i}(req, res) { res.json(helper(${i})); }\nrouter.post('/x${i}', auth, h${i});\n`, "const express = require('express');\nconst router = express.Router();\nfunction helper(x) { return x; }\nfunction auth(req, res, next) { next(); }\n\n", 'module.exports = router;\n') }, main: 'server.js' }), + 'elysia/chains': () => ({ files: { 'package.json': '{"name":"big","dependencies":{"elysia":"^1.0.0"}}\n', 'src/app.ts': fill((j) => `export const app${j} = new Elysia({ prefix: '/p${j}' })\n${Array.from({ length: 40 }, (_, k) => ` .get('/x${k}', () => helper(${k}))\n`).join('')};\n\n`, "import { Elysia } from 'elysia';\nfunction helper(x: number) { return x; }\n\n") }, main: 'src/app.ts' }), + 'nestjs/controller': () => ({ files: { 'package.json': '{"name":"big","dependencies":{"@nestjs/common":"^10.0.0","@nestjs/core":"^10.0.0"}}\n', 'src/big.controller.ts': fill((i) => ` @Get('x${i}')\n x${i}() {\n return helper(${i});\n }\n\n`, "import { Controller, Get } from '@nestjs/common';\nfunction helper(x: number) { return x; }\n\n@Controller('big')\nexport class BigController {\n", '}\n') }, main: 'src/big.controller.ts' }), + 'laravel/routes': () => { + const n = count(60); + return { files: { + 'composer.json': '{"require":{"laravel/framework":"^11.0"}}\n', + 'artisan': ' ` public function x${i}() { return ${i}; }\n`).join('')}}\n`, + 'routes/web.php': ` `Route::get('/x${i}', [BigController::class, 'x${i}']);\n`).join('')}`, + }, main: 'routes/web.php' }; + }, + 'drupal/routing': () => { + const n = count(172); + return { files: { + 'big.info.yml': "name: Big\ntype: module\ncore_version_requirement: ^10\n", + 'src/Controller/BigController.php': ` ` public function x${i}() { return []; }\n`).join('')}}\n`, + 'big.routing.yml': Array.from({ length: n }, (_, i) => `big.x${i}:\n path: '/x${i}'\n defaults:\n _controller: '\\Drupal\\big\\Controller\\BigController::x${i}'\n requirements:\n _permission: 'access content'\n\n`).join(''), + }, main: 'big.routing.yml' }; + }, + 'codeigniter/routes': () => { + const n = count(34); + return { files: { + 'index.php': " ` public function x${i}() { return ${i}; }\n`).join('')}}\n`, + 'application/config/routes.php': ` `$route['x${i}'] = 'big/x${i}';\n`).join('')}`, + }, main: 'application/config/routes.php' }; + }, + 'rails/routes': () => { + const n = count(34); + return { files: { + 'Gemfile': "source 'https://rubygems.org'\ngem 'rails'\n", + 'config/application.rb': "require 'rails/all'\n", + 'app/controllers/big_controller.rb': `class BigController < ApplicationController\n${Array.from({ length: n }, (_, i) => ` def x${i}\n end\n\n`).join('')}end\n`, + 'config/routes.rb': `Rails.application.routes.draw do\n${Array.from({ length: n }, (_, i) => ` get '/x${i}', to: 'big#x${i}'\n`).join('')}end\n`, + }, main: 'config/routes.rb' }; + }, + 'spring/controller': () => ({ files: { 'pom.xml': 'org.springframework.bootspring-boot-starter-web\n', 'src/main/java/x/BigController.java': fill((i) => ` @GetMapping("/x${i}")\n public String x${i}() {\n return helper(${i});\n }\n\n`, 'package x;\n\nimport org.springframework.web.bind.annotation.*;\n\n@RestController\n@RequestMapping("/big")\npublic class BigController {\n static String helper(int x) { return "" + x; }\n\n', '}\n') }, main: 'src/main/java/x/BigController.java' }), + 'play/routes': () => { + const n = count(40); + return { files: { + 'build.sbt': 'lazy val root = (project in file(".")).enablePlugins(PlayScala)\n', + 'app/controllers/Big.scala': `package controllers\n\nimport play.api.mvc._\n\nclass Big extends BaseController {\n${Array.from({ length: n }, (_, i) => ` def x${i} = Action { Ok("${i}") }\n`).join('')}}\n`, + 'conf/routes': Array.from({ length: n }, (_, i) => `GET /x${i} controllers.Big.x${i}\n`).join(''), + }, main: 'conf/routes' }; + }, + 'gin/routes': () => { + const n = count(90); + return { files: { + 'go.mod': 'module example.com/big\n\ngo 1.22\n\nrequire github.com/gin-gonic/gin v1.10.0\n', + 'main.go': `package main\n\nimport "github.com/gin-gonic/gin"\n\nfunc helper(x int) int { return x }\n\n${Array.from({ length: n }, (_, i) => `func handler${i}(c *gin.Context) { helper(${i}) }\n`).join('')}\nfunc main() {\n\tr := gin.Default()\n${Array.from({ length: n }, (_, i) => `\tr.GET("/x${i}", handler${i})\n`).join('')}\tr.Run()\n}\n`, + }, main: 'main.go' }; + }, + 'axum/routes': () => { + const n = count(110); + const routers = []; + for (let j = 0; j * 40 < n; j++) routers.push(`fn router${j}() -> Router {\n Router::new()\n${Array.from({ length: Math.min(40, n - j * 40) }, (_, k) => ` .route("/x${j * 40 + k}", get(handler${j * 40 + k}))\n`).join('')}}\n\n`); + return { files: { + 'Cargo.toml': '[package]\nname = "big"\nversion = "0.1.0"\n\n[dependencies]\naxum = "0.7"\n', + 'src/main.rs': `use axum::{routing::get, Router};\n\n${Array.from({ length: n }, (_, i) => `async fn handler${i}() -> &'static str { "x" }\n`).join('')}\n${routers.join('')}fn main() {}\n`, + }, main: 'src/main.rs' }; + }, + 'aspnet/controller': () => ({ files: { 'Big.csproj': '\n', 'Controllers/BigController.cs': fill((i) => ` [HttpGet("x${i}")]\n public string X${i}() {\n return Helper(${i});\n }\n\n`, 'using Microsoft.AspNetCore.Mvc;\n\n[ApiController]\n[Route("api/[controller]")]\npublic class BigController : ControllerBase {\n static string Helper(int x) { return "" + x; }\n\n', '}\n') }, main: 'Controllers/BigController.cs' }), + 'aspnet/minimal': () => ({ files: { 'Big.csproj': '\n', 'Program.cs': fill((i) => `app.MapGet("/x${i}", () => Helper(${i}));\n`, 'var builder = WebApplication.CreateBuilder(args);\nvar app = builder.Build();\nstatic string Helper(int x) { return "" + x; }\n\n', 'app.Run();\n') }, main: 'Program.cs' }), + 'vapor/routes': () => { + const n = count(110); + return { files: { + 'Package.swift': '// swift-tools-version:5.9\nimport PackageDescription\nlet package = Package(name: "big", dependencies: [.package(url: "https://github.com/vapor/vapor.git", from: "4.0.0")])\n', + 'Sources/App/routes.swift': `import Vapor\n\n${Array.from({ length: n }, (_, i) => `func handler${i}(req: Request) -> String { return "x" }\n`).join('')}\nfunc routes(_ app: Application) throws {\n${Array.from({ length: n }, (_, i) => ` app.get("x${i}", use: handler${i})\n`).join('')}}\n`, + }, main: 'Sources/App/routes.swift' }; + }, + 'react-router/routes': () => { + const n = count(105); + return { files: { + 'package.json': '{"name":"big","dependencies":{"react":"^18.0.0","react-router-dom":"^6.0.0"}}\n', + 'src/routes.tsx': `import React from 'react';\nimport { Routes, Route, useNavigate } from 'react-router-dom';\n\n${Array.from({ length: n }, (_, i) => `function Page${i}() { return
    ${i}
    ; }\n`).join('')}\nexport function Nav() {\n const navigate = useNavigate();\n${Array.from({ length: Math.min(n, 2000) }, (_, i) => ` const go${i} = () => navigate('/x${i}');\n`).join('')} return null;\n}\n\nexport function App() {\n return (\n \n${Array.from({ length: n }, (_, i) => ` } />\n`).join('')} \n );\n}\n`, + }, main: 'src/routes.tsx' }; + }, + 'vue-router/routes': () => { + const n = count(116); + return { files: { + 'package.json': '{"name":"big","dependencies":{"vue":"^3.0.0","vue-router":"^4.0.0"}}\n', + 'src/router.ts': `import { createRouter, createWebHistory } from 'vue-router';\n\n${Array.from({ length: n }, (_, i) => `const Page${i} = { template: '
    ${i}
    ' };\n`).join('')}\nexport const router = createRouter({\n history: createWebHistory(),\n routes: [\n${Array.from({ length: n }, (_, i) => ` { path: '/x${i}', name: 'x${i}', component: Page${i} },\n`).join('')} ],\n});\n\nexport function go(i: number) {\n router.push('/x1');\n}\n`, + }, main: 'src/router.ts' }; + }, + 'angular/routes': () => { + const n = count(140); + return { files: { + 'package.json': '{"name":"big","dependencies":{"@angular/core":"^17.0.0","@angular/router":"^17.0.0"}}\n', + 'src/app/app.routes.ts': `import { Component } from '@angular/core';\nimport { Routes } from '@angular/router';\n\n${Array.from({ length: n }, (_, i) => `@Component({ selector: 'p-${i}', template: '' })\nexport class Page${i}Component {}\n`).join('')}\nexport const routes: Routes = [\n${Array.from({ length: n }, (_, i) => ` { path: 'x${i}', component: Page${i}Component },\n`).join('')}];\n`, + }, main: 'src/app/app.routes.ts' }; + }, + 'tanstack/routes': () => { + const n = count(200); + return { files: { + 'package.json': '{"name":"big","dependencies":{"react":"^18.0.0","@tanstack/react-router":"^1.0.0"}}\n', + 'src/routes.tsx': `import React from 'react';\nimport { createRootRoute, createRoute } from '@tanstack/react-router';\n\nexport const rootRoute = createRootRoute();\n\n${Array.from({ length: n }, (_, i) => `function Page${i}() { return
    ${i}
    ; }\nexport const route${i} = createRoute({ getParentRoute: () => rootRoute, path: '/x${i}', component: Page${i} });\n`).join('')}`, + }, main: 'src/routes.tsx' }; + }, +}; + +// --- bridges, desktop commands, navigation, and more route styles -------------------------------- +Object.assign(CASES, { + 'swift-objc/bridge': () => { + const n = count(160); + return { files: { + 'Sources/Big.h': `#import \n\n@interface Big : NSObject\n${Array.from({ length: n }, (_, i) => `- (NSString *)thing${i}WithName:(NSString *)name;\n`).join('')}@end\n`, + 'Sources/Big.m': `#import "Big.h"\n\n@implementation Big\n${Array.from({ length: n }, (_, i) => `- (NSString *)thing${i}WithName:(NSString *)name {\n return name;\n}\n\n`).join('')}@end\n`, + 'Sources/Use.swift': `import Foundation\n\nfunc use(big: Big) {\n${Array.from({ length: n }, (_, i) => ` _ = big.thing${i}(name: "x")\n`).join('')}}\n`, + }, main: 'Sources/Big.m' }; + }, + 'rn/legacy-bridge': () => { + const n = count(140); + return { files: { + 'package.json': '{"name":"big","dependencies":{"react-native":"^0.74.0"}}\n', + 'ios/Big.m': `#import \n\n@interface Big : NSObject \n@end\n\n@implementation Big\nRCT_EXPORT_MODULE(Big)\n\n${Array.from({ length: n }, (_, i) => `RCT_EXPORT_METHOD(thing${i}:(NSString *)name) {\n}\n\n`).join('')}@end\n`, + 'src/use.js': `import { NativeModules } from 'react-native';\n\nexport function use() {\n${Array.from({ length: n }, (_, i) => ` NativeModules.Big.thing${i}('x');\n`).join('')}}\n`, + }, main: 'ios/Big.m' }; + }, + 'rn/events': () => { + const n = count(150); + return { files: { + 'package.json': '{"name":"big","dependencies":{"react-native":"^0.74.0"}}\n', + 'ios/Big.m': `#import \n\n@interface Big : RCTEventEmitter\n@end\n\n@implementation Big\nRCT_EXPORT_MODULE(Big)\n\n- (void)fire {\n${Array.from({ length: n }, (_, i) => ` [self sendEventWithName:@"e${i}" body:nil];\n`).join('')}}\n@end\n`, + 'src/listen.js': `import { NativeEventEmitter, NativeModules } from 'react-native';\n\nconst emitter = new NativeEventEmitter(NativeModules.Big);\n${Array.from({ length: n }, (_, i) => `function on${i}(e) {}\nemitter.addListener('e${i}', on${i});\n`).join('')}`, + }, main: 'src/listen.js' }; + }, + 'expo/modules': () => { + const n = count(110); + return { files: { + 'package.json': '{"name":"big","dependencies":{"expo":"^51.0.0","expo-modules-core":"^1.12.0"}}\n', + 'ios/BigModule.swift': `import ExpoModulesCore\n\npublic class BigModule: Module {\n public func definition() -> ModuleDefinition {\n Name("Big")\n${Array.from({ length: n }, (_, i) => ` AsyncFunction("fn${i}") { (x: Int) -> Int in\n return x\n }\n`).join('')} }\n}\n`, + 'src/use.ts': `import { requireNativeModule } from 'expo-modules-core';\n\nconst Big = requireNativeModule('Big');\n\nexport function use() {\n${Array.from({ length: n }, (_, i) => ` Big.fn${i}(1);\n`).join('')}}\n`, + }, main: 'ios/BigModule.swift' }; + }, + 'rn/paper-props': () => ({ files: { + 'package.json': '{"name":"big","dependencies":{"react-native":"^0.74.0"}}\n', + 'ios/BigViewManager.m': fill((i) => `RCT_EXPORT_VIEW_PROPERTY(prop${i}, NSString)\n`, '#import \n\n@interface BigViewManager : RCTViewManager\n@end\n\n@implementation BigViewManager\nRCT_EXPORT_MODULE(BigView)\n\n', '\n@end\n'), + 'src/BigView.js': "import { requireNativeComponent } from 'react-native';\nexport default requireNativeComponent('BigView');\n", + }, main: 'ios/BigViewManager.m' }), + 'tauri/commands': () => { + const n = count(110); + return { files: { + 'package.json': '{"name":"big","dependencies":{"@tauri-apps/api":"^2.0.0"}}\n', + 'src-tauri/Cargo.toml': '[package]\nname = "big"\nversion = "0.1.0"\n\n[dependencies]\ntauri = "2"\n', + 'src-tauri/src/main.rs': `${Array.from({ length: n }, (_, i) => `#[tauri::command]\nfn cmd${i}(x: i32) -> i32 {\n x\n}\n\n`).join('')}fn main() {\n tauri::Builder::default().invoke_handler(tauri::generate_handler![${Array.from({ length: n }, (_, i) => `cmd${i}`).join(', ')}]).run();\n}\n`, + 'src/use.ts': `import { invoke } from '@tauri-apps/api/core';\n\nexport async function use() {\n${Array.from({ length: n }, (_, i) => ` await invoke('cmd${i}', { x: 1 });\n`).join('')}}\n`, + }, main: 'src-tauri/src/main.rs' }; + }, + 'next/navigation': () => { + const files = { 'package.json': '{"name":"big","dependencies":{"next":"^14.0.0","react":"^18.0.0"}}\n' }; + for (let k = 0; k < 100; k++) files[`app/x${k}/page.tsx`] = `export default function Page${k}() { return
    ${k}
    ; }\n`; + files['app/nav.tsx'] = fill((i) => ` const go${i} = () => router.push('/x${i % 100}');\n`, "'use client';\nimport { useRouter } from 'next/navigation';\n\nexport function Nav() {\n const router = useRouter();\n", ' return null;\n}\n'); + return { files, main: 'app/nav.tsx' }; + }, + 'expo-router/navigation': () => { + const files = { 'package.json': '{"name":"big","dependencies":{"expo-router":"^3.0.0","react":"^18.0.0"}}\n' }; + for (let k = 0; k < 100; k++) files[`app/x${k}.tsx`] = `export default function Page${k}() { return null; }\n`; + files['components/nav.tsx'] = fill((i) => ` const go${i} = () => router.push('/x${i % 100}');\n`, "import { useRouter } from 'expo-router';\n\nexport function Nav() {\n const router = useRouter();\n", ' return null;\n}\n'); + return { files, main: 'components/nav.tsx' }; + }, + 'sveltekit/goto': () => { + const files = { 'package.json': '{"name":"big","devDependencies":{"@sveltejs/kit":"^2.0.0","svelte":"^4.0.0"}}\n', 'svelte.config.js': 'export default {};\n' }; + for (let k = 0; k < 100; k++) files[`src/routes/x${k}/+page.svelte`] = `

    ${k}

    \n`; + files['src/lib/nav.ts'] = fill((i) => `export const go${i} = () => goto('/x${i % 100}');\n`, "import { goto } from '$app/navigation';\n\n"); + return { files, main: 'src/lib/nav.ts' }; + }, + 'chi/routes': () => { + const n = count(95); + return { files: { + 'go.mod': 'module example.com/big\n\ngo 1.22\n\nrequire github.com/go-chi/chi/v5 v5.0.0\n', + 'main.go': `package main\n\nimport (\n\t"net/http"\n\n\t"github.com/go-chi/chi/v5"\n)\n\n${Array.from({ length: n }, (_, i) => `func handler${i}(w http.ResponseWriter, r *http.Request) {}\n`).join('')}\nfunc main() {\n\tr := chi.NewRouter()\n${Array.from({ length: n }, (_, i) => `\tr.Get("/x${i}", handler${i})\n`).join('')}\thttp.ListenAndServe(":8080", r)\n}\n`, + }, main: 'main.go' }; + }, + 'gorilla/routes': () => { + const n = count(120); + return { files: { + 'go.mod': 'module example.com/big\n\ngo 1.22\n\nrequire github.com/gorilla/mux v1.8.0\n', + 'main.go': `package main\n\nimport (\n\t"net/http"\n\n\t"github.com/gorilla/mux"\n)\n\n${Array.from({ length: n }, (_, i) => `func handler${i}(w http.ResponseWriter, r *http.Request) {}\n`).join('')}\nfunc main() {\n\tr := mux.NewRouter()\n${Array.from({ length: n }, (_, i) => `\tr.HandleFunc("/x${i}", handler${i}).Methods("GET")\n`).join('')}\thttp.ListenAndServe(":8080", r)\n}\n`, + }, main: 'main.go' }; + }, + 'actix/routes': () => ({ files: { 'Cargo.toml': '[package]\nname = "big"\nversion = "0.1.0"\n\n[dependencies]\nactix-web = "4"\n', 'src/main.rs': fill((i) => `#[get("/x${i}")]\nasync fn handler${i}() -> impl Responder {\n "x"\n}\n\n`, 'use actix_web::{get, Responder};\n\n', 'fn main() {}\n') }, main: 'src/main.rs' }), + 'rocket/routes': () => ({ files: { 'Cargo.toml': '[package]\nname = "big"\nversion = "0.1.0"\n\n[dependencies]\nrocket = "0.5"\n', 'src/main.rs': fill((i) => `#[get("/x${i}")]\nfn handler${i}() -> &'static str {\n "x"\n}\n\n`, '#[macro_use]\nextern crate rocket;\n\n', 'fn main() {}\n') }, main: 'src/main.rs' }), + 'js/events': () => ({ files: { 'package.json': '{"name":"big"}\n', 'src/events.js': fill((i) => `function on${i}(x) { return x; }\nemitter.on('e${i}', on${i});\nfunction fire${i}() { emitter.emit('e${i}', ${i}); }\n`, "const { EventEmitter } = require('events');\nconst emitter = new EventEmitter();\n\n") }, main: 'src/events.js' }), + 'c/fnptr-table': () => { + const n = count(75); + return one('src/big.c', `struct op { const char *name; int (*run)(int); };\n\n${Array.from({ length: n }, (_, i) => `static int op${i}(int x) { return x + ${i}; }\n`).join('')}\nstatic const struct op OPS[] = {\n${Array.from({ length: n }, (_, i) => ` {"op${i}", op${i}},\n`).join('')}};\n\nint dispatch(int i, int x) {\n return OPS[i].run(x);\n}\n`); + }, + 'spring/mappings': () => ({ files: { 'pom.xml': 'org.springframework.bootspring-boot-starter-web\n', 'src/main/java/x/BigController.java': fill((i) => ` @RequestMapping(value = "/x${i}", method = RequestMethod.POST)\n public ResponseEntity x${i}(@RequestBody String body) {\n return ResponseEntity.ok(service.handle(body));\n }\n\n`, 'package x;\n\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\n\n@RestController\npublic class BigController {\n private final BigService service = new BigService();\n\n', '}\n\nclass BigService {\n String handle(String body) { return body; }\n}\n') }, main: 'src/main/java/x/BigController.java' }), + // The cases above for Razor, Blazor and TanStack give the engine nothing it links + // (no component, no script, a root route with no options). These do. + 'tanstack/tree': () => { + const n = count(200); + return { files: { + 'package.json': '{"name":"big","dependencies":{"react":"^18.0.0","@tanstack/react-router":"^1.0.0"}}\n', + 'src/routes.tsx': `import React from 'react';\nimport { createRootRoute, createRoute, Outlet } from '@tanstack/react-router';\n\nfunction Root() { return ; }\nexport const rootRoute = createRootRoute({ component: Root });\n\n${Array.from({ length: n }, (_, i) => `function Page${i}() { return
    ${i}
    ; }\nexport const route${i} = createRoute({ getParentRoute: () => rootRoute, path: '/x${i}', component: Page${i} });\n`).join('')}`, + }, main: 'src/routes.tsx' }; + }, + 'blazor/components': () => { + const k = 400; + return { files: { + 'Components/Items.cs': `using Microsoft.AspNetCore.Components;\n\nnamespace App.Components;\n\n${Array.from({ length: k }, (_, i) => `public class Item${i} : ComponentBase { [Parameter] public int Value { get; set; } }\n`).join('')}`, + 'Models/Rows.cs': `namespace App.Models;\n\n${Array.from({ length: k }, (_, i) => `public class Row${i} { }\n`).join('')}`, + 'Pages/Big.razor': fill((i) => `\n

    @typeof(Row${(i * 3) % k})

    \n`, '@page "/big"\n@using App.Components\n@using App.Models\n', '\n@code {\n int[] items = new int[1];\n}\n'), + }, main: 'Pages/Big.razor' }; + }, + 'razor/script': () => ({ files: { + 'Models/Big.cs': 'namespace App.Models;\n\npublic class Big { }\n', + 'wwwroot/js/site.js': 'function helper(x) { return x; }\n', + 'Views/Big.cshtml': fill((i) => ` function thing${i}(name) {\n var value = helper(name);\n return thing${p(i)}(value);\n }\n\n`, '@model App.Models.Big\n
    \n\n'), + }, main: 'Views/Big.cshtml' }), + 'razor/directives': () => { + const k = 400; + return { files: { + 'Services/Svcs.cs': `namespace App.Services;\n\n${Array.from({ length: k }, (_, i) => `public class Svc${i} { }\n`).join('')}`, + 'Views/Big.cshtml': fill((i) => `@inject App.Services.Svc${i % k} S${i}\n

    @typeof(Svc${(i * 3) % k})

    \n`, '@model App.Services.Svc0\n'), + }, main: 'Views/Big.cshtml' }; + }, + 'fabric/spec': () => ({ files: { + 'package.json': '{"name":"big","dependencies":{"react-native":"^0.74.0"}}\n', + 'ios/BigView.mm': '#import \n\n@interface BigView : RCTViewComponentView\n@end\n\n@implementation BigView\n@end\n', + 'src/BigNativeComponent.ts': fill((i) => ` prop${i}?: string;\n onEvent${i}?: CT.DirectEventHandler>;\n`, "import { codegenNativeComponent } from 'react-native';\nimport type { ViewProps, CodegenTypes as CT } from 'react-native';\n\nexport interface NativeProps extends ViewProps {\n", "}\n\nexport default codegenNativeComponent('Big');\n"), + }, main: 'src/BigNativeComponent.ts' }), + // The bridge rows of the README the cases above leave out. + 'objc-swift/bridge': () => { + const n = count(150); + return { files: { + 'Sources/Big.swift': `import Foundation\n\n@objc class Big: NSObject {\n${Array.from({ length: n }, (_, i) => ` @objc func thing${i}(name: String) -> String {\n return name\n }\n\n`).join('')}}\n`, + 'Sources/Use.m': `#import "Big-Swift.h"\n\n@interface Use : NSObject\n@end\n\n@implementation Use\n- (void)use:(Big *)big {\n${Array.from({ length: n }, (_, i) => ` [big thing${i}WithName:@"x"];\n`).join('')}}\n@end\n`, + }, main: 'Sources/Big.swift' }; + }, + 'rn/turbomodule': () => { + const n = count(150); + return { files: { + 'package.json': '{"name":"big","dependencies":{"react-native":"^0.74.0"}}\n', + 'src/NativeBig.ts': `import type { TurboModule } from 'react-native';\nimport { TurboModuleRegistry } from 'react-native';\n\nexport interface Spec extends TurboModule {\n${Array.from({ length: n }, (_, i) => ` thing${i}(name: string): string;\n`).join('')}}\n\nexport default TurboModuleRegistry.getEnforcing('Big');\n`, + 'ios/Big.mm': `#import "Big.h"\n\n@implementation Big\nRCT_EXPORT_MODULE()\n\n${Array.from({ length: n }, (_, i) => `- (NSString *)thing${i}:(NSString *)name {\n return name;\n}\n\n`).join('')}@end\n`, + 'src/use.ts': `import Big from './NativeBig';\n\nexport function use() {\n${Array.from({ length: n }, (_, i) => ` Big.thing${i}('x');\n`).join('')}}\n`, + }, main: 'ios/Big.mm' }; + }, + 'rn/extern-swift': () => { + const n = count(150); + return { files: { + 'package.json': '{"name":"big","dependencies":{"react-native":"^0.74.0"}}\n', + 'ios/Big.m': `#import \n\n@interface RCT_EXTERN_MODULE(Big, NSObject)\n${Array.from({ length: n }, (_, i) => `RCT_EXTERN_METHOD(thing${i}:(NSString *)name)\n`).join('')}@end\n`, + 'ios/Big.swift': `import Foundation\n\n@objc(Big)\nclass Big: NSObject {\n${Array.from({ length: n }, (_, i) => ` @objc func thing${i}(_ name: String) {\n }\n\n`).join('')}}\n`, + 'src/use.js': `import { NativeModules } from 'react-native';\n\nexport function use() {\n${Array.from({ length: n }, (_, i) => ` NativeModules.Big.thing${i}('x');\n`).join('')}}\n`, + }, main: 'ios/Big.swift' }; + }, + 'rn/android-bridge': () => { + const n = count(160); + return { files: { + 'package.json': '{"name":"big","dependencies":{"react-native":"^0.74.0"}}\n', + 'android/src/main/java/com/big/BigModule.kt': `package com.big\n\nimport com.facebook.react.bridge.ReactApplicationContext\nimport com.facebook.react.bridge.ReactContextBaseJavaModule\nimport com.facebook.react.bridge.ReactMethod\n\nclass BigModule(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) {\n override fun getName(): String = "Big"\n\n${Array.from({ length: n }, (_, i) => ` @ReactMethod\n fun thing${i}(name: String) {\n }\n\n`).join('')}}\n`, + 'android/src/main/java/com/big/BigViewManager.java': `package com.big;\n\npublic class BigViewManager extends SimpleViewManager {\n${Array.from({ length: n }, (_, i) => ` @ReactProp(name = "prop${i}")\n public void setProp${i}(View view, String value) {\n }\n\n`).join('')}}\n`, + 'src/use.js': `import { NativeModules } from 'react-native';\n\nexport function use() {\n${Array.from({ length: n }, (_, i) => ` NativeModules.Big.thing${i}('x');\n`).join('')}}\n`, + }, main: 'android/src/main/java/com/big/BigModule.kt' }; + }, +}); + +const wanted = only ? only.split(',') : null; +const names = Object.keys(CASES).filter((name) => !wanted || wanted.some((w) => name === w || name.startsWith(w))); + +// A small first run, so the first case timed does not pay for loading the engine. +{ + const dir = mkdtempSync(join(tmpdir(), 'cg-bench-warm-')); + mkdirSync(join(dir, 'src')); + writeFileSync(join(dir, 'src', 'warm.ts'), 'export function warm() { return 1; }\n'); + (await CodeGraph.init(dir, { index: true })).close(); + rmSync(dir, { recursive: true, force: true }); +} + +const slow = []; +for (const name of names) { + const { files, main } = CASES[name](); + const dir = mkdtempSync(join(tmpdir(), 'cg-bench-big-')); + let size = 0; + let largest = 0; + for (const [path, text] of Object.entries(files)) { + mkdirSync(dirname(join(dir, path)), { recursive: true }); + writeFileSync(join(dir, path), text); + size += text.length; + largest = Math.max(largest, Buffer.byteLength(text)); + } + if (process.env.BENCH_WRITE) { + const out = join(process.env.BENCH_WRITE, name.replace('/', '-')); + for (const [path, text] of Object.entries(files)) { mkdirSync(dirname(join(out, path)), { recursive: true }); writeFileSync(join(out, path), text); } + rmSync(dir, { recursive: true, force: true }); + continue; + } + const started = Date.now(); + let failed = ''; + let symbols = 0; + let routes = 0; + let edges = 0; + try { + const cg = await CodeGraph.init(dir, { index: true }); + symbols = cg.getNodesInFile(main).filter((n) => n.kind !== 'file').length; + cg.close(); + const db = new DatabaseSync(join(dir, '.codegraph', 'codegraph.db')); + routes = db.prepare("SELECT count(*) AS n FROM nodes WHERE kind = 'route'").get().n; + edges = db.prepare('SELECT count(*) AS n FROM edges').get().n; + db.close(); + } catch (error) { + failed = ` FAILED: ${String(error?.message ?? error).slice(0, 90)}`; + } + const seconds = (Date.now() - started) / 1000; + rmSync(dir, { recursive: true, force: true }); + const perMb = seconds / (size / 1024 / 1024); + // A file over the engine's limit is left out, so its time says nothing. + const over = largest > MAX_SOURCE_FILE_SIZE_BYTES ? ` <-- NOT MEASURED: a file of ${(largest / 1048576).toFixed(2)} MB is over the size limit` : ''; + const mark = failed || over || (perMb > 2 ? ' <-- slow' : ''); + if (mark) slow.push(name); + console.log(`${name.padEnd(22)} ${seconds.toFixed(1).padStart(6)} s ${(size / 1048576).toFixed(2).padStart(5)} MB ${String(symbols).padStart(7)} symbols ${String(routes).padStart(6)} routes ${String(edges).padStart(7)} edges${mark}`); +} +console.log(slow.length ? `\nslow (over 2 s a megabyte), failed or not measured: ${slow.join(', ')}` : '\nnothing over 2 s a megabyte'); diff --git a/scripts/benchmarks/large-files/profile.mjs b/scripts/benchmarks/large-files/profile.mjs new file mode 100644 index 0000000000..ed8881cc35 --- /dev/null +++ b/scripts/benchmarks/large-files/profile.mjs @@ -0,0 +1,57 @@ +#!/usr/bin/env node +// Where the time goes for one benchmark case: the lines with the most CPU samples, over every +// thread of the run. A line of the engine is printed with its text from the build; a line +// outside the engine is named by its file, so time inside the parser itself +// (tree-sitter.wasm, the native kernel) shows as such and is not mistaken for the engine's. +// See docs/design/large-file-performance.md. +// +// node scripts/benchmarks/large-files/profile.mjs +// node scripts/benchmarks/large-files/profile.mjs other-languages dist 1.2 express/inline +// node scripts/benchmarks/large-files/profile.mjs kernel-languages dist 1.2 python table +// +// Profile at a size where the case takes some seconds: the line that grows with the square +// of the file is then most of the samples. PROFILE_LINES= prints more than 14 lines. +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const [harness, distArg, ...rest] = process.argv.slice(2); +if (!['kernel-languages', 'other-languages'].includes(harness) || !distArg || rest.length < 2) { + console.error('usage: profile.mjs '); + process.exit(2); +} +const dist = resolve(distArg); +const here = dirname(fileURLToPath(import.meta.url)); +const dir = mkdtempSync(join(tmpdir(), 'cg-profile-')); +const run = spawnSync(process.execPath, ['--cpu-prof', `--cpu-prof-dir=${dir}`, join(here, `${harness}.mjs`), dist, ...rest], { encoding: 'utf8' }); +process.stdout.write(run.stdout.split('\n').filter((line) => / s /.test(line)).join('\n') + '\n'); + +const samples = new Map(); +for (const file of readdirSync(dir).filter((name) => name.endsWith('.cpuprofile'))) { + const profile = JSON.parse(readFileSync(join(dir, file), 'utf8')); + const total = profile.timeDeltas.reduce((a, b) => a + b, 0); + const interval = total / Math.max(1, profile.samples.length); + for (const node of profile.nodes) { + const url = node.callFrame.url.replace(/\\/g, '/'); + if (!url) continue; + const where = url.includes('/dist/') ? url.split('/dist/')[1] : url.split('/').pop(); + for (const tick of node.positionTicks ?? []) { + const key = `${where}:${tick.line} (${node.callFrame.functionName || 'anonymous'})`; + samples.set(key, (samples.get(key) ?? 0) + tick.ticks * interval); + } + } +} +rmSync(dir, { recursive: true, force: true }); + +for (const [key, micros] of [...samples].sort((a, b) => b[1] - a[1]).slice(0, +(process.env.PROFILE_LINES ?? 14))) { + const [file, tail] = key.split(/:(?=\d)/); + let text = ''; + try { + text = readFileSync(join(dist, file), 'utf8').split('\n')[+tail.split(' ')[0] - 1].trim().slice(0, 110); + } catch { + // Not a file of the build: a line of Node's, or a function inside the parser. + } + console.log(` ${(micros / 1e6).toFixed(2).padStart(6)} s ${key}${text ? `\n ${text}` : ''}`); +} diff --git a/site/src/content/docs/getting-started/configuration.md b/site/src/content/docs/getting-started/configuration.md index deee46acec..4067985242 100644 --- a/site/src/content/docs/getting-started/configuration.md +++ b/site/src/content/docs/getting-started/configuration.md @@ -9,7 +9,7 @@ Next to none — CodeGraph is **zero-config by default**, with nothing to write - **Dependency, build, and cache directories** — `node_modules`, `vendor`, `dist`, `build`, `target`, `.venv`, `Pods`, `.next`, and the like across every [supported stack](/codegraph/reference/languages/) — so the graph is your code, not third-party noise. This holds even with no `.gitignore`. A `build` folder inside `src/` is the exception: no build step writes TypeScript, JSX, Vue, Svelte, Astro, Go, C# or Rust files into one, so those are indexed from it, and a Java, Kotlin or Scala package named `build` is indexed whole. - **Anything in your `.gitignore`** — honored in git repos via git, and in non-git projects by reading `.gitignore` directly (root and nested). -- **Files larger than 1 MB** — generated bundles, minified JS, vendored blobs. +- **Files larger than 4 MB** — generated bundles, minified JS, vendored blobs. `codegraph status` names any source file left out for its size. ## Excluding or including more diff --git a/src/extraction/cfml-extractor.ts b/src/extraction/cfml-extractor.ts index c872e5cb6d..ce72b4fc18 100644 --- a/src/extraction/cfml-extractor.ts +++ b/src/extraction/cfml-extractor.ts @@ -4,6 +4,7 @@ import { generateNodeId, NodeIdAllocator } from './tree-sitter-helpers'; import { TreeSitterExtractor } from './tree-sitter'; import { getParser } from './grammars'; import { indexParseBudgetMs, parseTimeoutMessage, parseWithinBudget } from './parse-budget'; +import { pushAll } from '../utils'; /** Tags whose own children include an expression: ``, ``, ``, ``, and `#…#`. */ const TAG_EXPRESSION_PARENTS: ReadonlySet = new Set([ @@ -136,12 +137,12 @@ export class CfmlExtractor { } this.nodes.push(node); } - this.edges.push(...result.edges); + pushAll(this.edges, result.edges); for (const ref of result.unresolvedReferences) { ref.language = this.language; this.unresolvedReferences.push(ref); } - this.errors.push(...result.errors); + pushAll(this.errors, result.errors); } /** Legacy tag-based CFML: walk ``/``, delegating `` bodies. */ @@ -458,8 +459,7 @@ export class CfmlExtractor { * methods scoped under the component. */ private delegateNestedTags(node: SyntaxNode, containerId: string, parentClassName?: string, declScope = false): void { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) this.visitTag(child, node.type, containerId, parentClassName, declScope); } } @@ -779,13 +779,11 @@ export class CfmlExtractor { */ private tagAttrValueNode(tag: SyntaxNode, attrName: string, wholeValue = false): SyntaxNode | null | undefined { const attrs: SyntaxNode[] = []; - for (let i = 0; i < tag.namedChildCount; i++) { - const child = tag.namedChild(i); + for (const child of tag.namedChildren) { if (!child) continue; if (child.type === 'cf_attribute') attrs.push(child); else if (child.type === 'cf_tag_attributes') { - for (let j = 0; j < child.namedChildCount; j++) { - const inner = child.namedChild(j); + for (const inner of child.namedChildren) { if (inner?.type === 'cf_attribute') attrs.push(inner); } } diff --git a/src/extraction/commonjs-requires.ts b/src/extraction/commonjs-requires.ts index 436a03385c..90662d18c3 100644 --- a/src/extraction/commonjs-requires.ts +++ b/src/extraction/commonjs-requires.ts @@ -20,6 +20,7 @@ import type { Language, UnresolvedReference } from '../types'; import { stripCommentsForRegex } from '../resolution/strip-comments'; +import { lineAt } from '../resolution/synth-utils'; const COMMONJS_LANGUAGES: ReadonlySet = new Set(['javascript', 'jsx', 'typescript', 'tsx']); @@ -58,7 +59,7 @@ export function commonJsRequireRefs(filePath: string, source: string, language: fromNodeId: `file:${filePath}`, referenceName: specifier, referenceKind: 'imports', - line: safe.slice(0, m.index).split('\n').length, + line: lineAt(safe, m.index), column: m.index - lineStart, filePath, language, diff --git a/src/extraction/function-ref.ts b/src/extraction/function-ref.ts index f01472b354..5c47b63f57 100644 --- a/src/extraction/function-ref.ts +++ b/src/extraction/function-ref.ts @@ -32,7 +32,8 @@ */ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText, getChildByField } from './tree-sitter-helpers'; +import { getNodeText, getChildByField, namedChildrenOf, childrenOf } from './tree-sitter-helpers'; +import { pushAll } from '../utils'; export interface FnRefCandidate { name: string; @@ -445,8 +446,7 @@ export function captureFnRefCandidates( switch (rule.mode) { case 'args': case 'list': { - for (let i = 0; i < container.namedChildCount; i++) { - const child = container.namedChild(i); + for (const child of container.namedChildren) { if (child) valueNodes.push(child); } break; @@ -589,9 +589,8 @@ function normalizeValue( return inner ? normalizeValue(inner, spec, source, depth + 1) : []; } const results: NormalizedRef[] = []; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); - if (child) results.push(...normalizeValue(child, spec, source, depth + 1)); + for (const child of node.namedChildren) { + if (child) pushAll(results, normalizeValue(child, spec, source, depth + 1)); } return results; } @@ -628,8 +627,7 @@ function normalizeValue( /** Rightmost descendant-or-self named child of one of the given types. */ function lastNamedOfType(node: SyntaxNode, types: Set): SyntaxNode | null { let found: SyntaxNode | null = null; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (!child) continue; if (types.has(child.type)) found = child; const deeper = lastNamedOfType(child, types); @@ -653,8 +651,7 @@ function normalizeSpecial( // the deferred obj.method class) case 'method_reference': { let last: SyntaxNode | null = null; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child && child.type === 'identifier') last = child; } if (!last) return []; @@ -691,8 +688,7 @@ function normalizeSpecial( case 'callable_reference': { let receiver: SyntaxNode | null = null; let member: SyntaxNode | null = null; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (!child) continue; if (child.type === 'type_identifier') receiver = child; if (child.type === 'simple_identifier') member = child; @@ -712,8 +708,7 @@ function normalizeSpecial( // nothing. case 'navigation_expression': { if (!getNodeText(node, source).startsWith('this::')) return []; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (child && child.type === 'navigation_suffix' && getNodeText(child, source).startsWith('::')) { const id = child.namedChild(child.namedChildCount - 1); if (id) return [{ name: `this.${getNodeText(id, source)}`, node: id }]; @@ -866,8 +861,7 @@ function normalizeSpecial( /** Content of a PHP string literal node (single- or double-quoted). */ function phpStringContent(node: SyntaxNode, source: string): string | null { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (child?.type === 'string_content') return getNodeText(child, source).trim(); } return null; @@ -965,8 +959,7 @@ export function goLocalBindings( if (names.has(name)) out.add(`${unit.id}|${name}`); }; const declares = (n: SyntaxNode): boolean => { - for (let i = 0; i < n.childCount; i++) { - const c = n.child(i); + for (const c of childrenOf(n)) { if (c && !c.isNamed && c.type === ':=') return true; } return false; diff --git a/src/extraction/kernel/index.ts b/src/extraction/kernel/index.ts index b39e1a3d03..112c0ee91d 100644 --- a/src/extraction/kernel/index.ts +++ b/src/extraction/kernel/index.ts @@ -20,6 +20,7 @@ import { indexParseBudgetMs, parseTimeoutResult } from '../parse-budget'; import { EXTRACTORS } from '../languages'; import { getKernel, kernelSupports } from './loader'; import { decodeExtractBuffers } from './decode'; +import { pushAll } from '../../utils'; import { KERNEL_ABI_VERSION as LAYOUT_ABI, META as LAYOUT_META, @@ -324,7 +325,7 @@ export function materializeKernelResult( ); decoded.durationMs = result.durationMs; // References read beside the tables (a CommonJS `require`) ride on the transport. - if (result.unresolvedReferences.length > 0) decoded.unresolvedReferences.push(...result.unresolvedReferences); + if (result.unresolvedReferences.length > 0) pushAll(decoded.unresolvedReferences, result.unresolvedReferences); return decoded; } @@ -355,7 +356,7 @@ export function tryKernelExtract( if (keepsReExportsAsWritten(source, pre, language)) restoreReExportSignatures(result, source); POST_PASSES[language]?.(result, source); // Read beside the tables, as TreeSitterExtractor does (a CommonJS `require`). - result.unresolvedReferences.push(...commonJsRequireRefs(filePath, source, language)); + pushAll(result.unresolvedReferences, commonJsRequireRefs(filePath, source, language)); result.durationMs = Date.now() - t0; return result; } catch (err) { diff --git a/src/extraction/languages/arkts.ts b/src/extraction/languages/arkts.ts index 8d452a2512..d0c4a9eca2 100644 --- a/src/extraction/languages/arkts.ts +++ b/src/extraction/languages/arkts.ts @@ -1,6 +1,7 @@ import type { LanguageExtractor } from '../tree-sitter-types'; import { typescriptExtractor } from './typescript'; import type { Node as SyntaxNode } from 'web-tree-sitter'; +import { namedChildrenOf } from '../tree-sitter-helpers'; /** * ArkTS (HarmonyOS / OpenHarmony, `.ets`) — a TypeScript superset whose @@ -48,8 +49,7 @@ const DECORATED_MEMBER_TYPES = new Set([ function collectDecoratorNames(node: SyntaxNode): string[] | undefined { const names: string[] = []; const nameOf = (dec: SyntaxNode): string | undefined => { - for (let i = 0; i < dec.namedChildCount; i++) { - const child = dec.namedChild(i); + for (const child of namedChildrenOf(dec)) { if (!child) continue; if (child.type === 'identifier') return child.text; if (child.type === 'call_expression') { @@ -62,33 +62,19 @@ function collectDecoratorNames(node: SyntaxNode): string[] | undefined { return undefined; }; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child?.type === 'decorator') { const n = nameOf(child); if (n) names.push(n); } } - const parent = node.parent; - if (parent) { - // Find this node among the parent's named children by start offset - // (wrapper identity is not stable across navigation), then walk backwards. - const start = node.startIndex; - let idx = -1; - for (let i = 0; i < parent.namedChildCount; i++) { - const sib = parent.namedChild(i); - if (sib && sib.startIndex === start) { - idx = i; - break; - } - } - for (let i = idx - 1; i >= 0; i--) { - const sib = parent.namedChild(i); - if (!sib || sib.type !== 'decorator') break; - const n = nameOf(sib); - if (n) names.unshift(n); - } + // Walked back from the declaration itself. Finding its place first, by + // counting the parent's children from the start, cost each declaration as + // much as it has siblings before it: 1.2 MB of functions took 21 seconds. + for (let sib = node.previousNamedSibling; sib && sib.type === 'decorator'; sib = sib.previousNamedSibling) { + const n = nameOf(sib); + if (n) names.unshift(n); } return names.length > 0 ? names : undefined; diff --git a/src/extraction/languages/c-cpp.ts b/src/extraction/languages/c-cpp.ts index 5863da2d55..6fb12f219f 100644 --- a/src/extraction/languages/c-cpp.ts +++ b/src/extraction/languages/c-cpp.ts @@ -1,7 +1,10 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getChildByField, getNodeText } from '../tree-sitter-helpers'; +import { getChildByField, getNodeText, namedChildrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; +/** Per tree, by a parent's id: what cppExtractor.getVisibility found among its children. */ +const CPP_VISIBILITY_SEEN = new WeakMap>(); + /** * Resolve the declared identifier inside a C declarator. A `declaration`'s * `declarator` field nests the name through `init_declarator` (with value), @@ -238,8 +241,7 @@ function findDeclaratorQualifiedId(declarator: SyntaxNode): SyntaxNode | undefin while (queue.length > 0) { const current = queue.shift()!; if (current.type === 'qualified_identifier') return current; - for (let i = 0; i < current.namedChildCount; i++) { - const child = current.namedChild(i); + for (const child of namedChildrenOf(current)) { // Don't descend into parameters, the trailing return type or the // clauses after them — `const std::string&`, `-> std::string`, // nlohmann/json's `noexcept(noexcept(JSONSerializer::to_json(…)))`, @@ -597,8 +599,7 @@ export const cExtractor: LanguageExtractor = { // to become the enum/struct node name. `typedef union { ... } name;` takes the // same route — otherwise the union body would mint a second, `` node // beside the alias. - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; if (child.type === 'enum_specifier' && getChildByField(child, 'body')) return 'enum'; if ( @@ -3029,26 +3030,31 @@ export const cppExtractor: LanguageExtractor = { return parameters ? getNodeText(parameters, source) + (node.type === 'declaration' ? ';' : '') : undefined; }, getVisibility: (node) => { - // Check for access specifier in parent + // Check for access specifier in parent. The answer is the parent's, so + // it is read once for each parent and kept: read again for every member, + // a file of twenty thousand functions spent a minute on it, each one + // reading every sibling it has. const parent = node.parent; - if (parent) { - for (let i = 0; i < parent.childCount; i++) { - const child = parent.child(i); - if (child?.type === 'access_specifier') { - const text = child.text; - if (text.includes('public')) return 'public'; - if (text.includes('private')) return 'private'; - if (text.includes('protected')) return 'protected'; - } - } + if (!parent) return undefined; + const tree = node.tree; + let seen = CPP_VISIBILITY_SEEN.get(tree); + if (!seen) CPP_VISIBILITY_SEEN.set(tree, (seen = new Map())); + if (seen.has(parent.id)) return seen.get(parent.id); + let found: 'public' | 'private' | 'protected' | undefined; + for (let child = parent.firstChild; child && !found; child = child.nextSibling) { + if (child.type !== 'access_specifier') continue; + const text = child.text; + if (text.includes('public')) found = 'public'; + else if (text.includes('private')) found = 'private'; + else if (text.includes('protected')) found = 'protected'; } - return undefined; + seen.set(parent.id, found); + return found; }, resolveTypeAliasKind: (node, _source) => { // C++ typedef: `typedef enum { ... } name;`, `typedef struct { ... } name;`, // or `typedef union { ... } name;` — see the C extractor. - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; if (child.type === 'enum_specifier' && getChildByField(child, 'body')) return 'enum'; if ( diff --git a/src/extraction/languages/cfscript.ts b/src/extraction/languages/cfscript.ts index fc951ad7af..37ec7dbc7c 100644 --- a/src/extraction/languages/cfscript.ts +++ b/src/extraction/languages/cfscript.ts @@ -1,11 +1,10 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText, getChildByField } from '../tree-sitter-helpers'; +import { getNodeText, getChildByField, childrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; /** CFML access modifiers (`public`/`private`/`package`/`remote`) on a function_declaration. */ function cfmlVisibility(node: SyntaxNode): 'public' | 'private' | 'protected' | 'internal' | undefined { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'access_type') { const text = child.text; if (text === 'public') return 'public'; diff --git a/src/extraction/languages/cpp-macro-methods.ts b/src/extraction/languages/cpp-macro-methods.ts index fd03766aa8..96db0825b4 100644 --- a/src/extraction/languages/cpp-macro-methods.ts +++ b/src/extraction/languages/cpp-macro-methods.ts @@ -33,6 +33,7 @@ import { Edge, ExtractionResult, Node } from '../../types'; import { generateNodeId } from '../tree-sitter-helpers'; import { normalizeCppReturnType, stripCppTemplateArgs } from './c-cpp'; import { scanCppBraceScopes } from './cpp-brace-scopes'; +import { pushAll } from '../../utils'; /** A function-like macro a file defines (not a variadic one: none defines a method in practice). */ interface CppMacro { @@ -79,8 +80,8 @@ export function mayDefineCppMacroMethods(source: string): boolean { export function appendCppMacroMethods(result: ExtractionResult, filePath: string, source: string, preParse: (source: string) => string): void { if (!mayDefineCppMacroMethods(source)) return; const minted = cppMacroMethods(filePath, source, preParse, result.nodes); - result.nodes.push(...minted.nodes); - result.edges.push(...minted.edges); + pushAll(result.nodes, minted.nodes); + pushAll(result.edges, minted.edges); } /** diff --git a/src/extraction/languages/csharp.ts b/src/extraction/languages/csharp.ts index a88b01f817..db07e2851d 100644 --- a/src/extraction/languages/csharp.ts +++ b/src/extraction/languages/csharp.ts @@ -1,5 +1,5 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText } from '../tree-sitter-helpers'; +import { getNodeText, childrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; /** @@ -71,8 +71,8 @@ export const csharpExtractor: LanguageExtractor = { structTypes: ['struct_declaration', 'record_struct_declaration'], classifyClassNode: (node) => { if (node.type === 'record_declaration') { - for (let i = 0; i < node.childCount; i++) { - if (node.child(i)?.type === 'struct') return 'struct'; + for (const child of childrenOf(node)) { + if (child.type === 'struct') return 'struct'; } } return 'class'; @@ -103,8 +103,7 @@ export const csharpExtractor: LanguageExtractor = { returnField: 'type', getReturnType: extractCsharpReturnType, getVisibility: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'modifier') { const text = child.text; if (text === 'public') return 'public'; @@ -121,8 +120,7 @@ export const csharpExtractor: LanguageExtractor = { return 'private'; }, isStatic: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'modifier' && child.text === 'static') { return true; } @@ -135,8 +133,7 @@ export const csharpExtractor: LanguageExtractor = { isConst: (node) => { let hasStatic = false; let hasReadonly = false; - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type !== 'modifier') continue; const t = child.text; if (t === 'const') return true; @@ -146,8 +143,7 @@ export const csharpExtractor: LanguageExtractor = { return hasStatic && hasReadonly; }, isAsync: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'modifier' && child.text === 'async') { return true; } diff --git a/src/extraction/languages/dart.ts b/src/extraction/languages/dart.ts index 76ad0b566b..16ba9cec4b 100644 --- a/src/extraction/languages/dart.ts +++ b/src/extraction/languages/dart.ts @@ -1,6 +1,6 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; import type { UnresolvedReference } from '../../types'; -import { getNodeText, BUILTIN_TYPE_NAMES } from '../tree-sitter-helpers'; +import { getNodeText, BUILTIN_TYPE_NAMES, childrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; /** @@ -51,8 +51,7 @@ export function pushDartTypeRefs( */ export function dartTypeAliasName(node: SyntaxNode): SyntaxNode | undefined { let name: SyntaxNode | undefined; - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (!child || child.type === '=' || child.type === 'type_parameters' || child.type === 'formal_parameter_list') break; if (child.type === 'type_identifier') name = child; } @@ -956,8 +955,7 @@ export const dartExtractor: LanguageExtractor = { // In Dart, 'async' is on the function_body (next sibling), not the signature const nextSibling = node.nextNamedSibling; if (nextSibling?.type === 'function_body') { - for (let i = 0; i < nextSibling.childCount; i++) { - const child = nextSibling.child(i); + for (const child of childrenOf(nextSibling)) { if (child?.type === 'async') return true; } } @@ -966,8 +964,7 @@ export const dartExtractor: LanguageExtractor = { isStatic: (node) => { // For method_signature, check for 'static' child if (node.type === 'method_signature') { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'static') return true; } } diff --git a/src/extraction/languages/erlang.ts b/src/extraction/languages/erlang.ts index c63840438d..f454cc7fa6 100644 --- a/src/extraction/languages/erlang.ts +++ b/src/extraction/languages/erlang.ts @@ -4,6 +4,7 @@ import { getChildByField, getPrecedingDocstring, namedArgCount, + namedChildrenOf, } from '../tree-sitter-helpers'; import type { LanguageExtractor, ExtractorContext } from '../tree-sitter-types'; @@ -72,8 +73,7 @@ function moduleExports(node: SyntaxNode, source: string, filePath: string): Set< let root: SyntaxNode = node; while (root.parent) root = root.parent; let result: Set | 'all' = new Set(); - for (let i = 0; i < root.namedChildCount; i++) { - const form = root.namedChild(i); + for (const form of namedChildrenOf(root)) { if (!form) continue; if ( form.type === 'compile_options_attribute' && diff --git a/src/extraction/languages/java.ts b/src/extraction/languages/java.ts index a7830a2d81..c7b41f3ee5 100644 --- a/src/extraction/languages/java.ts +++ b/src/extraction/languages/java.ts @@ -1,5 +1,5 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText, getChildByField } from '../tree-sitter-helpers'; +import { getNodeText, getChildByField, childrenOf } from '../tree-sitter-helpers'; import type { ExtractorContext, LanguageExtractor } from '../tree-sitter-types'; import { IMPLICIT_RECORD_ACCESSOR_DOC } from '../../types'; @@ -347,8 +347,7 @@ export const javaExtractor: LanguageExtractor = { return returnType ? getNodeText(returnType, source) + ' ' + paramsText : paramsText; }, getVisibility: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'modifiers') { const text = child.text; if (text.includes('public')) return 'public'; @@ -361,8 +360,7 @@ export const javaExtractor: LanguageExtractor = { isStatic: (node) => { // An interface constant is implicitly `public static final`. if (node.type === 'constant_declaration') return true; - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'modifiers' && child.text.includes('static')) { return true; } @@ -374,8 +372,7 @@ export const javaExtractor: LanguageExtractor = { // instance / `final`-only / `static`-only fields stay mutable `field`s. isConst: (node) => { if (node.type === 'constant_declaration') return true; - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'modifiers') { const text = child.text; return /\bstatic\b/.test(text) && /\bfinal\b/.test(text); diff --git a/src/extraction/languages/javascript.ts b/src/extraction/languages/javascript.ts index 17920e7fde..8d42a99e0b 100644 --- a/src/extraction/languages/javascript.ts +++ b/src/extraction/languages/javascript.ts @@ -1,4 +1,4 @@ -import { getNodeText, getChildByField } from '../tree-sitter-helpers'; +import { getNodeText, getChildByField, namedChildrenOf, childrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; import { classifyTsClassMember, hasStaticModifier } from './typescript'; @@ -37,8 +37,7 @@ export const javascriptExtractor: LanguageExtractor = { // Also handles wrapper patterns like: field = throttle((e) => { ... }) // field_definition → call_expression → arguments → arrow_function → body if (node.type === 'field_definition') { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; if (child.type === 'arrow_function' || child.type === 'function_expression') { return getChildByField(child, bodyField); @@ -46,8 +45,7 @@ export const javascriptExtractor: LanguageExtractor = { if (child.type === 'call_expression') { const args = getChildByField(child, 'arguments'); if (args) { - for (let j = 0; j < args.namedChildCount; j++) { - const arg = args.namedChild(j); + for (const arg of namedChildrenOf(args)) { if (arg && (arg.type === 'arrow_function' || arg.type === 'function_expression')) { return getChildByField(arg, bodyField); } @@ -72,8 +70,7 @@ export const javascriptExtractor: LanguageExtractor = { return false; }, isAsync: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'async') return true; } return false; @@ -83,8 +80,7 @@ export const javascriptExtractor: LanguageExtractor = { isStatic: hasStaticModifier, isConst: (node) => { if (node.type === 'lexical_declaration') { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'const') return true; } } diff --git a/src/extraction/languages/kotlin.ts b/src/extraction/languages/kotlin.ts index 20b1f566a5..05f7c4c1ca 100644 --- a/src/extraction/languages/kotlin.ts +++ b/src/extraction/languages/kotlin.ts @@ -1,11 +1,10 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText } from '../tree-sitter-helpers'; +import { getNodeText, childrenOf, namedChildrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; /** The visibility a Kotlin declaration's `modifiers` child spells out; public by default. */ -function kotlinVisibility(node: { childCount: number; child(i: number): { type: string; text: string } | null }): 'public' | 'private' | 'protected' | 'internal' { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); +function kotlinVisibility(node: SyntaxNode): 'public' | 'private' | 'protected' | 'internal' { + for (const child of childrenOf(node)) { if (child?.type === 'modifiers') { const text = child.text; if (text.includes('public')) return 'public'; @@ -31,8 +30,7 @@ const KOTLIN_NON_CLASS_RETURN = new Set(['Unit', 'Nothing']); */ function extractKotlinReturnType(node: SyntaxNode, source: string): string | undefined { let seenParams = false; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; if (child.type === 'function_value_parameters') { seenParams = true; @@ -72,8 +70,7 @@ function extractKotlinReturnType(node: SyntaxNode, source: string): string | und function kotlinPropertyInitializers(node: SyntaxNode): SyntaxNode[] { const out: SyntaxNode[] = []; let afterEq = false; - for (let i = 0; i < node.childCount; i++) { - const c = node.child(i); + for (const c of node.children) { if (!c) continue; if (!c.isNamed) { if (c.type === '=') afterEq = true; @@ -154,8 +151,7 @@ function kotlinFollowingAccessors(node: SyntaxNode): SyntaxNode[] { /** The named child right after the first `token` child of `node`, if any. */ function namedChildAfter(node: SyntaxNode, token: string): SyntaxNode | null { let seen = false; - for (let i = 0; i < node.childCount; i++) { - const c = node.child(i); + for (const c of childrenOf(node)) { if (!c) continue; if (!c.isNamed) { if (c.type === token) seen = true; @@ -176,11 +172,9 @@ function namedChildAfter(node: SyntaxNode, token: string): SyntaxNode | null { */ function kotlinClassHeaderCode(node: SyntaxNode): SyntaxNode[] { const out: SyntaxNode[] = []; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child?.type === 'primary_constructor') { - for (let j = 0; j < child.namedChildCount; j++) { - const param = child.namedChild(j); + for (const param of child.namedChildren) { const value = param?.type === 'class_parameter' ? namedChildAfter(param, '=') : null; if (value) out.push(value); } @@ -202,8 +196,7 @@ function kotlinClassHeaderCode(node: SyntaxNode): SyntaxNode[] { function isFunInterfaceNode(node: SyntaxNode): boolean { let hasFun = false; let hasInterfaceType = false; - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of node.children) { if (!child) continue; if (child.type === 'fun' && !child.isNamed) hasFun = true; if (child.type === 'user_type') { @@ -212,8 +205,7 @@ function isFunInterfaceNode(node: SyntaxNode): boolean { } // Pattern 2b: user_type("interface") is inside an ERROR child if (child.type === 'ERROR') { - for (let j = 0; j < child.childCount; j++) { - const gc = child.child(j); + for (const gc of child.children) { if (gc && gc.type === 'user_type') { const typeId = gc.namedChildren.find((c: SyntaxNode) => c.type === 'type_identifier'); if (typeId && typeId.text === 'interface') hasInterfaceType = true; @@ -436,11 +428,9 @@ export const kotlinExtractor: LanguageExtractor = { // an ERROR child — direct simple_identifier children are the misparsed method name. let nameText: string | null = null; if (node.type === 'function_declaration') { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child && child.type === 'ERROR') { - for (let j = 0; j < child.childCount; j++) { - const gc = child.child(j); + for (const gc of childrenOf(child)) { if (gc && gc.type === 'simple_identifier') { nameText = gc.text; break; @@ -452,8 +442,7 @@ export const kotlinExtractor: LanguageExtractor = { } // Fallback: direct simple_identifier child (Pattern 1: ERROR node at top level) if (!nameText) { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child && child.type === 'simple_identifier') { nameText = child.text; break; @@ -472,11 +461,9 @@ export const kotlinExtractor: LanguageExtractor = { // Pattern 1: body is in the next sibling lambda_literal const nextSibling = node.nextSibling; if (nextSibling && nextSibling.type === 'lambda_literal') { - for (let i = 0; i < nextSibling.namedChildCount; i++) { - const child = nextSibling.namedChild(i); + for (const child of nextSibling.namedChildren) { if (child && child.type === 'statements') { - for (let j = 0; j < child.namedChildCount; j++) { - const stmt = child.namedChild(j); + for (const stmt of child.namedChildren) { if (stmt) ctx.visitNode(stmt); } } @@ -502,8 +489,7 @@ export const kotlinExtractor: LanguageExtractor = { // misparsed the parent's body as an ERROR node (starting with `{`) and creates // a class_body sibling for the nested interface's body. Prefer the ERROR body // so the parent's methods are extracted. - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (child && child.type === 'ERROR') { const firstChild = child.child(0); if (firstChild && firstChild.type === '{') { @@ -523,8 +509,7 @@ export const kotlinExtractor: LanguageExtractor = { // interface Foo { } → has 'interface' keyword child // enum class Level { } → has 'enum' keyword child // class / data class / abstract class → default 'class' - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (!child) continue; if (child.type === 'interface') return 'interface'; if (child.type === 'enum') return 'enum'; @@ -536,8 +521,7 @@ export const kotlinExtractor: LanguageExtractor = { // AST: function_declaration > receiver_type > user_type, then ".", simple_identifier. // Only a plain user_type receiver counts (a nullable or function-type one // gives none), and a qualified one names its FIRST type_identifier. - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (!child) continue; if (child.type === 'receiver_type') { const userType = child.namedChildren.find((c: SyntaxNode) => c.type === 'user_type'); @@ -557,8 +541,7 @@ export const kotlinExtractor: LanguageExtractor = { // child, then the type node that follows it before the body. let params: SyntaxNode | null = null; let returnType: SyntaxNode | null = null; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; if (child.type === 'function_value_parameters') { params = child; @@ -585,8 +568,7 @@ export const kotlinExtractor: LanguageExtractor = { }, isAsync: (node) => { // Kotlin uses suspend keyword for coroutines - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'modifiers' && child.text.includes('suspend')) { return true; } @@ -602,14 +584,11 @@ export const kotlinExtractor: LanguageExtractor = { // to the `expect`). Match the AST node, not raw text, so an annotation // argument or identifier named "actual" can't false-positive. const mods: string[] = []; - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of node.children) { if (child?.type !== 'modifiers') continue; - for (let j = 0; j < child.childCount; j++) { - const pm = child.child(j); + for (const pm of child.children) { if (pm?.type !== 'platform_modifier') continue; - for (let k = 0; k < pm.childCount; k++) { - const kw = pm.child(k); + for (const kw of pm.children) { if (kw && (kw.type === 'expect' || kw.type === 'actual')) mods.push(kw.type); } } diff --git a/src/extraction/languages/lua.ts b/src/extraction/languages/lua.ts index ec59a50deb..ce941d1b25 100644 --- a/src/extraction/languages/lua.ts +++ b/src/extraction/languages/lua.ts @@ -1,6 +1,7 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; import { getNodeText, getChildByField } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; +import { pushAll } from '../../utils'; // Node names follow the vendored ABI-15 grammar (@tree-sitter-grammars/ // tree-sitter-lua), NOT the older tree-sitter-wasms build — see grammars.ts. @@ -11,7 +12,7 @@ function findDescendant(node: SyntaxNode, type: string): SyntaxNode | null { while (queue.length) { const n = queue.shift()!; if (n.type === type) return n; - queue.push(...n.namedChildren); + pushAll(queue, n.namedChildren); } return null; } diff --git a/src/extraction/languages/objc.ts b/src/extraction/languages/objc.ts index d55588566f..685c4d3fb3 100644 --- a/src/extraction/languages/objc.ts +++ b/src/extraction/languages/objc.ts @@ -1,5 +1,5 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getChildByField, getNodeText } from '../tree-sitter-helpers'; +import { getChildByField, getNodeText, namedChildrenOf } from '../tree-sitter-helpers'; import type { ExtractorContext, LanguageExtractor } from '../tree-sitter-types'; import { blankLoneMacroLines, @@ -11,8 +11,7 @@ import { } from './c-cpp'; function findCompoundStatement(node: SyntaxNode): SyntaxNode | null { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (child?.type === 'compound_statement') { return child; } @@ -51,8 +50,7 @@ const OBJC_TYPE_QUALIFIERS = new Set([ /** Collect the type identifiers under a `method_type`, in document order. */ function collectTypeIdentifiers(node: SyntaxNode, source: string, out: string[]): void { if (node.type === 'type_identifier') out.push(getNodeText(node, source).trim()); - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) collectTypeIdentifiers(child, source, out); } } @@ -149,8 +147,7 @@ export const objcExtractor: LanguageExtractor = { return findCompoundStatement(node); }, resolveTypeAliasKind: (node, _source) => { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; if (child.type === 'enum_specifier' && getChildByField(child, 'body')) return 'enum'; if (child.type === 'struct_specifier' && getChildByField(child, 'body')) @@ -174,11 +171,9 @@ export const objcExtractor: LanguageExtractor = { if (!classNode) return true; ctx.pushScope(classNode.id); - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child?.type === 'implementation_definition') { - for (let j = 0; j < child.namedChildCount; j++) { - const implChild = child.namedChild(j); + for (const implChild of child.namedChildren) { if (implChild) ctx.visitNode(implChild); } } diff --git a/src/extraction/languages/pascal.ts b/src/extraction/languages/pascal.ts index 164758f815..8c06866dfa 100644 --- a/src/extraction/languages/pascal.ts +++ b/src/extraction/languages/pascal.ts @@ -1,5 +1,5 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText, getChildByField } from '../tree-sitter-helpers'; +import { getNodeText, getChildByField, childrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; import { preParsePascal } from './pascal-preparse'; @@ -50,8 +50,7 @@ export const pascalExtractor: LanguageExtractor = { let current = node.parent; while (current) { if (current.type === 'declSection') { - for (let i = 0; i < current.childCount; i++) { - const child = current.child(i); + for (const child of childrenOf(current)) { if (child?.type === 'kPublic' || child?.type === 'kPublished') return 'public'; if (child?.type === 'kPrivate') return 'private'; @@ -67,8 +66,8 @@ export const pascalExtractor: LanguageExtractor = { return false; }, isStatic: (node) => { - for (let i = 0; i < node.childCount; i++) { - if (node.child(i)?.type === 'kClass') return true; + for (const child of childrenOf(node)) { + if (child.type === 'kClass') return true; } return false; }, diff --git a/src/extraction/languages/php.ts b/src/extraction/languages/php.ts index 0df5c8e09c..a9ebd4cf43 100644 --- a/src/extraction/languages/php.ts +++ b/src/extraction/languages/php.ts @@ -1,5 +1,5 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText, getChildByField } from '../tree-sitter-helpers'; +import { getNodeText, getChildByField, childrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; // include / require (+ _once) expression node types. These carry the @@ -328,8 +328,7 @@ export const phpExtractor: LanguageExtractor = { return node.type === 'trait_declaration' ? 'trait' : 'class'; }, getVisibility: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'visibility_modifier') { const text = child.text; if (text === 'public') return 'public'; @@ -340,8 +339,7 @@ export const phpExtractor: LanguageExtractor = { return 'public'; // PHP defaults to public }, isStatic: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'static_modifier') return true; } return false; diff --git a/src/extraction/languages/python.ts b/src/extraction/languages/python.ts index 99d0c48aca..e174964031 100644 --- a/src/extraction/languages/python.ts +++ b/src/extraction/languages/python.ts @@ -1,5 +1,6 @@ import { getNodeText, getChildByField } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; +import { minOf } from '../../utils'; export const pythonExtractor: LanguageExtractor = { functionTypes: ['function_definition'], @@ -104,7 +105,7 @@ function dedentDocstring(raw: string): string { const rest = lines.slice(1).filter((l) => l.trim().length > 0); const indent = rest.length === 0 ? 0 - : Math.min(...rest.map((l) => l.length - l.trimStart().length)); + : minOf(rest.map((l) => l.length - l.trimStart().length)); const out = [ lines[0]?.trim() ?? '', ...lines.slice(1).map((l) => l.slice(indent).trimEnd()), diff --git a/src/extraction/languages/r.ts b/src/extraction/languages/r.ts index 605619ee39..628ae87921 100644 --- a/src/extraction/languages/r.ts +++ b/src/extraction/languages/r.ts @@ -1,5 +1,5 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText, getChildByField } from '../tree-sitter-helpers'; +import { getNodeText, getChildByField, namedChildrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor, ExtractorContext } from '../tree-sitter-types'; /** @@ -58,8 +58,7 @@ function calleeName(call: SyntaxNode, source: string): string | null { function firstArgValue(call: SyntaxNode): SyntaxNode | null { const args = getChildByField(call, 'arguments'); if (!args) return null; - for (let i = 0; i < args.namedChildCount; i++) { - const arg = args.namedChild(i); + for (const arg of namedChildrenOf(args)) { if (arg?.type !== 'argument') continue; return getChildByField(arg, 'value'); } @@ -71,8 +70,7 @@ function literalOrIdentifier(node: SyntaxNode | null, source: string): string | if (!node) return null; if (node.type === 'identifier') return getNodeText(node, source); if (node.type === 'string') { - for (let i = 0; i < node.namedChildCount; i++) { - const c = node.namedChild(i); + for (const c of namedChildrenOf(node)) { if (c?.type === 'string_content') return getNodeText(c, source); } return ''; // empty string literal @@ -111,8 +109,7 @@ function extractClassMembers(classCall: SyntaxNode, classId: string, ctx: Extrac const args = getChildByField(classCall, 'arguments'); if (!args) return; let positional = 0; - for (let i = 0; i < args.namedChildCount; i++) { - const arg = args.namedChild(i); + for (const arg of args.namedChildren) { if (arg?.type !== 'argument') continue; const argName = getChildByField(arg, 'name'); const value = getChildByField(arg, 'value'); @@ -154,8 +151,7 @@ function extractClassMembers(classCall: SyntaxNode, classId: string, ctx: Extrac if (value?.type === 'call' && calleeName(value, ctx.source) === 'list') { const listArgs = getChildByField(value, 'arguments'); if (!listArgs) continue; - for (let j = 0; j < listArgs.namedChildCount; j++) { - const entry = listArgs.namedChild(j); + for (const entry of listArgs.namedChildren) { if (entry?.type === 'argument') emitMethodArg(entry, ctx); } } diff --git a/src/extraction/languages/ruby.ts b/src/extraction/languages/ruby.ts index f053fa8162..3b932e4a86 100644 --- a/src/extraction/languages/ruby.ts +++ b/src/extraction/languages/ruby.ts @@ -2,6 +2,14 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; import { getNodeText, getChildByField } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; +type RubyVisibility = 'public' | 'private' | 'protected'; + +/** + * Per tree, by a parent's id: the last method whose visibility was worked out + * under it (where it starts) and what it was. See rubyExtractor.getVisibility. + */ +const RUBY_VISIBILITY_SEEN = new WeakMap>(); + /** * A class method: `def self.x` or `def Widget.x` (a singleton_method), or a * `def` inside `class << self`. It shares its qualified name with an instance @@ -47,8 +55,7 @@ export const rubyExtractor: LanguageExtractor = { const args = node.childForFieldName('arguments') ?? node.namedChildren.find((c: SyntaxNode) => c.type === 'argument_list'); if (parentId && args) { - for (let i = 0; i < args.namedChildCount; i++) { - const arg = args.namedChild(i); + for (const arg of args.namedChildren) { // `Mod` is `constant`, `Foo::Bar` is `scope_resolution`. Skip // `extend self` / dynamic args (`include foo()`). if (arg && (arg.type === 'constant' || arg.type === 'scope_resolution')) { @@ -80,8 +87,7 @@ export const rubyExtractor: LanguageExtractor = { ctx.pushScope(moduleNode.id); const body = node.childForFieldName('body'); if (body) { - for (let i = 0; i < body.namedChildCount; i++) { - const child = body.namedChild(i); + for (const child of body.namedChildren) { if (child) ctx.visitNode(child); } } @@ -119,21 +125,35 @@ export const rubyExtractor: LanguageExtractor = { }, isStatic: isRubyClassMethod, getVisibility: (node) => { - // Ruby visibility is based on preceding visibility modifiers - let sibling = node.previousNamedSibling; - while (sibling) { + // Ruby visibility is based on preceding visibility modifiers. The walk + // back stops at the method it last answered for under the same parent + // and takes that answer: nothing between the two changed it. Without + // that, every method walked back over every sibling before it, and a + // class of seven thousand methods took twelve seconds over this alone. + const tree = node.tree; + let seen = RUBY_VISIBILITY_SEEN.get(tree); + if (!seen) RUBY_VISIBILITY_SEEN.set(tree, (seen = new Map())); + const parent = node.parent?.id ?? 0; + const start = node.startIndex; + const last = seen.get(parent); + // Only a method further down than the remembered one may lean on it. + const known = last && last.start < start ? last : undefined; + let visibility: RubyVisibility = 'public'; + for (let sibling = node.previousNamedSibling; sibling; sibling = sibling.previousNamedSibling) { + if (known && sibling.startIndex <= known.start) { + visibility = known.visibility; + break; + } if (sibling.type === 'call') { - const methodName = getChildByField(sibling, 'method'); - if (methodName) { - const text = methodName.text; - if (text === 'private') return 'private'; - if (text === 'protected') return 'protected'; - if (text === 'public') return 'public'; + const text = getChildByField(sibling, 'method')?.text; + if (text === 'private' || text === 'protected' || text === 'public') { + visibility = text; + break; } } - sibling = sibling.previousNamedSibling; } - return 'public'; + if (!last || last.start < start) seen.set(parent, { start, visibility }); + return visibility; }, extractImport: (node, source) => { const importText = source.substring(node.startIndex, node.endIndex).trim(); diff --git a/src/extraction/languages/rust.ts b/src/extraction/languages/rust.ts index c336a79ab1..2529d70117 100644 --- a/src/extraction/languages/rust.ts +++ b/src/extraction/languages/rust.ts @@ -1,5 +1,5 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText, getChildByField } from '../tree-sitter-helpers'; +import { getNodeText, getChildByField, childrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; /** @@ -128,15 +128,13 @@ export const rustExtractor: LanguageExtractor = { return sig; }, isAsync: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'async') return true; } return false; }, getVisibility: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'visibility_modifier') { return child.text.includes('pub') ? 'public' : 'private'; } diff --git a/src/extraction/languages/scala.ts b/src/extraction/languages/scala.ts index bd0d327b32..65d6ec9ea9 100644 --- a/src/extraction/languages/scala.ts +++ b/src/extraction/languages/scala.ts @@ -1,5 +1,5 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText } from '../tree-sitter-helpers'; +import { getNodeText, namedChildrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; function getValVarName(node: SyntaxNode, source: string): string | null { @@ -38,8 +38,7 @@ function emitScalaTypeRefs(typeNode: SyntaxNode, fromId: string, ctx: { addUnres } return; } - for (let i = 0; i < typeNode.namedChildCount; i++) { - const child = typeNode.namedChild(i); + for (const child of typeNode.namedChildren) { if (child) emitScalaTypeRefs(child, fromId, ctx, source); } } @@ -67,8 +66,7 @@ function extractScalaReturnType(node: SyntaxNode, source: string): string | unde } function extractVisibility(node: SyntaxNode): 'public' | 'private' | 'protected' { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; if (child.type === 'modifiers' || child.type === 'access_modifier') { const text = child.text; @@ -126,8 +124,7 @@ export const scalaExtractor: LanguageExtractor = { isAsync: () => false, isStatic: (node: SyntaxNode) => { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (child?.type === 'modifiers' && child.text.includes('static')) return true; } return false; @@ -185,8 +182,7 @@ export const scalaExtractor: LanguageExtractor = { // enum_case_definitions wraps simple_enum_case / full_enum_case children if (t === 'enum_case_definitions') { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (!child) continue; if (child.type === 'simple_enum_case' || child.type === 'full_enum_case') { const nameNode = child.childForFieldName('name'); @@ -200,8 +196,7 @@ export const scalaExtractor: LanguageExtractor = { if (t === 'extension_definition') { const body = node.childForFieldName('body'); if (body) { - for (let i = 0; i < body.namedChildCount; i++) { - const child = body.namedChild(i); + for (const child of body.namedChildren) { if (child) ctx.visitNode(child); } } @@ -215,8 +210,7 @@ export const scalaExtractor: LanguageExtractor = { const importText = getNodeText(node, source).trim(); const pathNode = node.childForFieldName('path'); if (pathNode) return { moduleName: getNodeText(pathNode, source), signature: importText }; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (child?.type === 'identifier' || child?.type === 'stable_identifier') { return { moduleName: getNodeText(child, source), signature: importText }; } diff --git a/src/extraction/languages/solidity.ts b/src/extraction/languages/solidity.ts index 220538a92d..8f3631c460 100644 --- a/src/extraction/languages/solidity.ts +++ b/src/extraction/languages/solidity.ts @@ -1,5 +1,5 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText, getChildByField } from '../tree-sitter-helpers'; +import { getNodeText, getChildByField, childrenOf, namedChildrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; /** @@ -26,8 +26,7 @@ import type { LanguageExtractor } from '../tree-sitter-types'; function getInheritanceAncestors(node: SyntaxNode, source: string): string[] { const ancestors: string[] = []; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (!child || child.type !== 'inheritance_specifier') continue; const ancestor = getChildByField(child, 'ancestor'); if (!ancestor) continue; @@ -45,8 +44,7 @@ function fallbackReceiveName(node: SyntaxNode): string { // tree-sitter-solidity reuses one node type for both `fallback() ...` and // `receive() ...` — the keyword is an unnamed/anonymous child. Walk all // children (named + unnamed) and pick the first whose text is one of these. - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (!child) continue; const t = child.text; if (t === 'fallback' || t === 'receive') return t; @@ -100,8 +98,7 @@ export const solidityExtractor: LanguageExtractor = { let returnType: SyntaxNode | undefined; let visibility: SyntaxNode | undefined; let mutability: SyntaxNode | undefined; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const [i, child] of node.namedChildren.entries()) { if (!child) continue; const fieldName = node.fieldNameForNamedChild(i); if (child.type === 'parameter' && fieldName !== 'return_type') { @@ -126,8 +123,7 @@ export const solidityExtractor: LanguageExtractor = { getVisibility: (node) => { // Solidity functions: public/private/internal/external — `external` maps // to 'public' for our purposes (callable from outside the contract). - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (child?.type !== 'visibility') continue; const t = child.text.trim(); if (t === 'public' || t === 'external') return 'public'; @@ -187,8 +183,7 @@ export const solidityExtractor: LanguageExtractor = { } ctx.pushScope(created.id); if (body) { - for (let i = 0; i < body.namedChildCount; i++) { - const child = body.namedChild(i); + for (const child of body.namedChildren) { if (child) ctx.visitNode(child); } } @@ -209,8 +204,7 @@ export const solidityExtractor: LanguageExtractor = { const created = ctx.createNode(kind, name, node); if (!created) return true; ctx.pushScope(created.id); - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (!child) continue; if (child === nameNode) continue; ctx.visitNode(child); diff --git a/src/extraction/languages/swift.ts b/src/extraction/languages/swift.ts index b574f16659..f2b9ca5455 100644 --- a/src/extraction/languages/swift.ts +++ b/src/extraction/languages/swift.ts @@ -1,5 +1,5 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText, getChildByField } from '../tree-sitter-helpers'; +import { getNodeText, getChildByField, namedChildrenOf, childrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; /** @@ -13,8 +13,7 @@ import type { LanguageExtractor } from '../tree-sitter-types'; */ function extractSwiftReturnType(node: SyntaxNode, source: string): string | undefined { let seenName = false; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; if (child.type === 'simple_identifier' && !seenName) { seenName = true; @@ -132,8 +131,7 @@ export const swiftExtractor: LanguageExtractor = { }, getVisibility: (node) => { // Check for visibility modifiers in Swift - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'modifiers') { const text = child.text; if (text.includes('public')) return 'public'; @@ -145,8 +143,7 @@ export const swiftExtractor: LanguageExtractor = { return 'internal'; // Swift defaults to internal }, isStatic: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'modifiers') { if (child.text.includes('static') || child.text.includes('class')) { return true; @@ -157,16 +154,14 @@ export const swiftExtractor: LanguageExtractor = { }, classifyClassNode: (node) => { // Swift uses class_declaration for classes, structs, and enums - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'struct') return 'struct'; if (child?.type === 'enum') return 'enum'; } return 'class'; }, isAsync: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'modifiers' && child.text.includes('async')) { return true; } diff --git a/src/extraction/languages/typescript.ts b/src/extraction/languages/typescript.ts index cff6b9349a..68b6346629 100644 --- a/src/extraction/languages/typescript.ts +++ b/src/extraction/languages/typescript.ts @@ -1,4 +1,4 @@ -import { getNodeText, getChildByField } from '../tree-sitter-helpers'; +import { getNodeText, getChildByField, childrenOf, namedChildrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; import { hasFlowPragma } from '../grammars'; import type { Node as SyntaxNode } from 'web-tree-sitter'; @@ -9,8 +9,8 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; * extractors, which parse class bodies alike. */ export function hasStaticModifier(node: SyntaxNode): boolean { - for (let i = 0; i < node.childCount; i++) { - if (node.child(i)?.type === 'static') return true; + for (const child of childrenOf(node)) { + if (child.type === 'static') return true; } return false; } @@ -30,8 +30,7 @@ export function classifyTsClassMember(node: SyntaxNode): 'method' | 'property' { if (node.type !== 'public_field_definition' && node.type !== 'field_definition') { return 'method'; // method_definition, getters/setters — untouched } - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; if (child.type === 'arrow_function' || child.type === 'function_expression') { return 'method'; @@ -39,8 +38,7 @@ export function classifyTsClassMember(node: SyntaxNode): 'method' | 'property' { if (child.type === 'call_expression') { const args = getChildByField(child, 'arguments'); if (args) { - for (let j = 0; j < args.namedChildCount; j++) { - const arg = args.namedChild(j); + for (const arg of namedChildrenOf(args)) { if (arg && (arg.type === 'arrow_function' || arg.type === 'function_expression')) { return 'method'; } @@ -124,8 +122,8 @@ export function isAmbientExport(node: SyntaxNode): boolean { if (current.type === 'statement_block' && hasExportDeclaration(current)) return false; if (current.type !== 'ambient_declaration') continue; // `declare global` is the keyword and a bare block, with no field names. - for (let i = 0; i < current.childCount; i++) { - if (current.child(i)?.type === 'global') return true; + for (const child of childrenOf(current)) { + if (child.type === 'global') return true; } const declared = current.namedChild(0); if (declared?.type === 'module' && getChildByField(declared, 'name')?.type === 'string') return true; @@ -135,8 +133,7 @@ export function isAmbientExport(node: SyntaxNode): boolean { /** A statement in `block` that exports by name or by assignment, not by declaring. */ function hasExportDeclaration(block: SyntaxNode): boolean { - for (let i = 0; i < block.namedChildCount; i++) { - const statement = block.namedChild(i); + for (const statement of namedChildrenOf(block)) { if (statement?.type === 'export_statement' && !getChildByField(statement, 'declaration')) return true; } return false; @@ -217,8 +214,7 @@ export const typescriptExtractor: LanguageExtractor = { // Also handles wrapper patterns like: field = withBatchedUpdates((e) => { ... }) // public_field_definition → call_expression → arguments → arrow_function → body if (node.type === 'public_field_definition') { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; if (child.type === 'arrow_function' || child.type === 'function_expression') { return getChildByField(child, bodyField); @@ -227,8 +223,7 @@ export const typescriptExtractor: LanguageExtractor = { if (child.type === 'call_expression') { const args = getChildByField(child, 'arguments'); if (args) { - for (let j = 0; j < args.namedChildCount; j++) { - const arg = args.namedChild(j); + for (const arg of namedChildrenOf(args)) { if (arg && (arg.type === 'arrow_function' || arg.type === 'function_expression')) { return getChildByField(arg, bodyField); } @@ -252,8 +247,7 @@ export const typescriptExtractor: LanguageExtractor = { return sig; }, getVisibility: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'accessibility_modifier') { const text = child.text; if (text === 'public') return 'public'; @@ -276,8 +270,7 @@ export const typescriptExtractor: LanguageExtractor = { return isAmbientExport(node); }, isAsync: (node) => { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'async') return true; } return false; @@ -287,8 +280,7 @@ export const typescriptExtractor: LanguageExtractor = { // For lexical_declaration, check if it's 'const' or 'let' // For variable_declaration, it's always 'var' if (node.type === 'lexical_declaration') { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'const') return true; } } diff --git a/src/extraction/languages/vbnet.ts b/src/extraction/languages/vbnet.ts index 35f6349538..48179b4838 100644 --- a/src/extraction/languages/vbnet.ts +++ b/src/extraction/languages/vbnet.ts @@ -1,5 +1,5 @@ import type { Node as SyntaxNode } from 'web-tree-sitter'; -import { getNodeText } from '../tree-sitter-helpers'; +import { getNodeText, childrenOf } from '../tree-sitter-helpers'; import type { LanguageExtractor } from '../tree-sitter-types'; /** @@ -15,8 +15,7 @@ export function ensureTrailingNewline(source: string): string { /** Case-insensitive member-modifier scan (VB keywords are case-insensitive). */ function hasModifier(node: SyntaxNode, re: RegExp): boolean { - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + for (const child of childrenOf(node)) { if (child?.type === 'member_modifier' && re.test(child.text)) return true; } return false; diff --git a/src/extraction/liquid-extractor.ts b/src/extraction/liquid-extractor.ts index 3536ec64e9..449f607a9c 100644 --- a/src/extraction/liquid-extractor.ts +++ b/src/extraction/liquid-extractor.ts @@ -517,19 +517,43 @@ export class LiquidExtractor { * Get the line number for a character index */ private getLineNumber(index: number): number { - const substring = this.source.substring(0, index); - return (substring.match(/\n/g) || []).length + 1; + // The line starts at or before the index: one more than the newlines before it. + const starts = this.lineStarts(); + if (!(index > 0)) return 1; + let low = 0; + let high = starts.length; + while (low < high) { + const mid = (low + high) >> 1; + if (starts[mid]! <= index) low = mid + 1; + else high = mid; + } + return low; } /** * Get the character index of the start of a line */ private getLineStart(lineNumber: number): number { - const lines = this.source.split('\n'); - let index = 0; - for (let i = 0; i < lineNumber - 1 && i < lines.length; i++) { - index += lines[i]!.length + 1; // +1 for newline + const starts = this.lineStarts(); + const line = Math.ceil(lineNumber) - 1; + if (!(line > 0)) return 0; + // Past the last line: where a line after it would start. + return line < starts.length ? starts[line]! : this.source.length + 1; + } + + /** + * Where each line of the source starts, read once. Both lookups above read + * the source again for every tag and filter they were asked about (the text + * before it for one, every line for the other): 1.2 MB of markup took 41 + * seconds. + */ + private lineStarts(): number[] { + if (!this.starts) { + this.starts = [0]; + for (let at = this.source.indexOf('\n'); at >= 0; at = this.source.indexOf('\n', at + 1)) this.starts.push(at + 1); } - return index; + return this.starts; } + + private starts: number[] | null = null; } diff --git a/src/extraction/store-worker.ts b/src/extraction/store-worker.ts index 5affa8b15a..fe520359c0 100644 --- a/src/extraction/store-worker.ts +++ b/src/extraction/store-worker.ts @@ -30,6 +30,7 @@ import { createDatabase, SqliteDatabase } from '../db/sqlite-adapter'; import { finalizeStoreBundle, type KernelStoreBundle, type StoreBundle } from './store-writer'; import { decodeExtractBuffers } from './kernel/decode'; import { collectBeforeExit } from '../worker-teardown'; +import { pushAll } from '../utils'; if (!parentPort) { throw new Error('store-worker must be run as a worker thread'); @@ -68,7 +69,7 @@ function decodeKernelBundle(bundle: KernelStoreBundle): StoreBundle { bundle.filePath, bundle.language ); - if (bundle.extraRefs?.length) decoded.unresolvedReferences.push(...bundle.extraRefs); + if (bundle.extraRefs?.length) pushAll(decoded.unresolvedReferences, bundle.extraRefs); return finalizeStoreBundle(decoded, bundle.filePath, bundle.language, bundle.file); } diff --git a/src/extraction/tree-sitter-helpers.ts b/src/extraction/tree-sitter-helpers.ts index fdfdd4467a..c00b271fe7 100644 --- a/src/extraction/tree-sitter-helpers.ts +++ b/src/extraction/tree-sitter-helpers.ts @@ -46,6 +46,40 @@ export class NodeIdAllocator { } } +/** + * A node's children, one after another. + * + * `node.child(i)` reads the children before the i-th to reach it when they + * are a flat run, as some thousand comment lines under one parent are, so a + * loop over them by index takes the square of their number: a megabyte of + * comment lines under a VB.NET module, four seconds. A cursor steps from + * each child to the next. Leaving the loop early releases the cursor. + */ +export function* childrenOf(node: SyntaxNode): Generator { + const cursor = node.walk(); + try { + if (!cursor.gotoFirstChild()) return; + do { + yield cursor.currentNode; + } while (cursor.gotoNextSibling()); + } finally { + cursor.delete(); + } +} + +/** A node's named children, one after another (see childrenOf). */ +export function* namedChildrenOf(node: SyntaxNode): Generator { + const cursor = node.walk(); + try { + if (!cursor.gotoFirstChild()) return; + do { + if (cursor.nodeIsNamed) yield cursor.currentNode; + } while (cursor.gotoNextSibling()); + } finally { + cursor.delete(); + } +} + /** * Extract text from a syntax node */ diff --git a/src/extraction/tree-sitter.ts b/src/extraction/tree-sitter.ts index aa62f756c2..8d7c6c957b 100644 --- a/src/extraction/tree-sitter.ts +++ b/src/extraction/tree-sitter.ts @@ -16,7 +16,7 @@ import { UnresolvedReference, } from '../types'; import { getParser, detectLanguage, isLanguageSupported, isFileLevelOnlyLanguage } from './grammars'; -import { NodeIdAllocator, getNodeText, getChildByField, getPrecedingDocstring, BUILTIN_TYPE_NAMES, namedArgCount } from './tree-sitter-helpers'; +import { NodeIdAllocator, getNodeText, getChildByField, getPrecedingDocstring, BUILTIN_TYPE_NAMES, namedArgCount, namedChildrenOf, childrenOf } from './tree-sitter-helpers'; import { FN_REF_SPECS, captureFnRefCandidates, goScopedFnRefScopes, type FnRefSpec, type FnRefCandidate } from './function-ref'; import { isGeneratedFile, isMinifiedContent } from './generated-detection'; import type { LanguageExtractor, ExtractorContext } from './tree-sitter-types'; @@ -45,6 +45,7 @@ import { tryKernelExtract, takeDeferredPreParse } from './kernel'; import { indexParseBudgetMs, parseTimeoutMessage, parseWithinBudget } from './parse-budget'; import { commonJsRequireRefs } from './commonjs-requires'; import { frameworks } from './lazy-frameworks'; +import { pushAll } from '../utils'; // Re-export for backward compatibility export { generateNodeId } from './tree-sitter-helpers'; @@ -171,8 +172,7 @@ function extractNameRaw(node: SyntaxNode, source: string, extractor: LanguageExt // For Dart method_signature, look inside inner signature types if (node.type === 'method_signature') { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (child && ( child.type === 'function_signature' || child.type === 'getter_signature' || @@ -181,8 +181,7 @@ function extractNameRaw(node: SyntaxNode, source: string, extractor: LanguageExt child.type === 'factory_constructor_signature' )) { // Find identifier inside the inner signature - for (let j = 0; j < child.namedChildCount; j++) { - const inner = child.namedChild(j); + for (const inner of namedChildrenOf(child)) { if (inner?.type === 'identifier') { return getNodeText(inner, source); } @@ -200,8 +199,7 @@ function extractNameRaw(node: SyntaxNode, source: string, extractor: LanguageExt } // Fall back to first identifier child - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if ( child && (child.type === 'identifier' || @@ -300,8 +298,7 @@ function firstSimpleIdentifier(node: SyntaxNode | null): SyntaxNode | null { while (stack.length > 0 && guard++ < 40) { const n = stack.shift()!; if (n.type === 'simple_identifier') return n; - for (let i = 0; i < n.namedChildCount; i++) { - const c = n.namedChild(i); + for (const c of n.namedChildren) { if (c) stack.push(c); } } @@ -890,6 +887,13 @@ export class TreeSitterExtractor { private source: string; private tree: Tree | null = null; private nodes: Node[] = []; + /** + * The file's nodes by id, the first of an id as `nodes.find` finds it. A + * member's qualified name is built from the ids on the stack above it, and + * each was looked for among all the nodes extracted so far: a file of + * fourteen thousand small classes went through them for every member. + */ + private nodesById = new Map(); private nodeIds = new NodeIdAllocator(); private edges: Edge[] = []; private unresolvedReferences: UnresolvedReference[] = []; @@ -955,6 +959,8 @@ export class TreeSitterExtractor { /** The routine headers of the source text, by line, for a broken tree's regions (#2514). */ private pascalTextRoutines: PascalTextRoutine[] | null = null; private pascalSourceLines: string[] | null = null; + /** The names a later statement of the file exports, read on first use (see isExportedLater). */ + private laterExports: Set | null = null; private pascalWithDepth = 0; private pascalDataNameSets = new Map>(); /** Bare names read in an expression, kept until the file shows which are variables (#2514). */ @@ -1113,6 +1119,7 @@ export class TreeSitterExtractor { const fileDocstring = this.extractor?.getBodyDocstring?.(this.tree.rootNode, this.source); if (fileDocstring) fileNode.docstring = fileDocstring; this.nodes.push(fileNode); + if (!this.nodesById.has(fileNode.id)) this.nodesById.set(fileNode.id, fileNode); // Push file node onto stack so top-level declarations get contains edges this.nodeStack.push(fileNode.id); @@ -1137,7 +1144,7 @@ export class TreeSitterExtractor { // A CommonJS `require('./x')` is a file import, like ESM's `import`. The // kernel reads the same (kernel/index.ts and the parse worker's transport). - this.unresolvedReferences.push(...commonJsRequireRefs(this.filePath, this.source, this.language)); + pushAll(this.unresolvedReferences, commonJsRequireRefs(this.filePath, this.source, this.language)); // hasError is routine for several grammars; warn only when no symbols survived. // (A re-export's import of its module is none: a barrel whose other lines @@ -1230,8 +1237,7 @@ export class TreeSitterExtractor { return; } this.maybeCaptureFnRefs(node, nodeType); - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) this.scanFnRefSubtree(child, depth + 1, walked); } } @@ -1504,8 +1510,7 @@ export class TreeSitterExtractor { break; } } - for (let i = 0; i < n.namedChildCount; i++) { - const c = n.namedChild(i); + for (const c of n.namedChildren) { if (c) dstack.push(c); } } @@ -1560,8 +1565,7 @@ export class TreeSitterExtractor { }); } } - for (let i = 0; i < n.namedChildCount; i++) { - const c = n.namedChild(i); + for (const c of n.namedChildren) { if (c) stack.push(c); } } @@ -1581,7 +1585,7 @@ export class TreeSitterExtractor { const written = getNodeText(object, this.source); const qualifier = written.slice(written.lastIndexOf('.') + 1).trim(); if (qualifier === 'this') return false; - const segments = this.nodes.find((d) => d.id === targetId)?.qualifiedName.split('::') ?? []; + const segments = this.nodesById.get(targetId)?.qualifiedName.split('::') ?? []; return segments[segments.length - 2] !== qualifier; } @@ -1711,8 +1715,7 @@ export class TreeSitterExtractor { const nsName = nameNode ? getNodeText(nameNode, this.source) : ''; if (nsName) { this.namespacePrefix.push(nsName); - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) this.visitNode(child); } this.namespacePrefix.pop(); @@ -1731,13 +1734,12 @@ export class TreeSitterExtractor { const nsName = this.extractor.extractPackage?.(node, this.source); if (nsName) { const topId = this.nodeStack[this.nodeStack.length - 1]; - const top = this.nodes.find((n) => n.id === topId); + const top = topId === undefined ? undefined : this.nodesById.get(topId); const outer = top?.kind === 'namespace' ? top : null; if (outer) this.nodeStack.pop(); const ns = this.createNode('namespace', outer ? `${outer.name}.${nsName}` : nsName, node); if (ns) this.nodeStack.push(ns.id); - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) this.visitNode(child); } if (ns) this.nodeStack.pop(); @@ -1996,8 +1998,7 @@ export class TreeSitterExtractor { if (modifiers) { const walkAttrArgs = (n: SyntaxNode): void => { this.extractStaticMemberRef(n); - for (let i = 0; i < n.namedChildCount; i++) { - const c = n.namedChild(i); + for (const c of n.namedChildren) { if (c) walkAttrArgs(c); } }; @@ -2125,8 +2126,7 @@ export class TreeSitterExtractor { // Visit children (unless the extract method already visited them) if (!skipChildren) { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) { this.visitNode(child); } @@ -2193,6 +2193,7 @@ export class TreeSitterExtractor { } this.nodes.push(newNode); + if (!this.nodesById.has(newNode.id)) this.nodesById.set(newNode.id, newNode); if (this.language === 'pascal' && node.type === 'declProc' && (kind === 'method' || kind === 'function')) { this.indexPascalRoutine(newNode, node); } @@ -2222,8 +2223,7 @@ export class TreeSitterExtractor { * Used to locate inner type nodes (e.g. enum_specifier inside a typedef). */ private findChildByTypes(node: SyntaxNode, types: string[]): SyntaxNode | null { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (child && types.includes(child.type)) return child; } return null; @@ -2240,8 +2240,7 @@ export class TreeSitterExtractor { if (!types || types.length === 0 || !this.extractor?.extractPackage) return null; let pkgNode: SyntaxNode | null = null; - for (let i = 0; i < rootNode.namedChildCount; i++) { - const child = rootNode.namedChild(i); + for (const child of namedChildrenOf(rootNode)) { if (child && types.includes(child.type)) { pkgNode = child; break; @@ -2310,7 +2309,7 @@ export class TreeSitterExtractor { parts.splice(0, parts.length, pathOwner); continue; } - const node = this.nodes.find((n) => n.id === nodeId); + const node = this.nodesById.get(nodeId); if (node && node.kind !== 'file') { parts.push(node.name); } @@ -2355,7 +2354,7 @@ export class TreeSitterExtractor { if (this.nodeStack.length === 0) return false; const parentId = this.nodeStack[this.nodeStack.length - 1]; if (!parentId) return false; - const parentNode = this.nodes.find((n) => n.id === parentId); + const parentNode = this.nodesById.get(parentId); if (!parentNode) return false; return ( parentNode.kind === 'class' || @@ -2603,8 +2602,7 @@ export class TreeSitterExtractor { case 'object_pattern': case 'array_pattern': case 'rest_pattern': - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) this.visitPatternDefaults(child); } return; @@ -2667,8 +2665,7 @@ export class TreeSitterExtractor { const args = getChildByField(valueNode, 'arguments'); let inner: SyntaxNode | null = null; if (args) { - for (let i = 0; i < args.namedChildCount; i++) { - const a = args.namedChild(i); + for (const a of namedChildrenOf(args)) { if (a && (a.type === 'arrow_function' || a.type === 'function_expression')) { inner = a; break; @@ -2791,8 +2788,7 @@ export class TreeSitterExtractor { const root = calleeText === 'styled' || REACT_COMPONENT_HOCS.has(calleeText); const first = args.namedChild(0); const base = root && (first?.type === 'identifier' || first?.type === 'member_expression') ? first : null; - for (let i = 0; i < args.namedChildCount; i++) { - const arg = args.namedChild(i); + for (const [i, arg] of args.namedChildren.entries()) { if (!arg || (base && arg.startIndex === base.startIndex)) continue; if (root && i === 0 && arg.type === 'call_expression' && this.isComponentWrapperCall(arg)) { this.walkComponentWrapper(arg); @@ -2923,8 +2919,7 @@ export class TreeSitterExtractor { const body = resolvedBody ?? node; // Visit all children for methods and properties - for (let i = 0; i < body.namedChildCount; i++) { - const child = body.namedChild(i); + for (const child of body.namedChildren) { if (child) { this.visitNode(child); } @@ -3088,8 +3083,7 @@ export class TreeSitterExtractor { let body = this.extractor.resolveBody?.(node, this.extractor.bodyField) ?? getChildByField(node, this.extractor.bodyField); if (!body) body = node; - for (let i = 0; i < body.namedChildCount; i++) { - const child = body.namedChild(i); + for (const child of body.namedChildren) { if (child) { this.visitNode(child); } @@ -3161,8 +3155,7 @@ export class TreeSitterExtractor { // no members to visit) if (body) { this.nodeStack.push(aggregateNode.id); - for (let i = 0; i < body.namedChildCount; i++) { - const child = body.namedChild(i); + for (const child of body.namedChildren) { if (child) { this.visitNode(child); } @@ -3227,8 +3220,7 @@ export class TreeSitterExtractor { this.visitClassHeaderCode(node); const memberTypes = this.extractor.enumMemberTypes; - for (let i = 0; i < body.namedChildCount; i++) { - const child = body.namedChild(i); + for (const child of body.namedChildren) { if (!child) continue; if (memberTypes?.includes(child.type)) { @@ -3238,8 +3230,7 @@ export class TreeSitterExtractor { const entryBody = member ? child.namedChildren.find((c) => c.type === 'class_body') : undefined; if (member && entryBody) { this.nodeStack.push(member.id); - for (let j = 0; j < entryBody.namedChildCount; j++) { - const inner = entryBody.namedChild(j); + for (const inner of entryBody.namedChildren) { if (inner) this.visitNode(inner); } this.nodeStack.pop(); @@ -3265,8 +3256,7 @@ export class TreeSitterExtractor { // Check for identifier-like children (Swift: simple_identifier, TS: property_identifier) let first: Node | null = null; let found = false; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child && (child.type === 'simple_identifier' || child.type === 'identifier' || child.type === 'property_identifier')) { const created = this.createNode('enum_member', getNodeText(child, this.source), child); first ??= created; @@ -3576,8 +3566,7 @@ export class TreeSitterExtractor { /** `value` when it is an object literal that owns at least one function member, else null. */ private ownedObjectValue(value: SyntaxNode | null): SyntaxNode | null { if (!value || (value.type !== 'object' && value.type !== 'object_expression') || !this.ownsObjectLiterals()) return null; - for (let i = 0; i < value.namedChildCount; i++) { - const member = value.namedChild(i); + for (const member of namedChildrenOf(value)) { if (member && this.ownedMemberFunction(member)) return value; } return null; @@ -3600,8 +3589,7 @@ export class TreeSitterExtractor { const valueStack = valuesUnderOwner ? ownerStack : enclosing; this.nodeStack = valueStack; this.maybeCaptureFnRefs(obj, obj.type); - for (let i = 0; i < obj.namedChildCount; i++) { - const member = obj.namedChild(i); + for (const member of obj.namedChildren) { if (!member) continue; const owned = this.ownedMemberFunction(member); this.nodeStack = owned ? ownerStack : valueStack; @@ -3757,8 +3745,7 @@ export class TreeSitterExtractor { * `key: function() {}` pairs and method shorthand `key() {}`. */ private extractObjectLiteralFunctions(obj: SyntaxNode): void { - for (let i = 0; i < obj.namedChildCount; i++) { - const member = obj.namedChild(i); + for (const member of obj.namedChildren) { if (!member) continue; if (member.type === 'pair') { const key = getChildByField(member, 'key'); @@ -3788,24 +3775,33 @@ export class TreeSitterExtractor { * default }`. The declaration's own `isExported` (an `export_statement` * ancestor) cannot see these, so a store written as `const useStore = * create(…)` + `export default useStore` read as unexported and its actions - * were never extracted. One anchored regex over the file source; JS-family - * callers only. + * were never extracted. JS-family callers only. + * + * The file is read for them once: every name an `export default NAME` or an + * `export { … }` names. Read again for each name, with a pattern compiled + * for it, a file of twenty thousand unexported constants took a second for + * every megabyte, and four times that for each doubling. */ private isExportedLater(name: string): boolean { if (!/^[A-Za-z_$][\w$]*$/.test(name)) return false; - // Unescaped, a `$` in the name (`items$`, `$store`) is a line-end anchor, - // not the character. Escaped as the kernel's `regex::escape` does, so - // both paths decide the same. - const n = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - // Inside `{ … }` the name is bounded by a character that can't continue - // an identifier, not by `\b`, which takes a `$` for a separator: it can't - // bound `items$` and finds `items` inside it. Spelled in ASCII, as the - // kernel spells it, since the kernel's `\w` is Unicode. - const re = new RegExp( - `^[ \\t]*export\\s+(?:default\\s+${n}\\s*;?[ \\t]*$|\\{(?:[^}]*[^0-9A-Za-z_$}])?${n}(?:[^0-9A-Za-z_$}][^}]*)?\\})`, - 'm' - ); - return re.test(this.source); + if (!this.laterExports) { + const names = new Set(); + // One statement, tried where a line opens with `export`. Inside + // `{ … }` a name is bounded by a character that can't continue an + // identifier, not by `\b`, which takes a `$` for a separator: it can't + // bound `items$` and finds `items` inside it. Spelled in ASCII, as the + // kernel spells it, since the kernel's `\w` is Unicode. + const statement = /[ \t]*export\s+(?:default\s+([A-Za-z_$][0-9A-Za-z_$]*)\s*;?[ \t]*$|\{([^}]*)\})/my; + for (const line of this.source.matchAll(/^[ \t]*export(?=\s)/gm)) { + statement.lastIndex = line.index!; + const found = statement.exec(this.source); + if (!found) continue; + if (found[1] !== undefined) names.add(found[1]); + else for (const word of found[2]!.match(/[0-9A-Za-z_$]+/g) ?? []) names.add(word); + } + this.laterExports = names; + } + return this.laterExports.has(name); } /** Property-key text with surrounding quotes stripped (`'foo'` → `foo`). */ @@ -3826,8 +3822,7 @@ export class TreeSitterExtractor { if (depth > 4) return null; const args = getChildByField(callNode, 'arguments'); if (!args) return null; - for (let i = 0; i < args.namedChildCount; i++) { - const arg = args.namedChild(i); + for (const arg of namedChildrenOf(args)) { if (!arg) continue; if (arg.type === 'arrow_function' || arg.type === 'function_expression') { const obj = this.functionReturnedObject(arg); @@ -3864,8 +3859,7 @@ export class TreeSitterExtractor { if (direct) return direct; // `(set, get) => { return {...} }` — scan top-level return statements. if (body.type === 'statement_block') { - for (let i = 0; i < body.namedChildCount; i++) { - const stmt = body.namedChild(i); + for (const stmt of namedChildrenOf(body)) { if (stmt?.type !== 'return_statement') continue; for (let j = 0; j < stmt.namedChildCount; j++) { const obj = asObject(stmt.namedChild(j)); @@ -3896,11 +3890,9 @@ export class TreeSitterExtractor { if (calleeName !== 'createApi' && calleeName !== 'injectEndpoints') return null; const args = getChildByField(callNode, 'arguments'); if (!args) return null; - for (let i = 0; i < args.namedChildCount; i++) { - const arg = args.namedChild(i); + for (const arg of namedChildrenOf(args)) { if (arg?.type !== 'object' && arg?.type !== 'object_expression') continue; - for (let j = 0; j < arg.namedChildCount; j++) { - const member = arg.namedChild(j); + for (const member of namedChildrenOf(arg)) { // Two equally-common spellings: `endpoints: build => ({...})` (pair with an // arrow value) and `endpoints(build) { return {...} }` (method shorthand). if (member?.type === 'pair') { @@ -3928,8 +3920,7 @@ export class TreeSitterExtractor { * never a node — so the generated `useXQuery` hook can't be bridged to it. */ private extractRtkEndpoints(obj: SyntaxNode): void { - for (let i = 0; i < obj.namedChildCount; i++) { - const member = obj.namedChild(i); + for (const member of obj.namedChildren) { if (member?.type !== 'pair') continue; const key = getChildByField(member, 'key'); const value = getChildByField(member, 'value'); @@ -3967,14 +3958,12 @@ export class TreeSitterExtractor { private rtkEndpointHandler(callNode: SyntaxNode): SyntaxNode | null { const args = getChildByField(callNode, 'arguments'); if (!args) return null; - for (let i = 0; i < args.namedChildCount; i++) { - const arg = args.namedChild(i); + for (const arg of namedChildrenOf(args)) { if (arg?.type !== 'object' && arg?.type !== 'object_expression') continue; let queryFn: SyntaxNode | null = null; let query: SyntaxNode | null = null; let firstFn: SyntaxNode | null = null; - for (let j = 0; j < arg.namedChildCount; j++) { - const member = arg.namedChild(j); + for (const member of arg.namedChildren) { // The handler may be `queryFn: () => …` / `query: () => …` (pair) or the // method-shorthand `query(arg) { … }` / `queryFn(arg) { … }`. let fn: SyntaxNode | null = null; @@ -4014,8 +4003,7 @@ export class TreeSitterExtractor { * ordinary destructures stay unextracted. */ private extractRtkHookBindings(pattern: SyntaxNode, isExported: boolean): void { - for (let i = 0; i < pattern.namedChildCount; i++) { - const binding = pattern.namedChild(i); + for (const binding of pattern.namedChildren) { if (binding?.type !== 'shorthand_property_identifier_pattern') continue; const name = getNodeText(binding, this.source); if (!RTK_HOOK_NAME_RE.test(name)) continue; @@ -4048,8 +4036,7 @@ export class TreeSitterExtractor { * actions) from a Pinia SETUP store's all-shorthand `return { foo, bar }` * (whose functions are body-local consts, walked normally instead). */ private objectHasInlineFunctions(obj: SyntaxNode): boolean { - for (let i = 0; i < obj.namedChildCount; i++) { - const member = obj.namedChild(i); + for (const member of namedChildrenOf(obj)) { if (member?.type === 'method_definition') return true; if (member?.type === 'pair') { const v = getChildByField(member, 'value'); @@ -4077,11 +4064,9 @@ export class TreeSitterExtractor { const args = getChildByField(callNode, 'arguments'); if (!args) return []; const objects: SyntaxNode[] = []; - for (let i = 0; i < args.namedChildCount; i++) { - const arg = args.namedChild(i); + for (const arg of args.namedChildren) { if (arg?.type !== 'object' && arg?.type !== 'object_expression') continue; - for (let j = 0; j < arg.namedChildCount; j++) { - const member = arg.namedChild(j); + for (const member of arg.namedChildren) { if (member?.type !== 'pair') continue; const key = getChildByField(member, 'key'); if (!key || !VUE_STORE_COLLECTION_NAMES.has(getNodeText(key, this.source))) continue; @@ -4101,8 +4086,7 @@ export class TreeSitterExtractor { * whether the object has such a collection. */ private extractStoreCollectionMethods(configObj: SyntaxNode): boolean { let found = false; - for (let j = 0; j < configObj.namedChildCount; j++) { - const member = configObj.namedChild(j); + for (const member of configObj.namedChildren) { if (member?.type !== 'pair') continue; const key = getChildByField(member, 'key'); if (!key || !VUE_STORE_COLLECTION_NAMES.has(getNodeText(key, this.source))) continue; @@ -4125,8 +4109,7 @@ export class TreeSitterExtractor { if (!callee || callee.type !== 'identifier' || getNodeText(callee, this.source) !== 'defineStore') return null; const args = getChildByField(callNode, 'arguments'); if (!args) return null; - for (let i = 0; i < args.namedChildCount; i++) { - const arg = args.namedChild(i); + for (const arg of namedChildrenOf(args)) { if (arg?.type !== 'arrow_function' && arg?.type !== 'function_expression') continue; const body = getChildByField(arg, 'body'); if (body?.type === 'statement_block') return arg; // block body ⇒ setup form @@ -4141,14 +4124,12 @@ export class TreeSitterExtractor { private extractPiniaSetupBody(setupFn: SyntaxNode): void { const body = getChildByField(setupFn, 'body'); if (!body || body.type !== 'statement_block') return; - for (let i = 0; i < body.namedChildCount; i++) { - const stmt = body.namedChild(i); + for (const stmt of body.namedChildren) { if (!stmt) continue; if (stmt.type === 'function_declaration') { this.extractFunction(stmt); } else if (this.extractor!.variableTypes.includes(stmt.type)) { - for (let j = 0; j < stmt.namedChildCount; j++) { - const decl = stmt.namedChild(j); + for (const decl of stmt.namedChildren) { if (decl?.type !== 'variable_declarator') continue; const v = getChildByField(decl, 'value'); if (v?.type === 'arrow_function' || v?.type === 'function_expression') { @@ -4191,8 +4172,7 @@ export class TreeSitterExtractor { this.language === 'arkts') { // Handle lexical_declaration and variable_declaration // These contain one or more variable_declarator children - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (child?.type === 'variable_declarator') { const nameNode = getChildByField(child, 'name'); const valueNode = getChildByField(child, 'value'); @@ -4521,8 +4501,7 @@ export class TreeSitterExtractor { // block-local). C allows several declarators per declaration // (`int a = 1, b = 2;`), so iterate them. if (!hasFunctionAncestor(node)) { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; // Accept only `init_declarator` (has a value) and pointer/array // declarators. A *bare* `identifier` declarator is deliberately @@ -4577,8 +4556,7 @@ export class TreeSitterExtractor { // A Rust impl's associated const is its type's (`Limits::MAX`), as its methods are. const owner = this.language === 'rust' ? rustImplItemOwner(node, this.source) : undefined; let declared: Node | null = null; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child?.type === 'identifier' || child?.type === 'variable_declarator') { const name = child.type === 'identifier' ? getNodeText(child, this.source) @@ -4734,8 +4712,7 @@ export class TreeSitterExtractor { } } const body = getChildByField(typeChild, this.extractor.bodyField) || typeChild; - for (let i = 0; i < body.namedChildCount; i++) { - const child = body.namedChild(i); + for (const child of body.namedChildren) { if (child) this.visitNode(child); } } @@ -4755,8 +4732,7 @@ export class TreeSitterExtractor { ?? getChildByField(innerEnum, this.extractor.bodyField); if (body) { const memberTypes = this.extractor.enumMemberTypes; - for (let i = 0; i < body.namedChildCount; i++) { - const child = body.namedChild(i); + for (const child of body.namedChildren) { if (!child) continue; if (memberTypes?.includes(child.type)) { this.extractEnumMembers(child); @@ -4857,8 +4833,7 @@ export class TreeSitterExtractor { */ private extractGoInterfaceMethods(interfaceType: SyntaxNode, ifaceId: string, decl: SyntaxNode): void { this.nodeStack.push(ifaceId); - for (let i = 0; i < interfaceType.namedChildCount; i++) { - const m = interfaceType.namedChild(i); + for (const m of interfaceType.namedChildren) { if (!m || (m.type !== 'method_elem' && m.type !== 'method_spec')) continue; const nameNode = getChildByField(m, 'name') ?? m.namedChild(0); if (!nameNode) continue; @@ -4895,8 +4870,7 @@ export class TreeSitterExtractor { if (value.type === 'object_type') { objectTypes.push(value); } else if (value.type === 'intersection_type') { - for (let i = 0; i < value.namedChildCount; i++) { - const op = value.namedChild(i); + for (const op of value.namedChildren) { if (op && op.type === 'object_type') objectTypes.push(op); } } else { @@ -4905,8 +4879,7 @@ export class TreeSitterExtractor { this.nodeStack.push(typeAliasNode.id); for (const objType of objectTypes) { - for (let i = 0; i < objType.namedChildCount; i++) { - const child = objType.namedChild(i); + for (const child of objType.namedChildren) { if (!child) continue; if (child.type !== 'property_signature' && child.type !== 'method_signature') continue; @@ -4971,8 +4944,7 @@ export class TreeSitterExtractor { const collectTuples = (n: SyntaxNode, depth: number): void => { if (depth > 6) return; // a type expression is shallow; cap defensively if (n.type === 'tuple_type') tuples.push(n); - for (let i = 0; i < n.namedChildCount; i++) { - const c = n.namedChild(i); + for (const c of n.namedChildren) { if (c) collectTuples(c, depth + 1); } }; @@ -4981,13 +4953,11 @@ export class TreeSitterExtractor { this.nodeStack.push(typeAliasNode.id); for (const tuple of tuples) { - for (let i = 0; i < tuple.namedChildCount; i++) { - const entry = tuple.namedChild(i); + for (const entry of tuple.namedChildren) { if (!entry || entry.type !== 'generic_type') continue; const typeArgs = getChildByField(entry, 'type_arguments'); if (!typeArgs) continue; - for (let j = 0; j < typeArgs.namedChildCount; j++) { - const arg = typeArgs.namedChild(j); + for (const arg of typeArgs.namedChildren) { if (!arg || arg.type !== 'literal_type') continue; // literal_type wraps the actual literal; only a string is a name. const strNode = arg.namedChild(0); @@ -5016,8 +4986,7 @@ export class TreeSitterExtractor { private isTsFunctionTypedProperty(propertySignature: SyntaxNode): boolean { const typeAnno = getChildByField(propertySignature, 'type'); if (!typeAnno) return false; - for (let i = 0; i < typeAnno.namedChildCount; i++) { - const inner = typeAnno.namedChild(i); + for (const inner of namedChildrenOf(typeAnno)) { if (inner && inner.type === 'function_type') return true; } return false; @@ -5129,8 +5098,7 @@ export class TreeSitterExtractor { column: dotted.startPosition.column, }); }; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child?.type === 'dotted_name') { this.createNode('import', getNodeText(child, this.source), node, { signature: importText, @@ -5341,8 +5309,7 @@ export class TreeSitterExtractor { break; } case 'use_list': - for (let i = 0; i < n.namedChildCount; i++) { - const c = n.namedChild(i); + for (const c of n.namedChildren) { if (c) collect(c, prefix); } break; @@ -5355,8 +5322,7 @@ export class TreeSitterExtractor { // use_wildcard → no specific binding to link. } }; - for (let i = 0; i < node.namedChildCount; i++) { - const c = node.namedChild(i); + for (const c of node.namedChildren) { if (c) collect(c, ''); } for (const p of paths) { @@ -5525,8 +5491,7 @@ export class TreeSitterExtractor { this.erlangAtomMacros = new Map(); let root: SyntaxNode = target; while (root.parent) root = root.parent; - for (let i = 0; i < root.namedChildCount; i++) { - const form = root.namedChild(i); + for (const form of root.namedChildren) { if (form?.type !== 'pp_define') continue; const lhs = getChildByField(form, 'lhs'); const defName = lhs ? getChildByField(lhs, 'name') : null; @@ -5965,8 +5930,7 @@ export class TreeSitterExtractor { // arguments. const emitThisHandlers = (args: SyntaxNode | null): void => { if (!args) return; - for (let j = 0; j < args.namedChildCount; j++) { - const arg = args.namedChild(j); + for (const arg of args.namedChildren) { if (arg?.type !== 'member_expression') continue; const obj = getChildByField(arg, 'object'); const prop = getChildByField(arg, 'property'); @@ -5994,8 +5958,9 @@ export class TreeSitterExtractor { column: node.startPosition.column, }); } - for (let i = 0; i < node.childCount; i++) { - const child = node.child(i); + let i = -1; + for (const child of childrenOf(node)) { + i++; if (!child || child.type !== 'property_identifier') continue; emitAttr(child); if (/^on[A-Z]/.test(getNodeText(child, this.source))) { @@ -6207,8 +6172,8 @@ export class TreeSitterExtractor { // (the most common form: `addObject:`, `storeImage:`, …) was named // without the colon and never matched its `storeImage:` method. let hasColon = false; - for (let i = 0; i < node.childCount; i++) { - if (node.child(i)?.type === ':') { hasColon = true; break; } + for (const child of childrenOf(node)) { + if (child.type === ':') { hasColon = true; break; } } const methodName: string = hasColon ? methodKeywords.map((k) => `${k}:`).join('') @@ -6257,8 +6222,8 @@ export class TreeSitterExtractor { } } let innerColon = false; - for (let i = 0; i < receiverField.childCount; i++) { - if (receiverField.child(i)?.type === ':') { innerColon = true; break; } + for (const child of childrenOf(receiverField)) { + if (child.type === ':') { innerColon = true; break; } } const innerSelector = innerColon ? innerKw.map((k) => `${k}:`).join('') : innerKw[0]; calleeName = innerSelector ? `${innerRecvName}.${innerSelector}().${methodName}` : methodName; @@ -6307,8 +6272,7 @@ export class TreeSitterExtractor { // tracked separately (#1258). if (this.language === 'cpp' && func) { let operatorName = ''; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (child?.type !== 'ERROR') continue; const op = child.namedChildren.find((c: SyntaxNode) => c.type === 'operator_name'); if (op) { operatorName = getNodeText(op, this.source); break; } @@ -6983,8 +6947,7 @@ export class TreeSitterExtractor { } let instantiates = false; const arities: number[] = []; - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { if (!child) continue; if (child.type === 'storage_class_specifier' && getNodeText(child, this.source) === 'extern') return none; if (child.type === 'identifier' || child.type === 'array_declarator') { @@ -7285,8 +7248,7 @@ export class TreeSitterExtractor { * node so the caller can walk it as the anon class's members. */ private findAnonymousClassBody(node: SyntaxNode): SyntaxNode | null { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of namedChildrenOf(node)) { // Java: `class_body`. C# uses the same node kind. if (child && (child.type === 'class_body' || child.type === 'declaration_list')) { return child; @@ -7347,8 +7309,7 @@ export class TreeSitterExtractor { // Walk the body's children so method_declaration nodes inside become // method nodes scoped to the anon class. this.nodeStack.push(classNode.id); - for (let i = 0; i < body.namedChildCount; i++) { - const child = body.namedChild(i); + for (const child of body.namedChildren) { if (child) this.visitNode(child); } this.nodeStack.pop(); @@ -7445,7 +7406,7 @@ export class TreeSitterExtractor { const attribute = sibling.namedChild(0); const name = attribute?.namedChild(0)?.text.replace(/\s/g, ''); if (name === 'tauri::command') { - const decorated = this.nodes.find(n => n.id === decoratedId); + const decorated = this.nodesById.get(decoratedId); if (decorated) decorated.decorators = ['tauri::command']; break; } @@ -7490,8 +7451,7 @@ export class TreeSitterExtractor { // Find the leading identifier: skip the `@` punct, unwrap // a call_expression if the decorator is invoked with args. let target: SyntaxNode | null = null; - for (let i = 0; i < n.namedChildCount; i++) { - const child = n.namedChild(i); + for (const child of namedChildrenOf(n)) { if (!child) continue; if (child.type === 'call_expression') { const fn = getChildByField(child, 'function') ?? child.namedChild(0); @@ -7529,8 +7489,7 @@ export class TreeSitterExtractor { // 1. Decorators that are direct children of the declaration // (method/property style, also some grammars for class). - for (let i = 0; i < declNode.namedChildCount; i++) { - const child = declNode.namedChild(i); + for (const child of declNode.namedChildren) { consider(child); // Java/Kotlin/C# put annotations INSIDE a `modifiers` node // (`@MyAnno public class X` → class_declaration → modifiers → annotation), @@ -7551,10 +7510,10 @@ export class TreeSitterExtractor { // (e.g. `@A class Foo {} @B class Bar {}` would otherwise // attribute @A to Bar). // - // Note on identity: tree-sitter web bindings return fresh JS - // wrapper objects from `parent`/`namedChild` navigation, so - // `sibling === declNode` is unreliable — `startIndex` does - // the matching instead. + // The walk starts from the declaration itself. Finding its place + // first, by counting the parent's children from the start, cost + // each declaration as much as it has siblings before it: a file of + // twenty thousand took minutes. // // A grammar that wraps the declaration (Dart's `declaration` // around a member with no body) puts the annotations before the @@ -7562,28 +7521,12 @@ export class TreeSitterExtractor { // between the annotations and the declaration (Dart) steps over them. const anchor = this.extractor?.getDeclarationWrapper?.(declNode) ?? declNode; const stepOver = this.extractor?.decoratorStepOverTypes; - const parent = anchor.parent; - if (parent) { - const declStart = anchor.startIndex; - let declIdx = -1; - for (let i = 0; i < parent.namedChildCount; i++) { - const sibling = parent.namedChild(i); - if (sibling && sibling.startIndex === declStart) { - declIdx = i; - break; - } - } - if (declIdx > 0) { - for (let j = declIdx - 1; j >= 0; j--) { - const sibling = parent.namedChild(j); - if (!sibling) continue; - if (stepOver?.includes(sibling.type)) continue; - if (sibling.type !== 'decorator' && sibling.type !== 'annotation' && sibling.type !== 'marker_annotation') { - break; // non-decorator separator → stop consuming - } - consider(sibling); - } + for (let sibling = anchor.previousNamedSibling; sibling; sibling = sibling.previousNamedSibling) { + if (stepOver?.includes(sibling.type)) continue; + if (sibling.type !== 'decorator' && sibling.type !== 'annotation' && sibling.type !== 'marker_annotation') { + break; // non-decorator separator → stop consuming } + consider(sibling); } } @@ -7638,8 +7581,7 @@ export class TreeSitterExtractor { parts = []; } }; - for (let i = 0; i < tokenTree.childCount; i++) { - const t = tokenTree.child(i); + for (const t of tokenTree.children) { if (!t) continue; if (t.type === 'identifier') { if (parts.length === 0) { @@ -7978,8 +7920,7 @@ export class TreeSitterExtractor { // the call that consumes it. if (this.language === 'cpp' && this.nodeStack.length > 0) { if (nodeType === 'declaration') { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child?.type !== 'init_declarator') continue; const decl = getChildByField(child, 'declarator'); if (decl?.type !== 'identifier') continue; @@ -8177,8 +8118,7 @@ export class TreeSitterExtractor { return; } - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) { visitForCallsAndStructure(child, node); } @@ -8205,11 +8145,9 @@ export class TreeSitterExtractor { column: superclass.startPosition.column, }); } - for (let j = 0; j < node.namedChildCount; j++) { - const argList = node.namedChild(j); + for (const argList of node.namedChildren) { if (argList?.type !== 'parameterized_arguments') continue; - for (let k = 0; k < argList.namedChildCount; k++) { - const typeName = argList.namedChild(k); + for (const typeName of argList.namedChildren) { if (!typeName) continue; const typeId = typeName.namedChildren.find( (c: SyntaxNode) => c.type === 'type_identifier' || c.type === 'identifier' @@ -8238,8 +8176,7 @@ export class TreeSitterExtractor { } // Look for extends/implements clauses - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (!child) continue; // Dart: `class A = B with M implements I;` keeps its supertypes in a @@ -8860,8 +8797,7 @@ export class TreeSitterExtractor { // which would otherwise mis-emit as type references. const params = getChildByField(node, 'parameters'); if (params) { - for (let i = 0; i < params.namedChildCount; i++) { - const child = params.namedChild(i); + for (const child of params.namedChildren) { if (!child || child.type !== 'parameter') continue; const paramType = getChildByField(child, 'type'); if (paramType) this.walkCsharpTypePosition(paramType, nodeId); @@ -8921,8 +8857,7 @@ export class TreeSitterExtractor { if (this.language !== 'csharp') return; const paramList = node.namedChildren.find((c: SyntaxNode) => c.type === 'parameter_list'); if (!paramList) return; - for (let i = 0; i < paramList.namedChildCount; i++) { - const param = paramList.namedChild(i); + for (const param of paramList.namedChildren) { if (!param || param.type !== 'parameter') continue; const paramType = getChildByField(param, 'type'); if (paramType) this.walkCsharpTypePosition(paramType, ownerId); @@ -8987,8 +8922,7 @@ export class TreeSitterExtractor { // `ref_type`, and any newer wrapping shapes the grammar adds. // Identifiers reached here are all type-positional (parameter/field // names are gated out before we descend). - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) this.walkCsharpTypePosition(child, fromNodeId); } } @@ -9044,8 +8978,7 @@ export class TreeSitterExtractor { return; } // optional_type / nullable_type / union_type / intersection_type / named_type → recurse - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) this.walkPhpTypePosition(child, fromNodeId); } } @@ -9085,8 +9018,7 @@ export class TreeSitterExtractor { } // Recurse into children (handles union_type, intersection_type, generic_type, etc.) - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) { this.extractTypeRefsFromSubtree(child, fromNodeId); } @@ -9110,8 +9042,7 @@ export class TreeSitterExtractor { const moduleName = name || path.basename(this.filePath).replace(/\.[^.]+$/, ''); this.createNode('module', moduleName, node); // Continue visiting children (interface/implementation sections) - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) this.visitNode(child); } return true; @@ -9132,8 +9063,7 @@ export class TreeSitterExtractor { // declConsts → container; visit children for individual declConst if (nodeType === 'declConsts') { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child?.type === 'declConst') { this.extractPascalConst(child); } @@ -9149,8 +9079,7 @@ export class TreeSitterExtractor { // declTypes → container for type declarations if (nodeType === 'declTypes') { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) this.visitNode(child); } return true; @@ -9158,8 +9087,7 @@ export class TreeSitterExtractor { // declVars → container for variable declarations if (nodeType === 'declVars') { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child?.type === 'declVar') { const nameNode = getChildByField(child, 'name'); if (nameNode) { @@ -9201,8 +9129,7 @@ export class TreeSitterExtractor { // declSection → visit children (propagates visibility via getVisibility) if (nodeType === 'declSection') { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) this.visitNode(child); } return true; @@ -9216,8 +9143,7 @@ export class TreeSitterExtractor { // interface/implementation sections → visit children if (nodeType === 'interface' || nodeType === 'implementation') { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child) this.visitNode(child); } return true; @@ -9287,8 +9213,7 @@ export class TreeSitterExtractor { else this.extractPascalHelperTypes(declHelper!, classNode.id); // Visit class body this.nodeStack.push(classNode.id); - for (let i = 0; i < body.namedChildCount; i++) { - const child = body.namedChild(i); + for (const child of body.namedChildren) { if (child) this.visitNode(child); } this.nodeStack.pop(); @@ -9299,8 +9224,7 @@ export class TreeSitterExtractor { if (ifaceNode) { // Visit interface members this.nodeStack.push(ifaceNode.id); - for (let i = 0; i < declIntf.namedChildCount; i++) { - const child = declIntf.namedChild(i); + for (const child of declIntf.namedChildren) { if (child) this.visitNode(child); } this.nodeStack.pop(); @@ -9315,8 +9239,7 @@ export class TreeSitterExtractor { if (enumNode) { // Extract enum members this.nodeStack.push(enumNode.id); - for (let i = 0; i < declEnum.namedChildCount; i++) { - const child = declEnum.namedChild(i); + for (const child of declEnum.namedChildren) { if (child?.type === 'declEnumValue') { const memberName = getChildByField(child, 'name'); if (memberName) { @@ -9341,8 +9264,7 @@ export class TreeSitterExtractor { */ private extractPascalUses(node: SyntaxNode): void { const importText = getNodeText(node, this.source).trim(); - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (child?.type === 'moduleName') { const unitName = getNodeText(child, this.source); this.createNode('import', unitName, child, { @@ -10178,8 +10100,7 @@ export class TreeSitterExtractor { * With `declarations`, a declaration in it is visited as a declaration. */ private visitPascalBlock(node: SyntaxNode, declarations = false): void { - for (let i = 0; i < node.namedChildCount; i++) { - const child = node.namedChild(i); + for (const child of node.namedChildren) { if (!child) continue; if (declarations && /^(?:decl|defProc$|interface$|implementation$)/.test(child.type)) { this.visitNode(child); @@ -10733,8 +10654,8 @@ export function extractFromSource( if (!fw.extract) continue; try { const fwResult = fw.extract(filePath, source); - result.nodes.push(...fwResult.nodes); - result.unresolvedReferences.push(...fwResult.references); + pushAll(result.nodes, fwResult.nodes); + pushAll(result.unresolvedReferences, fwResult.references); } catch (err) { result.errors.push({ message: `Framework extractor '${fw.name}' failed: ${ diff --git a/src/extraction/vue-extractor.ts b/src/extraction/vue-extractor.ts index d17e7d2e1d..4445f9f657 100644 --- a/src/extraction/vue-extractor.ts +++ b/src/extraction/vue-extractor.ts @@ -5,6 +5,8 @@ import { isLanguageSupported } from './grammars'; import { foldScriptResult, sfcFileNode, sfcScriptLanguage, SFC_SCRIPT_ELEMENT, sfcBlockLineRanges } from './sfc-script'; import { vueOptionsMembers } from './vue-options-api'; import { vueTemplateCalls } from './vue-template-calls'; +import { lineAt } from '../resolution/synth-utils'; +import { pushAll } from '../utils'; /** * Vue built-in components — skipped so a `` / `` in the @@ -139,13 +141,13 @@ export class VueExtractor { if (members.length === 0) return; const component = this.nodes.find((n) => n.id === componentNodeId); const owner = component?.name ?? 'component'; - const lineAt = (offset: number) => block.content.slice(0, offset).split('\n').length; + const lineOf = (offset: number) => lineAt(block.content, offset); const colAt = (offset: number) => offset - block.content.lastIndexOf('\n', offset - 1) - 1; const now = Date.now(); const created: Node[] = []; for (const m of members) { - const startLine = lineAt(m.start); - const endLine = lineAt(m.end); + const startLine = lineOf(m.start); + const endLine = lineOf(m.end); created.push({ id: generateNodeId(this.filePath, 'method', `${owner}.${m.name}`, startLine + block.startLine), kind: 'method', @@ -161,13 +163,17 @@ export class VueExtractor { }); } // Innermost member for a line: `computed: { x: { get() {…} } }` is one member. - const memberAt = (line: number): Node | undefined => { - let best: Node | undefined; - for (const n of created) { - if (n.startLine <= line && n.endLine >= line && (!best || n.startLine >= best.startLine)) best = n; - } - return best; - }; + // Written line by line once: by start, and of those that start together + // in their order, so the member a pass over all of them would end on is + // the one left on each line. Found by such a pass for each reference, a + // component of some thousand methods went through them all every time. + const byLine: Array = []; + const order = created.map((_, i) => i).sort((a, b) => created[a]!.startLine - created[b]!.startLine || a - b); + for (const i of order) { + const n = created[i]!; + for (let line = Math.max(0, n.startLine); line <= n.endLine; line++) byLine[line] = n; + } + const memberAt = (line: number): Node | undefined => (line >= 0 ? byLine[line] : undefined); // What the TS extractor attributed to the file (or to nothing narrower). const fileNode = result.nodes.find((n) => n.kind === 'file'); const narrower = new Set(result.nodes.filter((n) => n.kind !== 'file').map((n) => n.id)); @@ -182,7 +188,7 @@ export class VueExtractor { const member = memberAt(edge.line); if (member) edge.source = member.id; } - result.nodes.push(...created); + pushAll(result.nodes, created); } /** diff --git a/src/file-limits.ts b/src/file-limits.ts index 1ee377c611..3b1e3b46a8 100644 --- a/src/file-limits.ts +++ b/src/file-limits.ts @@ -4,9 +4,16 @@ import * as fsp from 'fs/promises'; /** * Largest source file CodeGraph will parse or read during resolution. Generated * bundles, minified sources, and dependency archives above this limit provide no - * useful symbols; 1 MB covers essentially all hand-written source. + * useful symbols. + * + * It was 1 MB, on the reasoning that 1 MB covers essentially all hand-written + * source. It does not: this repository's own src/resolution/name-matcher.ts is + * 1.9 MB and 37,000 lines, and at 1 MB the graph held none of it. At 4 MB that + * file is indexed and the generated parsers beside it (7 to 35 MB) still are + * not. Files between the two, such as a 1.7 MB generated protobuf file, are now + * indexed as well. */ -export const MAX_SOURCE_FILE_SIZE_BYTES = 1024 * 1024; +export const MAX_SOURCE_FILE_SIZE_BYTES = 4 * 1024 * 1024; /** * What stands in for the content of a file over MAX_SOURCE_FILE_SIZE_BYTES. Such a file is @@ -49,6 +56,54 @@ export function readSourceText(file: string, encoding: BufferEncoding = 'utf-8') } } +/** + * The longest run of name characters a pattern is given as written. No name, + * path, number or chain of members is this long; a longer one is data: an + * embedded asset, a key, a table of hex. + */ +export const LONGEST_NAME_RUN = 1024; + +/** What a longer run reads as: no part of a name, no blank, no bracket and no quote. */ +const RUN_FILL = '\u0001'; + +/** Whether a character code is a name's, or what joins names into one run: `A-Z a-z 0-9 _ $ . : / + = -`. */ +const IN_NAME_RUN = (() => { + const set = new Uint8Array(128); + for (const c of 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_$.:/+=-') set[c.charCodeAt(0)] = 1; + return set; +})(); + +/** + * `text` with every run of name characters longer than LONGEST_NAME_RUN + * blanked, at the same length: what the patterns that read a file for names + * are given. Such a pattern starts a name at each character of a run and + * reads to the run's end, so its time grows with the square of the run: one + * 30 KB string of hex cost a second, and a megabyte of it eighteen minutes. + * Returns `text` itself when it has no such run. + */ +export function withoutLongRuns(text: string): string { + let parts: string[] | null = null; + let copied = 0; + let start = -1; + for (let i = 0; i <= text.length; i++) { + const code = i < text.length ? text.charCodeAt(i) : 0; + if (code < 128 && IN_NAME_RUN[code] === 1) { + if (start < 0) start = i; + continue; + } + if (start >= 0) { + if (i - start > LONGEST_NAME_RUN) { + (parts ??= []).push(text.slice(copied, start), RUN_FILL.repeat(i - start)); + copied = i; + } + start = -1; + } + } + if (!parts) return text; + parts.push(text.slice(copied)); + return parts.join(''); +} + /** A source file's stats, and its bytes when they are within the limit (null = oversize). */ export interface BoundedSource { stats: fs.Stats; diff --git a/src/resolution/angular-template-synthesizer.ts b/src/resolution/angular-template-synthesizer.ts index b5b7ce206d..26560fa1c1 100644 --- a/src/resolution/angular-template-synthesizer.ts +++ b/src/resolution/angular-template-synthesizer.ts @@ -49,6 +49,8 @@ import type { ResolutionContext } from './types'; import type { MaybeYield } from './cooperative-yield'; import { isTestPath } from '../search/query-utils'; import { stripCommentsForRegex } from './strip-comments'; +import { lineAt, linesOf } from './synth-utils'; +import { nodesNamed, nodesUnder } from './nodes-around'; import { matchBracket, readFields, skipString } from './frameworks/object-literal'; import { dependsOn } from './frameworks/package-deps'; import { appRootFor, HOLE, toHref, type HrefLiteral } from './frameworks/expo-router'; @@ -70,14 +72,16 @@ const MAX_CHILDREN_PER_COMPONENT = 40; /** An element selector: `app-article-list`, not `[appDirective]` or `button[app-x]`. */ const ELEMENT_SELECTOR = /^[a-zA-Z][\w-]*$/; -const lineOfOffset = (text: string, at: number): number => { - let line = 1; - for (let i = 0; i < at && i < text.length; i++) if (text.charCodeAt(i) === 10) line++; - return line; -}; +/** + * The 1-based line of `at` in `text`, from the text's newline index + * (lineAt). Counted character by character from the text's start for each + * binding and each component, a file of some thousand components took the + * square of its length. + */ +const lineOfOffset = (text: string, at: number): number => (at > 0 ? lineAt(text, at) : 1); /** Every `@Component` class a file declares, with its selectors and template. */ -function componentsIn(file: string, content: string, nodes: readonly Node[], ctx: ResolutionContext): AngularComponent[] { +function componentsIn(file: string, content: string, ctx: ResolutionContext): AngularComponent[] { const out: AngularComponent[] = []; const safe = stripCommentsForRegex(content, 'typescript'); const decorator = /@Component\s*\(/g; @@ -93,7 +97,7 @@ function componentsIn(file: string, content: string, nodes: readonly Node[], ctx if (objEnd < 0) continue; const cls = /^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/.exec(safe.slice(close + 1, close + 400)); if (!cls) continue; - const node = nodes.find((n) => n.kind === 'class' && n.name === cls[1]); + const node = nodesNamed(ctx, file, cls[1]).find((n) => n.kind === 'class' && n.name === cls[1]); if (!node) continue; const fields = readFields(safe, open, objEnd); const selectorText = fields.get('selector')?.text; @@ -141,7 +145,7 @@ export function angularComponents(ctx: ResolutionContext): AngularComponent[] { if (!(ctx.fileContains?.(file, '@Component') ?? ctx.readFile(file)?.includes('@Component'))) continue; const content = ctx.readFile(file); if (!content) continue; - components.push(...componentsIn(file, content, ctx.getNodesInFile(file), ctx)); + for (const component of componentsIn(file, content, ctx)) components.push(component); } componentIndexes.set(ctx, { source, components }); return components; @@ -689,8 +693,7 @@ export async function angularTemplateEdges(ctx: ResolutionContext, onYield: Mayb // Event bindings: `(click)="toggleFavorite()"` runs the component's own // method when the user acts. The binding is the trigger Steps draws — // known only from the template, so it rides on the edge. - const own = ctx - .getNodesInFile(component.file) + const own = nodesUnder(ctx, component.file, component.node.qualifiedName) .filter((n) => (n.kind === 'method' || n.kind === 'property') && n.qualifiedName.startsWith(`${component.node.qualifiedName}::`)); const members = new Map(own.filter((n) => n.kind === 'method').map((n) => [n.name, n])); /** Members this template already links — only the first edge between two nodes survives the merge. */ @@ -731,12 +734,12 @@ export async function angularTemplateEdges(ctx: ResolutionContext, onYield: Mayb // Bindings: `[name]="icon()"`, `{{ label() }}`, `@if (loading())` read the // component every time it renders, so the hop carries no trigger. At most // one edge per member, so the class's own size bounds them. - let declaration: string[] | null = null; + let declaration: readonly string[] | null = null; const shapes = new Map(); const shape = (n: Node): MemberShape => { const known = shapes.get(n.id); if (known) return known; - declaration ??= (ctx.readFile(component.file) ?? '').split('\n'); + declaration ??= linesOf(ctx.readFile(component.file) ?? ''); const read = memberShape(declaration, n); shapes.set(n.id, read); return read; @@ -775,7 +778,7 @@ export async function angularTemplateEdges(ctx: ResolutionContext, onYield: Mayb // in a loop. The destination is the field this class wrote. const source = ctx.readFile(component.file); if (source) { - const lines = source.split('\n'); + const lines = linesOf(source); const body = lines.slice(component.node.startLine - 1, component.node.endLine).join('\n'); ROUTER_LINK_FIELD.lastIndex = 0; let f: RegExpExecArray | null; diff --git a/src/resolution/callback-synthesizer.ts b/src/resolution/callback-synthesizer.ts index 932c20aaf0..c347b7e573 100644 --- a/src/resolution/callback-synthesizer.ts +++ b/src/resolution/callback-synthesizer.ts @@ -26,7 +26,7 @@ import type { QueryBuilder } from '../db/queries'; import type { ResolutionContext } from './types'; import { isGeneratedFile } from '../extraction/generated-detection'; import { stripCommentsForRegex } from './strip-comments'; -import { escapeRegExp } from '../utils'; +import { escapeRegExp, maxOf } from '../utils'; import { cFnPointerDispatchEdges } from './c-fnptr-synthesizer'; import { cppTemplateArgumentEdges } from './cpp-template-instantiations'; import { goframeRouteEdges } from './goframe-synthesizer'; @@ -44,7 +44,7 @@ import { svelteKitLinkEdges, svelteKitPageComponentEdges } from './sveltekit-syn import { createYielder, type MaybeYield } from './cooperative-yield'; import { crossTierEdges, hasCrossTierPattern, hasTestRequestPattern, testRequestEdges } from './tier-synthesizer'; import { hasTauriPattern, tauriEdges } from './tauri-synthesizer'; -import { enclosingFn, makeLineAt } from './synth-utils'; +import { enclosingFn, makeLineAt, releaseLineAtTexts } from './synth-utils'; import { eventEmitterEdges } from './event-emitter-synthesizer'; import { resolveImportPath } from './import-resolver'; import { cppSpecializationArguments, crossesCodeBoundary, goRefQualification, isManualMockHiddenFrom, isManualMockPath, jsCodeBindsName } from './name-matcher'; @@ -53,6 +53,8 @@ import { overrideFilter } from './override-parameters'; import { declaredComponent, exportedComponent, lazyValueModules, wrappedComponentName } from './frameworks/react'; import { jsxCode } from './jsx-code'; import { isTestPath } from '../search/query-utils'; +import { withoutLongRuns } from '../file-limits'; +import { nodesNamed } from './nodes-around'; const REGISTRAR_NAME = /^(on[A-Z]\w*|subscribe|addListener|addEventListener|register|watch|listen|addCallback)$/; const DISPATCHER_NAME = /(emit|trigger|notify|dispatch|fire|publish|flush)/i; @@ -168,6 +170,7 @@ function releaseLineCaches(): void { sliceLinesSplit = []; lineOfSource = null; lineOfIndex = () => 1; + releaseLineAtTexts(); } function registrarField(src: string): string | null { @@ -2177,7 +2180,7 @@ function wrappedChild( exportOf: (module: string, exported: string) => Node | null ): Node | undefined { const declared = ownValueOf(name) !== undefined || - (ctx.getNodesInFileNamed?.(file, name) ?? ctx.getNodesInFile(file).filter((n) => n.name === name)) + (ctx.getNodesInFileNamed?.(file, name) ?? nodesNamed(ctx, file, name).filter((n) => n.name === name)) .some((n) => JSX_CHILD_KINDS.has(n.kind)); if (!declared && !projectImport(ctx, name, file)) return undefined; return jsxChild(ctx, name, file, importsOf, ownValueOf, exportOf); @@ -2255,11 +2258,29 @@ function spanTags(src: string, startLine: number): SpanTags { counted = m.index; if (!names.tags.get(m[1]!)) names.tags.set(m[1]!, opensTag(src, m.index, m[1]!) ? line : 0); } - for (const [name, first] of names.tags) if (first && writtenBare(src, name)) names.bare.add(name); + // Every word the code writes outside a tag, read once when the tags are + // many: searched for name by name, a file of eight thousand components + // read itself that many times. + const bare = names.tags.size > 16 ? wordsWrittenBare(src) : null; + for (const [name, first] of names.tags) { + if (first && (bare && /^[\w$]+$/.test(name) ? bare.has(name) : writtenBare(src, name))) names.bare.add(name); + } } return names; } +/** Every word (a run of `[\w$]`) `src` writes other than in a tag: what writtenBare answers for each of them. */ +function wordsWrittenBare(src: string): Set { + const words = new Set(); + const word = /[\w$]+/g; + for (let m = word.exec(src); m; m = word.exec(src)) { + const at = m.index; + if (src[at - 1] === '<' || (src[at - 1] === '/' && src[at - 2] === '<')) continue; + words.add(m[0]); + } + return words; +} + /** * Whether `fn`'s code (`names`, its span) binds `name` by `line`: a `const`, * a parameter (`jsCodeBindsName`) or a destructured name (`destructures`). @@ -2948,7 +2969,7 @@ function constantEventName(expr: string, file: string, ctx: ResolutionContext, m const m = /^\s*(?::[^=;]*)?[=:]\s*@?(["'`])([^"'`]+)\1/.exec(rest) ?? /^\s+@?(")([^"]+)"/.exec(rest); return m ? m[2]! : null; }; - const declaredIn = (f: string) => ctx.getNodesInFile(f).filter((n) => n.name === name && CONSTANT_KINDS.has(n.kind)); + const declaredIn = (f: string) => nodesNamed(ctx, f, name).filter((n) => n.name === name && CONSTANT_KINDS.has(n.kind)); const js = /\.(?:[cm]?[jt]sx?)$/.test(file); const language: Language = /\.tsx$/.test(file) ? 'tsx' : /\.[cm]?ts$/.test(file) ? 'typescript' : file.endsWith('.jsx') ? 'jsx' : 'javascript'; const importedFile = (local: string): string | null => { @@ -3149,7 +3170,7 @@ async function rnEventEdges(ctx: ResolutionContext, onYield: MaybeYield): Promis const bare = /^[A-Za-z_$][\w$.]*$/.test(arg) ? arg.slice(arg.lastIndexOf('.') + 1) : null; const line = lineOf(m.index); // The handler this file names — never a same-named function elsewhere. - const named = bare ? nodesInFile.find((n) => (n.kind === 'function' || n.kind === 'method') && n.name === bare) : undefined; + const named = bare ? nodesNamed(ctx, file, bare).find((n) => (n.kind === 'function' || n.kind === 'method') && n.name === bare) : undefined; const target = named ?? enclosingFn(nodesInFile, line); if (!target) continue; const map = jsHandlersByEvent.get(event) ?? new Map(); @@ -4482,7 +4503,7 @@ function sharedFolders(a: string, b: string): number { function reachableHandlers(targets: Node[], file: string, verb: string): Node[] { if (targets.length < 2) return targets; const shared = targets.map((t) => sharedFolders(file, t.filePath)); - const best = Math.max(...shared); + const best = maxOf(shared); if (verb === 'Send') return targets.filter((_, i) => shared[i] === best); return best > 0 ? targets.filter((_, i) => shared[i]! > 0) : targets; } @@ -5287,7 +5308,9 @@ export interface SynthPassDef { const ALWAYS = (): boolean => true; /** Conservative input gates for SYNTH_PASSES; keep these in sync when adding a pass. */ -export function hasSynthesisPattern(filePath: string, content: string): boolean { +export function hasSynthesisPattern(filePath: string, source: string): boolean { + // As the passes read it: a run no name is as long as holds no pattern. + const content = withoutLongRuns(source); // These passes consume declarations/layouts as well as dispatch sites. A // header or markup edit can change a channel whose endpoints live elsewhere. if (/\.(?:vue|svelte|dfm|fmx|nix|xml)$/.test(filePath)) return true; diff --git a/src/resolution/const-alias-synthesizer.ts b/src/resolution/const-alias-synthesizer.ts index 5880136164..90b6fc1d18 100644 --- a/src/resolution/const-alias-synthesizer.ts +++ b/src/resolution/const-alias-synthesizer.ts @@ -36,6 +36,7 @@ import { declarationText, initializerAt } from './frameworks/react'; import { isStatedDefaultExport } from './import-resolver'; import { resolveObjectLiteralBinding, resolveObjectLiteralMember } from './name-matcher'; import { FN_KINDS } from './synth-utils'; +import { nodesNamed } from './nodes-around'; const ALIAS_KINDS = ['constant', 'variable'] as const; const ALIAS_LANGUAGES = ['typescript', 'javascript', 'tsx', 'jsx']; @@ -173,7 +174,7 @@ function initializerOf(value: Node, ctx: ResolutionContext): string | null { /** What `file` declares as `name` at its own top level. */ function ownBinding(name: string, file: string, ctx: ResolutionContext): Node | undefined { - return (ctx.getNodesInFileNamed?.(file, name) ?? ctx.getNodesInFile(file).filter((n) => n.name === name)) + return (ctx.getNodesInFileNamed?.(file, name) ?? nodesNamed(ctx, file, name).filter((n) => n.name === name)) .find((n) => n.qualifiedName === name && BINDING_KINDS.has(n.kind)); } diff --git a/src/resolution/event-emitter-synthesizer.ts b/src/resolution/event-emitter-synthesizer.ts index e57e322b39..2f9379de0e 100644 --- a/src/resolution/event-emitter-synthesizer.ts +++ b/src/resolution/event-emitter-synthesizer.ts @@ -38,6 +38,7 @@ import type { MaybeYield } from './cooperative-yield'; import { FN_KINDS } from './synth-utils'; import { resolveImportPath } from './import-resolver'; import { isManualMockHiddenFrom } from './name-matcher'; +import { nodesAroundLineIn, nodesNamedIn } from './nodes-around'; /** `.on('e', handler)`: 1 the event; 2 an inline `function name`, or 3 `this.` and 4 a name. */ const ON_RE = /\.(?:on|once|addListener)\(\s*['"]([^'"]+)['"]\s*,\s*(?:function\s+(\w+)|(this\.)?(\w+))/g; @@ -223,7 +224,7 @@ function textOf(facts: FileFacts, node: Pick): { /** The function/method nodes whose lines contain `line`, innermost first. */ function fnChain(nodes: readonly Node[], line: number): Node[] { - return nodes + return nodesAroundLineIn(nodes, line) .filter((n) => FN_KINDS.has(n.kind) && n.startLine <= line && (n.endLine ?? n.startLine) >= line) .sort((a, b) => b.startLine - a.startLine || (a.endLine ?? a.startLine) - (b.endLine ?? b.startLine)); } @@ -237,7 +238,7 @@ function handlerAt(env: Env, facts: FileFacts, m: RegExpExecArray, line: number, if (inline) { // `on('mount', function onmount(parent) {…})`: the function expression is its own node. const nameLine = lineOf(facts, m.index + m[0].length - inline.length); - return facts.nodes.find((n) => FN_KINDS.has(n.kind) && n.name === inline && n.startLine === nameLine) ?? null; + return nodesNamedIn(facts.nodes, inline).find((n) => FN_KINDS.has(n.kind) && n.name === inline && n.startLine === nameLine) ?? null; } const name = m[4]!; const viaThis = m[3] !== undefined; @@ -259,7 +260,7 @@ function handlerAt(env: Env, facts: FileFacts, m: RegExpExecArray, line: number, if (bound) return ownMethod(env, facts, bound[1]!, chain.slice(i)) ?? resolvedReference(env, sources, `this.${bound[1]!}`, () => true); if (new RegExp(String.raw`\b(?:const|let|var)\s+${n}\s*=\s*(?:async\s+)?(?:function\b|\([^()]*\)\s*(?::[^=]*)?=>|[\w$]+\s*=>)|\bfunction\s*\*?\s*${n}\s*\(`).test(text)) { const end = fn.endLine ?? fn.startLine; - return facts.nodes.find((x) => x.kind === 'function' && x.name === name && x.startLine >= fn.startLine && (x.endLine ?? x.startLine) <= end) ?? null; + return nodesNamedIn(facts.nodes, name).find((x) => x.kind === 'function' && x.name === name && x.startLine >= fn.startLine && (x.endLine ?? x.startLine) <= end) ?? null; } const local = localBinding(text, name, ''); if (local?.kind === 'import') break; @@ -295,7 +296,7 @@ function resolvedReference(env: Env, sources: readonly string[], refName: string /** The nodes a reference at `line` can be attributed to: the enclosing functions, then whatever else spans the line, then the file. */ function referenceSources(facts: FileFacts, line: number, chain: readonly Node[]): string[] { const ids = chain.map((n) => n.id); - for (const n of facts.nodes) { + for (const n of nodesAroundLineIn(facts.nodes, line)) { if (n.kind === 'file' || FN_KINDS.has(n.kind)) continue; if (n.startLine <= line && (n.endLine ?? n.startLine) >= line) ids.push(n.id); } @@ -322,7 +323,7 @@ function fnRefsOf(env: Env, sourceId: string): Map { * when it can't tell which. */ function ownMethod(env: Env, facts: FileFacts, name: string, chain: readonly Node[]): Node | null | undefined { - const methods = facts.nodes.filter((n) => n.kind === 'method' && n.name === name); + const methods = nodesNamedIn(facts.nodes, name).filter((n) => n.kind === 'method' && n.name === name); if (methods.length === 0) return undefined; const owner = thisFunction(facts, chain); const cls = owner ? ownerClass(env, owner) : null; @@ -343,7 +344,7 @@ function ownMethod(env: Env, facts: FileFacts, name: string, chain: readonly Nod * defines none. */ function ownFunction(facts: FileFacts, name: string, line: number, chain: readonly Node[]): Node | null | undefined { - const local = facts.nodes.filter((n) => n.kind === 'function' && n.name === name); + const local = nodesNamedIn(facts.nodes, name).filter((n) => n.kind === 'function' && n.name === name); if (local.length <= 1) return local[0]; const scope = chain[0]?.id ?? null; const inScope = local @@ -538,7 +539,7 @@ function fieldClass(env: Env, owner: Node, field: string): Node | null { const content = env.ctx.readFile(owner.filePath); if (content) { const facts = fileFacts(env.ctx, owner.filePath, content); - const declared = facts.nodes.find((n) => (n.kind === 'property' || n.kind === 'field') && n.name === field && + const declared = nodesNamedIn(facts.nodes, field).find((n) => (n.kind === 'property' || n.kind === 'field') && n.name === field && n.startLine >= owner.startLine && (n.endLine ?? n.startLine) <= (owner.endLine ?? owner.startLine)); if (declared) cls = classReferencedAt(env, owner.filePath, [declared.id], declared.startLine, null); if (!cls) { @@ -671,13 +672,13 @@ function anonymousLocal(facts: FileFacts, site: Site, name: string): number | nu for (const offset of offsets) { if (offset >= site.index) break; const line = lineOf(facts, offset); - const inOther = facts.nodes.some((f) => FN_KINDS.has(f.kind) && f.startLine <= line && (f.endLine ?? f.startLine) >= line && + const inOther = nodesAroundLineIn(facts.nodes, line).some((f) => FN_KINDS.has(f.kind) && f.startLine <= line && (f.endLine ?? f.startLine) >= line && !site.chain.some((c) => c.id === f.id)); if (!inOther) found = offset; } if (found === null) return null; const line = lineOf(facts, found); - const moduleLevel = facts.nodes.some((x) => (x.kind === 'constant' || x.kind === 'variable') && x.name === name && x.startLine === line); + const moduleLevel = nodesNamedIn(facts.nodes, name).some((x) => (x.kind === 'constant' || x.kind === 'variable') && x.name === name && x.startLine === line); return moduleLevel ? null : found; } @@ -693,9 +694,9 @@ function moduleKeys(env: Env, facts: FileFacts, name: string, tail: string): rea const where = imported.module !== null ? `mod:${imported.module}` : `pkg:${imported.source}`; return [`${where}#${imported.exported}${suffix}`]; } - const decl = facts.nodes.find((n) => + const decl = nodesNamedIn(facts.nodes, name).find((n) => (n.kind === 'constant' || n.kind === 'variable') && n.name === name && - !facts.nodes.some((f) => FN_KINDS.has(f.kind) && f.startLine < n.startLine && (f.endLine ?? f.startLine) >= n.startLine)); + !nodesAroundLineIn(facts.nodes, n.startLine).some((f) => FN_KINDS.has(f.kind) && f.startLine < n.startLine && (f.endLine ?? f.startLine) >= n.startLine)); if (!decl) return null; const keys = [`bind:${facts.file}#${name}${suffix}`]; for (const exported of exportNamesOf(env, facts, name)) keys.push(`mod:${facts.file}#${exported}${suffix}`); @@ -751,10 +752,10 @@ function exportNamesOf(env: Env, facts: FileFacts, name: string): string[] { * (`const { WebSocket } = require('..')`), the project's only class of that name. */ function classNamed(env: Env, facts: FileFacts, name: string, line: number): Node | null { - const spanning = facts.nodes.filter((n) => n.startLine <= line && (n.endLine ?? n.startLine) >= line).map((n) => n.id); + const spanning = nodesAroundLineIn(facts.nodes, line).filter((n) => n.startLine <= line && (n.endLine ?? n.startLine) >= line).map((n) => n.id); const bound = classReferencedAt(env, facts.file, spanning, line, name); if (bound) return bound; - const own = facts.nodes.filter((n) => CLASS_KINDS.has(n.kind) && n.name === name); + const own = nodesNamedIn(facts.nodes, name).filter((n) => CLASS_KINDS.has(n.kind) && n.name === name); if (own.length > 0) return own.length === 1 ? own[0]! : null; const imported = importedModule(env, facts, name); if (!imported || imported.module === null) return null; diff --git a/src/resolution/expo-router-synthesizer.ts b/src/resolution/expo-router-synthesizer.ts index 1e8e090f86..2f061b427c 100644 --- a/src/resolution/expo-router-synthesizer.ts +++ b/src/resolution/expo-router-synthesizer.ts @@ -38,6 +38,7 @@ import { stringEnd, toHref, } from './frameworks/expo-router'; +import { lineAt } from './synth-utils'; const JS_LANGS: ReadonlySet = new Set(['typescript', 'javascript', 'tsx', 'jsx']); const JS_FILE = /\.(?:[cm]?[jt]sx?)$/; @@ -73,7 +74,7 @@ export async function expoRouterReturnEdges(ctx: ResolutionContext, onYield: May NAV_FED_BY_CALL.lastIndex = 0; let m: RegExpExecArray | null; while ((m = NAV_FED_BY_CALL.exec(stripped)) !== null) { - const line = stripped.slice(0, m.index).split('\n').length; + const line = lineAt(stripped, m.index); sites.push({ file, line, method: m[1]!, callee: m[2]! }); } } @@ -192,7 +193,7 @@ function screensInBody( found.set(route.id, { node: route, href: href.display, - line: helper.startLine + body.slice(0, start).split('\n').length - 1, + line: helper.startLine + lineAt(body, start) - 1, column: start - lineStart, }); if (found.size > MAX_SCREENS_PER_HELPER) return null; diff --git a/src/resolution/frameworks/angular-router.ts b/src/resolution/frameworks/angular-router.ts index eba108d249..1fa2a91d9e 100644 --- a/src/resolution/frameworks/angular-router.ts +++ b/src/resolution/frameworks/angular-router.ts @@ -64,6 +64,8 @@ import { type RouteTable, } from './expo-router'; import { destinationsForHref } from './nextjs'; +import { lineAt } from '../synth-utils'; +import { nodesAroundLine, nodesNamed } from '../nodes-around'; // ============================================================================= // Reading a routes array @@ -258,7 +260,7 @@ export function parseAngularRoutes(content: string): { routes: AngularRoute[]; m const redirects: AngularRedirect[] = []; if (!ROUTER_IMPORT.test(content)) return { routes, mounts, redirects }; const safe = stripCommentsForRegex(content, 'typescript'); - const lineOf = (at: number) => safe.slice(0, at).split('\n').length; + const lineOf = (at: number) => lineAt(safe, at); const seenPaths = new Set(); const walked = new Set(); @@ -400,7 +402,7 @@ function lazyComponent(spec: string, member: string | null, fromFile: string, co } } if (!name) return null; - return context.getNodesInFile(file).find((n) => n.kind === 'class' && n.name === name) ?? null; + return nodesNamed(context, file, name).find((n) => n.kind === 'class' && n.name === name) ?? null; } /** A path's segments with each `{expr}` read from the constant it names, as seen from `file` — where the route (or the mount) is written. */ @@ -423,7 +425,7 @@ function routeComponent(encoded: string, fromFile: string, context: ResolutionCo const lazy = LAZY_COMPONENT_REF.exec(encoded); if (lazy) return lazyComponent(lazy[1]!, lazy[2] === 'default' ? null : lazy[2]!, fromFile, context); const file = declaringFile(encoded, fromFile, context); - return file ? (context.getNodesInFile(file).find((n) => n.kind === 'class' && n.name === encoded) ?? null) : null; + return file ? (nodesNamed(context, file, encoded).find((n) => n.kind === 'class' && n.name === encoded) ?? null) : null; } // ============================================================================= @@ -1091,8 +1093,7 @@ export const angularRouterResolver: FrameworkResolver = { // `navigate(['..', id], { relativeTo: this.route })` goes somewhere relative to here. const extras = nthArgumentText(lines, ref.line, ref.column, verb, 1); if (extras && /\brelativeTo\b/.test(extras)) return null; - const owner = context - .getNodesInFile(ref.filePath) + const owner = nodesAroundLine(context, ref.filePath, ref.line) .filter((n) => n.kind === 'class' && n.startLine <= ref.line && n.endLine >= ref.line) .reduce((inner, n) => (!inner || n.startLine >= inner.startLine ? n : inner), null); const href = angularDestination(arg, ref.filePath, owner, context, 0, true); diff --git a/src/resolution/frameworks/astro.ts b/src/resolution/frameworks/astro.ts index fc4f99a098..1b653a1d42 100644 --- a/src/resolution/frameworks/astro.ts +++ b/src/resolution/frameworks/astro.ts @@ -9,6 +9,7 @@ import { Node } from '../../types'; import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types'; import { pageComponentRef, resolvePageComponent } from './page-component'; import { inReferencingFolder } from './component-folder'; +import { lineAt } from '../synth-utils'; /** * Astro virtual module prefixes — framework-provided, not user code @@ -148,7 +149,7 @@ export const astroResolver: FrameworkResolver = { // APIRoute = …`, `export async function POST(…)`. for (const m of content.matchAll(ENDPOINT_EXPORT)) { const verb = m[1] ?? m[2]!; - const line = content.slice(0, m.index).split('\n').length; + const line = lineAt(content, m.index); references.push({ fromNodeId: route.id, referenceName: verb, referenceKind: 'references', line, column: 0, filePath, language, candidates: [verb] }); } } diff --git a/src/resolution/frameworks/codeigniter.ts b/src/resolution/frameworks/codeigniter.ts index 0ee8587c87..76c9cdb16e 100644 --- a/src/resolution/frameworks/codeigniter.ts +++ b/src/resolution/frameworks/codeigniter.ts @@ -22,6 +22,8 @@ import { Node } from '../../types'; import { FrameworkResolver, ResolutionContext, ResolvedRef, UnresolvedRef } from '../types'; import { stripCommentsForRegex } from '../strip-comments'; +import { lineAt } from '../synth-utils'; +import { nodesNamedLower } from '../nodes-around'; const ROUTES_FILE = /(?:^|\/)application\/(?:modules\/[^/]+\/)?config\/(?:[^/]+\/)?routes\.php$/; const CONTROLLER_FILE = /^(?:.*?\/)?(?:application\/controllers|modules\/([^/]+)\/controllers)\/(.+)\.php$/; @@ -134,7 +136,7 @@ function conventionRoutes(filePath: string, baseUrl: string, safe: string): { no const routePath = name.toLowerCase() === 'index' ? baseUrl : `${baseUrl}/${name.toLowerCase()}`; if (seen.has(routePath)) continue; seen.add(routePath); - const line = safe.slice(0, m.index).split('\n').length; + const line = lineAt(safe, m.index); const route = routeNode(filePath, line, 'ANY', routePath, now); nodes.push(route); references.push({ @@ -168,7 +170,7 @@ function explicitRoutes(filePath: string, safe: string): { nodes: Node[]; refere while ((m = ROUTE_RE.exec(safe)) !== null) { const [, pattern, verb, handler] = m; if (pattern === '404_override' || pattern === 'translate_uri_dashes' || !handler) continue; - const line = safe.slice(0, m.index).split('\n').length; + const line = lineAt(safe, m.index); const routePath = pattern === 'default_controller' ? '/' : `/${pattern!.replace(/^\/+/, '')}`; const route = routeNode(filePath, line, (verb ?? 'ANY').toUpperCase(), routePath, now); nodes.push(route); @@ -196,8 +198,8 @@ function methodOf(cls: Node, name: string, context: ResolutionContext): Node | n if (seen.has(type.id)) continue; seen.add(type.id); const prefix = `${type.qualifiedName}::`.toLowerCase(); - const own = context.getNodesInFile(type.filePath).find( - (n) => n.kind === 'method' && n.name.toLowerCase() === lower && n.qualifiedName.toLowerCase().startsWith(prefix) + const own = nodesNamedLower(context, type.filePath, lower).find( + (n) => n.kind === 'method' && n.qualifiedName.toLowerCase().startsWith(prefix) ); if (own) return own; for (const parent of context.getSupertypeNodes?.(type.id) ?? []) { @@ -303,7 +305,7 @@ export const codeigniterResolver: FrameworkResolver = { if (name.startsWith(METHOD_REF)) { const [file, method] = name.slice(METHOD_REF.length).split('|'); - return resolved(context.getNodesInFile(file!).find((n) => n.kind === 'method' && n.name === method), 0.95); + return resolved(method === undefined ? undefined : nodesNamedLower(context, file!, method.toLowerCase()).find((n) => n.kind === 'method' && n.name === method), 0.95); } if (name.startsWith(ROUTE_REF)) { const [root, handler] = name.slice(ROUTE_REF.length).split('|'); diff --git a/src/resolution/frameworks/csharp.ts b/src/resolution/frameworks/csharp.ts index aed3434311..c836aecbf8 100644 --- a/src/resolution/frameworks/csharp.ts +++ b/src/resolution/frameworks/csharp.ts @@ -10,6 +10,7 @@ import { stripCommentsForRegex } from '../strip-comments'; import { pickByNameAndKind } from './name-heuristic'; import { csharpTypeArityFits } from '../name-matcher'; import { aspnetAttributeRoutes, aspnetDeclaredTemplates, aspnetRoutePath } from './aspnet-routes'; +import { lineAt } from '../synth-utils'; export const aspnetResolver: FrameworkResolver = { name: 'aspnet', @@ -192,7 +193,7 @@ export const aspnetResolver: FrameworkResolver = { // `app.MapGet("api/todos", …)` serves `/api/todos`. const routePath = joinCsPath('', rawPath!); const method = verb!.toUpperCase(); - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const routeNode: Node = { id: `route:${filePath}:${line}:${method}:${routePath}`, @@ -240,7 +241,7 @@ export const aspnetResolver: FrameworkResolver = { while ((match = groupRegex.exec(safe)) !== null) { const [, verb, handlerName, sub] = match; const method = verb!.toUpperCase(); - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const before = safe.slice(0, match.index); const classMatch = [...before.matchAll(/\bclass\s+([A-Za-z_]\w*)/g)].pop(); if (!classMatch) continue; @@ -294,7 +295,7 @@ export const aspnetResolver: FrameworkResolver = { const literals = [...args.matchAll(/"([^"]+)"/g)].map((l) => joinCsPath('', l[1]!.replace(/\{\s*nameof\s*\(\s*(\w+)\s*\)\s*\}/g, '$1'))); const constant = /^([A-Za-z_]\w*)\.([A-Za-z_]\w*)$/.exec(args); const targets = literals.length > 0 ? literals.map((p) => ({ name: p, key: p })) : constant ? [{ name: `${constant[1]}.${constant[2]}`, key: `const:${constant[1]}.${constant[2]}` }] : []; - const line = safe.slice(0, match.index + verb.index).split('\n').length; + const line = lineAt(safe, match.index + verb.index); for (const t of targets) { const id = `route:${filePath}:${line}:${method}:${t.name}`; nodes.push({ diff --git a/src/resolution/frameworks/drupal.ts b/src/resolution/frameworks/drupal.ts index 5bbd30d6b5..8626bc8d31 100644 --- a/src/resolution/frameworks/drupal.ts +++ b/src/resolution/frameworks/drupal.ts @@ -59,8 +59,9 @@ import { generateNodeId } from '../../extraction/tree-sitter-helpers'; import { Node } from '../../types'; import { FrameworkResolver, ResolutionContext, ResolvedRef, UnresolvedRef } from '../types'; -import { makeLineAt } from '../synth-utils'; +import { makeLineAt, lineAt } from '../synth-utils'; import { matchBracket } from './object-literal'; +import { nodesNamed } from '../nodes-around'; // --------------------------------------------------------------------------- // Helpers @@ -249,7 +250,7 @@ function extractDrupalHooks( const name = fm[1]!; if (!funcLineMap.has(name)) { // line = number of newlines before match start + 1 - funcLineMap.set(name, content.slice(0, fm.index).split('\n').length); + funcLineMap.set(name, lineAt(content, fm.index)); } } @@ -762,7 +763,7 @@ export const drupalResolver: FrameworkResolver = { if (name.startsWith(FQCN_REF)) return resolved(classByFqcn(name.slice(FQCN_REF.length).replace(':', ''), context), 0.9); if (name.startsWith(CLASS_REF)) { const [file, className] = name.slice(CLASS_REF.length).split('#'); - return resolved(context.getNodesInFile(file!).find((n) => n.kind === 'class' && n.name === className), 0.95); + return resolved(nodesNamed(context, file!, className).find((n) => n.kind === 'class' && n.name === className), 0.95); } const onContainer = CONTAINER_CALL.exec(name); @@ -782,8 +783,7 @@ export const drupalResolver: FrameworkResolver = { const classNodes = context.getNodesByName(className!); for (const cls of classNodes) { if (cls.kind !== 'class') continue; - const fileNodes = context.getNodesInFile(cls.filePath); - const method = fileNodes.find((n) => n.kind === 'method' && n.name === methodName); + const method = nodesNamed(context, cls.filePath, methodName).find((n) => n.kind === 'method' && n.name === methodName); if (method) { return { original: ref, targetNodeId: method.id, confidence: 0.9, resolvedBy: 'framework' }; } diff --git a/src/resolution/frameworks/expo-modules.ts b/src/resolution/frameworks/expo-modules.ts index 09c55d5c41..795269e13c 100644 --- a/src/resolution/frameworks/expo-modules.ts +++ b/src/resolution/frameworks/expo-modules.ts @@ -49,6 +49,7 @@ import { import { resolveImportPath } from '../import-resolver'; import { stripCommentsForRegex } from '../strip-comments'; import { escapeRegExp } from '../../utils'; +import { lineAt } from '../synth-utils'; /** * Match `Function("name")`, `AsyncFunction("name")`, or `Property("name")` @@ -123,7 +124,7 @@ function extractExpoMethods(filePath: string, source: string, language: 'swift' const methodName = m[2]!; // Compute line number from match index. const before = source.slice(0, m.index); - const startLine = before.split('\n').length; + const startLine = lineAt(source, m.index); // Avoid duplicates if the same method literal appears twice in one // file (e.g., declared and re-declared inside a `View {...}` block). const dedupKey = `${methodName}:${startLine}`; diff --git a/src/resolution/frameworks/expo-router.ts b/src/resolution/frameworks/expo-router.ts index e6641a4608..331daea687 100644 --- a/src/resolution/frameworks/expo-router.ts +++ b/src/resolution/frameworks/expo-router.ts @@ -45,6 +45,7 @@ import type { } from '../types'; import { stripCommentsForRegex } from '../strip-comments'; import { dependsOn } from './package-deps'; +import { lineAt } from '../synth-utils'; // ============================================================================= // Route files @@ -778,7 +779,7 @@ export const expoRouterResolver: FrameworkResolver = { const method = (m[1] ?? m[2])!; if (seen.has(method)) continue; seen.add(method); - const line = stripped.slice(0, m.index).split('\n').length; + const line = lineAt(stripped, m.index); const node: Node = { id: `route:${filePath}:${line}:${method}:${apiPath}`, kind: 'route', @@ -823,7 +824,7 @@ export const expoRouterResolver: FrameworkResolver = { fromNodeId: node.id, referenceName: screen.name, referenceKind: 'calls', - line: stripped.slice(0, screen.index).split('\n').length, + line: lineAt(stripped, screen.index), column: 0, filePath, language, diff --git a/src/resolution/frameworks/express.ts b/src/resolution/frameworks/express.ts index d82a70a545..da4fa41219 100644 --- a/src/resolution/frameworks/express.ts +++ b/src/resolution/frameworks/express.ts @@ -9,6 +9,7 @@ import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from import { REGEX_START_BEFORE, stripCommentsForRegex } from '../strip-comments'; import { resolveImportPath } from '../import-resolver'; import { dependsOn } from './package-deps'; +import { lineAt } from '../synth-utils'; /** The languages a route file is read in here and by the Elysia resolver, which shares these readers. */ export type ScriptLanguage = 'typescript' | 'javascript' | 'tsx' | 'jsx'; @@ -111,7 +112,7 @@ function replyRefs(safe: string, bodyStart: number, bodyEnd: number, fromNodeId: fromNodeId, referenceName: `${m[1]}.${m[2]}`, referenceKind: 'calls', - line: safe.slice(0, at).split('\n').length, + line: lineAt(safe, at), column: at - (safe.lastIndexOf('\n', at - 1) + 1), filePath, language, @@ -221,7 +222,7 @@ export const expressResolver: FrameworkResolver = { const method = match[2]!; const routePath = match[3]!; if (method === 'use' && !routePath.startsWith('/')) continue; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const routeNode: Node = { id: `route:${filePath}:${line}:${method.toUpperCase()}:${routePath}`, kind: 'route', @@ -258,7 +259,7 @@ export const expressResolver: FrameworkResolver = { if (!call) break; const closeParen = call.close; const method = link[1]!; - const line = safe.slice(0, openParen).split('\n').length; + const line = lineAt(safe, openParen); const args = call.structure.slice(1, -1); const routeNode: Node = { id: `route:${filePath}:${line}:${method.toUpperCase()}:${routePath}`, diff --git a/src/resolution/frameworks/fabric.ts b/src/resolution/frameworks/fabric.ts index e5c15e835c..87d062193d 100644 --- a/src/resolution/frameworks/fabric.ts +++ b/src/resolution/frameworks/fabric.ts @@ -48,6 +48,7 @@ import { FrameworkExtractionResult, FrameworkResolver, } from '../types'; +import { firstIndexOfEach, lineAt } from '../synth-utils'; const CODEGEN_DECL_RE = /\b(codegenNativeComponent|requireNativeComponent)\s*(?:<[^>]+>)?\s*\(\s*['"]([A-Za-z_][A-Za-z0-9_]*)['"]/g; @@ -169,8 +170,7 @@ function extractLegacyViewManagerNodes(filePath: string, source: string): Node[] // works for legacy too. The native class IS the manager itself in this // case; the convention-based suffix lookup in the synthesizer // (`Manager`, `ViewManager`) will find it. - const before = source.slice(0, implMatch.index ?? 0); - const startLine = before.split('\n').length; + const startLine = lineAt(source, implMatch.index ?? 0); nodes.push({ id: `fabric-component:${filePath}:${componentName}:${startLine}`, kind: 'component', @@ -196,8 +196,7 @@ function extractLegacyViewManagerNodes(filePath: string, source: string): Node[] const propName = m[1]!; if (seen.has(propName)) continue; seen.add(propName); - const propBefore = source.slice(0, m.index); - const propLine = propBefore.split('\n').length; + const propLine = lineAt(source, m.index); nodes.push({ id: `fabric-prop:${filePath}:${propName}:${propLine}`, kind: 'property', @@ -242,8 +241,7 @@ function extractJvmViewManagerNodes(filePath: string, source: string): Node[] { const now = Date.now(); const nodes: Node[] = []; - const classBefore = source.slice(0, classMatch.index ?? 0); - const startLine = classBefore.split('\n').length; + const startLine = lineAt(source, classMatch.index ?? 0); nodes.push({ id: `fabric-component:${filePath}:${componentName}:${startLine}`, kind: 'component', @@ -271,8 +269,7 @@ function extractJvmViewManagerNodes(filePath: string, source: string): Node[] { const propName = m[1]!; if (seen.has(propName)) continue; seen.add(propName); - const propBefore = source.slice(0, m.index); - const propLine = propBefore.split('\n').length; + const propLine = lineAt(source, m.index); nodes.push({ id: `fabric-prop:${filePath}:${propName}:${propLine}`, kind: 'property', @@ -292,6 +289,9 @@ function extractJvmViewManagerNodes(filePath: string, source: string): Node[] { return nodes; } +/** Up to this many props, each is looked for on its own, as before. */ +const FEW_PROPS = 24; + function extractFabricNodes(filePath: string, source: string): Node[] { if (!isFabricSpec(source)) return []; @@ -303,9 +303,9 @@ function extractFabricNodes(filePath: string, source: string): Node[] { while ((m = CODEGEN_DECL_RE.exec(source)) !== null) { const declaredWith = m[1]!; const componentName = m[2]!; - const before = source.slice(0, m.index); - const startLine = before.split('\n').length; - const startColumn = before.length - before.lastIndexOf('\n') - 1; + const startLine = lineAt(source, m.index); + // From the last newline before the declaration, without copying the source up to it. + const startColumn = m.index - (m.index > 0 ? source.lastIndexOf('\n', m.index - 1) : -1) - 1; // The component itself — kind: 'component' so the existing // reactJsxChildEdges synthesizer matches `` JSX tags to @@ -338,10 +338,19 @@ function extractFabricNodes(filePath: string, source: string): Node[] { const body = findNativePropsBody(source); if (body) { const props = extractPropNames(body); + // A prop is placed where its name first occurs from the interface's body + // on. Looked for one prop at a time, that read the body from its first + // line for each of them (and looked for the body itself each time), the + // square of an interface's size. Past a few props, where each first + // occurs in the body is read in one pass: every name is in the body, so + // its first occurrence from the body's start is its first in the body. + const bodyStart = source.indexOf(body); + const firsts = bodyStart >= 0 && props.length > FEW_PROPS ? firstIndexOfEach(body, props) : null; for (const propName of props) { - const propBefore = source.indexOf(propName, source.indexOf(body)); + const inBody = firsts?.get(propName); + const propBefore = inBody !== undefined && inBody >= 0 ? bodyStart + inBody : source.indexOf(propName, bodyStart); const propLine = - propBefore >= 0 ? source.slice(0, propBefore).split('\n').length : 1; + propBefore >= 0 ? lineAt(source, propBefore) : 1; nodes.push({ id: `fabric-prop:${filePath}:${propName}:${propLine}`, kind: 'property', diff --git a/src/resolution/frameworks/go.ts b/src/resolution/frameworks/go.ts index 58453a9ee3..e80cef275b 100644 --- a/src/resolution/frameworks/go.ts +++ b/src/resolution/frameworks/go.ts @@ -9,6 +9,7 @@ import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from import { stripCommentsForRegex } from '../strip-comments'; import { GO_TYPE_KINDS, isGoBareName } from '../name-matcher'; import { pickByNameAndKind } from './name-heuristic'; +import { lineAt } from '../synth-utils'; export const goResolver: FrameworkResolver = { name: 'go', @@ -125,7 +126,7 @@ export const goResolver: FrameworkResolver = { const methodPrefix = matchGo122MethodPattern(routePath!, rawMethod!); if (!routePath!.startsWith('/') && !methodPrefix) continue; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); // "GET /users/{id}" -> method GET, path /users/{id} const path = methodPrefix ? routePath!.slice(methodPrefix.length).trimStart() : routePath!; const method = methodPrefix diff --git a/src/resolution/frameworks/goframe.ts b/src/resolution/frameworks/goframe.ts index 6127972142..fa90444502 100644 --- a/src/resolution/frameworks/goframe.ts +++ b/src/resolution/frameworks/goframe.ts @@ -34,6 +34,7 @@ import { Node } from '../../types'; import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types'; import { stripCommentsForRegex } from '../strip-comments'; +import { lineAt } from '../synth-utils'; /** * A request type carrying a routable `g.Meta` tag. `g.Meta` is, by GoFrame @@ -84,7 +85,7 @@ export const goframeResolver: FrameworkResolver = { const methodMatch = META_METHOD_RE.exec(tag!); // GoFrame defaults to all methods when `method:` is omitted. const method = methodMatch ? methodMatch[1]!.toUpperCase() : 'ANY'; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); // The handler's signature qualifies the request type with its package // (`req *cash.ListReq`); encode `pkg.Type` so the synthesizer can match it. const joinKey = pkg ? `${pkg}.${requestType}` : requestType!; diff --git a/src/resolution/frameworks/java.ts b/src/resolution/frameworks/java.ts index ebcea2c2be..392c0af71b 100644 --- a/src/resolution/frameworks/java.ts +++ b/src/resolution/frameworks/java.ts @@ -8,6 +8,8 @@ import { Node } from '../../types'; import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types'; import { stripCommentsForRegex } from '../strip-comments'; import { pickByNameAndKind } from './name-heuristic'; +import { lineAt } from '../synth-utils'; +import { nodesAroundLine } from '../nodes-around'; export const springResolver: FrameworkResolver = { name: 'spring', @@ -251,7 +253,7 @@ export const springResolver: FrameworkResolver = { if (!annotation) continue; const method = VERB[match[1]!]!; const paths = parseMappingPaths(annotation.args, consts); - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); // The method it decorates: the declaration it is written on (#851). const handler = annotatedMethodName(safe, match.index, lang); for (const routePath of classPrefixes.flatMap(prefix => paths.map(sub => joinPath(prefix, sub)))) { @@ -300,7 +302,7 @@ export const springResolver: FrameworkResolver = { const verbM = args.match(/method\s*=\s*[{\[]?\s*(?:RequestMethod\.)?(\w+)/); const method = verbM ? verbM[1]!.toUpperCase() : 'ANY'; const paths = parseMappingPaths(args, consts); - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); for (const routePath of classPrefixes.flatMap(prefix => paths.map(sub => joinPath(prefix, sub)))) { const routeNode: Node = { id: `route:${filePath}:${line}:${method}:${routePath}`, @@ -460,7 +462,7 @@ function extractSpringValueBindings( while ((m = valueRe.exec(safe)) !== null) { const key = m[1]!.trim(); if (!key) continue; - const line = safe.slice(0, m.index).split('\n').length; + const line = lineAt(safe, m.index); const bindNode: Node = { id: `spring-value:${filePath}:${line}:${key}`, kind: 'constant', @@ -491,7 +493,7 @@ function extractSpringValueBindings( while ((m = cpRe.exec(safe)) !== null) { const prefix = m[1]!.trim(); if (!prefix) continue; - const line = safe.slice(0, m.index).split('\n').length; + const line = lineAt(safe, m.index); const bindNode: Node = { id: `spring-cp:${filePath}:${line}:${prefix}`, kind: 'constant', @@ -742,7 +744,7 @@ function routeHandlerAt(ref: UnresolvedRef, context: ResolutionContext): Node | if (ref.referenceKind !== 'references' || (ref.language !== 'java' && ref.language !== 'kotlin')) return null; if (!ref.fromNodeId.startsWith(`route:${ref.filePath}:${ref.line}:`)) return null; let handler: Node | null = null; - for (const node of context.getNodesInFile(ref.filePath)) { + for (const node of nodesAroundLine(context, ref.filePath, ref.line)) { if ((node.kind !== 'method' && node.kind !== 'function') || node.name !== ref.referenceName) continue; if (node.startLine > ref.line || node.endLine < ref.line) continue; if (!handler || node.startLine > handler.startLine) handler = node; diff --git a/src/resolution/frameworks/laravel.ts b/src/resolution/frameworks/laravel.ts index 92c7309d96..d95eced282 100644 --- a/src/resolution/frameworks/laravel.ts +++ b/src/resolution/frameworks/laravel.ts @@ -8,6 +8,8 @@ import { posix } from 'path'; import { Node } from '../../types'; import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types'; import { stripCommentsForRegex } from '../strip-comments'; +import { lineAt } from '../synth-utils'; +import { nodesNamed } from '../nodes-around'; /** * Laravel facade mappings to underlying classes @@ -129,7 +131,7 @@ export const laravelResolver: FrameworkResolver = { let match: RegExpExecArray | null; while ((match = routeRegex.exec(safe)) !== null) { const [, method, routePath, handlerExpr] = match; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const upper = method!.toUpperCase(); const inFile = joinRoutePath(prefixAt(groups, match.index), routePath!); const routeNode: Node = { @@ -165,7 +167,7 @@ export const laravelResolver: FrameworkResolver = { const resourceRegex = /Route::(resource|apiResource)\s*\(\s*['"]([^'"]+)['"]\s*(?:,\s*([^)]+))?\)/g; while ((match = resourceRegex.exec(safe)) !== null) { const [, _fn, resourceName, handlerExpr] = match; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const inFile = joinRoutePath(prefixAt(groups, match.index), resourceName!); const routeNode: Node = { id: `route:${filePath}:${line}:RESOURCE:${resourceName}`, @@ -689,7 +691,7 @@ function resolveControllerMethod( } const rel = controller.replace(/\\/g, '/'); const methodIn = (filePath: string): string | null => - context.getNodesInFile(filePath).find((n) => n.kind === 'method' && n.name === method)?.id ?? null; + nodesNamed(context, filePath, method).find((n) => n.kind === 'method' && n.name === method)?.id ?? null; const conventional = `app/Http/Controllers/${rel}.php`; if (context.fileExists(conventional)) { diff --git a/src/resolution/frameworks/nestjs.ts b/src/resolution/frameworks/nestjs.ts index d3effb119d..c3985e6de9 100644 --- a/src/resolution/frameworks/nestjs.ts +++ b/src/resolution/frameworks/nestjs.ts @@ -31,6 +31,7 @@ import { } from '../types'; import { stripCommentsForRegex } from '../strip-comments'; import { declaredDependencies } from './package-deps'; +import { lineAt } from '../synth-utils'; // --------------------------------------------------------------------------- // Public surface — see comment at top of file. This file owns four NestJS @@ -727,10 +728,6 @@ function joinHttpPath(prefix: string, sub: string): string { return '/' + parts.join('/'); } -function lineAt(safe: string, index: number): number { - return safe.slice(0, index).split('\n').length; -} - function detectLanguage(filePath: string): JsLang { if (filePath.endsWith('.ts') || filePath.endsWith('.tsx')) return 'typescript'; return 'javascript'; diff --git a/src/resolution/frameworks/next-proxy.ts b/src/resolution/frameworks/next-proxy.ts index fcb409e9fb..b33e2c2174 100644 --- a/src/resolution/frameworks/next-proxy.ts +++ b/src/resolution/frameworks/next-proxy.ts @@ -14,6 +14,7 @@ import type { ResolutionContext } from '../types'; import { stripCommentsForRegex } from '../strip-comments'; import { HOLE, readStringAt } from './expo-router'; import { matchBracket, readFields, skipString } from './object-literal'; +import { nodesNamed } from '../nodes-around'; const PROXY_EXTENSIONS = ['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs']; @@ -87,7 +88,7 @@ export function nextProxyFor(context: ResolutionContext, dir: string, root: stri /\bexport\s+default\s+(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/.exec(safe)?.[1] ?? /\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*;?\s*$/m.exec(safe)?.[1] ?? /\bexport\s*\{[^}]*?\b([A-Za-z_$][\w$]*)\s+as\s+(?:default|middleware|proxy)\b[^}]*\}(?!\s*from\b)/.exec(safe)?.[1]; - const entry = (local ? nodes.find((n) => ENTRY_KINDS.has(n.kind) && n.name === local) : undefined) ?? nodes.find((n) => n.kind === 'file'); + const entry = (local ? nodesNamed(context, file, local).find((n) => ENTRY_KINDS.has(n.kind) && n.name === local) : undefined) ?? nodes.find((n) => n.kind === 'file'); return entry ? { file, entry } : null; } diff --git a/src/resolution/frameworks/nextjs.ts b/src/resolution/frameworks/nextjs.ts index a2aba3d5dd..dd6f8338e5 100644 --- a/src/resolution/frameworks/nextjs.ts +++ b/src/resolution/frameworks/nextjs.ts @@ -51,6 +51,7 @@ import { type HrefLiteral, type RouteTable, } from './expo-router'; +import { lineAt } from '../synth-utils'; const ROUTE_LANGUAGES: readonly Language[] = ['typescript', 'javascript', 'tsx', 'jsx']; const HTTP_EXPORTS = 'GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS'; @@ -256,7 +257,7 @@ export const nextjsResolver: FrameworkResolver = { const nodes: Node[] = []; const references: UnresolvedRef[] = []; const stripped = stripCommentsForRegex(content, 'typescript'); - const lineOf = (index: number): number => stripped.slice(0, index).split('\n').length; + const lineOf = (index: number): number => lineAt(stripped, index); if (file.kind === 'handler') { // `export async function GET(req) {…}` / `export const POST = …` — one route per method. diff --git a/src/resolution/frameworks/page-component.ts b/src/resolution/frameworks/page-component.ts index 38d311b113..bbd19847ae 100644 --- a/src/resolution/frameworks/page-component.ts +++ b/src/resolution/frameworks/page-component.ts @@ -13,6 +13,7 @@ import type { Language, Node } from '../../types'; import type { ResolutionContext, ResolvedRef, UnresolvedRef } from '../types'; +import { nodesNamed } from '../nodes-around'; /** The component name a single-file-component extractor gives a file: its basename, extension off. */ export function pageComponentName(filePath: string, extension: string): string { @@ -37,8 +38,7 @@ export function pageComponentRef(route: Node, extension: string, language: Langu /** A page route's reference to its file's own component, or null when this is not one. */ export function resolvePageComponent(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null { if (ref.referenceKind !== 'calls' || !ref.fromNodeId.startsWith(`route:${ref.filePath}:`)) return null; - const component = context - .getNodesInFile(ref.filePath) + const component = nodesNamed(context, ref.filePath, ref.referenceName) .find((n) => n.kind === 'component' && n.name === ref.referenceName); return component ? { original: ref, targetNodeId: component.id, confidence: 0.95, resolvedBy: 'framework' } : null; } diff --git a/src/resolution/frameworks/play.ts b/src/resolution/frameworks/play.ts index 1f40609ee9..4501364630 100644 --- a/src/resolution/frameworks/play.ts +++ b/src/resolution/frameworks/play.ts @@ -19,6 +19,7 @@ import { Node } from '../../types'; import { FrameworkResolver, ResolutionContext, ResolvedRef, UnresolvedRef } from '../types'; import { isPlayRoutesFile } from '../../extraction/grammars'; import { isJavaOutsideImport, retargetSelfOverload } from '../name-matcher'; +import { nodesNamed } from '../nodes-around'; const ROUTE_LINE = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\S+)\s+(.+)$/; const METHOD_KINDS = new Set(['method', 'function']); @@ -74,7 +75,7 @@ export const playResolver: FrameworkResolver = { const members = new Map(); for (const cls of group) { const memberQn = `${cls.qualifiedName}::${methodName}`; - for (const n of context.getNodesInFile(cls.filePath)) { + for (const n of nodesNamed(context, cls.filePath, methodName)) { if (METHOD_KINDS.has(n.kind) && n.name === methodName && n.qualifiedName === memberQn) members.set(n.id, n); } } diff --git a/src/resolution/frameworks/python.ts b/src/resolution/frameworks/python.ts index 777016f2ac..7667270e70 100644 --- a/src/resolution/frameworks/python.ts +++ b/src/resolution/frameworks/python.ts @@ -9,6 +9,7 @@ import { FrameworkResolver, UnresolvedRef, ResolutionContext, FrameworkExtractio import { stripCommentsForRegex } from '../strip-comments'; import { resolveImportPath } from '../import-resolver'; import { pickByNameAndKind } from './name-heuristic'; +import { lineAt } from '../synth-utils'; export const djangoResolver: FrameworkResolver = { name: 'django', @@ -76,7 +77,7 @@ export const djangoResolver: FrameworkResolver = { let match: RegExpExecArray | null; while ((match = routeRegex.exec(safe)) !== null) { const [, _fn, urlPath, handlerExpr] = match; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const routeNode: Node = { id: `route:${filePath}:${line}:${urlPath}`, @@ -118,7 +119,7 @@ export const djangoResolver: FrameworkResolver = { const prefix = match[1]!.replace(/^\^|\/?\$$/g, ''); const viewset = match[2]!.split('.').pop()!; if (!/View(Set)?$/.test(viewset)) continue; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const routeNode: Node = { id: `route:${filePath}:${line}:VIEWSET:${prefix}`, kind: 'route', @@ -332,7 +333,7 @@ export const fastapiResolver: FrameworkResolver = { own.set(file, vars); const byLine = new Map(); const deco = /@([A-Za-z_]\w*)\.(?:get|post|put|patch|delete|options|head)\s*\(/g; - while ((m = deco.exec(safe)) !== null) byLine.set(safe.slice(0, m.index).split('\n').length, m[1]!); + while ((m = deco.exec(safe)) !== null) byLine.set(lineAt(safe, m.index), m[1]!); receivers.set(file, byLine); const inc = /\b([A-Za-z_]\w*)\.include_router\s*\(\s*([A-Za-z_][\w.]*)\s*((?:,[^)]*)?)\)/g; while ((m = inc.exec(safe)) !== null) { @@ -453,7 +454,7 @@ function extractDecoratorRoutes(filePath: string, content: string, opts: Decorat const m = match[opts.methodFromGroup]!.match(/['"]([A-Z]+)['"]/i); if (m) method = m[1]!.toUpperCase(); } - const line = content.slice(0, match.index).split('\n').length; + const line = lineAt(content, match.index); const name = method ? `${method} ${routePath || '/'}` : (routePath || '/'); const routeNode: Node = { id: `route:${filePath}:${line}:${method}:${routePath}`, @@ -509,7 +510,7 @@ function extractFlaskRestful(filePath: string, safe: string): FrameworkExtractio while ((m = re.exec(safe)) !== null) { const className = m[1]!; const paths = (m[2]!.match(/['"]([^'"]+)['"]/g) || []).map((s) => s.slice(1, -1)); - const line = safe.slice(0, m.index).split('\n').length; + const line = lineAt(safe, m.index); for (const routePath of paths) { const routeNode: Node = { id: `route:${filePath}:${line}:ANY:${routePath}`, @@ -580,7 +581,7 @@ function extractFlaskUrlRules(filePath: string, safe: string): FrameworkExtracti const methods = listed ? (listed.match(/['"](\w+)['"]/g) ?? []).map((q) => q.slice(1, -1).toUpperCase()) : [classView ? 'ANY' : 'GET']; - const line = safe.slice(0, m.index).split('\n').length; + const line = lineAt(safe, m.index); const name = target.split('.').pop()!; for (const routePath of paths) { for (const method of methods) { diff --git a/src/resolution/frameworks/react-native.ts b/src/resolution/frameworks/react-native.ts index d5e71f7ca7..9508ca3acc 100644 --- a/src/resolution/frameworks/react-native.ts +++ b/src/resolution/frameworks/react-native.ts @@ -58,6 +58,7 @@ * belongs in the callback synthesizer's cross-language channel. */ import type { Node } from '../../types'; +import { lineAt } from '../synth-utils'; import { FrameworkResolver, ResolutionContext, @@ -130,11 +131,9 @@ function parseObjcRNExports( (className ? defaultObjcModuleName(className) : null); if (!moduleName) return results; - const lineOf = (idx: number): number => { - let line = 1; - for (let i = 0; i < idx && i < source.length; i++) if (source.charCodeAt(i) === 10) line++; - return line; - }; + // From the text's newline index: counted from its start for each macro, a + // module of some thousand exported methods read itself that many times. + const lineOf = (idx: number): number => (idx > 0 ? lineAt(source, idx) : 1); // RCT_EXPORT_METHOD(selectorFirstKw:(args)…) // The first keyword (everything up to the first `:` or open paren) is the @@ -191,11 +190,9 @@ export function parseObjcRNExterns( const className = remap?.[2] ?? plain?.[1] ?? null; if (!moduleName || !className) return results; - const lineOf = (idx: number): number => { - let line = 1; - for (let i = 0; i < idx && i < source.length; i++) if (source.charCodeAt(i) === 10) line++; - return line; - }; + // From the text's newline index: counted from its start for each macro, a + // module of some thousand exported methods read itself that many times. + const lineOf = (idx: number): number => (idx > 0 ? lineAt(source, idx) : 1); const methodRegex = /RCT_EXTERN_METHOD\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)/g; let m: RegExpExecArray | null; diff --git a/src/resolution/frameworks/react.ts b/src/resolution/frameworks/react.ts index 4e342d6ae3..87f0853946 100644 --- a/src/resolution/frameworks/react.ts +++ b/src/resolution/frameworks/react.ts @@ -12,10 +12,11 @@ import { resolveImportPath } from '../import-resolver'; import { defaultExportBinding, extractLocalExportAliases } from '../alias-binding'; import { stripCommentsForRegex } from '../strip-comments'; import { escapeRegExp } from '../../utils'; -import { FN_KINDS, makeLineAt } from '../synth-utils'; +import { FN_KINDS, makeLineAt, lineAt } from '../synth-utils'; import { isTestPath } from '../../search/query-utils'; import { matchBracket, skipString } from './object-literal'; import { inReferencingFolder } from './component-folder'; +import { nodesNamed } from '../nodes-around'; /** The languages React components, hooks and contexts are written and used in. */ const REACT_SCRIPT_LANGUAGES: ReadonlySet = new Set(['typescript', 'javascript', 'tsx', 'jsx']); @@ -180,7 +181,7 @@ export const reactResolver: FrameworkResolver = { const declarations = scanRouteDeclarations(content, allowsJsx(filePath)); for (const route of declarations) { const { path: routePath, parts, at } = route; - const line = content.slice(0, at).split('\n').length; + const line = lineAt(content, at); const routeNode: Node = { id: `route:${filePath}:${line}:${routePath}`, kind: 'route', @@ -314,7 +315,7 @@ function constantPathValue(expr: string, fromFile: string, context: ResolutionCo file = resolved; if (mapping.exportedName && mapping.exportedName !== 'default' && mapping.exportedName !== '*') name = mapping.exportedName; } - const decl = context.getNodesInFile(file).find((n) => n.name === name && (n.kind === 'constant' || n.kind === 'variable')); + const decl = nodesNamed(context, file, name).find((n) => n.name === name && (n.kind === 'constant' || n.kind === 'variable')); if (!decl) return null; const lines = context.readFile(file)?.split('\n') ?? []; const text = lines.slice(decl.startLine - 1, decl.endLine).join('\n'); @@ -346,7 +347,7 @@ export function configHrefExpression(expr: string, fromFile: string, context: Re file = resolved; if (mapping.exportedName && mapping.exportedName !== 'default' && mapping.exportedName !== '*') name = mapping.exportedName; } - const decl = context.getNodesInFile(file).find((n) => n.name === name && (n.kind === 'constant' || n.kind === 'variable')); + const decl = nodesNamed(context, file, name).find((n) => n.name === name && (n.kind === 'constant' || n.kind === 'variable')); if (!decl) return null; const lines = context.readFile(file)?.split('\n') ?? []; const text = lines.slice(decl.startLine - 1, decl.endLine).join('\n'); @@ -553,9 +554,8 @@ export function exportedComponent( const code = stripCommentsForRegex(context.readFile(file) ?? '', 'typescript'); const local = ownExport(code, name); if (local) { - const nodes = context.getNodesInFile(file); const declaredAs = (binding: string): Node | undefined => { - const named = nodes.filter((n) => n.name === binding && EXPORTED_COMPONENT_KINDS.has(n.kind)); + const named = nodesNamed(context, file, binding).filter((n) => n.name === binding && EXPORTED_COMPONENT_KINDS.has(n.kind)); return named.find((n) => n.qualifiedName === binding) ?? named[0]; }; const exported = declaredAs(local); @@ -727,7 +727,7 @@ export function lazyValueModules(filePath: string, context: ResolutionContext): /** The module-level `const`, `let` or `var` `filePath` declares as `name`. */ function declaredValue(name: string, filePath: string, context: ResolutionContext): Node | undefined { - return (context.getNodesInFileNamed?.(filePath, name) ?? context.getNodesInFile(filePath).filter((n) => n.name === name)) + return (context.getNodesInFileNamed?.(filePath, name) ?? nodesNamed(context, filePath, name).filter((n) => n.name === name)) .find((n) => (n.kind === 'constant' || n.kind === 'variable') && n.qualifiedName === name); } @@ -931,7 +931,7 @@ function layoutComponent(spec: string, ref: UnresolvedRef, context: ResolutionCo // import names — never a same-named component somewhere else. if (mapping.isDefault || mapping.exportedName === 'default') return lazyRouteComponent(mapping.source, ref.filePath, context); const file = resolveImportPath(mapping.source, ref.filePath, ref.language, context); - return file ? context.getNodesInFile(file).find((n) => n.name === mapping.exportedName && COMPONENT_KINDS.has(n.kind))?.id ?? null : null; + return file ? nodesNamed(context, file, mapping.exportedName).find((n) => n.name === mapping.exportedName && COMPONENT_KINDS.has(n.kind))?.id ?? null : null; } interface RouteDeclaration { @@ -1346,8 +1346,21 @@ function scanRoutes( const inherited = options.table?.layouts ?? []; const renders = (s: RouteScope): boolean => Boolean(s.component || s.lazy); const holds = (outer: RouteScope, start: number, end: number): boolean => outer.start < start && outer.end >= end; + // The scopes that reach each stretch of the source, in their own order: a + // scope around a place reaches the stretch the place is in. Looked for + // among every scope for each route, a table of eight thousand routes took + // the square of their number. + const STRETCH = 4096; + const stretches: RouteScope[][] = []; + const placed = scopes.every((s) => s.start >= 0 && s.end >= s.start && Number.isFinite(s.end)); + if (placed) { + for (const s of scopes) { + for (let b = Math.floor(s.start / STRETCH); b <= Math.floor(s.end / STRETCH); b++) (stretches[b] ??= []).push(s); + } + } + const near = (start: number): readonly RouteScope[] => (placed && start >= 0 ? stretches[Math.floor(start / STRETCH)] ?? [] : scopes); const around = (start: number, end: number): RouteScope[] => - scopes.filter((outer) => holds(outer, start, end)).sort((a, b) => a.start - b.start); + near(start).filter((outer) => holds(outer, start, end)).sort((a, b) => a.start - b.start); const shown = (p: RoutePart): string => p.lit ?? `{${p.expr}}`; const layoutOf = (s: RouteScope): string => (s.component ?? s.lazy)!; const partsOf = new Map(); @@ -1369,14 +1382,23 @@ function scanRoutes( }; const pages = new Set(scopes.filter((s) => !s.pathless && !s.opaque && (s.jsx || s.outlet || renders(s)) && addressed(s))); const layout = (c: RouteScope): boolean => renders(c) && !c.opaque; + // The pages that render something, by the path each claims. + const pagesAt = new Map(); + for (const inner of scopes) { + if (!pages.has(inner) || !renders(inner)) continue; + const path = pathOf.get(inner)!; + const same = pagesAt.get(path); + if (same) same.push(inner); + else pagesAt.set(path, [inner]); + } const routes: RouteDeclaration[] = []; for (const scope of pages) { const path = pathOf.get(scope)!; // A route around others is the layout they render inside; when one of // them claims its address, the page there is that one — not the layout, // nor a `` that only groups them. - if (scopes.some((inner) => pages.has(inner) && !inner.jsx === !scope.jsx && renders(inner) && - holds(scope, inner.start, inner.end) && pathOf.get(inner) === path)) continue; + if ((pagesAt.get(path) ?? []).some((inner) => !inner.jsx === !scope.jsx && + holds(scope, inner.start, inner.end))) continue; // A route object renders inside the route objects around it; a ``, // inside the routes around it of either kind. const layouts = [...inherited, ...around(scope.start, scope.end) @@ -2397,7 +2419,7 @@ const COMPONENT_KINDS = new Set(['component', 'function', 'class']); * owner in its qualified name; an import is no declaration. */ function ownDeclarations(name: string, filePath: string, context: ResolutionContext): Node[] { - return (context.getNodesInFileNamed?.(filePath, name) ?? context.getNodesInFile(filePath).filter((n) => n.name === name)) + return (context.getNodesInFileNamed?.(filePath, name) ?? nodesNamed(context, filePath, name).filter((n) => n.name === name)) .filter((n) => n.qualifiedName === name && n.kind !== 'import' && n.kind !== 'export' && n.kind !== 'file'); } diff --git a/src/resolution/frameworks/ruby.ts b/src/resolution/frameworks/ruby.ts index 7d81024dc5..d985de1ab3 100644 --- a/src/resolution/frameworks/ruby.ts +++ b/src/resolution/frameworks/ruby.ts @@ -7,6 +7,8 @@ import { Node } from '../../types'; import { FrameworkResolver, FrameworkExtractionResult, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types'; import { stripCommentsForRegex } from '../strip-comments'; +import { lineAt } from '../synth-utils'; +import { nodesNamed } from '../nodes-around'; /** * A `resources` line's `only:` / `except:` action list, written any way Rails @@ -146,7 +148,7 @@ export const railsResolver: FrameworkResolver = { let match: RegExpExecArray | null; while ((match = routeRegex.exec(safe)) !== null) { const [, method, routePath, ctrl, action] = match; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const upper = method!.toUpperCase(); const routeNode: Node = { id: `route:${filePath}:${line}:${upper}:${routePath}`, @@ -190,7 +192,7 @@ export const railsResolver: FrameworkResolver = { else if (except) actions = actions.filter((a) => !except.has(a)); // `resources :articles` → ArticlesController; `resource :user` → UsersController. const ctrl = plural ? resName : pluralize(resName); - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); for (const action of actions) { const spec = RESTFUL_ROUTES[action]!; const path = spec.path(resName); @@ -378,7 +380,7 @@ function resolveControllerAction(ctrlPath: string, action: string, context: Reso // Rails convention: `articles` → app/controllers/articles_controller.rb. const direct = `app/controllers/${ctrlPath}_controller.rb`; if (context.fileExists(direct)) { - const m = context.getNodesInFile(direct).find((n) => (n.kind === 'method' || n.kind === 'function') && n.name === action); + const m = nodesNamed(context, direct, action).find((n) => (n.kind === 'method' || n.kind === 'function') && n.name === action); if (m) return m.id; } // Fall back: controller class by name, then the action method in its file — @@ -392,7 +394,7 @@ function resolveControllerAction(ctrlPath: string, action: string, context: Reso const own = ctrlPath.includes('/') ? all.filter((n) => ('/' + n.filePath).endsWith(suffix)) : []; const classes = own.length > 0 ? own : all; for (const ctrl of classes) { - const m = context.getNodesInFile(ctrl.filePath).find((n) => (n.kind === 'method' || n.kind === 'function') && n.name === action); + const m = nodesNamed(context, ctrl.filePath, action).find((n) => (n.kind === 'method' || n.kind === 'function') && n.name === action); if (m) return m.id; } return null; diff --git a/src/resolution/frameworks/rust.ts b/src/resolution/frameworks/rust.ts index e147528f24..af8122efac 100644 --- a/src/resolution/frameworks/rust.ts +++ b/src/resolution/frameworks/rust.ts @@ -10,6 +10,7 @@ import { stripCommentsForRegex } from '../strip-comments'; import { getCargoWorkspaceCrateMap } from './cargo-workspace'; import { isRustNameInScope } from '../name-matcher'; import { pickByNameAndKind } from './name-heuristic'; +import { lineAt } from '../synth-utils'; /** * Whether the item a name heuristic found is one the reference can name: @@ -102,7 +103,7 @@ export const rustResolver: FrameworkResolver = { // rustfmt wraps a long `.route(` call so its handler sits below it (#2326). const handlerSite = (exprEnd: number, expr: string, handler: string) => { const offset = exprEnd - expr.length + expr.lastIndexOf(handler); - return { line: safe.slice(0, offset).split('\n').length, column: offset - safe.lastIndexOf('\n', offset - 1) - 1 }; + return { line: lineAt(safe, offset), column: offset - safe.lastIndexOf('\n', offset - 1) - 1 }; }; // Actix-web / Rocket attribute: #[get("/path")] fn handler(..) @@ -111,7 +112,7 @@ export const rustResolver: FrameworkResolver = { let match: RegExpExecArray | null; while ((match = attrRegex.exec(safe)) !== null) { const [, method, routePath] = match; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const upper = method!.toUpperCase(); const routeNode: Node = { @@ -159,7 +160,7 @@ export const rustResolver: FrameworkResolver = { const pathMatch = args.match(/^\s*"([^"]+)"\s*,/); if (!pathMatch) continue; const routePath = pathMatch[1]!; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const methodBody = args.slice(pathMatch[0].length); const bodyAt = openIdx + 1 + pathMatch[0].length; @@ -244,7 +245,7 @@ export const rustResolver: FrameworkResolver = { const resourceRegex = /web::resource\s*\(\s*"([^"]+)"\s*\)/g; while ((match = resourceRegex.exec(safe)) !== null) { const routePath = match[1]!; - const startLine = safe.slice(0, match.index).split('\n').length; + const startLine = lineAt(safe, match.index); const after = match.index + match[0].length; // Bound the resource's method chain at the next resource() to avoid bleed. const nextRes = safe.indexOf('web::resource', after); @@ -264,7 +265,7 @@ export const rustResolver: FrameworkResolver = { let m2: RegExpExecArray | null; let found = false; while ((m2 = methodTo.exec(chain)) !== null) { - const mLine = startLine + chain.slice(0, m2.index).split('\n').length - 1; + const mLine = startLine + lineAt(chain, m2.index) - 1; pushActixRoute(routePath, m2[1]!, m2[2]!, mLine, after + m2.index + m2[0].length); found = true; } @@ -278,7 +279,7 @@ export const rustResolver: FrameworkResolver = { // App-level: .route("/path", web::METHOD().to(handler)). const appRouteRegex = /\.route\s*\(\s*"([^"]+)"\s*,\s*web::(get|post|put|patch|delete|head)\s*\(\s*\)\s*\.to\s*\(\s*([A-Za-z_][\w:]*)/g; while ((match = appRouteRegex.exec(safe)) !== null) { - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); pushActixRoute(match[1]!, match[2]!, match[3]!, line, match.index + match[0].length); } diff --git a/src/resolution/frameworks/swift-objc.ts b/src/resolution/frameworks/swift-objc.ts index e12e9294ad..6991d05110 100644 --- a/src/resolution/frameworks/swift-objc.ts +++ b/src/resolution/frameworks/swift-objc.ts @@ -38,6 +38,7 @@ import { swiftBaseNamesForObjcSelector, isObjcExposed, } from '../swift-objc-bridge'; +import { linesOf } from '../synth-utils'; /** * Memoized "Swift base name → ObjC method nodes" map. @@ -157,10 +158,18 @@ const SOURCE_PROBE_LINES = 3; function declarationSourceWindow(node: Node, context: ResolutionContext): string { const content = context.readFile(node.filePath); if (!content) return ''; - const lines = content.split(/\r?\n/); + // The file's lines, split once (linesOf) where they were split for each + // ObjC message a Swift method might answer: a class of eight thousand + // `@objc` methods, each sent to once, split its file that many times. + // linesOf splits at `\n`, where this split at `\r?\n`: a line that ends + // in `\r` before its newline is read without it, as before. + const lines = linesOf(content); const startIdx = Math.max(0, node.startLine - 1 - SOURCE_PROBE_LINES); const endIdx = Math.min(lines.length, node.startLine); - return lines.slice(startIdx, endIdx).join('\n'); + return lines + .slice(startIdx, endIdx) + .map((line, i) => (startIdx + i < lines.length - 1 && line.endsWith('\r') ? line.slice(0, -1) : line)) + .join('\n'); } /** diff --git a/src/resolution/frameworks/swift.ts b/src/resolution/frameworks/swift.ts index 9ad2e95b3b..6e41471d01 100644 --- a/src/resolution/frameworks/swift.ts +++ b/src/resolution/frameworks/swift.ts @@ -8,6 +8,8 @@ import { Node } from '../../types'; import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types'; import { stripCommentsForRegex } from '../strip-comments'; import { pickByNameAndKind } from './name-heuristic'; +import { lineAt } from '../synth-utils'; +import { nodesAroundLine } from '../nodes-around'; // No extract(): a SwiftUI view is its own struct node, and a UIKit controller // its class. A one-line `component`/`class` twin per `struct X: View` (and per @@ -306,7 +308,7 @@ export const vaporResolver: FrameworkResolver = { let match: RegExpExecArray | null; while ((match = routeRegex.exec(safe)) !== null) { const [, receiver, method, segsStr, handlerExpr] = match; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const upper = method!.toUpperCase(); const routePath = (groupPrefix.get(receiver!) ?? '') + segJoin('', segsStr!) || '/'; @@ -346,7 +348,7 @@ export const vaporResolver: FrameworkResolver = { const pathArgs = (argText: string) => argText.split(',').filter((a) => /^\s*"[^"]*"\s*$/.test(a)).join(','); while ((match = onRegex.exec(safe)) !== null) { const [, receiver, method, segsStr, handlerExpr] = match; - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const routePath = (groupPrefix.get(receiver!) ?? '') + segJoin('', pathArgs(segsStr!)) || '/'; const id = `route:${filePath}:${line}:${method}:${routePath}`; nodes.push({ @@ -377,7 +379,7 @@ export const vaporResolver: FrameworkResolver = { method = on[1]!; segs = on[2]!; } - const line = safe.slice(0, match.index).split('\n').length; + const line = lineAt(safe, match.index); const routePath = (groupPrefix.get(receiver!) ?? '') + segJoin('', segs) || '/'; const id = `route:${filePath}:${line}:${method}:${routePath}`; nodes.push({ @@ -499,8 +501,7 @@ function resolveVaporHandler(typePath: string | null, method: string, ref: Unres if (typePath === null) { // `use: self.index` / `use: index`: the type whose body holds the route — // its own method in this file, else one declared in another extension of it. - const owner = context - .getNodesInFile(ref.filePath) + const owner = nodesAroundLine(context, ref.filePath, ref.line) .filter((n) => SWIFT_TYPE_KINDS.has(n.kind) && n.startLine <= ref.line && n.endLine >= ref.line) .reduce((inner, n) => (!inner || n.startLine >= inner.startLine ? n : inner), null); if (!owner) { @@ -531,8 +532,7 @@ function resolveVaporHandler(typePath: string | null, method: string, ref: Unres const declared = new RegExp(String.raw`\bextension\s+${segs.join(String.raw`\s*\.\s*`)}\b`); const inExtension = callables.filter((n) => { if (ownerOf(n) !== type) return false; - const owner = context - .getNodesInFile(n.filePath) + const owner = nodesAroundLine(context, n.filePath, n.startLine) .filter((o) => SWIFT_TYPE_KINDS.has(o.kind) && o.name === type && o.startLine <= n.startLine && o.endLine >= n.endLine) .reduce((inner, o) => (!inner || o.startLine >= inner.startLine ? o : inner), null); if (!owner) return false; diff --git a/src/resolution/frameworks/tanstack-router.ts b/src/resolution/frameworks/tanstack-router.ts index 935389fabc..2ff3c723df 100644 --- a/src/resolution/frameworks/tanstack-router.ts +++ b/src/resolution/frameworks/tanstack-router.ts @@ -62,6 +62,7 @@ import { type RouteTable, } from './expo-router'; import { destinationsForHref } from './nextjs'; +import { lineAt } from '../synth-utils'; const ROUTE_LANGUAGES: readonly Language[] = ['typescript', 'javascript', 'tsx', 'jsx']; @@ -168,7 +169,7 @@ export function parseTanstackRoutes(content: string): TanstackRouteEntry[] { if (!ROUTE_FACTORY.test(content)) return []; const safe = stripCommentsForRegex(content, 'typescript'); const out: TanstackRouteEntry[] = []; - const lineOf = (index: number): number => safe.slice(0, index).split('\n').length; + const lineOf = (index: number): number => lineAt(safe, index); // ---- file-based: the path is the first argument, the options follow ---- const fileRoutes = /\bcreate(?:Lazy)?FileRoute\s*\(/g; diff --git a/src/resolution/frameworks/vue-router.ts b/src/resolution/frameworks/vue-router.ts index a62e0629e2..f20114a7f6 100644 --- a/src/resolution/frameworks/vue-router.ts +++ b/src/resolution/frameworks/vue-router.ts @@ -65,6 +65,7 @@ import { } from './expo-router'; import { destinationsForHref } from './nextjs'; import { resolveImportPath } from '../import-resolver'; +import { lineAt } from '../synth-utils'; const ROUTE_LANGUAGES: readonly Language[] = ['typescript', 'javascript', 'vue']; @@ -139,7 +140,7 @@ export function parseVueRoutes(content: string, filePath = ''): VueRouteEntry[] const out: VueRouteEntry[] = []; const seen = new Set(); const walked = new Set(); - const lineOf = (at: number) => safe.slice(0, at).split('\n').length; + const lineOf = (at: number) => lineAt(safe, at); const visit = (obj: { start: number; end: number }, prefix: string | null, layouts: VueLayout[], depth: number): void => { const fields = readFields(safe, obj.start, obj.end); diff --git a/src/resolution/frameworks/vue.ts b/src/resolution/frameworks/vue.ts index 79e1302854..9b362227fd 100644 --- a/src/resolution/frameworks/vue.ts +++ b/src/resolution/frameworks/vue.ts @@ -11,6 +11,7 @@ import { isJsPathImportRef, resolveImportPath } from '../import-resolver'; import { dependsOn } from './package-deps'; import { pageComponentRef, resolvePageComponent } from './page-component'; import { inReferencingFolder } from './component-folder'; +import { nodesNamed } from '../nodes-around'; /** The languages a Vue app's scripts are written in. */ const VUE_SCRIPT_LANGUAGES: ReadonlySet = new Set(['vue', 'javascript', 'typescript', 'tsx', 'jsx']); @@ -325,8 +326,7 @@ function moduleFileNode(file: string | null, ref: UnresolvedRef, context: Resolu /** Does the reference's own file declare a function (or a const holding one) by that name? */ function declaresOwnFunction(ref: UnresolvedRef, context: ResolutionContext): boolean { - return context - .getNodesInFile(ref.filePath) + return nodesNamed(context, ref.filePath, ref.referenceName) .some((n) => n.name === ref.referenceName && (n.kind === 'function' || n.kind === 'constant' || n.kind === 'variable')); } @@ -358,8 +358,7 @@ function resolveComponent( if (matches.length === 0) return null; const componentIn = (file: string): string | null => { - const nodes = context.getNodesInFile(file); - const component = nodes.find((n) => n.kind === 'component' && n.name === name); + const component = nodesNamed(context, file, name).find((n) => n.kind === 'component' && n.name === name); return component ? component.id : null; }; diff --git a/src/resolution/import-lookup.ts b/src/resolution/import-lookup.ts new file mode 100644 index 0000000000..d9d22587c8 --- /dev/null +++ b/src/resolution/import-lookup.ts @@ -0,0 +1,90 @@ +/** + * A file's imports, looked up by the name each binds or by the module each is + * from. + * + * Resolving a reference asks which of its file's imports its name reads, and + * asks more than once on the way. Each ask went through all of the file's + * imports, so a generated file of some thousand imports — an icon set's + * index, a package's re-exports — went through all of them for every + * reference it holds: forty seconds for 1.2 MB of Python imports, a quarter + * of that in TypeScript or Java. + * + * Here the imports are indexed once for the array the context hands out, and + * dropped with it. A file of a few imports is still read through: it is as + * quick, and builds nothing. Every lookup answers in the imports' own order, + * as a pass over them does. + */ + +import type { ImportMapping } from './types'; + +/** Below this many imports a pass over them is as quick as a lookup. */ +const FEW_IMPORTS = 16; + +type Placed = { at: number; imp: ImportMapping }; + +/** By a file's imports, as the context hands them out: those of each local name, with their place among them. */ +const IMPORTS_BY_LOCAL_NAME = new WeakMap>(); +/** By a file's imports, as the context hands them out: those from each source, with their place among them. */ +const IMPORTS_BY_SOURCE = new WeakMap>(); + +function indexed(memo: WeakMap>, imports: ImportMapping[], key: (imp: ImportMapping) => string): Map { + let index = memo.get(imports); + if (!index) { + index = new Map(); + for (let at = 0; at < imports.length; at++) { + const imp = imports[at]!; + const same = index.get(key(imp)); + if (same) same.push({ at, imp }); + else index.set(key(imp), [{ at, imp }]); + } + memo.set(imports, index); + } + return index; +} + +const byLocalName = (imports: ImportMapping[]): Map => indexed(IMPORTS_BY_LOCAL_NAME, imports, (imp) => imp.localName); +const bySource = (imports: ImportMapping[]): Map => indexed(IMPORTS_BY_SOURCE, imports, (imp) => imp.source); + +/** The imports of `imports` bound to `name`, in their order. */ +export function importsBoundTo(imports: ImportMapping[], name: string): ImportMapping[] { + if (imports.length < FEW_IMPORTS) return imports.filter((imp) => imp.localName === name); + return byLocalName(imports).get(name)?.map((found) => found.imp) ?? []; +} + +/** The imports of `imports` from `source`, in their order. */ +export function importsFrom(imports: ImportMapping[], source: string): ImportMapping[] { + if (imports.length < FEW_IMPORTS) return imports.filter((imp) => imp.source === source); + return bySource(imports).get(source)?.map((found) => found.imp) ?? []; +} + +/** + * The imports a reference named `name` reads, in their order: the one bound + * to the name itself, and those bound to what stands before one of its dots + * (`a.b.c` reads `a` and `a.b`). What going through `imports` for + * `imp.localName === name || name.startsWith(imp.localName + '.')` gives. + */ +export function importsReadBy(imports: ImportMapping[], name: string): ImportMapping[] { + if (imports.length < FEW_IMPORTS) return imports.filter((imp) => imp.localName === name || name.startsWith(imp.localName + '.')); + const index = byLocalName(imports); + let found = index.get(name)?.slice() ?? []; + for (let dot = name.indexOf('.'); dot >= 0; dot = name.indexOf('.', dot + 1)) { + const before = index.get(name.slice(0, dot)); + if (before) found = found.concat(before); + } + return found.length <= 1 ? found.map((f) => f.imp) : found.sort((a, b) => a.at - b.at).map((f) => f.imp); +} + +/** + * The imports a Python member reference can read, in their order: those bound + * to its receiver, and those whose module its name spells out (`pkg.mod` for + * `pkg.mod.func`). The others resolvePythonModuleMember passes over. + */ +export function pythonMemberImports(imports: ImportMapping[], receiver: string, name: string): ImportMapping[] { + if (imports.length < FEW_IMPORTS) return imports; + const found = new Map(); + for (const bound of byLocalName(imports).get(receiver) ?? []) found.set(bound.at, bound.imp); + for (let dot = name.indexOf('.'); dot >= 0; dot = name.indexOf('.', dot + 1)) { + for (const spelled of bySource(imports).get(name.slice(0, dot)) ?? []) found.set(spelled.at, spelled.imp); + } + return [...found].sort((a, b) => a[0] - b[0]).map(([, imp]) => imp); +} diff --git a/src/resolution/import-resolver.ts b/src/resolution/import-resolver.ts index 62c6b28b99..c3e43dc6da 100644 --- a/src/resolution/import-resolver.ts +++ b/src/resolution/import-resolver.ts @@ -9,6 +9,7 @@ import * as fs from 'fs'; import * as path from 'path'; import { Language, Node } from '../types'; import { UnresolvedRef, ResolvedRef, ResolutionContext, ImportMapping, ReExport } from './types'; +import { importsBoundTo, importsFrom, importsReadBy, pythonMemberImports } from './import-lookup'; import { applyAliases, aliasAndBaseUrlCandidates } from './path-aliases'; import { extractLocalExportAliases } from './alias-binding'; import { resolveWorkspaceImport, workspaceImportTargets, type WorkspaceImportTargets } from './workspace-packages'; @@ -46,6 +47,7 @@ import { retargetSelfOverload, } from './name-matcher'; import { JS_ARRAY_METHODS } from './js-builtins'; +import { nodesNamed } from './nodes-around'; /** * Extension resolution order by language @@ -345,7 +347,7 @@ function moduleBindingsFirst(filePath: string, nodes: Node[]): Node[] { /** The file's nodes named `name`, in `getNodesInFile` order. */ function nodesInFileNamed(filePath: string, name: string, context: ResolutionContext): Node[] { - return context.getNodesInFileNamed?.(filePath, name) ?? context.getNodesInFile(filePath).filter((n) => n.name === name); + return context.getNodesInFileNamed?.(filePath, name) ?? nodesNamed(context, filePath, name).filter((n) => n.name === name); } /** @@ -987,14 +989,14 @@ function pythonModuleOfScript( context: ResolutionContext ): string | null { if (PYTHON_STDLIB_MODULES.has(specifier.split('.')[0]!)) return null; - const taken = context.getImportMappings(fromFile, 'python') - .filter((imp) => imp.source === specifier && !imp.isNamespace) + const taken = importsFrom(context.getImportMappings(fromFile, 'python'), specifier) + .filter((imp) => !imp.isNamespace) .map((imp) => imp.exportedName); if (taken.length === 0) return null; for (let dir = importerDir; dir; dir = parentDir(dir)) { if (dir !== importerDir && index.packageDirs.has(dir)) continue; const file = pythonModuleUnder(dir, relPath, index); - if (!file || context.getImportMappings(file, 'python').some((imp) => imp.source === specifier)) continue; + if (!file || importsFrom(context.getImportMappings(file, 'python'), specifier).length > 0) continue; const defined = new Set(context.getNodesInFile(file).filter(isPythonModuleLevelDef).map((n) => n.name)); if (taken.every((name) => defined.has(name))) return file; } @@ -2060,10 +2062,10 @@ export function extractImportMappings( content: string, language: Language ): ImportMapping[] { - const mappings: ImportMapping[] = []; - + // Each language's list is handed on as it is. Spread into a `push`, a + // file of some hundred thousand imports overflowed the stack. if (language === 'typescript' || language === 'javascript' || language === 'tsx' || language === 'jsx' || language === 'arkts') { - mappings.push(...extractJSImports(content)); + return extractJSImports(content); } else if (language === 'svelte' || language === 'vue' || language === 'astro') { // Svelte/Vue single-file components import via plain ES6 inside their // `` in the raw source of a Svelte or Astro file was taken for a script block and handed to the JavaScript or TypeScript extractor, wherever it was written. The usual way to emit structured data, {@html ``} is a string in a template expression. Its "body", `${…}`, does not parse, so the file was stored with "parse produced no symbols … contributes nothing to the graph" and `status` listed it under "could not be parsed", beside its real symbols. With the closing tag escaped (`<\/script>`) and the component's script written below the markup, the string's `` and the component lost every symbol. Astro read a `` in the raw source was taken for a script block + * and handed to the JavaScript or TypeScript extractor, wherever it was + * written. The common way to emit structured data, + * + * {@html ``} + * + * is a string inside a template expression: its "body" is `${…}`, which does + * not parse, so the file was stored with "parse produced no symbols — the + * file is indexed but contributes nothing to the graph" and `status` listed + * it under "could not be parsed", though its real script was indexed. With + * the closing tag escaped (`<\/script>`) and the component's script written + * after the markup, the string's `` + * and the component lost every symbol. + * + * A `', + '', + `{@html ${T}${T}}`, + '', + '

    {hello()}

    ', +); +const ESCAPED = LITERAL.replace('`}', '<\\/script>`}'); +const ONLY = lines('', '', '

    {hello()}

    '); + +describe('a ', + )); + expect(r.errors).toEqual([]); + expect(symbols(r)).toEqual(['later@6', 'ready@5']); + // The markup between the two is still read. + expect(calls(r)).toEqual(expect.arrayContaining(['JSON.stringify@1', 'fmt@2'])); + expect(r.unresolvedReferences.some((u) => u.referenceName === 'Header' && u.line === 3)).toBe(true); + }); + + it('holds for a template literal over several lines, with JavaScript in it', () => { + const r = extractFromSource('src/routes/+layout.svelte', lines( + '', + `{@html ${T}`, + '\t', + `${T}}`, + )); + expect(r.errors).toEqual([]); + // `boot` is text the page is sent, not a function of this component. + expect(symbols(r)).toEqual(['real@2']); + expect(calls(r)).toContain('serialize@6'); + }); + + it('holds for a string, a concatenation and a nested template', () => { + for (const expression of [ + `{@html ''}`, + `{@html ""}`, + `{@html ${T}\${head ? ${T}${T} : ''}${T}}`, + `{@html ${T}${T}}`, + `\${JSON.stringify(schema)}${T}} />`, + ]) { + const r = extractFromSource('src/routes/+page.svelte', lines(expression, '')); + expect(r.errors, expression).toEqual([]); + expect(symbols(r), expression).toEqual(['real@3']); + } + }); + + it('reads past braces, strings and comments inside an expression to its end', () => { + const r = extractFromSource('src/lib/List.svelte', lines( + '{#each items as { id, name } (id)}', + `\t
  • {name}
  • `, + '{/each}', + `{@html /* */ note(${T}${T})}`, + '', + )); + expect(r.errors).toEqual([]); + expect(symbols(r)).toEqual(['real@6']); + expect(calls(r)).toContain('label@2'); + }); + + it('never hides the script that follows an expression or a comment it cannot close', () => { + for (const markup of [ + '

    {oops

    ', + '', + '', + '', + )); + expect(r.errors).toEqual([]); + expect(symbols(r)).toEqual(['current@5']); + }); + + it('is not read inside a quoted attribute value', () => { + const r = extractFromSource('src/lib/Frame.svelte', lines( + '', + '', + ``, + )); + expect(r.errors).toEqual([]); + expect(symbols(r)).toEqual(['real@2']); + }); +}); + +describe('a ', + '', + '', + '', + '', + ]) { + for (const markup of [`\n\t${data}\n`, data]) { + const r = extractFromSource('src/routes/+layout.svelte', lines('', markup, '

    {fmt(ready)}

    ')); + expect(r.errors, markup).toEqual([]); + expect(symbols(r), markup).toEqual(['ready@2']); + expect(calls(r).map((c) => c.replace(/@\d+$/, '')), markup).toEqual(['fmt']); + expect(r.unresolvedReferences.some((u) => u.referenceName === 'Row'), markup).toBe(false); + } + } + }); + + it('still reads a type that is JavaScript', () => { + for (const attribute of [ + 'type="module"', + 'type="text/javascript"', + 'type="text/javascript; charset=utf-8"', + 'type="application/javascript"', + 'type="text/partytown"', + 'type="text/typescript"', + // svelte-preprocess's bare name. + 'type="ts"', + // Not a `type` at all. + 'data-type="lazy"', + ]) { + const r = extractFromSource('src/routes/+layout.svelte', lines( + '', + `\t', + '', + )); + expect(r.errors, attribute).toEqual([]); + expect(symbols(r), attribute).toEqual(['track@3']); + } + }); +}); + +describe("a Svelte component's own scripts", () => { + it('are found before and after markup, module and instance, around an inline one', () => { + for (const module of ['context="module"', 'module']) { + const r = extractFromSource('src/lib/Card.svelte', lines( + `', + '', + '', + `\t{@html ${T}${T}}`, + '', + '
    {title(card)}
    ', + '', + '', + )); + expect(r.errors, module).toEqual([]); + expect(symbols(r), module).toEqual(expect.arrayContaining(['load@3', 'prerender@2', 'schema@14', 'toggle@15'])); + expect(symbols(r).some((s) => /@(?:[5-9]|10)$/.test(s)), module).toBe(false); + // Runes are the compiler's, not calls; the rest are the component's. + const made = calls(r); + expect(made, module).toEqual(expect.arrayContaining(['fetchCard@3', 'JSON.stringify@7', 'title@9', 'toSchema@14'])); + expect(made.some((c) => c.startsWith('$')), module).toBe(false); + } + }); + + it('keep a JavaScript ', + '', + '', + )); + expect(r.errors).toEqual([]); + expect(symbols(r)).toEqual(['a@8', 'gtag@4']); + }); + + it('read an opening tag whose quoted attribute holds a ">"', () => { + const r = extractFromSource('src/lib/Pick.svelte', lines( + '', + '

    {pick()}

    ', + )); + expect(r.errors).toEqual([]); + expect(symbols(r)).toEqual(['first@1', 'pick@2']); + }); +}); + +describe('a ${T};`, + 'function front() { return tag; }', + '---', + '', + '', + )); + expect(r.errors).toEqual([]); + expect(symbols(r)).toEqual(['client@8', 'front@4', 'schema@2', 'tag@3']); + // Read once, as frontmatter. + expect(calls(r).filter((c) => c === 'JSON.stringify@3')).toHaveLength(1); + }); + + it('is not a script block in a set:html template literal', () => { + const r = extractFromSource('src/pages/index.astro', lines( + '---', + 'const schema = { a: 1 };', + '---', + `\${JSON.stringify(schema)}${T}} />`, + '

    {fmt(schema)}

    ', + `
    \${fmt(schema)}${T}>
    `, + '', + )); + expect(r.errors).toEqual([]); + expect(symbols(r)).toEqual(['schema@2']); + expect(calls(r)).toEqual(expect.arrayContaining(['JSON.stringify@4', 'fmt@5'])); + }); + + it('is still one as an element inside an expression', () => { + const r = extractFromSource('src/pages/index.astro', lines( + '---', + 'const on = true;', + '---', + '{on && }', + '{on ? : }', + )); + expect(r.errors).toEqual([]); + expect(symbols(r)).toEqual(['a@5', 'b@5', 'on@2', 'track@4']); + }); + + it('is data, not TypeScript, when its type is not JavaScript', () => { + const r = extractFromSource('src/pages/index.astro', lines( + '---', + 'const a = 1;', + '---', + '', + '', + '

    {fmt(a)}

    ', + )); + expect(r.errors).toEqual([]); + expect(symbols(r)).toEqual(['a@2']); + expect(calls(r)).toEqual(['fmt@6']); + }); +}); + +describe('the viewer highlights the scripts the extractor read', () => { + it('not the one inside an expression, nor one that is data', () => { + const body = (source: string, host: 'svelte' | 'astro') => syntaxRegionsFor(source, host)?.map((r) => source.slice(r.start, r.end)); + expect(body(LITERAL, 'svelte')).toEqual(['\n\tconst x = 1;\n\tfunction hello() { return x; }\n']); + expect(body('\n\n', 'svelte')).toEqual(['\nlet x = 1;\n']); + expect(body(`---\nconst a = 1;\n---\n\${a}${T}} />\n\n`, 'astro')) + .toEqual(['const a = 1;', '\nlet x = 1;\n']); + }); +}); + +describe.each(['default', 'wasm'])('an indexed project with a ', + ), + }; + for (const [rel, content] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true }); + fs.writeFileSync(path.join(root, rel), content); + } + cg = await CodeGraph.init(root, { index: true }); + }, 60_000); + + afterAll(() => { + cg?.close(); + fs.rmSync(root, { recursive: true, force: true }); + if (kernel === undefined) delete process.env.CODEGRAPH_KERNEL; + else process.env.CODEGRAPH_KERNEL = kernel; + }); + + it('lists no file as unparsed', () => { + expect(cg!.getIndexHealth().parseErrors).toEqual([]); + }); + + it('has the function of every file, the one written after the markup too', () => { + const where = cg!.getNodesByKind('function').filter((n) => n.name === 'hello').map((n) => `${n.filePath}:${n.startLine}`).sort(); + expect(where).toEqual(['a-literal.svelte:3', 'b-escaped.svelte:3', 'c-only.svelte:3', 'src/routes/+page.svelte:5']); + }); +}); diff --git a/src/extraction/astro-extractor.ts b/src/extraction/astro-extractor.ts index 0ecba779aa..37333a0bdc 100644 --- a/src/extraction/astro-extractor.ts +++ b/src/extraction/astro-extractor.ts @@ -2,7 +2,7 @@ import { Node, Edge, ExtractionResult, ExtractionError, UnresolvedReference } fr import { generateNodeId } from './tree-sitter-helpers'; import { TreeSitterExtractor } from './tree-sitter'; import { isLanguageSupported } from './grammars'; -import { foldScriptResult, sfcFileNode, SFC_SCRIPT_ELEMENT, sfcBlockLineRanges } from './sfc-script'; +import { foldScriptResult, sfcFileNode, sfcMarkupElements, sfcElementLineRanges, isJavaScriptBlock, type SfcMarkupElement } from './sfc-script'; /** * Astro built-in components — compiler-provided (``) or shipped by @@ -33,12 +33,21 @@ export class AstroExtractor { private edges: Edge[] = []; private unresolvedReferences: UnresolvedReference[] = []; private errors: ExtractionError[] = []; + private markupElements: SfcMarkupElement[] | null = null; constructor(filePath: string, source: string) { this.filePath = filePath; this.source = source; } + /** + * The ``. - const scriptRegex = new RegExp(SFC_SCRIPT_ELEMENT); - let match; - - while ((match = scriptRegex.exec(this.source)) !== null) { - if (match.groups?.content === undefined) continue; - const content = match.groups.content; - - // Calculate the 0-indexed line where the content begins. The content - // starts right after the opening tag's `>` — its leading `\n` is part - // of the content, so relative line 1 sits ON the tag's closing line - // (do not add 1 here; that double-counts the embedded newline). - const beforeScript = this.source.substring(0, match.index); - const scriptTagLine = (beforeScript.match(/\n/g) || []).length; - const openingTag = match[0].substring(0, match[0].indexOf('>') + 1); - const openingTagLines = (openingTag.match(/\n/g) || []).length; - const contentStartLine = scriptTagLine + openingTagLines; // 0-indexed + // body, and one whose `type` is not JavaScript (`application/ld+json`, + // a `text/template`) holds data. + for (const element of this.elements()) { + if (element.tag !== 'script' || element.content === undefined || !isJavaScriptBlock(element.attrs)) continue; + const content = element.content; + + // The 0-indexed line where the content begins. The content starts right + // after the opening tag's `>` — its leading `\n` is part of the content, + // so relative line 1 sits ON the tag's closing line (do not add 1 here; + // that double-counts the embedded newline). + const contentStartLine = (this.source.substring(0, element.contentIndex).match(/\n/g) || []).length; blocks.push({ content, startLine: contentStartLine }); } @@ -230,7 +233,7 @@ export class AstroExtractor { // A self-closing tag covers nothing: its attributes // (`set:html={serializeJsonLd(schema)}`) are template expressions. - coveredRanges.push(...sfcBlockLineRanges(this.source)); + coveredRanges.push(...sfcElementLineRanges(this.source, this.elements())); return coveredRanges; } diff --git a/src/extraction/razor-script.ts b/src/extraction/razor-script.ts index be5a9c9e68..5aec613a87 100644 --- a/src/extraction/razor-script.ts +++ b/src/extraction/razor-script.ts @@ -235,9 +235,4 @@ export function blankRazorComments(source: string): string { return out.join(''); } -/** Whether a ``, and that script was parsed with the markup in between and * contributed nothing (#2989). * - * Shared by the three extractors and the viewer's syntax regions. It carries - * the `g` flag, so each loop runs on its own copy (`new RegExp(...)`). + * Read by the Vue and Razor extractors and, for Vue, the viewer's syntax + * regions; Svelte and Astro take their elements from {@link sfcMarkupElements}, + * which reads the markup around them. It carries the `g` flag, so each loop + * runs on its own copy (`new RegExp(...)`). */ export const SFC_SCRIPT_ELEMENT = /]*?)?(?:\/>|>(?[\s\S]*?)<\/script\s*>)/g; @@ -91,6 +93,345 @@ export function sfcBlockLineRanges(source: string): Array<[number, number]> { return ranges; } +/** + * Whether a ``} + * + * That "element" was handed to the TypeScript extractor, `${…}` did not + * parse, and the file was recorded as unparsed beside its real symbols. With + * the closing tag escaped (`<\/script>`) it ran on to the `` of the + * component's own script below, and the component lost every symbol. + * + * So the markup is read from the top, and what is not markup is stepped over: + * + * - an HTML comment; + * - a template expression `{…}`, to its own closing brace, through the + * strings, template literals, comments and braces of the JavaScript in + * it. Svelte has no markup inside an expression. Astro does (JSX), so an + * element there counts, outside the expression's strings; + * - a quoted attribute value (`srcdoc=""`), and in Astro + * a template-literal one; + * - Astro's frontmatter; + * - the body of each element found, which is code or CSS. + * + * Whatever cannot be closed (a `{` with no `}`, a quote alone on its line, a + * regex literal read as something else) is left as text and the scan goes on + * behind it, and a Svelte expression that reaches a `