-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathwasm-worker-entry.ts
More file actions
894 lines (840 loc) · 28.3 KB
/
Copy pathwasm-worker-entry.ts
File metadata and controls
894 lines (840 loc) · 28.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
/**
* WASM parse worker entry point.
*
* Runs as a Node.js `worker_threads` worker. Owns every tree-sitter WASM call
* so that fatal V8 aborts from the grammar (#965) kill only this worker —
* never the main build process.
*
* For each `parse` request:
* 1. Pick the language by file extension.
* 2. Lazy-load the WASM grammar (first request per language).
* 3. Parse the source.
* 4. Run the extractor.
* 5. Run the unified AST visitor walk (ast-store, complexity, CFG, dataflow)
* so that all analysis data is pre-computed before the tree is freed.
* 6. `tree.delete()` in a finally block to release WASM linear memory.
* 7. Serialize ExtractorOutput to a structured-clone-safe form and respond.
*
* The worker does NOT import from `./parser.js` — that module owns
* process-global parser/grammar caches that are not worker-safe. Instead
* this file keeps its own per-worker caches and its own (local) language
* registry. Extractors are imported directly from `../extractors/index.js`.
*/
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parentPort } from 'node:worker_threads';
import type { Tree } from 'web-tree-sitter';
import { Language, Parser, Query } from 'web-tree-sitter';
import { computeLOCMetrics, computeMaintainabilityIndex } from '../ast-analysis/metrics.js';
import {
AST_STRING_CONFIGS,
AST_TYPE_MAPS,
astStopRecurseKinds,
CFG_RULES,
COMPLEXITY_RULES,
DATAFLOW_RULES,
HALSTEAD_RULES,
} from '../ast-analysis/rules/index.js';
import { walkWithVisitors } from '../ast-analysis/visitor.js';
import { functionName as getFuncName } from '../ast-analysis/visitor-utils.js';
import { createAstStoreVisitor } from '../ast-analysis/visitors/ast-store-visitor.js';
import { createCfgVisitor } from '../ast-analysis/visitors/cfg-visitor.js';
import { createComplexityVisitor } from '../ast-analysis/visitors/complexity-visitor.js';
import { createDataflowVisitor } from '../ast-analysis/visitors/dataflow-visitor.js';
import {
extractBashSymbols,
extractClojureSymbols,
extractCppSymbols,
extractCSharpSymbols,
extractCSymbols,
extractCudaSymbols,
extractDartSymbols,
extractElixirSymbols,
extractErlangSymbols,
extractFSharpSymbols,
extractGleamSymbols,
extractGoSymbols,
extractGroovySymbols,
extractHaskellSymbols,
extractHCLSymbols,
extractJavaSymbols,
extractJuliaSymbols,
extractKotlinSymbols,
extractLuaSymbols,
extractObjCSymbols,
extractOCamlSymbols,
extractPHPSymbols,
extractPythonSymbols,
extractRSymbols,
extractRubySymbols,
extractRustSymbols,
extractScalaSymbols,
extractSoliditySymbols,
extractSwiftSymbols,
extractSymbols,
extractVerilogSymbols,
extractZigSymbols,
} from '../extractors/index.js';
import type {
CfgBlock,
CfgEdge,
DataflowResult,
Definition,
ExtractorOutput,
LanguageId,
LanguageRegistryEntry,
TreeSitterNode,
Visitor,
WalkOptions,
WalkResults,
} from '../types.js';
import type {
SerializedExtractorOutput,
WorkerParseRequest,
WorkerRequest,
WorkerResponse,
} from './wasm-worker-protocol.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/** Grammars ship at `<repo-root>/grammars/`. Worker file is at
* `src/domain/wasm-worker-entry.ts` (or `dist/domain/wasm-worker-entry.js`);
* both resolve to the same relative path. */
function grammarPath(name: string): string {
return path.join(__dirname, '..', '..', 'grammars', name);
}
// ── Shared JS/TS/TSX query patterns (mirrors parser.ts) ─────────────────────
const COMMON_QUERY_PATTERNS: string[] = [
'(function_declaration name: (identifier) @fn_name) @fn_node',
'(variable_declarator name: (identifier) @varfn_name value: (arrow_function) @varfn_value)',
'(variable_declarator name: (identifier) @varfn_name value: (function_expression) @varfn_value)',
'(method_definition name: (property_identifier) @meth_name) @meth_node',
'(method_definition name: (private_property_identifier) @meth_name) @meth_node',
'(import_statement source: (string) @imp_source) @imp_node',
'(export_statement) @exp_node',
'(call_expression function: (identifier) @callfn_name) @callfn_node',
'(call_expression function: (member_expression) @callmem_fn) @callmem_node',
'(call_expression function: (subscript_expression) @callsub_fn) @callsub_node',
'(new_expression constructor: (identifier) @newfn_name) @newfn_node',
'(new_expression constructor: (member_expression) @newmem_fn) @newmem_node',
'(expression_statement (assignment_expression left: (member_expression) @assign_left right: (_) @assign_right)) @assign_node',
];
const JS_CLASS_PATTERN: string = '(class_declaration name: (identifier) @cls_name) @cls_node';
const TS_EXTRA_PATTERNS: string[] = [
'(class_declaration name: (type_identifier) @cls_name) @cls_node',
'(abstract_class_declaration name: (type_identifier) @cls_name) @cls_node',
'(interface_declaration name: (type_identifier) @iface_name) @iface_node',
'(type_alias_declaration name: (type_identifier) @type_name) @type_node',
];
// ── Local language registry ─────────────────────────────────────────────────
// Local copy — re-using parser.ts's registry would drag in its process-wide
// parser/grammar caches, which are not safe to share across worker threads.
const LANGUAGE_REGISTRY: LanguageRegistryEntry[] = [
{
id: 'javascript',
extensions: ['.js', '.jsx', '.mjs', '.cjs'],
grammarFile: 'tree-sitter-javascript.wasm',
extractor: extractSymbols,
required: true,
},
{
id: 'typescript',
extensions: ['.ts'],
grammarFile: 'tree-sitter-typescript.wasm',
extractor: extractSymbols,
required: true,
},
{
id: 'tsx',
extensions: ['.tsx'],
grammarFile: 'tree-sitter-tsx.wasm',
extractor: extractSymbols,
required: true,
},
{
id: 'hcl',
extensions: ['.tf', '.hcl'],
grammarFile: 'tree-sitter-hcl.wasm',
extractor: extractHCLSymbols,
required: false,
},
{
id: 'python',
extensions: ['.py', '.pyi'],
grammarFile: 'tree-sitter-python.wasm',
extractor: extractPythonSymbols,
required: false,
},
{
id: 'go',
extensions: ['.go'],
grammarFile: 'tree-sitter-go.wasm',
extractor: extractGoSymbols,
required: false,
},
{
id: 'rust',
extensions: ['.rs'],
grammarFile: 'tree-sitter-rust.wasm',
extractor: extractRustSymbols,
required: false,
},
{
id: 'java',
extensions: ['.java'],
grammarFile: 'tree-sitter-java.wasm',
extractor: extractJavaSymbols,
required: false,
},
{
id: 'csharp',
extensions: ['.cs'],
grammarFile: 'tree-sitter-c_sharp.wasm',
extractor: extractCSharpSymbols,
required: false,
},
{
id: 'ruby',
extensions: ['.rb', '.rake', '.gemspec'],
grammarFile: 'tree-sitter-ruby.wasm',
extractor: extractRubySymbols,
required: false,
},
{
id: 'php',
extensions: ['.php', '.phtml'],
grammarFile: 'tree-sitter-php.wasm',
extractor: extractPHPSymbols,
required: false,
},
{
id: 'c',
extensions: ['.c', '.h'],
grammarFile: 'tree-sitter-c.wasm',
extractor: extractCSymbols,
required: false,
},
{
id: 'cpp',
extensions: ['.cpp', '.cc', '.cxx', '.hpp'],
grammarFile: 'tree-sitter-cpp.wasm',
extractor: extractCppSymbols,
required: false,
},
{
id: 'kotlin',
extensions: ['.kt', '.kts'],
grammarFile: 'tree-sitter-kotlin.wasm',
extractor: extractKotlinSymbols,
required: false,
},
{
id: 'swift',
extensions: ['.swift'],
grammarFile: 'tree-sitter-swift.wasm',
extractor: extractSwiftSymbols,
required: false,
},
{
id: 'scala',
extensions: ['.scala'],
grammarFile: 'tree-sitter-scala.wasm',
extractor: extractScalaSymbols,
required: false,
},
{
id: 'bash',
extensions: ['.sh', '.bash'],
grammarFile: 'tree-sitter-bash.wasm',
extractor: extractBashSymbols,
required: false,
},
{
id: 'elixir',
extensions: ['.ex', '.exs'],
grammarFile: 'tree-sitter-elixir.wasm',
extractor: extractElixirSymbols,
required: false,
},
{
id: 'lua',
extensions: ['.lua'],
grammarFile: 'tree-sitter-lua.wasm',
extractor: extractLuaSymbols,
required: false,
},
{
id: 'dart',
extensions: ['.dart'],
grammarFile: 'tree-sitter-dart.wasm',
extractor: extractDartSymbols,
required: false,
},
{
id: 'zig',
extensions: ['.zig'],
grammarFile: 'tree-sitter-zig.wasm',
extractor: extractZigSymbols,
required: false,
},
{
id: 'haskell',
extensions: ['.hs'],
grammarFile: 'tree-sitter-haskell.wasm',
extractor: extractHaskellSymbols,
required: false,
},
{
id: 'ocaml',
extensions: ['.ml'],
grammarFile: 'tree-sitter-ocaml.wasm',
extractor: extractOCamlSymbols,
required: false,
},
{
id: 'ocaml-interface',
extensions: ['.mli'],
grammarFile: 'tree-sitter-ocaml_interface.wasm',
extractor: extractOCamlSymbols,
required: false,
},
{
id: 'fsharp',
extensions: ['.fs', '.fsx'],
grammarFile: 'tree-sitter-fsharp.wasm',
extractor: extractFSharpSymbols,
required: false,
},
{
id: 'fsharp-signature',
extensions: ['.fsi'],
grammarFile: 'tree-sitter-fsharp_signature.wasm',
extractor: extractFSharpSymbols,
required: false,
},
{
id: 'gleam',
extensions: ['.gleam'],
grammarFile: 'tree-sitter-gleam.wasm',
extractor: extractGleamSymbols,
required: false,
},
{
id: 'clojure',
extensions: ['.clj', '.cljs', '.cljc'],
grammarFile: 'tree-sitter-clojure.wasm',
extractor: extractClojureSymbols,
required: false,
},
{
id: 'julia',
extensions: ['.jl'],
grammarFile: 'tree-sitter-julia.wasm',
extractor: extractJuliaSymbols,
required: false,
},
{
id: 'r',
extensions: ['.r', '.R'],
grammarFile: 'tree-sitter-r.wasm',
extractor: extractRSymbols,
required: false,
},
{
id: 'erlang',
extensions: ['.erl', '.hrl'],
grammarFile: 'tree-sitter-erlang.wasm',
extractor: extractErlangSymbols,
required: false,
},
{
id: 'solidity',
extensions: ['.sol'],
grammarFile: 'tree-sitter-solidity.wasm',
extractor: extractSoliditySymbols,
required: false,
},
{
id: 'objc',
extensions: ['.m'],
grammarFile: 'tree-sitter-objc.wasm',
extractor: extractObjCSymbols,
required: false,
},
{
id: 'cuda',
extensions: ['.cu', '.cuh'],
grammarFile: 'tree-sitter-cuda.wasm',
extractor: extractCudaSymbols,
required: false,
},
{
id: 'groovy',
extensions: ['.groovy', '.gvy'],
grammarFile: 'tree-sitter-groovy.wasm',
extractor: extractGroovySymbols,
required: false,
},
{
id: 'verilog',
extensions: ['.v', '.sv'],
grammarFile: 'tree-sitter-verilog.wasm',
extractor: extractVerilogSymbols,
required: false,
},
];
const _extToLang: Map<string, LanguageRegistryEntry> = new Map();
for (const entry of LANGUAGE_REGISTRY) {
for (const ext of entry.extensions) {
_extToLang.set(ext.toLowerCase(), entry);
}
}
// ── Per-worker caches (not shared across workers) ───────────────────────────
let _runtimeInitialized = false;
// Value of `null` means "tried to load, grammar is optional and failed" —
// we cache the failure so we don't retry on every file.
const _parsers: Map<string, Parser | null> = new Map();
const _queries: Map<string, Query> = new Map();
async function initRuntime(): Promise<void> {
if (_runtimeInitialized) return;
await Parser.init();
_runtimeInitialized = true;
}
/**
* Load the grammar for a language on demand. Returns the cached parser, or
* `null` if the grammar is optional and failed to load (same convention as
* parser.ts). Throws for required grammars that fail.
*/
async function loadLanguageLazy(entry: LanguageRegistryEntry): Promise<Parser | null> {
if (_parsers.has(entry.id)) return _parsers.get(entry.id) ?? null;
try {
const lang = await Language.load(grammarPath(entry.grammarFile));
const parser = new Parser();
parser.setLanguage(lang);
_parsers.set(entry.id, parser);
// Build the JS/TS/TSX query (mirrors parser.ts::doLoadLanguage)
if (entry.extractor === extractSymbols && !_queries.has(entry.id)) {
const isTS = entry.id === 'typescript' || entry.id === 'tsx';
const patterns = isTS
? [...COMMON_QUERY_PATTERNS, ...TS_EXTRA_PATTERNS]
: [...COMMON_QUERY_PATTERNS, JS_CLASS_PATTERN];
_queries.set(entry.id, new Query(lang, patterns.join('\n')));
}
return parser;
} catch (e: unknown) {
if (entry.required) {
throw new Error(`Required parser ${entry.id} failed to initialize: ${(e as Error).message}`);
}
_parsers.set(entry.id, null);
return null;
}
}
// ── Per-function walk-result shapes (mirrors engine.ts, kept local) ─────────
interface ComplexityFuncResult {
funcNode: TreeSitterNode;
funcName: string | null;
metrics: {
cognitive: number;
cyclomatic: number;
maxNesting: number;
halstead?: { volume: number; difficulty: number; effort: number; bugs: number };
};
}
interface CfgFuncResult {
funcNode: TreeSitterNode;
blocks: CfgBlock[];
edges: CfgEdge[];
cyclomatic?: number;
}
// ── Helpers mirroring engine.ts (copied, db-free) ───────────────────────────
function hasFuncBody(d: {
name: string;
kind: string;
line: number;
endLine?: number | null;
}): boolean {
return (
(d.kind === 'function' || d.kind === 'method') &&
d.line > 0 &&
d.endLine != null &&
d.endLine > d.line &&
!d.name.includes('.')
);
}
function indexByLine<T extends { funcNode: TreeSitterNode }>(results: T[]): Map<number, T[]> {
const byLine = new Map<number, T[]>();
for (const r of results) {
if (!r.funcNode) continue;
const line = r.funcNode.startPosition.row + 1;
if (!byLine.has(line)) byLine.set(line, []);
byLine.get(line)?.push(r);
}
return byLine;
}
function matchResultToDef<T extends { funcNode: TreeSitterNode }>(
candidates: T[] | undefined,
defName: string,
): T | undefined {
if (!candidates) return undefined;
if (candidates.length === 1) return candidates[0];
return (
candidates.find((r) => {
const n = r.funcNode.childForFieldName('name');
return n && n.text === defName;
}) ?? candidates[0]
);
}
/** Override a definition's cyclomatic complexity with a CFG-derived value and recompute MI. */
function overrideCyclomaticFromCfg(def: Definition, cfgCyclomatic: number): void {
if (!def.complexity) return;
if (cfgCyclomatic <= 0) return;
def.complexity.cyclomatic = cfgCyclomatic;
const { loc, halstead } = def.complexity;
const volume = halstead ? halstead.volume : 0;
const commentRatio = loc && loc.loc > 0 ? loc.commentLines / loc.loc : 0;
def.complexity.maintainabilityIndex = computeMaintainabilityIndex(
volume,
cfgCyclomatic,
loc?.sloc ?? 0,
commentRatio,
);
}
function storeComplexityResults(results: WalkResults, defs: Definition[], langId: string): void {
const byLine = indexByLine((results.complexity || []) as ComplexityFuncResult[]);
for (const def of defs) {
if ((def.kind === 'function' || def.kind === 'method') && def.line && !def.complexity) {
const funcResult = matchResultToDef(byLine.get(def.line), def.name);
if (!funcResult) continue;
const { metrics } = funcResult;
const loc = computeLOCMetrics(funcResult.funcNode, langId);
const volume = metrics.halstead ? metrics.halstead.volume : 0;
const commentRatio = loc.loc > 0 ? loc.commentLines / loc.loc : 0;
const mi = computeMaintainabilityIndex(volume, metrics.cyclomatic, loc.sloc, commentRatio);
def.complexity = {
cognitive: metrics.cognitive,
cyclomatic: metrics.cyclomatic,
maxNesting: metrics.maxNesting,
halstead: metrics.halstead,
loc,
maintainabilityIndex: mi,
};
}
}
}
function storeCfgResults(results: WalkResults, defs: Definition[]): void {
const byLine = indexByLine((results.cfg || []) as CfgFuncResult[]);
for (const def of defs) {
if (
(def.kind === 'function' || def.kind === 'method') &&
def.line &&
!def.cfg?.blocks?.length
) {
const cfgResult = matchResultToDef(byLine.get(def.line), def.name);
if (!cfgResult) continue;
def.cfg = { blocks: cfgResult.blocks, edges: cfgResult.edges };
if (cfgResult.cyclomatic != null) {
overrideCyclomaticFromCfg(def, cfgResult.cyclomatic);
}
}
}
}
// ── Per-file visitor setup (db-free version of engine.ts::setupVisitors) ────
interface SetupResult {
visitors: Visitor[];
walkerOpts: WalkOptions;
astVisitor: Visitor | null;
complexityVisitor: Visitor | null;
cfgVisitor: Visitor | null;
dataflowVisitor: Visitor | null;
}
/**
* Build the AST-store visitor for `langId`. Returns `null` when AST is
* disabled or the language has no AST type map. db-free — passes an empty
* nodeIdMap. The main thread re-resolves parent node IDs in
* `features/ast.ts::collectFileAstRows`.
*/
function buildAstVisitor(
langId: string,
defs: ExtractorOutput['definitions'],
relPath: string,
enabled: boolean,
): Visitor | null {
if (!enabled) return null;
const astTypeMap = AST_TYPE_MAPS.get(langId);
if (!astTypeMap) return null;
const stringConfig = AST_STRING_CONFIGS.get(langId);
return createAstStoreVisitor(
astTypeMap,
defs,
relPath,
new Map<string, number>(),
stringConfig,
astStopRecurseKinds(langId),
);
}
/**
* Build the complexity visitor when enabled, the language has complexity
* rules, and at least one definition still lacks a `complexity` payload.
* Side-effect: extends `walkerOpts` with nesting-node types and a
* `getFunctionName` resolver suitable for this language.
*/
function buildComplexityVisitor(
langId: string,
defs: ExtractorOutput['definitions'],
enabled: boolean,
walkerOpts: WalkOptions,
): Visitor | null {
if (!enabled) return null;
const cRules = COMPLEXITY_RULES.get(langId);
if (!cRules || !defs.some((d) => hasFuncBody(d) && !d.complexity)) return null;
const hRules = HALSTEAD_RULES.get(langId);
const visitor = createComplexityVisitor(cRules, hRules, { fileLevelWalk: true, langId });
for (const t of cRules.nestingNodes) walkerOpts.nestingNodeTypes?.add(t);
const dfRules = DATAFLOW_RULES.get(langId);
walkerOpts.getFunctionName = (node: TreeSitterNode): string | null => {
const nameNode = node.childForFieldName('name');
if (nameNode) return nameNode.text;
// dfRules shape varies per language; visitor-utils accepts any shape
if (dfRules) return getFuncName(node, dfRules as any);
return null;
};
return visitor;
}
/** Build the CFG visitor when enabled and at least one definition still lacks blocks. */
function buildCfgVisitor(
langId: string,
defs: ExtractorOutput['definitions'],
enabled: boolean,
): Visitor | null {
if (!enabled) return null;
const cfgRulesForLang = CFG_RULES.get(langId);
if (!cfgRulesForLang) return null;
const needsCfg = defs.some(
(d) => hasFuncBody(d) && d.cfg !== null && !Array.isArray(d.cfg?.blocks),
);
if (!needsCfg) return null;
return createCfgVisitor(cfgRulesForLang);
}
/** Build the dataflow visitor when enabled and `symbols.dataflow` is not yet populated. */
function buildDataflowVisitor(
langId: string,
symbols: ExtractorOutput,
enabled: boolean,
): Visitor | null {
if (!enabled) return null;
const dfRules = DATAFLOW_RULES.get(langId);
if (!dfRules || symbols.dataflow) return null;
return createDataflowVisitor(dfRules);
}
function setupVisitorsLocal(
symbols: ExtractorOutput,
relPath: string,
langId: string,
opts: WorkerParseRequest['opts'],
): SetupResult {
const defs = symbols.definitions || [];
const walkerOpts: WalkOptions = {
functionNodeTypes: new Set<string>(),
nestingNodeTypes: new Set<string>(),
getFunctionName: (_node: TreeSitterNode) => null,
};
const astVisitor = buildAstVisitor(langId, defs, relPath, !!opts.ast);
const complexityVisitor = buildComplexityVisitor(langId, defs, !!opts.complexity, walkerOpts);
const cfgVisitor = buildCfgVisitor(langId, defs, !!opts.cfg);
const dataflowVisitor = buildDataflowVisitor(langId, symbols, !!opts.dataflow);
const visitors: Visitor[] = [];
if (astVisitor) visitors.push(astVisitor);
if (complexityVisitor) visitors.push(complexityVisitor);
if (cfgVisitor) visitors.push(cfgVisitor);
if (dataflowVisitor) visitors.push(dataflowVisitor);
return { visitors, walkerOpts, astVisitor, complexityVisitor, cfgVisitor, dataflowVisitor };
}
// ── Main parse handler ──────────────────────────────────────────────────────
/**
* Run tree-sitter parse + extractor on `code`. Returns `null` when either
* step yields no usable output. Throws (for the caller to report back to the
* pool) only on a hard tree-sitter parse error.
*/
function parseAndExtract(
parser: Parser,
entry: LanguageRegistryEntry,
filePath: string,
code: string,
): { tree: Tree; symbols: ExtractorOutput } | null {
let tree: Tree | null;
try {
tree = parser.parse(code);
} catch (e: unknown) {
// Parse error — report back but keep worker alive.
throw new Error(`parse failed: ${(e as Error).message}`);
}
if (!tree) return null;
// Extractor — on failure, skip file (ok:true, null) to match parser.ts
// behavior where extractor issues don't crash the build. Dispose the tree
// before returning null so WASM linear memory doesn't accumulate in the worker.
let symbols: ExtractorOutput | null;
try {
const query = _queries.get(entry.id);
// tree-sitter's Tree/Query are structurally compatible with
// TreeSitterTree/TreeSitterQuery at runtime — same cast style as
// parser.ts::wasmExtractSymbols (parser.ts:789).
symbols = entry.extractor(tree as any, filePath, query as any) ?? null;
} catch {
disposeTree(tree);
return null;
}
if (!symbols) {
disposeTree(tree);
return null;
}
return { tree, symbols };
}
/**
* Project the visitor `ast-store` rows into the wire-safe shape returned to
* the main thread. Strips `file` and `parentNodeId` — both are re-resolved in
* `features/ast.ts::collectFileAstRows`. Always returns an array (even empty)
* so `engine.ts::fileNeedsWasmTree` doesn't treat the file as un-walked and
* trigger a full ensureWasmTrees re-parse (#1036).
*/
function projectAstNodes(results: WalkResults): SerializedExtractorOutput['astNodes'] {
const astRows = (results['ast-store'] || []) as Array<{
line: number;
kind: string;
name: string | null | undefined;
text: string | null;
receiver: string | null;
file?: string;
parentNodeId?: number | null;
}>;
return astRows.map((n) => ({
line: n.line,
kind: n.kind,
name: n.name ?? '',
text: n.text ?? undefined,
receiver: n.receiver ?? undefined,
}));
}
/**
* Run the configured visitor walk over `tree.rootNode` and apply each
* visitor's results back onto `symbols`. Returns the serialized astNodes
* (or `undefined` when AST is disabled / no rows produced).
*
* Mirrors engine.ts:791-829. Runs BEFORE `tree.delete()` because
* storeComplexityResults / storeCfgResults read `funcNode` off live nodes.
*/
function runVisitorWalk(
tree: Tree,
symbols: ExtractorOutput,
langId: string,
setup: SetupResult,
): SerializedExtractorOutput['astNodes'] {
if (setup.visitors.length === 0) return undefined;
// rootNode shape matches TreeSitterNode at runtime — same cast as parser.ts:789.
const results = walkWithVisitors(tree.rootNode as any, setup.visitors, langId, setup.walkerOpts);
const defs = symbols.definitions || [];
let serializedAstNodes: SerializedExtractorOutput['astNodes'];
if (setup.astVisitor) serializedAstNodes = projectAstNodes(results);
if (setup.complexityVisitor) storeComplexityResults(results, defs, langId);
if (setup.cfgVisitor) storeCfgResults(results, defs);
if (setup.dataflowVisitor) symbols.dataflow = results.dataflow as DataflowResult;
return serializedAstNodes;
}
/**
* Pack the in-memory ExtractorOutput into the structured-clone-safe shape
* sent back across the worker boundary. Converts the typeMap into a tuple
* array and intentionally omits `_tree` (cannot cross the boundary).
*/
function serializeExtractorOutput(
symbols: ExtractorOutput,
langId: LanguageId,
code: string,
astNodes: SerializedExtractorOutput['astNodes'],
): SerializedExtractorOutput {
return {
definitions: symbols.definitions,
calls: symbols.calls,
imports: symbols.imports,
classes: symbols.classes,
exports: symbols.exports,
typeMap: Array.from(symbols.typeMap.entries()),
_langId: langId,
_lineCount: code.split('\n').length,
dataflow: symbols.dataflow,
astNodes,
...(symbols.fnRefBindings?.length ? { fnRefBindings: symbols.fnRefBindings } : {}),
...(symbols.newExpressions?.length ? { newExpressions: symbols.newExpressions } : {}),
...(symbols.definePropertyReceivers?.size
? { definePropertyReceivers: Array.from(symbols.definePropertyReceivers.entries()) }
: {}),
};
}
/**
* Release WASM linear memory backing a tree. Best-effort — swallows errors so
* the worker keeps serving requests. Deferring this would let trees accumulate
* in the worker's WASM heap and defeat the point of isolating parse calls.
*/
function disposeTree(tree: Tree | null): void {
if (!tree) return;
const deletable = tree as unknown as { delete?: () => void };
if (typeof deletable.delete !== 'function') return;
try {
deletable.delete();
} catch {
// best-effort cleanup — swallow; worker continues.
}
}
async function handleParse(msg: WorkerParseRequest): Promise<SerializedExtractorOutput | null> {
const ext = path.extname(msg.filePath).toLowerCase();
const entry = _extToLang.get(ext);
if (!entry) return null;
await initRuntime();
const parser = await loadLanguageLazy(entry);
if (!parser) return null;
const parsed = parseAndExtract(parser, entry, msg.filePath, msg.code);
if (!parsed) return null;
const { tree, symbols } = parsed;
try {
const setup = setupVisitorsLocal(symbols, msg.filePath, entry.id, msg.opts);
// astNodes kept in the serialized shape (without `file`/`parentNodeId`),
// not assigned back to symbols.astNodes — ExtractorOutput.astNodes is
// ASTNodeRow[] (DB row shape with node_id), which is a different type.
const serializedAstNodes = runVisitorWalk(tree, symbols, entry.id, setup);
return serializeExtractorOutput(symbols, entry.id as LanguageId, msg.code, serializedAstNodes);
} finally {
// ALWAYS release WASM memory before responding (see disposeTree note).
disposeTree(tree);
}
}
// ── Worker message loop ─────────────────────────────────────────────────────
if (!parentPort) {
throw new Error('wasm-worker-entry must be run as a worker_thread');
}
// Test-only crash marker. When the code contains this exact magic token
// and CODEGRAPH_WASM_WORKER_TEST_CRASH=1 is set in the worker env, the
// worker calls process.exit(1) mid-parse — simulating a V8 fatal from the
// grammar so we can unit-test pool crash recovery without a real V8 abort.
const TEST_CRASH_MAGIC = '__CODEGRAPH_WASM_WORKER_TEST_CRASH__';
// The pool terminates workers via `Worker.terminate()`; no graceful-shutdown
// handshake is needed. Worker only handles `parse` messages.
parentPort.on('message', async (msg: WorkerRequest) => {
if (msg.type !== 'parse') return;
if (
process.env.CODEGRAPH_WASM_WORKER_TEST_CRASH === '1' &&
typeof msg.code === 'string' &&
msg.code.includes(TEST_CRASH_MAGIC)
) {
// Simulate a fatal V8 abort — hard-exit the worker.
process.exit(1);
}
try {
const result = await handleParse(msg);
const res: WorkerResponse = { type: 'result', id: msg.id, ok: true, result };
parentPort!.postMessage(res);
} catch (e: unknown) {
const res: WorkerResponse = {
type: 'result',
id: msg.id,
ok: false,
error: (e as Error).message ?? String(e),
};
parentPort!.postMessage(res);
}
});