forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextraction.test.ts
More file actions
4461 lines (3723 loc) · 144 KB
/
extraction.test.ts
File metadata and controls
4461 lines (3723 loc) · 144 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
/**
* Extraction Tests
*
* Tests for the tree-sitter extraction system.
*/
import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { CodeGraph } from '../src';
import { extractFromSource, scanDirectory } from '../src/extraction';
import { detectLanguage, isLanguageSupported, getSupportedLanguages, initGrammars, loadAllGrammars, isSourceFile } from '../src/extraction/grammars';
import { normalizePath } from '../src/utils';
beforeAll(async () => {
await initGrammars();
await loadAllGrammars();
});
// Create a temporary directory for each test
function createTempDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
}
// Clean up temporary directory
function cleanupTempDir(dir: string): void {
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true, force: true });
}
}
describe('Language Detection', () => {
it('should detect TypeScript files', () => {
expect(detectLanguage('src/index.ts')).toBe('typescript');
expect(detectLanguage('components/Button.tsx')).toBe('tsx');
});
it('should detect JavaScript files', () => {
expect(detectLanguage('index.js')).toBe('javascript');
expect(detectLanguage('App.jsx')).toBe('jsx');
expect(detectLanguage('config.mjs')).toBe('javascript');
});
it('should detect Python files', () => {
expect(detectLanguage('main.py')).toBe('python');
});
it('should detect Go files', () => {
expect(detectLanguage('main.go')).toBe('go');
});
it('should detect Rust files', () => {
expect(detectLanguage('lib.rs')).toBe('rust');
});
it('should detect Java files', () => {
expect(detectLanguage('Main.java')).toBe('java');
});
it('should detect C files', () => {
expect(detectLanguage('main.c')).toBe('c');
expect(detectLanguage('utils.h')).toBe('c');
});
it('should detect C++ files', () => {
expect(detectLanguage('main.cpp')).toBe('cpp');
expect(detectLanguage('class.hpp')).toBe('cpp');
});
it('should detect C# files', () => {
expect(detectLanguage('Program.cs')).toBe('csharp');
});
it('should detect PHP files', () => {
expect(detectLanguage('index.php')).toBe('php');
});
it('should detect Ruby files', () => {
expect(detectLanguage('app.rb')).toBe('ruby');
});
it('should detect Swift files', () => {
expect(detectLanguage('ViewController.swift')).toBe('swift');
});
it('should detect Kotlin files', () => {
expect(detectLanguage('MainActivity.kt')).toBe('kotlin');
expect(detectLanguage('build.gradle.kts')).toBe('kotlin');
});
it('should detect Dart files', () => {
expect(detectLanguage('main.dart')).toBe('dart');
});
it('should detect Objective-C files', () => {
expect(detectLanguage('AppDelegate.m')).toBe('objc');
expect(detectLanguage('ViewController.mm')).toBe('objc');
const objcHeader = '@interface Foo : NSObject\n@end\n';
expect(detectLanguage('Foo.h', objcHeader)).toBe('objc');
expect(detectLanguage('stdio.h', '#ifndef STDIO_H\nvoid printf();\n#endif\n')).toBe('c');
});
it('should return unknown for unsupported extensions', () => {
expect(detectLanguage('styles.css')).toBe('unknown');
expect(detectLanguage('data.json')).toBe('unknown');
});
});
describe('Language Support', () => {
it('should report supported languages', () => {
expect(isLanguageSupported('typescript')).toBe(true);
expect(isLanguageSupported('python')).toBe(true);
expect(isLanguageSupported('go')).toBe(true);
expect(isLanguageSupported('unknown')).toBe(false);
});
it('should list all supported languages', () => {
const languages = getSupportedLanguages();
expect(languages).toContain('typescript');
expect(languages).toContain('javascript');
expect(languages).toContain('python');
expect(languages).toContain('go');
expect(languages).toContain('rust');
expect(languages).toContain('java');
expect(languages).toContain('csharp');
expect(languages).toContain('php');
expect(languages).toContain('ruby');
expect(languages).toContain('swift');
expect(languages).toContain('kotlin');
expect(languages).toContain('dart');
});
});
describe('TypeScript Extraction', () => {
it('should extract function declarations', () => {
const code = `
export function processPayment(amount: number): Promise<Receipt> {
return stripe.charge(amount);
}
`;
const result = extractFromSource('payment.ts', code);
// File node + function node
const fileNode = result.nodes.find((n) => n.kind === 'file');
expect(fileNode).toBeDefined();
expect(fileNode?.name).toBe('payment.ts');
const funcNode = result.nodes.find((n) => n.kind === 'function');
expect(funcNode).toMatchObject({
kind: 'function',
name: 'processPayment',
language: 'typescript',
isExported: true,
});
expect(funcNode?.signature).toContain('amount: number');
});
it('should extract class declarations', () => {
const code = `
export class PaymentService {
private stripe: StripeClient;
constructor(apiKey: string) {
this.stripe = new StripeClient(apiKey);
}
async charge(amount: number): Promise<Receipt> {
return this.stripe.charge(amount);
}
}
`;
const result = extractFromSource('service.ts', code);
const classNode = result.nodes.find((n) => n.kind === 'class');
const methodNodes = result.nodes.filter((n) => n.kind === 'method');
expect(classNode).toBeDefined();
expect(classNode?.name).toBe('PaymentService');
expect(classNode?.isExported).toBe(true);
expect(methodNodes.length).toBeGreaterThanOrEqual(1);
const chargeMethod = methodNodes.find((m) => m.name === 'charge');
expect(chargeMethod).toBeDefined();
});
it('should extract interfaces', () => {
const code = `
export interface User {
id: string;
name: string;
email: string;
}
`;
const result = extractFromSource('types.ts', code);
const fileNode = result.nodes.find((n) => n.kind === 'file');
expect(fileNode).toBeDefined();
const ifaceNode = result.nodes.find((n) => n.kind === 'interface');
expect(ifaceNode).toMatchObject({
kind: 'interface',
name: 'User',
isExported: true,
});
});
it('should extract type references from interface property signatures', () => {
const code = `
import type { IPage } from '../PromoterList';
import type { IOrderField } from '../types';
interface Hprops {
value?: Partial<IPage> & Partial<IOrderField>;
}
`;
const result = extractFromSource('HeaderFilter.ts', code);
const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
});
it('should extract type references from interface method signatures', () => {
const code = `
import type { IPage } from '../PromoterList';
import type { IOrderField } from '../types';
interface MethodForm {
fetchPage(arg: IPage): IOrderField;
}
`;
const result = extractFromSource('MethodForm.ts', code);
const refs = result.unresolvedReferences.filter((r) => r.referenceKind === 'references');
expect(refs.some((r) => r.referenceName === 'IPage')).toBe(true);
expect(refs.some((r) => r.referenceName === 'IOrderField')).toBe(true);
});
it('should track function calls', () => {
const code = `
function main() {
const result = processData();
console.log(result);
}
`;
const result = extractFromSource('main.ts', code);
expect(result.unresolvedReferences.length).toBeGreaterThan(0);
const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
expect(calls.some((c) => c.referenceName === 'processData')).toBe(true);
});
});
describe('Arrow Function Export Extraction', () => {
it('should extract exported arrow functions assigned to const', () => {
const code = `
export const useAuth = (): AuthContextValue => {
return useContext(AuthContext);
};
`;
const result = extractFromSource('hooks.ts', code);
const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
expect(funcNode).toBeDefined();
expect(funcNode).toMatchObject({
kind: 'function',
name: 'useAuth',
isExported: true,
});
});
it('should extract exported function expressions assigned to const', () => {
const code = `
export const processData = function(input: string): string {
return input.trim();
};
`;
const result = extractFromSource('utils.ts', code);
const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
expect(funcNode).toBeDefined();
expect(funcNode).toMatchObject({
kind: 'function',
name: 'processData',
isExported: true,
});
});
it('should not extract non-exported arrow functions as exported', () => {
const code = `
const internalHelper = () => {
return 42;
};
`;
const result = extractFromSource('internal.ts', code);
const helperNode = result.nodes.find((n) => n.name === 'internalHelper');
expect(helperNode).toBeDefined();
expect(helperNode?.isExported).toBeFalsy();
});
it('should still skip truly anonymous arrow functions', () => {
const code = `
const items = [1, 2, 3].map((x) => x * 2);
`;
const result = extractFromSource('anon.ts', code);
// The inline arrow function passed to .map() has no variable_declarator parent
// and should remain anonymous (skipped)
const anonFunctions = result.nodes.filter(
(n) => n.kind === 'function' && n.name === '<anonymous>'
);
expect(anonFunctions).toHaveLength(0);
});
it('should extract multiple exported arrow functions from the same file', () => {
const code = `
export const add = (a: number, b: number): number => a + b;
export const subtract = (a: number, b: number): number => a - b;
const internal = () => 'not exported';
`;
const result = extractFromSource('math.ts', code);
const exported = result.nodes.filter((n) => n.kind === 'function' && n.isExported);
expect(exported).toHaveLength(2);
expect(exported.map((n) => n.name).sort()).toEqual(['add', 'subtract']);
const internalNode = result.nodes.find((n) => n.name === 'internal');
expect(internalNode).toBeDefined();
expect(internalNode?.isExported).toBeFalsy();
});
it('should extract arrow functions in JavaScript files', () => {
const code = `
export const fetchData = async () => {
const response = await fetch('/api/data');
return response.json();
};
`;
const result = extractFromSource('api.js', code);
const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'fetchData');
expect(funcNode).toBeDefined();
expect(funcNode).toMatchObject({
kind: 'function',
name: 'fetchData',
isExported: true,
});
});
});
describe('Type Alias Extraction', () => {
it('should extract exported type aliases in TypeScript', () => {
const code = `
export type AuthContextValue = {
user: User | null;
login: () => void;
logout: () => void;
};
`;
const result = extractFromSource('types.ts', code);
const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
expect(typeNode).toMatchObject({
kind: 'type_alias',
name: 'AuthContextValue',
isExported: true,
});
});
it('should extract non-exported type aliases', () => {
const code = `
type InternalState = {
loading: boolean;
error: string | null;
};
`;
const result = extractFromSource('internal.ts', code);
const typeNode = result.nodes.find((n) => n.kind === 'type_alias');
expect(typeNode).toMatchObject({
kind: 'type_alias',
name: 'InternalState',
isExported: false,
});
});
it('should extract multiple type aliases from the same file', () => {
const code = `
export type UnitSystem = 'metric' | 'imperial';
export type DateFormat = 'ISO' | 'US' | 'EU';
type Internal = string;
`;
const result = extractFromSource('config.ts', code);
const typeAliases = result.nodes.filter((n) => n.kind === 'type_alias');
expect(typeAliases).toHaveLength(3);
const exported = typeAliases.filter((n) => n.isExported);
expect(exported).toHaveLength(2);
expect(exported.map((n) => n.name).sort()).toEqual(['DateFormat', 'UnitSystem']);
});
});
describe('Exported Variable Extraction', () => {
it('should extract exported const with call expression (Zustand store)', () => {
const code = `
export const useUIStore = create<UIState>((set) => ({
isOpen: false,
toggle: () => set((s) => ({ isOpen: !s.isOpen })),
}));
`;
const result = extractFromSource('store.ts', code);
const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'useUIStore');
expect(varNode).toBeDefined();
expect(varNode?.isExported).toBe(true);
});
it('should extract exported const with object literal', () => {
const code = `
export const config = {
apiUrl: 'https://api.example.com',
timeout: 5000,
};
`;
const result = extractFromSource('config.ts', code);
const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'config');
expect(varNode).toBeDefined();
expect(varNode?.isExported).toBe(true);
});
it('should extract exported const with array literal', () => {
const code = `
export const SCREEN_NAMES = ['home', 'settings', 'profile'] as const;
`;
const result = extractFromSource('constants.ts', code);
const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'SCREEN_NAMES');
expect(varNode).toBeDefined();
expect(varNode?.isExported).toBe(true);
});
it('should extract exported const with primitive value', () => {
const code = `
export const MAX_RETRIES = 3;
export const API_VERSION = "v2";
`;
const result = extractFromSource('constants.ts', code);
const variables = result.nodes.filter((n) => n.kind === 'constant');
expect(variables).toHaveLength(2);
expect(variables.map((n) => n.name).sort()).toEqual(['API_VERSION', 'MAX_RETRIES']);
});
it('should NOT duplicate arrow functions as both function and variable', () => {
const code = `
export const useAuth = () => {
return useContext(AuthContext);
};
`;
const result = extractFromSource('hooks.ts', code);
// Should be extracted as function (from arrow function handler), NOT as variable
const funcNodes = result.nodes.filter((n) => n.kind === 'function' && n.name === 'useAuth');
const varNodes = result.nodes.filter((n) => n.kind === 'variable' && n.name === 'useAuth');
expect(funcNodes).toHaveLength(1);
expect(varNodes).toHaveLength(0);
});
it('should extract non-exported const as non-exported variable', () => {
const code = `
const internalConfig = {
debug: true,
};
`;
const result = extractFromSource('internal.ts', code);
// Non-exported const at file level should be extracted as a constant (not exported)
const varNodes = result.nodes.filter((n) => (n.kind === 'variable' || n.kind === 'constant') && n.name === 'internalConfig');
expect(varNodes).toHaveLength(1);
expect(varNodes[0]?.isExported).toBeFalsy();
});
it('should extract Zod schema exports', () => {
const code = `
export const userSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email(),
});
`;
const result = extractFromSource('schemas.ts', code);
const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'userSchema');
expect(varNode).toBeDefined();
expect(varNode?.isExported).toBe(true);
});
it('should extract XState machine exports', () => {
const code = `
export const authMachine = createMachine({
id: "auth",
initial: "idle",
states: {
idle: {},
authenticated: {},
},
});
`;
const result = extractFromSource('machine.ts', code);
const varNode = result.nodes.find((n) => n.kind === 'constant' && n.name === 'authMachine');
expect(varNode).toBeDefined();
expect(varNode?.isExported).toBe(true);
});
it('should extract calls from a top-level variable initializer (issue #425)', () => {
const code = `
import { getTokenMp } from './api/upload';
const token = getTokenMp();
`;
const result = extractFromSource('app.ts', code);
const call = result.unresolvedReferences.find(
(ref) => ref.referenceKind === 'calls' && ref.referenceName === 'getTokenMp'
);
expect(call).toBeDefined();
});
});
describe('File Node Extraction', () => {
it('should create a file-kind node for each parsed file', () => {
const code = `
export function greet(name: string): string {
return "Hello " + name;
}
`;
const result = extractFromSource('greeter.ts', code);
const fileNode = result.nodes.find((n) => n.kind === 'file');
expect(fileNode).toBeDefined();
expect(fileNode?.name).toBe('greeter.ts');
expect(fileNode?.filePath).toBe('greeter.ts');
expect(fileNode?.language).toBe('typescript');
expect(fileNode?.startLine).toBe(1);
});
it('should create file nodes for Python files', () => {
const code = `
def main():
pass
`;
const result = extractFromSource('main.py', code);
const fileNode = result.nodes.find((n) => n.kind === 'file');
expect(fileNode).toBeDefined();
expect(fileNode?.name).toBe('main.py');
expect(fileNode?.language).toBe('python');
});
it('should create containment edges from file node to top-level declarations', () => {
const code = `
export function foo() {}
export function bar() {}
`;
const result = extractFromSource('fns.ts', code);
const fileNode = result.nodes.find((n) => n.kind === 'file');
expect(fileNode).toBeDefined();
// There should be contains edges from the file node to each function
const containsEdges = result.edges.filter(
(e) => e.source === fileNode?.id && e.kind === 'contains'
);
expect(containsEdges.length).toBeGreaterThanOrEqual(2);
});
});
describe('Python Extraction', () => {
it('should extract function definitions', () => {
const code = `
def calculate_total(items: list, tax_rate: float) -> float:
"""Calculate total with tax."""
subtotal = sum(item.price for item in items)
return subtotal * (1 + tax_rate)
`;
const result = extractFromSource('calc.py', code);
const fileNode = result.nodes.find((n) => n.kind === 'file');
expect(fileNode).toBeDefined();
const funcNode = result.nodes.find((n) => n.kind === 'function');
expect(funcNode).toMatchObject({
kind: 'function',
name: 'calculate_total',
language: 'python',
});
});
it('should extract class definitions', () => {
const code = `
class UserService:
"""Service for managing users."""
def __init__(self, db):
self.db = db
def get_user(self, user_id: str) -> User:
return self.db.find_user(user_id)
`;
const result = extractFromSource('service.py', code);
const classNode = result.nodes.find((n) => n.kind === 'class');
expect(classNode).toBeDefined();
expect(classNode?.name).toBe('UserService');
});
});
describe('Go Extraction', () => {
it('should extract function declarations', () => {
const code = `
package main
func ProcessOrder(order Order) (Receipt, error) {
// Process the order
return Receipt{}, nil
}
`;
const result = extractFromSource('main.go', code);
const funcNode = result.nodes.find((n) => n.kind === 'function');
expect(funcNode).toBeDefined();
expect(funcNode?.name).toBe('ProcessOrder');
});
it('should extract method declarations', () => {
const code = `
package main
type Service struct {
db *Database
}
func (s *Service) GetUser(id string) (*User, error) {
return s.db.FindUser(id)
}
`;
const result = extractFromSource('service.go', code);
const methodNode = result.nodes.find((n) => n.kind === 'method');
expect(methodNode).toBeDefined();
expect(methodNode?.name).toBe('GetUser');
});
});
describe('Rust Extraction', () => {
it('should extract function declarations', () => {
const code = `
pub fn process_data(input: &str) -> Result<Output, Error> {
// Process data
Ok(Output::new())
}
`;
const result = extractFromSource('lib.rs', code);
const funcNode = result.nodes.find((n) => n.kind === 'function');
expect(funcNode).toBeDefined();
expect(funcNode?.name).toBe('process_data');
expect(funcNode?.visibility).toBe('public');
});
it('should extract struct declarations', () => {
const code = `
pub struct User {
pub id: String,
pub name: String,
email: String,
}
`;
const result = extractFromSource('models.rs', code);
const structNode = result.nodes.find((n) => n.kind === 'struct');
expect(structNode).toBeDefined();
expect(structNode?.name).toBe('User');
});
it('should extract trait declarations', () => {
const code = `
pub trait Repository {
fn find(&self, id: &str) -> Option<Entity>;
fn save(&mut self, entity: Entity) -> Result<(), Error>;
}
`;
const result = extractFromSource('traits.rs', code);
const traitNode = result.nodes.find((n) => n.kind === 'trait');
expect(traitNode).toBeDefined();
expect(traitNode?.name).toBe('Repository');
});
it('should extract impl Trait for Type as implements edges', () => {
const code = `
pub struct MyCache {}
pub trait Cache {
fn get(&self, key: &str) -> Option<String>;
}
impl Cache for MyCache {
fn get(&self, key: &str) -> Option<String> {
None
}
}
`;
const result = extractFromSource('cache.rs', code);
// Should have an unresolved reference for implements
const implRef = result.unresolvedReferences.find(
(r) => r.referenceKind === 'implements' && r.referenceName === 'Cache'
);
expect(implRef).toBeDefined();
// The struct MyCache should be the source
const myCacheNode = result.nodes.find((n) => n.name === 'MyCache' && n.kind === 'struct');
expect(myCacheNode).toBeDefined();
expect(implRef?.fromNodeId).toBe(myCacheNode?.id);
});
it('should extract trait supertraits as extends references', () => {
const code = `
pub trait Display {}
pub trait Error: Display {
fn description(&self) -> &str;
}
`;
const result = extractFromSource('error.rs', code);
const extendsRef = result.unresolvedReferences.find(
(r) => r.referenceKind === 'extends' && r.referenceName === 'Display'
);
expect(extendsRef).toBeDefined();
const errorTrait = result.nodes.find((n) => n.name === 'Error' && n.kind === 'trait');
expect(errorTrait).toBeDefined();
expect(extendsRef?.fromNodeId).toBe(errorTrait?.id);
});
it('should not create implements edges for plain impl blocks', () => {
const code = `
pub struct Counter {
count: u32,
}
impl Counter {
pub fn new() -> Counter {
Counter { count: 0 }
}
pub fn increment(&mut self) {
self.count += 1;
}
}
`;
const result = extractFromSource('counter.rs', code);
// Should have no implements references (no trait involved)
const implRefs = result.unresolvedReferences.filter(
(r) => r.referenceKind === 'implements'
);
expect(implRefs).toHaveLength(0);
});
});
describe('Java Extraction', () => {
it('should extract class declarations', () => {
const code = `
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
public User getUser(String id) {
return repository.findById(id);
}
}
`;
const result = extractFromSource('UserService.java', code);
const classNode = result.nodes.find((n) => n.kind === 'class');
expect(classNode).toBeDefined();
expect(classNode?.name).toBe('UserService');
expect(classNode?.visibility).toBe('public');
});
it('should extract method declarations', () => {
const code = `
public class Calculator {
public static int add(int a, int b) {
return a + b;
}
}
`;
const result = extractFromSource('Calculator.java', code);
const methodNode = result.nodes.find((n) => n.kind === 'method' && n.name === 'add');
expect(methodNode).toBeDefined();
expect(methodNode?.isStatic).toBe(true);
});
it('wraps top-level declarations in a namespace from package_declaration', () => {
const code = `
package com.example.foo;
public class Bar {
public String greet() { return "hi"; }
}
`;
const result = extractFromSource('Bar.java', code);
const ns = result.nodes.find((n) => n.kind === 'namespace');
expect(ns?.name).toBe('com.example.foo');
const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
expect(cls?.qualifiedName).toBe('com.example.foo::Bar');
const greet = result.nodes.find((n) => n.kind === 'method' && n.name === 'greet');
expect(greet?.qualifiedName).toBe('com.example.foo::Bar::greet');
});
it('does not wrap when no package is declared', () => {
const code = `
public class Bar {
public String greet() { return "hi"; }
}
`;
const result = extractFromSource('Bar.java', code);
expect(result.nodes.find((n) => n.kind === 'namespace')).toBeUndefined();
const cls = result.nodes.find((n) => n.kind === 'class' && n.name === 'Bar');
expect(cls?.qualifiedName).toBe('Bar');
});
it('extracts anonymous-class overrides from `new T() { ... }`', () => {
// The pattern that breaks the trace through `strategy.foo()` in
// libraries like guava's Splitter: the lambda-returned anonymous
// class overrides abstract methods on the base, but without
// extracting those overrides the interface→impl synthesizer has
// nothing to bridge.
const code = `
package com.example;
abstract class Base {
abstract int compute(int x);
}
public class Factory {
public Base make() {
return new Base() {
@Override
int compute(int x) { return x + 1; }
};
}
}
`;
const result = extractFromSource('Factory.java', code);
const anon = result.nodes.find((n) => n.kind === 'class' && /Base\$anon@/.test(n.name));
expect(anon, 'anonymous Base subclass should be extracted as a class').toBeDefined();
const compute = result.nodes.find(
(n) => n.kind === 'method' && n.name === 'compute' && n.qualifiedName.includes('$anon@')
);
expect(compute, 'override method should be a method on the anon class').toBeDefined();
expect(compute!.qualifiedName).toContain('Factory::make::<Base$anon@');
expect(compute!.qualifiedName.endsWith('::compute')).toBe(true);
// Anon class must extend Base so Phase 5.5 (interface-impl) can bridge.
const extendsRef = result.unresolvedReferences.find(
(r) => r.referenceKind === 'extends' && r.referenceName === 'Base' && r.fromNodeId === anon!.id
);
expect(extendsRef, 'anon class should carry an `extends Base` reference').toBeDefined();
// The enclosing `make` method still emits an instantiates edge to Base —
// anon extraction must not swallow that signal.
const instantiatesRef = result.unresolvedReferences.find(
(r) => r.referenceKind === 'instantiates' && r.referenceName === 'Base'
);
expect(instantiatesRef, 'enclosing method should still instantiate Base').toBeDefined();
});
it('extracts anonymous-class overrides inside a lambda body', () => {
// The exact guava pattern: a lambda is passed to a constructor, and the
// lambda body returns `new T() { @Override ... }`. The anon class must
// still surface even though it sits inside a lambda_expression node.
const code = `
package com.example;
interface Strategy {
java.util.Iterator<String> iterator(String s);
}
abstract class BaseIter implements java.util.Iterator<String> {
abstract int separatorStart(int start);
}
public class Splitter {
private final Strategy strategy;
public Splitter(Strategy s) { this.strategy = s; }
public static Splitter on(char c) {
return new Splitter((seq) ->
new BaseIter() {
@Override
int separatorStart(int start) { return start + 1; }
@Override public boolean hasNext() { return false; }
@Override public String next() { return null; }
});
}
}
`;
const result = extractFromSource('Splitter.java', code);
const anon = result.nodes.find((n) => n.kind === 'class' && /BaseIter\$anon@/.test(n.name));
expect(anon, 'anon BaseIter inside the lambda body should be extracted').toBeDefined();
const sepStart = result.nodes.find(
(n) =>
n.kind === 'method' &&
n.name === 'separatorStart' &&
n.qualifiedName.includes('$anon@')
);
expect(sepStart, 'override inside the lambda-returned anon class should be a method node').toBeDefined();
});
});
describe('C# Extraction', () => {
it('should extract class declarations', () => {
const code = `
public class OrderService
{
private readonly IOrderRepository _repository;
public OrderService(IOrderRepository repository)
{
_repository = repository;
}
public async Task<Order> GetOrderAsync(string id)
{
return await _repository.FindByIdAsync(id);
}
}
`;
const result = extractFromSource('OrderService.cs', code);
const classNode = result.nodes.find((n) => n.kind === 'class');
expect(classNode).toBeDefined();
expect(classNode?.name).toBe('OrderService');
expect(classNode?.visibility).toBe('public');
});
});
describe('PHP Extraction', () => {
it('should extract class declarations', () => {
const code = `<?php
class UserController
{
private UserService $userService;
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
public function show(string $id): User
{
return $this->userService->find($id);
}
}
`;
const result = extractFromSource('UserController.php', code);
const classNode = result.nodes.find((n) => n.kind === 'class');
expect(classNode).toBeDefined();
expect(classNode?.name).toBe('UserController');
});
it('should extract class inheritance (extends) and interface implementation', () => {
const code = `<?php
class ChildController extends BaseController implements Serializable, JsonSerializable
{