1+ import { createHash } from 'crypto'
12import * as fs from 'fs'
23import * as path from 'path'
34
4- import { getLanguageConfig } from './languages'
5+ import {
6+ findLanguageConfigByExtension ,
7+ getLanguageConfig ,
8+ languageTable ,
9+ loadQueryText ,
10+ } from './languages'
511
612import type { LanguageConfig } from './languages'
713import 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
4592type 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+
264339function 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