Skip to content

Commit ee6f617

Browse files
Sync public snapshot from freebuff-private
1 parent c2ce3b6 commit ee6f617

6 files changed

Lines changed: 597 additions & 33 deletions

File tree

‎packages/code-map/__tests__/parse.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@ import {
66
} from '@codebuff/common/testing/mocks/tree-sitter'
77
import { describe, it, expect } from 'bun:test'
88

9+
import packageJson from '../package.json'
910
import {
1011
parseTokens,
1112
DEBUG_PARSING,
13+
GRAMMAR_PACKAGES,
1214
getFileTokenScores,
1315
type TokenCallerMap,
1416
type FileTokenData,
@@ -637,4 +639,14 @@ console.log('Total:', formatCurrency(total));
637639
expect(result.tokenCallers).toBeDefined()
638640
})
639641
})
642+
643+
// Users' parse caches are keyed on these versions: a grammar upgrade they
644+
// miss would keep serving parses from the old grammar.
645+
it('keys the parse cache on the installed grammar packages', () => {
646+
for (const name of ['web-tree-sitter', '@vscode/tree-sitter-wasm']) {
647+
const version =
648+
packageJson.dependencies[name as keyof typeof packageJson.dependencies]
649+
expect(GRAMMAR_PACKAGES.split(' ')).toContain(`${name}@${version}`)
650+
}
651+
})
640652
})

‎packages/code-map/src/languages.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,13 @@ export function findLanguageConfigByExtension(
250250
return languageTable.find((c) => c.extensions.includes(ext))
251251
}
252252

253+
/** When loaded with bun, the query is a path to the file, not its content. */
254+
export function loadQueryText(cfg: LanguageConfig): string {
255+
return path.isAbsolute(cfg.queryPathOrContent)
256+
? fs.readFileSync(cfg.queryPathOrContent, 'utf8')
257+
: cfg.queryPathOrContent
258+
}
259+
253260
/* ------------------------------------------------------------------ */
254261
/* 10. Language configuration loader */
255262
/* ------------------------------------------------------------------ */
@@ -273,14 +280,9 @@ export async function createLanguageConfig(
273280
const parser = new Parser()
274281
parser.setLanguage(lang)
275282

276-
// When loaded with bun, the queryText is a path to the file, not the content of the file.
277-
const queryContent = path.isAbsolute(cfg.queryPathOrContent)
278-
? fs.readFileSync(cfg.queryPathOrContent, 'utf8')
279-
: cfg.queryPathOrContent
280-
281283
cfg.language = lang
282284
cfg.parser = parser
283-
cfg.query = new Query(lang, queryContent)
285+
cfg.query = new Query(lang, loadQueryText(cfg))
284286
} catch (err) {
285287
// Let the runtime-specific implementation handle error logging
286288
throw err

‎packages/code-map/src/parse.ts‎

Lines changed: 100 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
1+
import { createHash } from 'crypto'
12
import * as fs from 'fs'
23
import * as path from 'path'
34

4-
import { getLanguageConfig } from './languages'
5+
import {
6+
findLanguageConfigByExtension,
7+
getLanguageConfig,
8+
languageTable,
9+
loadQueryText,
10+
} from './languages'
511

612
import type { LanguageConfig } from './languages'
713
import type { Parser, Query } from 'web-tree-sitter'
@@ -37,9 +43,50 @@ type ParsedTokens = {
3743
calls: string[]
3844
}
3945

40-
type ParsedTokensForScoring = ParsedTokens & {
46+
/** One file's parse. It depends only on the file's text and its grammar. */
47+
export type ParsedSource = ParsedTokens & {
48+
/** The text's length as the parse byte limits count it. */
4149
bytes: number
42-
skipped: boolean
50+
}
51+
52+
/** `failed` (the read or parse threw) still counts as a parsed file with no
53+
* tokens; `skipped` (over a limit, or no text) does not count at all. */
54+
type ParsedTokensForScoring = ParsedSource & {
55+
status: 'parsed' | 'failed' | 'skipped'
56+
}
57+
58+
/** Parses kept from an earlier build, so a build re-parses only the files that
59+
* changed. `get` is asked before a file is read and answers only while the
60+
* file is unchanged since its parse was stored; `set` receives each
61+
* successful parse of a file this build read. */
62+
export interface ParseCache {
63+
get(filePath: string): Promise<ParsedSource | undefined>
64+
set(filePath: string, parsed: ParsedSource): void
65+
}
66+
67+
/** Bump when the same text would parse to different tokens. */
68+
const PARSE_FORMAT = 1
69+
/** The grammar packages in package.json, which a test keeps in step. */
70+
export const GRAMMAR_PACKAGES =
71+
'web-tree-sitter@0.25.10 @vscode/tree-sitter-wasm@0.1.4'
72+
73+
let parseCacheVersion: string | undefined
74+
75+
/** Names everything a stored parse depends on besides the file's text: the
76+
* parse format, the grammars and every language's query. A cache stored under
77+
* another version must be discarded. */
78+
export function getParseCacheVersion(): string {
79+
if (parseCacheVersion) return parseCacheVersion
80+
const hash = createHash('sha256').update(
81+
`${PARSE_FORMAT}\n${GRAMMAR_PACKAGES}`,
82+
)
83+
for (const language of languageTable) {
84+
hash.update(
85+
`\n${language.extensions.join(',')}\n${language.wasmFile}\n${loadQueryText(language)}`,
86+
)
87+
}
88+
parseCacheVersion = hash.digest('hex')
89+
return parseCacheVersion
4390
}
4491

4592
type SourceReader = (filePath: string) => string | null | Promise<string | null>
@@ -64,6 +111,7 @@ export async function getFileTokenScores(
64111
projectRoot: string,
65112
filePaths: string[],
66113
readFile?: SourceReader,
114+
cache?: ParseCache,
67115
): Promise<FileTokenData> {
68116
const startTime = Date.now()
69117
const tokenScores: Record<string, Record<string, number>> = {}
@@ -81,17 +129,36 @@ export async function getFileTokenScores(
81129
}
82130

83131
const fullPath = path.join(projectRoot, filePath)
84-
const languageConfig = await getLanguageConfig(fullPath)
85-
if (!languageConfig) continue
86-
87-
const parsed = await parseTokensForScoring({
88-
filePath,
89-
fullPath,
90-
languageConfig,
91-
readFile,
92-
remainingBytes: MAX_TOTAL_PARSE_BYTES - totalParsedBytes,
93-
})
94-
if (parsed.skipped) continue
132+
if (!findLanguageConfigByExtension(fullPath)) continue
133+
134+
const remainingBytes = MAX_TOTAL_PARSE_BYTES - totalParsedBytes
135+
const cached = await cache?.get(filePath)
136+
let parsed: ParsedTokensForScoring
137+
if (cached) {
138+
parsed = fitsParseLimits(
139+
cached.bytes,
140+
MAX_PARSE_FILE_BYTES,
141+
remainingBytes,
142+
)
143+
? { ...cached, status: 'parsed' }
144+
: emptyParsedTokens('skipped')
145+
} else {
146+
const languageConfig = await getLanguageConfig(fullPath)
147+
if (!languageConfig) continue
148+
149+
parsed = await parseTokensForScoring({
150+
filePath,
151+
fullPath,
152+
languageConfig,
153+
readFile,
154+
remainingBytes,
155+
})
156+
if (parsed.status === 'parsed') {
157+
const { numLines, identifiers, calls, bytes } = parsed
158+
cache?.set(filePath, { numLines, identifiers, calls, bytes })
159+
}
160+
}
161+
if (parsed.status === 'skipped') continue
95162

96163
parsedFiles++
97164
totalParsedBytes += parsed.bytes
@@ -175,7 +242,7 @@ async function parseTokensForScoring(params: {
175242
console.error(`Error reading source: ${e}`)
176243
console.log(filePath)
177244
}
178-
return emptyParsedTokens(false)
245+
return emptyParsedTokens('failed')
179246
}
180247
}
181248

@@ -191,7 +258,7 @@ function parseTokensWithLimits(
191258
const maxBytes = options.maxBytes ?? MAX_PARSE_FILE_BYTES
192259
const remainingBytes = options.remainingBytes ?? MAX_TOTAL_PARSE_BYTES
193260
if (remainingBytes <= 0) {
194-
return emptyParsedTokens(true)
261+
return emptyParsedTokens('skipped')
195262
}
196263

197264
const source = loadSourceWithinLimits({
@@ -201,7 +268,7 @@ function parseTokensWithLimits(
201268
remainingBytes,
202269
})
203270
if (!source) {
204-
return emptyParsedTokens(true)
271+
return emptyParsedTokens('skipped')
205272
}
206273

207274
if (!parser || !query) {
@@ -223,14 +290,14 @@ function parseTokensWithLimits(
223290
identifiers: identifiers ?? [],
224291
calls: calls ?? [],
225292
bytes: source.bytes,
226-
skipped: false,
293+
status: 'parsed',
227294
}
228295
} catch (e) {
229296
if (DEBUG_PARSING) {
230297
console.error(`Error parsing query: ${e}`)
231298
console.log(filePath)
232299
}
233-
return emptyParsedTokens(false)
300+
return emptyParsedTokens('failed')
234301
}
235302
}
236303

@@ -244,7 +311,7 @@ function loadSourceWithinLimits(params: {
244311

245312
if (!readFile) {
246313
const bytes = fs.statSync(filePath).size
247-
if (bytes > maxBytes || bytes > remainingBytes) return null
314+
if (!fitsParseLimits(bytes, maxBytes, remainingBytes)) return null
248315

249316
return {
250317
code: fs.readFileSync(filePath, 'utf8'),
@@ -256,11 +323,19 @@ function loadSourceWithinLimits(params: {
256323
if (code === null) return null
257324

258325
const bytes = Buffer.byteLength(code, 'utf8')
259-
if (bytes > maxBytes || bytes > remainingBytes) return null
326+
if (!fitsParseLimits(bytes, maxBytes, remainingBytes)) return null
260327

261328
return { code, bytes }
262329
}
263330

331+
function fitsParseLimits(
332+
bytes: number,
333+
maxBytes: number,
334+
remainingBytes: number,
335+
): boolean {
336+
return bytes <= maxBytes && bytes <= remainingBytes
337+
}
338+
264339
function scoreFileTokens(fullPath: string, parsed: ParsedTokens): FileCallData {
265340
const scores: Record<string, number> = {}
266341
const dirs = path.dirname(fullPath).split(path.sep)
@@ -329,13 +404,15 @@ function boostScoresByExternalCalls(
329404
}
330405
}
331406

332-
function emptyParsedTokens(skipped: boolean): ParsedTokensForScoring {
407+
function emptyParsedTokens(
408+
status: 'failed' | 'skipped',
409+
): ParsedTokensForScoring {
333410
return {
334411
numLines: 0,
335412
identifiers: [],
336413
calls: [],
337414
bytes: 0,
338-
skipped,
415+
status,
339416
}
340417
}
341418

0 commit comments

Comments
 (0)