forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree-sitter.ts
More file actions
3119 lines (2857 loc) · 121 KB
/
Copy pathtree-sitter.ts
File metadata and controls
3119 lines (2857 loc) · 121 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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Tree-sitter Parser Wrapper
*
* Handles parsing source code and extracting structural information.
*/
import { Node as SyntaxNode, Tree } from 'web-tree-sitter';
import * as path from 'path';
import {
Language,
Node,
Edge,
NodeKind,
ExtractionResult,
ExtractionError,
UnresolvedReference,
} from '../types';
import { getParser, detectLanguage, isLanguageSupported, isFileLevelOnlyLanguage } from './grammars';
import { generateNodeId, getNodeText, getChildByField, getPrecedingDocstring } from './tree-sitter-helpers';
import type { LanguageExtractor, ExtractorContext } from './tree-sitter-types';
import { EXTRACTORS } from './languages';
import { LiquidExtractor } from './liquid-extractor';
import { SvelteExtractor } from './svelte-extractor';
import { DfmExtractor } from './dfm-extractor';
import { VueExtractor } from './vue-extractor';
import { MyBatisExtractor } from './mybatis-extractor';
import {
getAllFrameworkResolvers,
getApplicableFrameworks,
} from '../resolution/frameworks';
// Re-export for backward compatibility
export { generateNodeId } from './tree-sitter-helpers';
/**
* Extract the name from a node based on language
*/
function extractName(node: SyntaxNode, source: string, extractor: LanguageExtractor): string {
const hookName = extractor.resolveName?.(node, source);
if (hookName) return hookName;
// Try field name first
const nameNode = getChildByField(node, extractor.nameField);
if (nameNode) {
// Unwrap pointer_declarator(s) for C/C++ pointer return types
let resolved = nameNode;
while (resolved.type === 'pointer_declarator') {
const inner = getChildByField(resolved, 'declarator') || resolved.namedChild(0);
if (!inner) break;
resolved = inner;
}
// Handle complex declarators (C/C++)
if (resolved.type === 'function_declarator' || resolved.type === 'declarator') {
const innerName = getChildByField(resolved, 'declarator') || resolved.namedChild(0);
return innerName ? getNodeText(innerName, source) : getNodeText(resolved, source);
}
// Lua: `function t.f()` / `function t:m()` — the name node is a dot/method
// index expression; the simple name is the trailing field/method (the table
// receiver is captured separately via getReceiverType).
if (resolved.type === 'dot_index_expression') {
const field = getChildByField(resolved, 'field');
if (field) return getNodeText(field, source);
}
if (resolved.type === 'method_index_expression') {
const method = getChildByField(resolved, 'method');
if (method) return getNodeText(method, source);
}
return getNodeText(resolved, source);
}
// 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);
if (child && (
child.type === 'function_signature' ||
child.type === 'getter_signature' ||
child.type === 'setter_signature' ||
child.type === 'constructor_signature' ||
child.type === 'factory_constructor_signature'
)) {
// Find identifier inside the inner signature
for (let j = 0; j < child.namedChildCount; j++) {
const inner = child.namedChild(j);
if (inner?.type === 'identifier') {
return getNodeText(inner, source);
}
}
}
}
}
// Arrow/function expressions get their name from the parent variable_declarator,
// not from identifiers in their body. Without this, single-expression arrow
// functions like `const fn = () => someIdentifier` get named "someIdentifier"
// instead of "fn", because the fallback below finds the body identifier.
if (node.type === 'arrow_function' || node.type === 'function_expression') {
return '<anonymous>';
}
// Fall back to first identifier child
for (let i = 0; i < node.namedChildCount; i++) {
const child = node.namedChild(i);
if (
child &&
(child.type === 'identifier' ||
child.type === 'type_identifier' ||
child.type === 'simple_identifier' ||
child.type === 'constant')
) {
return getNodeText(child, source);
}
}
return '<anonymous>';
}
/**
* Tree-sitter node kinds that represent constructor invocations
* (`new Foo()` and friends). Used by extractInstantiation to emit
* an `instantiates` reference targeting the class name.
*/
const INSTANTIATION_KINDS: ReadonlySet<string> = new Set([
'new_expression', // typescript / javascript / tsx / jsx
'object_creation_expression', // java / c#
'instance_creation_expression', // some grammars
]);
/**
* TreeSitterExtractor - Main extraction class
*/
export class TreeSitterExtractor {
private filePath: string;
private language: Language;
private source: string;
private tree: Tree | null = null;
private nodes: Node[] = [];
private edges: Edge[] = [];
private unresolvedReferences: UnresolvedReference[] = [];
private errors: ExtractionError[] = [];
private extractor: LanguageExtractor | null = null;
private nodeStack: string[] = []; // Stack of parent node IDs
private methodIndex: Map<string, string> | null = null; // lookup key → node ID for Pascal defProc lookup
constructor(filePath: string, source: string, language?: Language) {
this.filePath = filePath;
this.source = source;
this.language = language || detectLanguage(filePath, source);
this.extractor = EXTRACTORS[this.language] || null;
}
/**
* Parse and extract from the source code
*/
extract(): ExtractionResult {
const startTime = Date.now();
if (!isLanguageSupported(this.language)) {
return {
nodes: [],
edges: [],
unresolvedReferences: [],
errors: [
{
message: `Unsupported language: ${this.language}`,
filePath: this.filePath,
severity: 'error',
code: 'unsupported_language',
},
],
durationMs: Date.now() - startTime,
};
}
const parser = getParser(this.language);
if (!parser) {
return {
nodes: [],
edges: [],
unresolvedReferences: [],
errors: [
{
message: `Failed to get parser for language: ${this.language}`,
filePath: this.filePath,
severity: 'error',
code: 'parser_error',
},
],
durationMs: Date.now() - startTime,
};
}
try {
this.tree = parser.parse(this.source) ?? null;
if (!this.tree) {
throw new Error('Parser returned null tree');
}
// Create file node representing the source file
const fileNode: Node = {
id: `file:${this.filePath}`,
kind: 'file',
name: path.basename(this.filePath),
qualifiedName: this.filePath,
filePath: this.filePath,
language: this.language,
startLine: 1,
endLine: this.source.split('\n').length,
startColumn: 0,
endColumn: 0,
isExported: false,
updatedAt: Date.now(),
};
this.nodes.push(fileNode);
// Push file node onto stack so top-level declarations get contains edges
this.nodeStack.push(fileNode.id);
// File-level package declaration (Kotlin/Java). Creates an implicit
// `namespace` node wrapping every top-level declaration so their
// qualifiedName carries the FQN — required for cross-file import
// resolution on JVM languages where filename ≠ class name.
const packageNodeId = this.extractFilePackage(this.tree.rootNode);
if (packageNodeId) this.nodeStack.push(packageNodeId);
this.visitNode(this.tree.rootNode);
if (packageNodeId) this.nodeStack.pop();
this.nodeStack.pop();
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
// WASM memory errors leave the module in a corrupted state — all subsequent
// parses would also fail. Re-throw so the worker can detect and crash,
// forcing a clean restart with a fresh heap.
if (msg.includes('memory access out of bounds') || msg.includes('out of memory')) {
throw error;
}
this.errors.push({
message: `Parse error: ${msg}`,
filePath: this.filePath,
severity: 'error',
code: 'parse_error',
});
} finally {
// Free tree-sitter WASM memory immediately — trees hold native heap memory
// invisible to V8's GC that accumulates across thousands of files.
if (this.tree) {
this.tree.delete();
this.tree = null;
}
// Release source string to reduce GC pressure
this.source = '';
}
return {
nodes: this.nodes,
edges: this.edges,
unresolvedReferences: this.unresolvedReferences,
errors: this.errors,
durationMs: Date.now() - startTime,
};
}
/**
* Visit a node and extract information
*/
private visitNode(node: SyntaxNode): void {
if (!this.extractor) return;
const nodeType = node.type;
let skipChildren = false;
// Language-specific custom visitor hook
if (this.extractor.visitNode) {
const ctx = this.makeExtractorContext();
const handled = this.extractor.visitNode(node, ctx);
if (handled) return;
}
// Pascal-specific AST handling
if (this.language === 'pascal') {
skipChildren = this.visitPascalNode(node);
if (skipChildren) return;
}
// Check for function declarations
// For Python/Ruby, function_definition inside a class should be treated as method
if (this.extractor.functionTypes.includes(nodeType)) {
if (this.isInsideClassLikeNode() && this.extractor.methodTypes.includes(nodeType)) {
// Inside a class - treat as method
this.extractMethod(node);
skipChildren = true; // extractMethod visits children via visitFunctionBody
} else {
this.extractFunction(node);
skipChildren = true; // extractFunction visits children via visitFunctionBody
}
}
// Check for class declarations
else if (this.extractor.classTypes.includes(nodeType)) {
// Some languages reuse class_declaration for structs/enums (e.g. Swift)
const classification = this.extractor.classifyClassNode?.(node) ?? 'class';
if (classification === 'struct') {
this.extractStruct(node);
} else if (classification === 'enum') {
this.extractEnum(node);
} else if (classification === 'interface') {
this.extractInterface(node);
} else if (classification === 'trait') {
this.extractClass(node, 'trait');
} else {
this.extractClass(node);
}
skipChildren = true; // extractClass visits body children
}
// Extra class node types (e.g. Dart mixin_declaration, extension_declaration)
else if (this.extractor.extraClassNodeTypes?.includes(nodeType)) {
this.extractClass(node);
skipChildren = true;
}
// Check for method declarations (only if not already handled by functionTypes)
else if (this.extractor.methodTypes.includes(nodeType)) {
this.extractMethod(node);
skipChildren = true; // extractMethod visits children via visitFunctionBody
}
// Check for interface/protocol/trait declarations
else if (this.extractor.interfaceTypes.includes(nodeType)) {
this.extractInterface(node);
skipChildren = true; // extractInterface visits body children
}
// Check for struct declarations
else if (this.extractor.structTypes.includes(nodeType)) {
this.extractStruct(node);
skipChildren = true; // extractStruct visits body children
}
// Check for enum declarations
else if (this.extractor.enumTypes.includes(nodeType)) {
this.extractEnum(node);
skipChildren = true; // extractEnum visits body children
}
// Check for type alias declarations (e.g. `type X = ...` in TypeScript)
// For Go, type_spec wraps struct/interface definitions — resolveTypeAliasKind
// detects these and extractTypeAlias creates the correct node kind.
else if (this.extractor.typeAliasTypes.includes(nodeType)) {
skipChildren = this.extractTypeAlias(node);
}
// Check for class properties (e.g. C# property_declaration)
else if (this.extractor.propertyTypes?.includes(nodeType) && this.isInsideClassLikeNode()) {
this.extractProperty(node);
skipChildren = true;
}
// Check for class fields (e.g. Java field_declaration, C# field_declaration)
else if (this.extractor.fieldTypes?.includes(nodeType) && this.isInsideClassLikeNode()) {
this.extractField(node);
skipChildren = true;
}
// Check for variable declarations (const, let, var, etc.)
// Only extract top-level variables (not inside functions/methods)
else if (this.extractor.variableTypes.includes(nodeType) && !this.isInsideClassLikeNode()) {
this.extractVariable(node);
skipChildren = true; // extractVariable handles children
}
// `export_statement` itself is not extracted — the walker descends
// into children, where the inner declaration (lexical_declaration,
// function_declaration, class_declaration, etc.) is dispatched to
// its own extractor. `isExported` walks the parent chain, so the
// exported flag is preserved automatically.
//
// Calling extractExportedVariables here AND descending caused every
// `export const X = ...` to produce two nodes for the same symbol —
// one kind:'variable' from extractExportedVariables and one
// kind:'constant' from extractVariable. The dedicated dispatch is
// the correct one (it picks kind from isConst, captures the
// initializer signature, and walks type annotations); the
// export-statement helper was redundant.
// Check for imports
else if (this.extractor.importTypes.includes(nodeType)) {
this.extractImport(node);
}
// Check for function calls
else if (this.extractor.callTypes.includes(nodeType)) {
this.extractCall(node);
}
// `new Foo(...)` / `Foo::new(...)` / object_creation_expression —
// produce an `instantiates` reference. Children still walked so
// nested calls inside the constructor args (`new Foo(bar())`) get
// their own `calls` refs.
else if (INSTANTIATION_KINDS.has(nodeType)) {
this.extractInstantiation(node);
// Java/C# `new T(...) { ... }` — anonymous class with body. Without
// extracting it as a class node + its methods, the interface→impl
// synthesizer (Phase 5.5) can't bridge T's abstract methods to the
// anonymous overrides, and an agent investigating a call through T
// (`strategy.iterator(...)` where strategy is a Strategy lambda body)
// has to Read the file to find the actual implementation.
const anonBody = this.findAnonymousClassBody(node);
if (anonBody) {
this.extractAnonymousClass(node, anonBody);
skipChildren = true;
}
}
// (Decorator handling lives inside the symbol-creating extractors
// — extractClass / extractFunction / extractProperty — because the
// decorator node sits BEFORE the symbol in the AST and the walker
// would otherwise see the wrong nodeStack head.)
// Rust: `impl Trait for Type { ... }` — creates implements edge from Type to Trait
else if (nodeType === 'impl_item') {
this.extractRustImplItem(node);
}
// TypeScript interface members: property_signature (`foo: T`, `foo?: T`)
// and method_signature (`foo(arg: A): R`) both carry type annotations the
// interface walker would otherwise drop. Extract them as `references`
// edges from the interface so resolvers can wire callers/impact for
// types that only appear in interface members.
else if (
(nodeType === 'property_signature' || nodeType === 'method_signature') &&
this.isInsideClassLikeNode() &&
this.TYPE_ANNOTATION_LANGUAGES.has(this.language)
) {
const parentId = this.nodeStack[this.nodeStack.length - 1];
if (parentId) {
this.extractTypeAnnotations(node, parentId);
}
// don't skipChildren — nested signatures still need traversal
}
// Visit children (unless the extract method already visited them)
if (!skipChildren) {
for (let i = 0; i < node.namedChildCount; i++) {
const child = node.namedChild(i);
if (child) {
this.visitNode(child);
}
}
}
}
/**
* Create a Node object
*/
private createNode(
kind: NodeKind,
name: string,
node: SyntaxNode,
extra?: Partial<Node>
): Node | null {
// Skip nodes with empty/missing names — they are not meaningful symbols
// and would cause FK violations when edges reference them (see issue #42)
if (!name) {
return null;
}
const id = generateNodeId(this.filePath, kind, name, node.startPosition.row + 1);
// Some grammars (e.g. Dart) model a function/method body as a *sibling* of
// the signature node, so the declaration node's own range is just the
// signature line. Extend endLine to the resolved body when it sits beyond
// the node so the node spans its body — required for any body-level analysis
// (callees, the callback synthesizer's body scan, context slices). Guarded to
// only ever extend: for child-body grammars the body is within range (no-op).
let endLine = node.endPosition.row + 1;
if (kind === 'function' || kind === 'method') {
const body = this.extractor?.resolveBody?.(node, this.extractor.bodyField);
if (body && body.endPosition.row + 1 > endLine) {
endLine = body.endPosition.row + 1;
}
}
const newNode: Node = {
id,
kind,
name,
qualifiedName: this.buildQualifiedName(name),
filePath: this.filePath,
language: this.language,
startLine: node.startPosition.row + 1,
endLine,
startColumn: node.startPosition.column,
endColumn: node.endPosition.column,
updatedAt: Date.now(),
...extra,
};
this.nodes.push(newNode);
// Add containment edge from parent
if (this.nodeStack.length > 0) {
const parentId = this.nodeStack[this.nodeStack.length - 1];
if (parentId) {
this.edges.push({
source: parentId,
target: id,
kind: 'contains',
});
}
}
return newNode;
}
/**
* Find first named child whose type is in the given list.
* 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);
if (child && types.includes(child.type)) return child;
}
return null;
}
/**
* Find a `packageTypes` child under the root, create a `namespace` node
* for it, and return its id so the caller can scope top-level
* declarations underneath. Returns null when no package header is
* present (script files, .kts without a package).
*/
private extractFilePackage(rootNode: SyntaxNode): string | null {
const types = this.extractor?.packageTypes;
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);
if (child && types.includes(child.type)) {
pkgNode = child;
break;
}
}
if (!pkgNode) return null;
const pkgName = this.extractor.extractPackage(pkgNode, this.source);
if (!pkgName) return null;
const ns = this.createNode('namespace', pkgName, pkgNode);
return ns?.id ?? null;
}
/**
* Build qualified name from node stack
*/
private buildQualifiedName(name: string): string {
// Build a qualified name from the semantic hierarchy only (no file path).
// The file path is stored separately in filePath and pollutes FTS if included here.
const parts: string[] = [];
for (const nodeId of this.nodeStack) {
const node = this.nodes.find((n) => n.id === nodeId);
if (node && node.kind !== 'file') {
parts.push(node.name);
}
}
parts.push(name);
return parts.join('::');
}
/**
* Build an ExtractorContext for passing to language-specific visitNode hooks.
*/
private makeExtractorContext(): ExtractorContext {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
return {
createNode: (kind, name, node, extra) => self.createNode(kind, name, node, extra),
visitNode: (node) => self.visitNode(node),
visitFunctionBody: (body, functionId) => self.visitFunctionBody(body, functionId),
addUnresolvedReference: (ref) => self.unresolvedReferences.push(ref),
pushScope: (nodeId) => self.nodeStack.push(nodeId),
popScope: () => self.nodeStack.pop(),
get filePath() { return self.filePath; },
get source() { return self.source; },
get nodeStack() { return self.nodeStack; },
get nodes() { return self.nodes; },
};
}
/**
* Check if the current node stack indicates we are inside a class-like node
* (class, struct, interface, trait). File nodes do not count as class-like.
*/
private isInsideClassLikeNode(): boolean {
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);
if (!parentNode) return false;
return (
parentNode.kind === 'class' ||
parentNode.kind === 'struct' ||
parentNode.kind === 'interface' ||
parentNode.kind === 'trait' ||
parentNode.kind === 'enum' ||
parentNode.kind === 'module'
);
}
/**
* Extract a function
*/
private extractFunction(node: SyntaxNode, nameOverride?: string): void {
if (!this.extractor) return;
// If the language provides getReceiverType and this function has a receiver
// (e.g., Rust function_item inside an impl block), extract as method instead
if (this.extractor.getReceiverType?.(node, this.source)) {
this.extractMethod(node);
return;
}
// nameOverride is supplied only for explicitly-named anonymous functions the
// caller resolved itself (e.g. arrow values of exported-const object members
// — SvelteKit actions). Inline-object arrows reached by the general walker
// get no override, so they still fall through to the <anonymous> skip below.
let name = nameOverride ?? extractName(node, this.source, this.extractor);
// For arrow functions and function expressions assigned to variables,
// resolve the name from the parent variable_declarator.
// e.g. `export const useAuth = () => { ... }` — the arrow_function node
// has no `name` field; the name lives on the variable_declarator.
if (
!nameOverride &&
name === '<anonymous>' &&
(node.type === 'arrow_function' || node.type === 'function_expression')
) {
const parent = node.parent;
if (parent?.type === 'variable_declarator') {
const varName = getChildByField(parent, 'name');
if (varName) {
name = getNodeText(varName, this.source);
}
}
}
if (name === '<anonymous>') return; // Skip anonymous functions
// Check for misparse artifacts (e.g. C++ macros causing "namespace detail" functions)
// Skip the node but still visit the body for calls and structural nodes
if (this.extractor.isMisparsedFunction?.(name, node)) {
const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
?? getChildByField(node, this.extractor.bodyField);
if (body) {
this.visitFunctionBody(body, '');
}
return;
}
const docstring = getPrecedingDocstring(node, this.source);
const signature = this.extractor.getSignature?.(node, this.source);
const visibility = this.extractor.getVisibility?.(node);
const isExported = this.extractor.isExported?.(node, this.source);
const isAsync = this.extractor.isAsync?.(node);
const isStatic = this.extractor.isStatic?.(node);
const funcNode = this.createNode('function', name, node, {
docstring,
signature,
visibility,
isExported,
isAsync,
isStatic,
});
if (!funcNode) return;
// Extract type annotations (parameter types and return type)
this.extractTypeAnnotations(node, funcNode.id);
// Extract decorators applied to the function (rare in JS/TS but
// present in Python `@decorator def f():` and Java/Kotlin
// annotations on free functions).
this.extractDecoratorsFor(node, funcNode.id);
// Push to stack and visit body
this.nodeStack.push(funcNode.id);
const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
?? getChildByField(node, this.extractor.bodyField);
if (body) {
this.visitFunctionBody(body, funcNode.id);
}
this.nodeStack.pop();
}
/**
* Extract a class
*/
private extractClass(node: SyntaxNode, kind: NodeKind = 'class'): void {
if (!this.extractor) return;
const name = extractName(node, this.source, this.extractor);
const docstring = getPrecedingDocstring(node, this.source);
const visibility = this.extractor.getVisibility?.(node);
const isExported = this.extractor.isExported?.(node, this.source);
const classNode = this.createNode(kind, name, node, {
docstring,
visibility,
isExported,
});
if (!classNode) return;
// Extract extends/implements
this.extractInheritance(node, classNode.id);
// Extract decorators applied to the class (`@Foo class X {}`).
this.extractDecoratorsFor(node, classNode.id);
// Push to stack and visit body
this.nodeStack.push(classNode.id);
let body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
?? getChildByField(node, this.extractor.bodyField);
if (!body) body = node;
// Visit all children for methods and properties
for (let i = 0; i < body.namedChildCount; i++) {
const child = body.namedChild(i);
if (child) {
this.visitNode(child);
}
}
this.nodeStack.pop();
}
/**
* Extract a method
*/
private extractMethod(node: SyntaxNode): void {
if (!this.extractor) return;
// For languages with receiver types (Go, Rust), include receiver in qualified name
// so FTS can match "scrapeLoop.run" → qualified_name "...::scrapeLoop::run"
const receiverType = this.extractor.getReceiverType?.(node, this.source);
// For most languages, only extract as method if inside a class-like node
// Languages with methodsAreTopLevel (e.g. Go) always treat them as methods
// Languages with getReceiverType (e.g. Rust) extract as method when receiver is found
if (!this.isInsideClassLikeNode() && !this.extractor.methodsAreTopLevel && !receiverType) {
// Skip method_definition nodes inside object literals (getters/setters/methods
// in inline objects). These are ephemeral and create noise (e.g., Svelte context
// objects: `ctx.set({ get view() { ... } })`).
if (node.parent?.type === 'object' || node.parent?.type === 'object_expression') {
const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
?? getChildByField(node, this.extractor.bodyField);
if (body) {
this.visitFunctionBody(body, '');
}
return;
}
// Not inside a class-like node and no receiver type, treat as function
this.extractFunction(node);
return;
}
const name = extractName(node, this.source, this.extractor);
// Check for misparse artifacts (e.g. C++ "switch" inside macro-confused class body)
if (this.extractor.isMisparsedFunction?.(name, node)) {
const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
?? getChildByField(node, this.extractor.bodyField);
if (body) {
this.visitFunctionBody(body, '');
}
return;
}
const docstring = getPrecedingDocstring(node, this.source);
const signature = this.extractor.getSignature?.(node, this.source);
const visibility = this.extractor.getVisibility?.(node);
const isAsync = this.extractor.isAsync?.(node);
const isStatic = this.extractor.isStatic?.(node);
const extraProps: Partial<Node> = {
docstring,
signature,
visibility,
isAsync,
isStatic,
};
if (receiverType) {
extraProps.qualifiedName = `${receiverType}::${name}`;
}
const methodNode = this.createNode('method', name, node, extraProps);
if (!methodNode) return;
// For methods with a receiver type but no class-like parent on the stack
// (e.g., Rust impl blocks), add a contains edge from the owning struct/trait
if (receiverType && !this.isInsideClassLikeNode()) {
const ownerNode = this.nodes.find(
(n) =>
n.name === receiverType &&
n.filePath === this.filePath &&
(n.kind === 'struct' || n.kind === 'class' || n.kind === 'enum' || n.kind === 'trait')
);
if (ownerNode) {
this.edges.push({
source: ownerNode.id,
target: methodNode.id,
kind: 'contains',
});
}
}
// Extract type annotations (parameter types and return type)
this.extractTypeAnnotations(node, methodNode.id);
// Extract decorators (`@Get('/list') list() {}`).
this.extractDecoratorsFor(node, methodNode.id);
// Push to stack and visit body
this.nodeStack.push(methodNode.id);
const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
?? getChildByField(node, this.extractor.bodyField);
if (body) {
this.visitFunctionBody(body, methodNode.id);
}
this.nodeStack.pop();
}
/**
* Extract an interface/protocol/trait
*/
private extractInterface(node: SyntaxNode): void {
if (!this.extractor) return;
const name = extractName(node, this.source, this.extractor);
const docstring = getPrecedingDocstring(node, this.source);
const isExported = this.extractor.isExported?.(node, this.source);
const kind: NodeKind = this.extractor.interfaceKind ?? 'interface';
const interfaceNode = this.createNode(kind, name, node, {
docstring,
isExported,
});
if (!interfaceNode) return;
// Extract extends (interface inheritance)
this.extractInheritance(node, interfaceNode.id);
// Visit body children for interface methods and nested types
this.nodeStack.push(interfaceNode.id);
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);
if (child) {
this.visitNode(child);
}
}
this.nodeStack.pop();
}
/**
* Extract a struct
*/
private extractStruct(node: SyntaxNode): void {
if (!this.extractor) return;
// Skip forward declarations and type references (no body = not a definition)
const body = getChildByField(node, this.extractor.bodyField);
if (!body) return;
const name = extractName(node, this.source, this.extractor);
const docstring = getPrecedingDocstring(node, this.source);
const visibility = this.extractor.getVisibility?.(node);
const isExported = this.extractor.isExported?.(node, this.source);
const structNode = this.createNode('struct', name, node, {
docstring,
visibility,
isExported,
});
if (!structNode) return;
// Extract inheritance (e.g. Swift: struct HTTPMethod: RawRepresentable)
this.extractInheritance(node, structNode.id);
// Push to stack for field extraction
this.nodeStack.push(structNode.id);
for (let i = 0; i < body.namedChildCount; i++) {
const child = body.namedChild(i);
if (child) {
this.visitNode(child);
}
}
this.nodeStack.pop();
}
/**
* Extract an enum
*/
private extractEnum(node: SyntaxNode): void {
if (!this.extractor) return;
// Skip forward declarations and type references (no body = not a definition)
const body = this.extractor.resolveBody?.(node, this.extractor.bodyField)
?? getChildByField(node, this.extractor.bodyField);
if (!body) return;
const name = extractName(node, this.source, this.extractor);
const docstring = getPrecedingDocstring(node, this.source);
const visibility = this.extractor.getVisibility?.(node);
const isExported = this.extractor.isExported?.(node, this.source);
const enumNode = this.createNode('enum', name, node, {
docstring,
visibility,
isExported,
});
if (!enumNode) return;
// Extract inheritance (e.g. Swift: enum AFError: Error)
this.extractInheritance(node, enumNode.id);
// Push to stack and visit body children (enum members, nested types, methods)
this.nodeStack.push(enumNode.id);
const memberTypes = this.extractor.enumMemberTypes;
for (let i = 0; i < body.namedChildCount; i++) {
const child = body.namedChild(i);
if (!child) continue;
if (memberTypes?.includes(child.type)) {
this.extractEnumMembers(child);
} else {
this.visitNode(child);
}
}
this.nodeStack.pop();
}
/**
* Extract enum member names from an enum member node.
* Handles multi-case declarations (Swift: `case put, delete`) and single-case patterns.
*/
private extractEnumMembers(node: SyntaxNode): void {
// Try field-based name first (e.g. Rust enum_variant has a 'name' field)
const nameNode = getChildByField(node, 'name');
if (nameNode) {
this.createNode('enum_member', getNodeText(nameNode, this.source), node);
return;
}
// Check for identifier-like children (Swift: simple_identifier, TS: property_identifier)
let found = false;
for (let i = 0; i < node.namedChildCount; i++) {
const child = node.namedChild(i);
if (child && (child.type === 'simple_identifier' || child.type === 'identifier' || child.type === 'property_identifier')) {
this.createNode('enum_member', getNodeText(child, this.source), child);
found = true;
}
}
// If the node itself IS the identifier (e.g. TS property_identifier directly in enum body)
if (!found && node.namedChildCount === 0) {
this.createNode('enum_member', getNodeText(node, this.source), node);
}
}
/**
* Extract a class property declaration (e.g. C# `public string Name { get; set; }`).
* Extracts as 'property' kind node inside the owning class.
*/
private extractProperty(node: SyntaxNode): void {
if (!this.extractor) return;
const docstring = getPrecedingDocstring(node, this.source);
const visibility = this.extractor.getVisibility?.(node);
const isStatic = this.extractor.isStatic?.(node) ?? false;
const hookName = this.extractor.extractPropertyName?.(node, this.source);
const nameNode = hookName
? null
: getChildByField(node, 'name') || node.namedChildren.find(c => c.type === 'identifier');
const name = hookName ?? (nameNode ? getNodeText(nameNode, this.source) : null);
if (!name) return;
// Get property type from the type child (first named child that isn't modifier or identifier)
const typeNode = node.namedChildren.find(
c => c.type !== 'modifier' && c.type !== 'modifiers'
&& c.type !== 'identifier' && c.type !== 'accessor_list'
&& c.type !== 'accessors' && c.type !== 'equals_value_clause'
);
const typeText = typeNode ? getNodeText(typeNode, this.source) : undefined;
const signature = typeText ? `${typeText} ${name}` : name;
const propNode = this.createNode('property', name, node, {
docstring,
signature,
visibility,
isStatic,
});
// `@Inject() private svc: Foo` and similar — capture the
// decorator->target relationship for class properties too.
if (propNode) {
this.extractDecoratorsFor(node, propNode.id);
// Emit `references` edges from the property to types named in its
// type annotation (#381). The generic walker handles TS-style
// `type_annotation` children; the C# branch walks the `type` field.
this.extractTypeAnnotations(node, propNode.id);
}