-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathjavascript.test.ts
More file actions
2773 lines (2488 loc) · 114 KB
/
Copy pathjavascript.test.ts
File metadata and controls
2773 lines (2488 loc) · 114 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
/**
* JavaScript/TypeScript parser tests.
*
* NOTE: These tests require vitest and web-tree-sitter to be installed.
* Run: npm install
* Then: npm test
*/
import { beforeAll, describe, expect, it } from 'vitest';
import { createParsers, extractSymbols } from '../../src/domain/parser.js';
import { setTypeMapEntry } from '../../src/extractors/helpers.js';
describe('JavaScript parser', () => {
let parsers: any;
beforeAll(async () => {
parsers = await createParsers();
});
function parseJS(code) {
const parser = parsers.get('javascript');
const tree = parser.parse(code);
return extractSymbols(tree, 'test.js');
}
it('extracts named function declarations', () => {
const symbols = parseJS(`function greet(name) { return "hello " + name; }`);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'greet', kind: 'function', line: 1 }),
);
});
it('extracts arrow function assignments', () => {
const symbols = parseJS(`const add = (a, b) => a + b;`);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'add', kind: 'function' }),
);
});
it('extracts generator function declarations', () => {
const symbols = parseJS(`function* gen() { yield 1; }`);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'gen', kind: 'function' }),
);
});
it('extracts variable-declared generator functions', () => {
const symbols = parseJS(`const gen = function*() { yield 1; };`);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'gen', kind: 'function' }),
);
});
it('attributes calls inside generator body to the generator', () => {
// Use multi-line generators so line ranges are non-overlapping and the
// attribution can be verified by line number containment.
const symbols = parseJS(
'function* gen9() {\n yield* gen8();\n}\nfunction* gen8() { yield 1; }',
);
const gen9Def = symbols.definitions.find((d) => d.name === 'gen9');
const gen8Def = symbols.definitions.find((d) => d.name === 'gen8');
expect(gen9Def).toBeDefined();
expect(gen8Def).toBeDefined();
// The call to gen8 must exist.
const gen8Call = symbols.calls.find((c) => c.name === 'gen8');
expect(gen8Call).toBeDefined();
// The call's line must fall within gen9's range — proving it is attributed
// to gen9's body, not to file level or to gen8 itself.
expect(gen8Call!.line).toBeGreaterThanOrEqual(gen9Def!.line);
expect(gen8Call!.line).toBeLessThanOrEqual(gen9Def!.endLine!);
// Negative: the call must NOT fall within gen8's own range (not self-attributed).
const callIsInsideGen8 =
gen8Call!.line >= gen8Def!.line && gen8Call!.line <= (gen8Def!.endLine ?? gen8Def!.line);
expect(callIsInsideGen8).toBe(false);
});
it('captures calls inside yield* expressions', () => {
const symbols = parseJS(`function* delegator() { yield* inner(); }`);
expect(symbols.calls).toContainEqual(expect.objectContaining({ name: 'inner' }));
});
it('extracts class declarations', () => {
const symbols = parseJS(`class Foo { bar() {} }`);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'Foo', kind: 'class' }),
);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'Foo.bar', kind: 'method' }),
);
});
it('extracts class field definitions with initializers as method definitions', () => {
const symbols = parseJS(`class C1 { f8 = () => { return 1; } }`);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'C1.f8', kind: 'method' }),
);
});
it('extracts static class field definitions as method definitions', () => {
const symbols = parseJS(`class C6 { static staticProperty = function() {}; }`);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'C6.staticProperty', kind: 'method' }),
);
});
it('does not extract scalar static field definitions as method definitions', () => {
const symbols = parseJS(`class C7 { static x = 42; }`);
const names = symbols.definitions.map((d: { name: string }) => d.name);
expect(names).not.toContain('C7.x');
});
it('extracts static blocks as method definitions with unique names', () => {
const symbols = parseJS(`class C6 { static { f1(); } static { f2(); } }`);
// Each static block gets a unique name with line:column suffix to avoid collisions
const staticDefs = symbols.definitions.filter((d) => d.name.startsWith('C6.<static:'));
expect(staticDefs).toHaveLength(2);
expect(staticDefs[0]).toMatchObject({ kind: 'method' });
expect(staticDefs[1]).toMatchObject({ kind: 'method' });
// Names must be distinct even on the same line
expect(staticDefs[0].name).not.toBe(staticDefs[1].name);
});
it('extracts import statements', () => {
const symbols = parseJS(`import { foo, bar } from './baz';`);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].source).toBe('./baz');
expect(symbols.imports[0].names).toContain('foo');
expect(symbols.imports[0].names).toContain('bar');
});
// Regression coverage for #1730: `import { X as Y }` must record the local
// binding (Y) — what call sites actually reference — in `names`, plus the
// `{ local, imported }` rename pair so call-edge resolution can recover the
// original exported symbol (X) when a call site uses the local alias.
describe('renamed import specifiers (#1730)', () => {
it('records the local alias, not the source name, in imports[].names', () => {
const symbols = parseJS(`import { collectFiles as collectFilesUtil } from './helpers';`);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].names).toEqual(['collectFilesUtil']);
});
it('records the local -> original rename pair in renamedImports', () => {
const symbols = parseJS(`import { collectFiles as collectFilesUtil } from './helpers';`);
expect(symbols.imports[0].renamedImports).toEqual([
{ local: 'collectFilesUtil', imported: 'collectFiles' },
]);
});
it('does not set renamedImports for non-renamed specifiers', () => {
const symbols = parseJS(`import { foo, bar } from './baz';`);
expect(symbols.imports[0].renamedImports).toBeUndefined();
});
it('handles a mix of renamed and non-renamed specifiers in one statement', () => {
const symbols = parseJS(
`import { foo, collectFiles as collectFilesUtil, bar } from './mixed';`,
);
expect(symbols.imports[0].names).toEqual(['foo', 'collectFilesUtil', 'bar']);
expect(symbols.imports[0].renamedImports).toEqual([
{ local: 'collectFilesUtil', imported: 'collectFiles' },
]);
});
it('records the external-alias -> declared-name rename pair for export_specifier (reexport) statements (#1823)', () => {
// export_specifier semantics differ from import_specifier (name = local
// declaration being re-exported, alias = external name a consumer of
// this barrel imports), so `names` keeps recording the declared name
// (collectFiles) — barrel/reexport tracing keys off it (see
// resolveBarrelExport). renamedImports separately records the
// { local: externalAlias, imported: declaredName } pair so barrel
// resolution can translate a consumer's requested external name back
// to the declared name.
const symbols = parseJS(`export { collectFiles as friendlyName } from './helpers';`);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].reexport).toBe(true);
expect(symbols.imports[0].names).toEqual(['collectFiles']);
expect(symbols.imports[0].renamedImports).toEqual([
{ local: 'friendlyName', imported: 'collectFiles' },
]);
});
it('does not set renamedImports for non-renamed export_specifier (reexport) statements', () => {
const symbols = parseJS(`export { collectFiles } from './helpers';`);
expect(symbols.imports[0].renamedImports).toBeUndefined();
});
});
describe('inline per-specifier type-only import modifier (#1813)', () => {
function parseTS(code) {
const parser = parsers.get('typescript');
const tree = parser.parse(code);
return extractSymbols(tree, 'test.ts');
}
it('records the type-only specifier in typeOnlyNames for a mixed statement', () => {
const symbols = parseTS(`import { openRepo, type Repository } from './db';`);
expect(symbols.imports[0].names).toEqual(['openRepo', 'Repository']);
expect(symbols.imports[0].typeOnly).toBe(false);
expect(symbols.imports[0].typeOnlyNames).toEqual(['Repository']);
});
it('records the type-only specifier regardless of its position in the statement', () => {
const symbols = parseTS(`import { type Repository, openRepo } from './db';`);
expect(symbols.imports[0].typeOnlyNames).toEqual(['Repository']);
});
it('records every type-only name when multiple specifiers use the inline modifier', () => {
const symbols = parseTS(`import { type A, type B, value } from './mixed';`);
expect(symbols.imports[0].typeOnlyNames).toEqual(['A', 'B']);
});
it('recognizes the `typeof` modifier as well as `type`', () => {
const symbols = parseTS(`import { typeof Z, value } from './mixed';`);
expect(symbols.imports[0].typeOnlyNames).toEqual(['Z']);
});
it('does not set typeOnlyNames when no specifier uses the inline modifier', () => {
const symbols = parseTS(`import { foo, bar } from './baz';`);
expect(symbols.imports[0].typeOnlyNames).toBeUndefined();
});
it('does not set typeOnlyNames for a whole-statement `import type` (already covered by typeOnly)', () => {
const symbols = parseTS(`import type { Foo, Bar } from './types';`);
expect(symbols.imports[0].typeOnly).toBe(true);
expect(symbols.imports[0].typeOnlyNames).toBeUndefined();
});
it('records the local alias, not the source name, for a renamed type-only specifier', () => {
const symbols = parseTS(`import { type Repository as Repo, openRepo } from './db';`);
expect(symbols.imports[0].names).toEqual(['Repo', 'openRepo']);
expect(symbols.imports[0].typeOnlyNames).toEqual(['Repo']);
expect(symbols.imports[0].renamedImports).toEqual([
{ local: 'Repo', imported: 'Repository' },
]);
});
});
describe('dynamic import() destructuring through parens/as-cast wrappers (#1781)', () => {
function parseTS(code) {
const parser = parsers.get('typescript');
const tree = parser.parse(code);
return extractSymbols(tree, 'test.ts');
}
// Before the fix, extractDynamicImportNames walked up from the import()
// call through at most one optional await_expression before requiring the
// immediate parent to be a variable_declarator. Wrapping the awaited call
// in redundant parens and/or a TS `as {...}` cast — exactly the pattern
// used throughout native-orchestrator.ts — inserted extra
// parenthesized_expression/as_expression layers that broke the walk-up,
// so `names` came back empty and the destructured bindings never got
// credited as real consumers of the target module's exports (#1781).
it('extracts destructured names from a bare dynamic import (no wrapper)', () => {
const symbols = parseJS(`const { a, b } = await import('./foo.js');`);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].names).toEqual(['a', 'b']);
expect(symbols.imports[0].dynamicImport).toBe(true);
});
it('extracts destructured names when the awaited import is wrapped in redundant parens', () => {
const symbols = parseTS(`const { a, b } = (await import('./foo.js'));`);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].names).toEqual(['a', 'b']);
});
it('extracts destructured names through a TypeScript `as {...}` type assertion (no parens)', () => {
const symbols = parseTS(`const { a, b } = await import('./foo.js') as { a: Fn; b: Fn };`);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].names).toEqual(['a', 'b']);
});
it('extracts destructured names through a TypeScript `satisfies {...}` assertion', () => {
// TS 4.9+ `satisfies` is structurally identical to `as` here (Greptile
// follow-up to #1781) — same walk-up gap would otherwise reproduce.
const symbols = parseTS(
`const { a, b } = await import('./foo.js') satisfies { a: Fn; b: Fn };`,
);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].names).toEqual(['a', 'b']);
});
it('extracts destructured names through parens + `as`-cast combined (exact repro shape)', () => {
// Matches native-orchestrator.ts's actual production pattern:
// const { X, Y } = (await import('./mod.js')) as { X: Fn; Y: Fn };
const symbols = parseTS(`
const { buildDataflowVerticesFromMap, buildDataflowEdges } =
(await import('../../../../features/dataflow.js')) as {
buildDataflowVerticesFromMap: (db: unknown) => number;
buildDataflowEdges: (db: unknown) => Promise<void>;
};
`);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].source).toBe('../../../../features/dataflow.js');
expect(symbols.imports[0].names).toEqual([
'buildDataflowVerticesFromMap',
'buildDataflowEdges',
]);
expect(symbols.imports[0].dynamicImport).toBe(true);
});
it('still extracts a single namespace-style binding through parens + as-cast', () => {
const symbols = parseTS(`const mod = (await import('./foo.js')) as { a: number };`);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].names).toEqual(['mod']);
});
});
describe('dynamic import() destructuring rename (#1824)', () => {
function parseTS(code) {
const parser = parsers.get('typescript');
const tree = parser.parse(code);
return extractSymbols(tree, 'test.ts');
}
// `extractDynamicImportNames`'s pair_pattern branch preferred the
// tree-sitter `key` field (the name exported by the target module) over
// `value` (the local binding actually referenced by call sites) — the
// same class of bug fixed for static `import { X as Y }` specifiers in
// #1730. `names` must carry the local alias, with the local -> original
// mapping recorded in `renamedImports` so call-edge resolution can still
// find the target module's real export.
it('records the local alias, not the exported name, for a renamed destructure', () => {
const symbols = parseJS(`const { a: b } = await import('./mod.js');`);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].names).toEqual(['b']);
expect(symbols.imports[0].renamedImports).toEqual([{ local: 'b', imported: 'a' }]);
});
it('handles a mix of renamed and plain destructured bindings', () => {
const symbols = parseJS(`const { a, realName: alias, c } = await import('./mod.js');`);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].names).toEqual(['a', 'alias', 'c']);
expect(symbols.imports[0].renamedImports).toEqual([{ local: 'alias', imported: 'realName' }]);
});
it('does not record renamedImports when no specifier is renamed', () => {
const symbols = parseJS(`const { a, b } = await import('./mod.js');`);
expect(symbols.imports[0].names).toEqual(['a', 'b']);
expect(symbols.imports[0].renamedImports).toBeUndefined();
});
it('records the local alias through a default value on a renamed destructure', () => {
const symbols = parseJS(`const { a: b = null } = await import('./mod.js');`);
expect(symbols.imports[0].names).toEqual(['b']);
expect(symbols.imports[0].renamedImports).toEqual([{ local: 'b', imported: 'a' }]);
});
it('records the rename through parens + as-cast wrappers', () => {
const symbols = parseTS(
`const { realName: alias } = (await import('./mod.js')) as { realName: Fn };`,
);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].names).toEqual(['alias']);
expect(symbols.imports[0].renamedImports).toEqual([{ local: 'alias', imported: 'realName' }]);
});
it('strips quotes from a string-literal destructuring key (Greptile follow-up)', () => {
// `{ 'foo-bar': local }` — the key's raw text includes quotes; using it
// verbatim as `imported` would make the resolver look for an export
// literally named `'foo-bar'`, which never matches.
const symbols = parseJS(`const { 'foo-bar': local } = await import('./mod.js');`);
expect(symbols.imports[0].names).toEqual(['local']);
expect(symbols.imports[0].renamedImports).toEqual([{ local: 'local', imported: 'foo-bar' }]);
});
it('unwraps a computed string-literal destructuring key the same way', () => {
const symbols = parseJS(`const { ['foo-bar']: local } = await import('./mod.js');`);
expect(symbols.imports[0].names).toEqual(['local']);
expect(symbols.imports[0].renamedImports).toEqual([{ local: 'local', imported: 'foo-bar' }]);
});
it('still tracks the local binding for a non-string computed key, without a rename pair', () => {
// `[Symbol()]` has no statically resolvable export name — the local
// binding must still be tracked, just without a renamedImports entry.
const symbols = parseJS(`const { [Symbol()]: local } = await import('./mod.js');`);
expect(symbols.imports[0].names).toEqual(['local']);
expect(symbols.imports[0].renamedImports).toBeUndefined();
});
});
it('extracts call expressions', () => {
const symbols = parseJS(`import { foo } from './bar'; foo(); baz();`);
expect(symbols.calls).toContainEqual(expect.objectContaining({ name: 'foo' }));
expect(symbols.calls).toContainEqual(expect.objectContaining({ name: 'baz' }));
});
it('extracts class instantiation as calls', () => {
const symbols = parseJS(`
const e = new CodegraphError("msg");
new Foo();
throw new ParseError("x");
const bar = new ns.Bar();
`);
expect(symbols.calls).toContainEqual(expect.objectContaining({ name: 'CodegraphError' }));
expect(symbols.calls).toContainEqual(expect.objectContaining({ name: 'Foo' }));
expect(symbols.calls).toContainEqual(expect.objectContaining({ name: 'ParseError' }));
expect(symbols.calls).toContainEqual(expect.objectContaining({ name: 'Bar', receiver: 'ns' }));
});
it('handles re-exports from barrel files', () => {
const symbols = parseJS(`export { default as Widget } from './Widget';`);
expect(symbols.imports).toHaveLength(1);
expect(symbols.imports[0].reexport).toBe(true);
});
it('tags .call()/.apply() on plain identifiers as dynamic/reflection (#1778)', () => {
// `fn.call(null, arg)` — plain-identifier receiver; the wrapped function is the
// real callee, but invoking it via .call/.apply is a genuinely reflective
// mechanism, so it's tagged dynamic/reflection — matching the native Rust engine
// (Option A of #1778; the WASM extractor previously stripped this tag for
// identifier receivers only, to work around a dedup-collision bug now fixed
// narrowly in build-edges.ts's emitDirectCallEdgesForCall, see #1687/#1778).
const symbols = parseJS(`fn.call(null, arg); obj.apply(undefined, args);`);
const fnCall = symbols.calls.find((c) => c.name === 'fn');
expect(fnCall).toBeDefined();
expect(fnCall.dynamic).toBe(true);
expect(fnCall.dynamicKind).toBe('reflection');
const objCall = symbols.calls.find((c) => c.name === 'obj');
expect(objCall).toBeDefined();
expect(objCall.dynamic).toBe(true);
expect(objCall.dynamicKind).toBe('reflection');
});
it('captures receiver for method calls', () => {
const symbols = parseJS(`
obj.method();
standalone();
this.foo();
arr[0].bar();
a.b.c();
`);
const method = symbols.calls.find((c) => c.name === 'method');
expect(method).toBeDefined();
expect(method.receiver).toBe('obj');
const standalone = symbols.calls.find((c) => c.name === 'standalone');
expect(standalone).toBeDefined();
expect(standalone.receiver).toBeUndefined();
const foo = symbols.calls.find((c) => c.name === 'foo');
expect(foo).toBeDefined();
expect(foo.receiver).toBe('this');
const c = symbols.calls.find((c) => c.name === 'c');
expect(c).toBeDefined();
expect(c.receiver).toBe('a.b');
});
describe('typeMap extraction', () => {
function parseTS(code) {
const parser = parsers.get('typescript');
const tree = parser.parse(code);
return extractSymbols(tree, 'test.ts');
}
it('extracts typeMap from type annotations with confidence 0.9', () => {
const symbols = parseTS(`const x: Router = express.Router();`);
expect(symbols.typeMap).toBeInstanceOf(Map);
expect(symbols.typeMap.get('x')).toEqual({ type: 'Router', confidence: 0.9 });
});
it('extracts typeMap from generic types', () => {
const symbols = parseTS(`const m: Map<string, number> = new Map();`);
expect(symbols.typeMap.get('m')).toEqual(
expect.objectContaining({ type: 'Map', confidence: 1.0 }),
);
});
it('infers type from new expressions with confidence 1.0', () => {
const symbols = parseTS(`const r = new Router();`);
expect(symbols.typeMap.get('r')).toEqual({ type: 'Router', confidence: 1.0 });
});
it('extracts parameter types into typeMap with confidence 0.9', () => {
const symbols = parseTS(`function process(req: Request, res: Response) {}`);
expect(symbols.typeMap.get('req')).toEqual({ type: 'Request', confidence: 0.9 });
expect(symbols.typeMap.get('res')).toEqual({ type: 'Response', confidence: 0.9 });
});
it('extracts class field annotations into class-scoped typeMap key (issue #1458)', () => {
const symbols = parseTS(`
class UserService {
private repo: Repository;
run() { this.repo.save(); }
}
`);
// Primary: class-scoped key at 0.9 — prevents cross-class collision.
expect(symbols.typeMap.get('UserService.repo')).toEqual({
type: 'Repository',
confidence: 0.9,
});
// Fallback bare keys at lower confidence for single-class files.
expect(symbols.typeMap.get('repo')).toEqual({ type: 'Repository', confidence: 0.6 });
expect(symbols.typeMap.get('this.repo')).toEqual({ type: 'Repository', confidence: 0.6 });
});
it('prevents cross-class collision for same-named fields (issue #1458)', () => {
const symbols = parseTS(`
class OrderService {
private repo: OrderRepository;
}
class UserService {
private repo: UserRepository;
}
`);
// Each class gets its own scoped key — no collision.
expect(symbols.typeMap.get('OrderService.repo')).toEqual({
type: 'OrderRepository',
confidence: 0.9,
});
expect(symbols.typeMap.get('UserService.repo')).toEqual({
type: 'UserRepository',
confidence: 0.9,
});
// Bare "repo" key should hold the first class's type at 0.6 (second write is same confidence, no overwrite).
expect(symbols.typeMap.get('repo')?.confidence).toBe(0.6);
});
it('class expression (None path) seeds bare keys at 0.9, not a class-scoped key (issue #1500)', () => {
// `const Foo = class { ... }` is a class expression — tree-sitter emits
// a `class` node (not `class_declaration`), so enclosing_type_map_class /
// typeMapClass returns null/None and the None branch fires.
const symbols = parseTS(`
const Foo = class {
private repo: Repo;
run() { this.repo.save(); }
};
`);
// None path: bare keys at full confidence (0.9), no class-scoped key.
expect(symbols.typeMap.get('repo')).toEqual({ type: 'Repo', confidence: 0.9 });
expect(symbols.typeMap.get('this.repo')).toEqual({ type: 'Repo', confidence: 0.9 });
// Must NOT produce a class-scoped key (no class name is available).
expect(symbols.typeMap.has('Foo.repo')).toBe(false);
});
it('returns empty typeMap when no annotations', () => {
const symbols = parseJS(`const x = 42; function foo(a, b) {}`);
expect(symbols.typeMap).toBeInstanceOf(Map);
expect(symbols.typeMap.size).toBe(0);
});
it('skips union and intersection types', () => {
const symbols = parseTS(`const x: string | number = 42;`);
expect(symbols.typeMap.has('x')).toBe(false);
});
it('handles let/var declarations with type annotations', () => {
const symbols = parseTS(`let app: Express = createApp();`);
expect(symbols.typeMap.get('app')).toEqual({ type: 'Express', confidence: 0.9 });
});
it('prefers constructor over annotation on the same declaration', () => {
const symbols = parseTS(`const x: Base = new Derived();`);
// Constructor on same declaration wins (confidence 1.0) because the runtime type
// is what matters for call resolution: x.render() → Derived.render, not Base.render.
// Cross-scope pollution is prevented by setTypeMapEntry's higher-confidence gate.
expect(symbols.typeMap.get('x')).toEqual({ type: 'Derived', confidence: 1.0 });
});
it('extracts factory method patterns with confidence 0.7', () => {
const symbols = parseJS(`const client = HttpClient.create();`);
expect(symbols.typeMap.get('client')).toEqual({ type: 'HttpClient', confidence: 0.7 });
});
it('ignores lowercase factory calls', () => {
const symbols = parseJS(`const result = utils.create();`);
expect(symbols.typeMap.has('result')).toBe(false);
});
it('ignores built-in globals like Math, JSON, Promise', () => {
const symbols = parseJS(`
const r = Math.random();
const d = JSON.parse('{}');
const p = Promise.resolve(42);
`);
expect(symbols.typeMap.has('r')).toBe(false);
expect(symbols.typeMap.has('d')).toBe(false);
expect(symbols.typeMap.has('p')).toBe(false);
});
// Regression: GH #964 — tree-sitter can produce partial/corrupted trees in
// which an identifier node has empty `text`. Previously the factory path
// crashed with "Cannot read properties of undefined (reading 'toLowerCase')"
// because `objName[0]` is undefined for an empty string. The guard now
// mirrors the Python extractor's short-circuit check.
it('does not crash when factory call has an empty-text identifier', () => {
// Build a mock tree that mimics `const x = <empty-identifier>.create()`.
// The walk path calls handleVarDeclaratorTypeMap → factory branch, which
// reads `obj.text` ("") and would previously call "".toLowerCase() via
// `objName[0]!.toLowerCase()`. The fix's `objName[0] &&` guard short-circuits.
const pos = { row: 0, column: 0 };
const makeNode = (
type: string,
text = '',
fields: Record<string, any> = {},
children: any[] = [],
) => {
const node: any = {
type,
text,
startPosition: pos,
endPosition: pos,
childCount: children.length,
child: (i: number) => children[i] ?? null,
childForFieldName: (name: string) => fields[name] ?? null,
parent: null,
};
for (const c of children) {
c.parent = node;
}
return node;
};
const emptyIdentifier = makeNode('identifier', '');
const createName = makeNode('property_identifier', 'create');
const memberExpr = makeNode(
'member_expression',
'.create',
{
object: emptyIdentifier,
property: createName,
},
[emptyIdentifier, createName],
);
const callExpr = makeNode(
'call_expression',
'.create()',
{
function: memberExpr,
},
[memberExpr],
);
const nameIdent = makeNode('identifier', 'x');
const declarator = makeNode(
'variable_declarator',
'x = .create()',
{
name: nameIdent,
value: callExpr,
},
[nameIdent, callExpr],
);
const lexDecl = makeNode('lexical_declaration', 'const x = .create();', {}, [declarator]);
const root = makeNode('program', '', {}, [lexDecl]);
const fakeTree: any = { rootNode: root };
// Before the fix this would throw TypeError. Now it should complete and
// simply leave `x` out of the typeMap (empty identifier is ignored).
expect(() => extractSymbols(fakeTree, 'test.js')).not.toThrow();
const symbols = extractSymbols(fakeTree, 'test.js');
expect(symbols.typeMap.has('x')).toBe(false);
});
});
describe('Phase 8.3d: property write pts tracking', () => {
function parseJS(code) {
const parser = parsers.get('javascript');
const tree = parser.parse(code);
return extractSymbols(tree, 'test.js');
}
it('seeds typeMap with composite key for obj.prop = identifier', () => {
const symbols = parseJS(`
const handlers = {};
handlers.auth = authMiddleware;
`);
expect(symbols.typeMap.get('handlers.auth')).toEqual({
type: 'authMiddleware',
confidence: 0.85,
});
});
it('ignores chained writes (a.b.c = x)', () => {
const symbols = parseJS(`a.b.c = handler;`);
expect(symbols.typeMap.has('a.b.c')).toBe(false);
expect(symbols.typeMap.has('b.c')).toBe(false);
});
it('seeds typeMap for this.prop = new ClassName() using class-scoped key', () => {
const symbols = parseJS(`
class UserService {
constructor() {
this.logger = new Logger('UserService');
}
}
`);
expect(symbols.typeMap.get('UserService.logger')).toEqual({
type: 'Logger',
confidence: 1.0,
});
expect(symbols.typeMap.has('this.logger')).toBe(false);
});
it('uses this.prop key when no enclosing class is present', () => {
const symbols = parseJS(`
function setup() {
this.logger = new Logger();
}
`);
expect(symbols.typeMap.get('this.logger')).toEqual({ type: 'Logger', confidence: 1.0 });
});
it('scopes this.prop typeMap key to enclosing class — no collision across classes', () => {
const symbols = parseJS(`
class ClassA {
constructor() { this.service = new ServiceA(); }
}
class ClassB {
constructor() { this.service = new ServiceB(); }
}
`);
expect(symbols.typeMap.get('ClassA.service')).toEqual({ type: 'ServiceA', confidence: 1.0 });
expect(symbols.typeMap.get('ClassB.service')).toEqual({ type: 'ServiceB', confidence: 1.0 });
expect(symbols.typeMap.has('this.service')).toBe(false);
});
it('uses this.prop fallback for named class expressions (expression name not resolver-visible)', () => {
// `const Foo = class Bar { ... }` — the resolver derives callerClass from the
// binding name `Foo`, never from the expression name `Bar`. Storing as `Bar.x`
// would produce an unreachable key, so we fall back to `this.x` instead.
const symbols = parseJS(`
const Foo = class Bar {
constructor() { this.x = new X(); }
};
`);
expect(symbols.typeMap.get('this.x')).toEqual({ type: 'X', confidence: 1.0 });
expect(symbols.typeMap.has('Bar.x')).toBe(false);
});
it('does not seed typeMap for this.prop = identifier (only new expressions)', () => {
const symbols = parseJS(`
class Foo {
init(logger) { this.logger = logger; }
}
`);
expect(symbols.typeMap.has('this.logger')).toBe(false);
expect(symbols.typeMap.has('Foo.logger')).toBe(false);
});
it('ignores non-identifier RHS (a.prop = obj.method)', () => {
const symbols = parseJS(`router.use = obj.method;`);
expect(symbols.typeMap.has('router.use')).toBe(false);
});
it('ignores BUILTIN_GLOBALS as object names', () => {
const symbols = parseJS(`
console.warn = customWarn;
Object.assign = myAssign;
process.on = myHandler;
window.onload = myHandler;
document.ready = myHandler;
globalThis.fetch = myFetch;
`);
expect(symbols.typeMap.has('console.warn')).toBe(false);
expect(symbols.typeMap.has('Object.assign')).toBe(false);
expect(symbols.typeMap.has('process.on')).toBe(false);
expect(symbols.typeMap.has('window.onload')).toBe(false);
expect(symbols.typeMap.has('document.ready')).toBe(false);
expect(symbols.typeMap.has('globalThis.fetch')).toBe(false);
});
it('first-write wins when same key appears twice at equal confidence', () => {
const parser = parsers.get('typescript');
const tree = parser.parse(`
handlers.auth = firstMiddleware;
handlers.auth = secondMiddleware;
`);
const symbols = extractSymbols(tree, 'test.ts');
// Both writes are at 0.85; first-write wins (equal confidence does not promote)
expect(symbols.typeMap.get('handlers.auth')?.type).toBe('firstMiddleware');
});
it('higher-confidence entry promotes over lower-confidence entry (setTypeMapEntry)', () => {
const typeMap = new Map<string, { type: string; confidence: number }>();
// Seed with a low-confidence write (property-write confidence: 0.85)
setTypeMapEntry(typeMap, 'handlers.auth', 'firstMiddleware', 0.85);
// A higher-confidence annotation (0.9) should overwrite
setTypeMapEntry(typeMap, 'handlers.auth', 'AnnotatedHandler', 0.9);
expect(typeMap.get('handlers.auth')).toEqual({ type: 'AnnotatedHandler', confidence: 0.9 });
});
});
describe('Phase 8.2: inter-procedural return-type propagation', () => {
function parseTS(code) {
const parser = parsers.get('typescript');
const tree = parser.parse(code);
return extractSymbols(tree, 'test.ts');
}
describe('returnTypeMap extraction', () => {
it('records explicit TS return type annotation with confidence 1.0', () => {
const symbols = parseTS(`function createUser(): User { return new User(); }`);
expect(symbols.returnTypeMap).toBeInstanceOf(Map);
expect(symbols.returnTypeMap.get('createUser')).toEqual({ type: 'User', confidence: 1.0 });
});
it('infers return type from return new Constructor() with confidence 0.85', () => {
const symbols = parseTS(`function buildRouter() { return new Router(); }`);
expect(symbols.returnTypeMap.get('buildRouter')).toEqual({
type: 'Router',
confidence: 0.85,
});
});
it('prefers annotation over inferred return type', () => {
const symbols = parseTS(`function create(): Service { return new OtherService(); }`);
expect(symbols.returnTypeMap.get('create')).toEqual({ type: 'Service', confidence: 1.0 });
});
it('qualifies method return types with class name', () => {
const symbols = parseTS(`
class UserService {
getUser(): User { return new User(); }
}
`);
expect(symbols.returnTypeMap.get('UserService.getUser')).toEqual({
type: 'User',
confidence: 1.0,
});
});
it('records arrow function return type from variable declarator', () => {
const symbols = parseTS(`const createRepo = (): Repo => new Repo();`);
expect(symbols.returnTypeMap.get('createRepo')).toEqual({ type: 'Repo', confidence: 1.0 });
});
it('does not record constructor methods', () => {
const symbols = parseTS(`class Foo { constructor() {} }`);
expect(symbols.returnTypeMap.has('Foo.constructor')).toBe(false);
});
});
describe('intra-file propagation via returnTypeMap', () => {
it('propagates return type of annotated function — confidence 0.9 (1.0 - 0.1 × hop 1)', () => {
const symbols = parseTS(`
function createUser(): User { return new User(); }
const u = createUser();
`);
expect(symbols.typeMap.get('u')).toEqual({ type: 'User', confidence: 0.9 });
});
it('propagates return type inferred from return new — confidence 0.75 (0.85 - 0.1)', () => {
const symbols = parseTS(`
function buildRouter() { return new Router(); }
const r = buildRouter();
`);
expect(symbols.typeMap.get('r')).toEqual({ type: 'Router', confidence: 0.75 });
});
it('propagates return type via method call on typed receiver', () => {
const symbols = parseTS(`
class UserService {
getUser(): User { return new User(); }
}
const svc: UserService = new UserService();
const u = svc.getUser();
`);
expect(symbols.typeMap.get('u')).toEqual({ type: 'User', confidence: 0.9 });
});
it('resolves one-hop method chain — getService().getRepo()', () => {
const symbols = parseTS(`
function getService(): UserService { return new UserService(); }
class UserService {
getRepo(): Repo { return new Repo(); }
}
const repo = getService().getRepo();
`);
expect(symbols.typeMap.get('repo')).toEqual({ type: 'Repo', confidence: 0.8 });
});
it('does not override higher-confidence annotation with propagated type', () => {
const symbols = parseTS(`
function createUser(): User { return new User(); }
const u: Admin = createUser();
`);
// Annotation (0.9) wins over propagated (0.9) — setTypeMapEntry keeps first seen
expect(symbols.typeMap.get('u')?.type).toBe('Admin');
});
it('does not propagate for plain function calls with no return type info', () => {
const symbols = parseTS(`
function doSomething() { return 42; }
const x = doSomething();
`);
expect(symbols.typeMap.has('x')).toBe(false);
});
});
});
it('does not set receiver for .call()/.apply()/.bind() unwrapped calls', () => {
const symbols = parseJS(`fn.call(null, arg);`);
const fnCall = symbols.calls.find((c) => c.name === 'fn');
expect(fnCall).toBeDefined();
expect(fnCall.receiver).toBeUndefined();
});
it('tags f.call({}) as dynamic/reflection even alongside a direct f() call (#1687/#1778)', () => {
// `f(); f.call({})` — at the PARSER level, each call site is classified on its
// own terms: the direct `f()` call is static, and `f.call({})` is tagged
// dynamic/reflection regardless of the sibling direct call, matching native.
// The #1687 dedup-collision (collapsing these two call sites into a single
// graph edge without letting the reflection tag wrongly flip an
// already-recorded dyn=0 edge) is a build-edges.ts concern, verified at the
// graph level in tests/integration/issue-1778-reflection-dynamic-kind-parity.test.ts
// — not here, since the parser has no visibility into sibling call sites.
const symbols = parseJS(`const f = function () {}.bind({}); f(); f.call({});`);
const fCallCalls = symbols.calls.filter((c) => c.name === 'f');
expect(fCallCalls.length).toBe(2);
expect(fCallCalls[0].dynamic).toBeFalsy(); // f() — direct call
expect(fCallCalls[1].dynamic).toBe(true); // f.call({}) — reflection
expect(fCallCalls[1].dynamicKind).toBe('reflection');
});
it('still emits dynamic/reflection for .call on member-expression object', () => {
// `obj.method.call({})` — inner callee requires a resolution hop; stays dynamic.
const symbols = parseJS(`obj.method.call({});`);
const methodCall = symbols.calls.find((c) => c.name === 'method');
expect(methodCall).toBeDefined();
expect(methodCall.dynamic).toBe(true);
expect(methodCall.dynamicKind).toBe('reflection');
});
describe('callback pattern extraction', () => {
// Commander patterns
it('extracts Commander .command().action() with arrow function', () => {
const symbols = parseJS(
`program.command('build [dir]').action(async (dir, opts) => { run(); });`,
);
const def = symbols.definitions.find((d) => d.name === 'command:build');
expect(def).toBeDefined();
expect(def.kind).toBe('function');
});
it('extracts Commander command with angle-bracket arg', () => {
const symbols = parseJS(`program.command('query <name>').action(() => { search(); });`);
const def = symbols.definitions.find((d) => d.name === 'command:query');
expect(def).toBeDefined();
expect(def.kind).toBe('function');
});
it('does not extract Commander action with named handler', () => {
const symbols = parseJS(`program.command('test').action(handleTest);`);
const defs = symbols.definitions.filter((d) => d.name.startsWith('command:'));
expect(defs).toHaveLength(0);
});
it('still extracts calls inside Commander callback body', () => {
const symbols = parseJS(
`program.command('build [dir]').action(async (dir) => { buildGraph(dir); });`,
);
expect(symbols.calls).toContainEqual(expect.objectContaining({ name: 'buildGraph' }));
});
// Express patterns
it('extracts Express app.get route', () => {
const symbols = parseJS(`app.get('/api/users', (req, res) => { res.json([]); });`);
const def = symbols.definitions.find((d) => d.name === 'route:GET /api/users');
expect(def).toBeDefined();
expect(def.kind).toBe('function');
});
it('extracts Express router.post route', () => {
const symbols = parseJS(`router.post('/api/items', async (req, res) => { save(); });`);
const def = symbols.definitions.find((d) => d.name === 'route:POST /api/items');
expect(def).toBeDefined();
expect(def.kind).toBe('function');
});
it('does not extract Map.get as Express route', () => {
const symbols = parseJS(`myMap.get('someKey');`);
const defs = symbols.definitions.filter((d) => d.name.startsWith('route:'));
expect(defs).toHaveLength(0);
});
// Event patterns
it('extracts emitter.on event callback', () => {
const symbols = parseJS(`emitter.on('data', (chunk) => { process(chunk); });`);
const def = symbols.definitions.find((d) => d.name === 'event:data');
expect(def).toBeDefined();
expect(def.kind).toBe('function');
});
it('extracts server.once event callback', () => {
const symbols = parseJS(`server.once('listening', () => { log(); });`);
const def = symbols.definitions.find((d) => d.name === 'event:listening');
expect(def).toBeDefined();
expect(def.kind).toBe('function');
});
it('does not extract event with named handler as definition', () => {
const symbols = parseJS(`emitter.on('data', handleData);`);
const defs = symbols.definitions.filter((d) => d.name.startsWith('event:'));
expect(defs).toHaveLength(0);
// But we DO get a call edge to the named handler
expect(symbols.calls).toContainEqual(