-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathjavascript.rs
More file actions
2738 lines (2546 loc) · 115 KB
/
Copy pathjavascript.rs
File metadata and controls
2738 lines (2546 loc) · 115 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
use super::helpers::*;
use super::SymbolExtractor;
use crate::cfg::build_function_cfg;
use crate::complexity::compute_all_metrics;
use crate::types::*;
use tree_sitter::{Node, Tree};
/// Well-known JS globals that must not be recorded as pts targets.
/// Mirrors the `BUILTIN_GLOBALS` set in `src/extractors/javascript.ts`.
const JS_BUILTIN_GLOBALS: &[&str] = &[
"Math", "JSON", "Promise", "Array", "Object", "Date", "Error",
"Symbol", "Map", "Set", "RegExp", "Number", "String", "Boolean",
"WeakMap", "WeakSet", "WeakRef", "Proxy", "Reflect", "Intl",
"ArrayBuffer", "SharedArrayBuffer", "DataView", "Atomics", "BigInt",
"Float32Array", "Float64Array", "Int8Array", "Int16Array", "Int32Array",
"Uint8Array", "Uint16Array", "Uint32Array", "Uint8ClampedArray",
"URL", "URLSearchParams", "TextEncoder", "TextDecoder",
"AbortController", "AbortSignal", "Headers", "Request", "Response",
"FormData", "Blob", "File", "ReadableStream", "WritableStream",
"TransformStream", "console", "Buffer", "EventEmitter", "Stream",
];
pub struct JsExtractor;
impl SymbolExtractor for JsExtractor {
fn extract(&self, tree: &Tree, source: &[u8], file_path: &str) -> FileSymbols {
let mut symbols = FileSymbols::new(file_path.to_string());
walk_tree(&tree.root_node(), source, &mut symbols, match_js_node);
walk_ast_nodes(&tree.root_node(), source, &mut symbols.ast_nodes);
walk_tree(&tree.root_node(), source, &mut symbols, match_js_type_map);
walk_tree(&tree.root_node(), source, &mut symbols, match_js_return_type_map);
// Pre-ES6 prototype methods: `Foo.prototype.bar = fn` and `Foo.prototype = { bar: fn }`
walk_tree(&tree.root_node(), source, &mut symbols, match_js_prototype_methods);
// call_assignments runs after type_map is populated (needs receiver types)
walk_tree(&tree.root_node(), source, &mut symbols, match_js_call_assignments);
symbols
}
}
// ── Type inference helpers ──────────────────────────────────────────────────
/// Extract simple type name from a type_annotation node.
/// Returns the type name for simple types and generics, None for unions/intersections/arrays.
fn extract_simple_type_name<'a>(node: &Node<'a>, source: &'a [u8]) -> Option<&'a str> {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
match child.kind() {
"type_identifier" | "identifier" => return Some(node_text(&child, source)),
"generic_type" => {
return child.child(0).map(|n| node_text(&n, source));
}
"parenthesized_type" => return extract_simple_type_name(&child, source),
_ => {}
}
}
}
None
}
/// Extract constructor type name from a new_expression node.
fn extract_new_expr_type_name<'a>(node: &Node<'a>, source: &'a [u8]) -> Option<&'a str> {
if node.kind() != "new_expression" {
return None;
}
let ctor = node.child_by_field_name("constructor").or_else(|| node.child(1))?;
match ctor.kind() {
"identifier" => Some(node_text(&ctor, source)),
"member_expression" => {
named_child_text(&ctor, "property", source)
}
_ => None,
}
}
fn match_js_type_map(node: &Node, source: &[u8], symbols: &mut FileSymbols, _depth: usize) {
match node.kind() {
"variable_declarator" => {
if let Some(name_n) = node.child_by_field_name("name") {
if name_n.kind() == "identifier" {
let var_name = node_text(&name_n, source);
// Type annotation: confidence 0.9
if let Some(type_anno) = find_child(node, "type_annotation") {
if let Some(type_name) = extract_simple_type_name(&type_anno, source) {
push_type_map_entry(symbols, var_name.to_string(), type_name.to_string());
}
}
// Constructor: confidence 1.0 (overrides annotation in edge builder)
if let Some(value_n) = node.child_by_field_name("value") {
if value_n.kind() == "new_expression" {
if let Some(type_name) = extract_new_expr_type_name(&value_n, source) {
symbols.type_map.push(TypeMapEntry {
name: var_name.to_string(),
type_name: type_name.to_string(),
confidence: 1.0,
});
}
}
// Phase 8.3e: Object.create({ key: fn }) → composite pts key per property
if value_n.kind() == "call_expression" {
seed_object_create_entries(var_name, &value_n, source, symbols);
}
}
}
}
}
// Phase 8.3e: Object.defineProperty / defineProperties → composite pts key
"call_expression" => {
seed_define_property_entries(node, source, symbols);
}
"required_parameter" | "optional_parameter" => {
let name_node = node.child_by_field_name("pattern")
.or_else(|| node.child_by_field_name("left"))
.or_else(|| node.child(0));
if let Some(name_node) = name_node {
if name_node.kind() == "identifier" {
if let Some(type_anno) = find_child(node, "type_annotation") {
if let Some(type_name) = extract_simple_type_name(&type_anno, source) {
push_type_map_entry(
symbols,
node_text(&name_node, source).to_string(),
type_name.to_string(),
);
}
}
}
}
}
// Phase 8.3d: property-write pts tracking — `obj.prop = fn` seeds composite key.
"assignment_expression" => {
let lhs = node.child_by_field_name("left");
let rhs = node.child_by_field_name("right");
if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
if lhs.kind() == "member_expression" && rhs.kind() == "identifier" {
let obj = lhs.child_by_field_name("object");
let prop = lhs.child_by_field_name("property");
if let (Some(obj), Some(prop)) = (obj, prop) {
if obj.kind() == "identifier" {
let obj_name = node_text(&obj, source);
if !is_js_builtin_global(obj_name) {
let key = format!("{}.{}", obj_name, node_text(&prop, source));
let rhs_name = node_text(&rhs, source).to_string();
symbols.type_map.push(TypeMapEntry {
name: key,
type_name: rhs_name,
confidence: 0.85,
});
}
}
}
}
}
}
// TypeScript class field declarations: `private repo: Repository<User>`
// Seeds both "repo" and "this.repo" so that `this.repo.method()` calls
// can be resolved to the interface/class type via the type map.
"public_field_definition" | "field_definition" => {
let name_node = node.child_by_field_name("name")
.or_else(|| node.child_by_field_name("property"))
.or_else(|| find_child(node, "property_identifier"));
if let Some(name_node) = name_node {
let kind = name_node.kind();
if kind == "property_identifier" || kind == "identifier"
|| kind == "private_property_identifier"
{
let field_name = node_text(&name_node, source).to_string();
if let Some(type_anno) = find_child(node, "type_annotation") {
if let Some(type_name) = extract_simple_type_name(&type_anno, source) {
push_type_map_entry(symbols, field_name.clone(), type_name.to_string());
// "this.fieldName" key resolves `this.repo.method()` calls.
push_type_map_entry(symbols, format!("this.{}", field_name), type_name.to_string());
}
}
}
}
}
_ => {}
}
}
/// Returns true for JS built-in global objects whose property writes should not be tracked.
/// Mirrors the TypeScript `BUILTIN_GLOBALS` set in `src/extractors/javascript.ts`.
fn is_js_builtin_global(name: &str) -> bool {
matches!(
name,
"Math" | "JSON" | "Promise" | "Array" | "Object" | "Date" | "Error"
| "Symbol" | "Map" | "Set" | "RegExp" | "Number" | "String" | "Boolean"
| "WeakMap" | "WeakSet" | "WeakRef" | "Proxy" | "Reflect" | "Intl"
// Binary/typed data
| "ArrayBuffer" | "SharedArrayBuffer" | "DataView" | "Atomics" | "BigInt"
| "Float32Array" | "Float64Array"
| "Int8Array" | "Int16Array" | "Int32Array"
| "Uint8Array" | "Uint16Array" | "Uint32Array" | "Uint8ClampedArray"
// Web platform globals
| "URL" | "URLSearchParams"
| "TextEncoder" | "TextDecoder"
| "AbortController" | "AbortSignal"
| "Headers" | "Request" | "Response"
| "FormData" | "Blob" | "File"
| "ReadableStream" | "WritableStream" | "TransformStream"
// Browser/runtime globals
| "console" | "process" | "window" | "document" | "globalThis"
// Node.js built-ins
| "Buffer" | "EventEmitter" | "Stream"
)
}
// ── Phase 8.3e: Object.defineProperty / defineProperties / create ────────────
/// Seed composite pts keys for `Object.defineProperty(obj, "key", { value: fn })`
/// and `Object.defineProperties(obj, { "key": { value: fn }, ... })`.
fn seed_define_property_entries(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let Some(callee) = node.child_by_field_name("function") else { return };
if callee.kind() != "member_expression" { return; }
let Some(callee_obj) = callee.child_by_field_name("object") else { return };
if node_text(&callee_obj, source) != "Object" { return; }
let Some(callee_prop) = callee.child_by_field_name("property") else { return };
let method = node_text(&callee_prop, source);
if method != "defineProperty" && method != "defineProperties" { return; }
let args_node = node.child_by_field_name("arguments")
.or_else(|| find_child(node, "arguments"));
let Some(args_node) = args_node else { return };
// Collect non-punctuation argument nodes in order
let mut args: Vec<Node> = Vec::new();
for i in 0..args_node.child_count() {
let Some(child) = args_node.child(i) else { continue };
if !matches!(child.kind(), "(" | ")" | ",") {
args.push(child);
}
}
if method == "defineProperty" {
// Object.defineProperty(obj, "key", { value: fn })
if args.len() < 3 { return; }
if args[0].kind() != "identifier" { return; }
let obj_name = node_text(&args[0], source);
let Some(key) = extract_string_fragment(&args[1], source) else { return };
let Some(target) = find_descriptor_value(&args[2], source) else { return };
symbols.type_map.push(TypeMapEntry {
name: format!("{}.{}", obj_name, key),
type_name: target.to_string(),
confidence: 0.85,
});
} else {
// Object.defineProperties(obj, { "key": { value: fn }, ... })
if args.len() < 2 { return; }
if args[0].kind() != "identifier" { return; }
let obj_name = node_text(&args[0], source).to_string();
if args[1].kind() != "object" { return; }
seed_descriptor_object(&obj_name, &args[1], source, symbols);
}
}
/// Seed composite pts keys from `const obj = Object.create({ f1, f2 })`.
fn seed_object_create_entries(var_name: &str, call_node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let Some(callee) = call_node.child_by_field_name("function") else { return };
if callee.kind() != "member_expression" { return; }
let Some(callee_obj) = callee.child_by_field_name("object") else { return };
if node_text(&callee_obj, source) != "Object" { return; }
let Some(callee_prop) = callee.child_by_field_name("property") else { return };
if node_text(&callee_prop, source) != "create" { return; }
let args_node = call_node.child_by_field_name("arguments")
.or_else(|| find_child(call_node, "arguments"));
let Some(args_node) = args_node else { return };
// First non-punctuation argument = prototype object
let proto = (0..args_node.child_count())
.filter_map(|i| args_node.child(i))
.find(|n| !matches!(n.kind(), "(" | ")" | ","));
let Some(proto) = proto else { return };
if proto.kind() != "object" { return };
for i in 0..proto.child_count() {
let Some(child) = proto.child(i) else { continue };
match child.kind() {
"shorthand_property_identifier" => {
// { f1 } shorthand — property name equals value name
let name = node_text(&child, source);
symbols.type_map.push(TypeMapEntry {
name: format!("{}.{}", var_name, name),
type_name: name.to_string(),
confidence: 0.85,
});
}
"pair" => {
let Some(key_n) = child.child_by_field_name("key") else { continue };
let Some(val_n) = child.child_by_field_name("value") else { continue };
if val_n.kind() != "identifier" { continue; }
let key = if key_n.kind() == "string" {
extract_string_fragment(&key_n, source).map(|s| s.to_string())
} else {
Some(node_text(&key_n, source).to_string())
};
let Some(key) = key else { continue };
symbols.type_map.push(TypeMapEntry {
name: format!("{}.{}", var_name, key),
type_name: node_text(&val_n, source).to_string(),
confidence: 0.85,
});
}
_ => {}
}
}
}
/// Iterate over the properties of a `defineProperties` descriptor object and seed the type_map.
fn seed_descriptor_object(obj_name: &str, obj_node: &Node, source: &[u8], symbols: &mut FileSymbols) {
for i in 0..obj_node.child_count() {
let Some(child) = obj_node.child(i) else { continue };
if child.kind() != "pair" { continue; }
let Some(key_n) = child.child_by_field_name("key") else { continue };
let Some(val_n) = child.child_by_field_name("value") else { continue };
let key = if key_n.kind() == "string" {
extract_string_fragment(&key_n, source).map(|s| s.to_string())
} else {
Some(node_text(&key_n, source).to_string())
};
let Some(key) = key else { continue };
let Some(target) = find_descriptor_value(&val_n, source) else { continue };
symbols.type_map.push(TypeMapEntry {
name: format!("{}.{}", obj_name, key),
type_name: target.to_string(),
confidence: 0.85,
});
}
}
/// Extract the text of the `string_fragment` child of a string node, i.e. content without quotes.
fn extract_string_fragment<'a>(node: &Node<'a>, source: &'a [u8]) -> Option<&'a str> {
if node.kind() != "string" { return None; }
find_child(node, "string_fragment").map(|n| node_text(&n, source))
}
/// Find the `value` identifier in a property descriptor object `{ value: fn }`.
fn find_descriptor_value<'a>(node: &Node<'a>, source: &'a [u8]) -> Option<&'a str> {
if node.kind() != "object" { return None; }
for i in 0..node.child_count() {
let Some(child) = node.child(i) else { continue };
if child.kind() != "pair" { continue; }
let Some(key) = child.child_by_field_name("key") else { continue };
if node_text(&key, source) != "value" { continue; }
let Some(val) = child.child_by_field_name("value") else { continue };
if val.kind() == "identifier" {
return Some(node_text(&val, source));
}
}
None
}
// ── Return-type map extraction (Phase 8.2 parity) ───────────────────────────
/// Walk the AST collecting function/method return types into `symbols.return_type_map`.
/// Mirrors `extractReturnTypeMapWalk` in src/extractors/javascript.ts.
fn match_js_return_type_map(node: &Node, source: &[u8], symbols: &mut FileSymbols, _depth: usize) {
match node.kind() {
"function_declaration" | "generator_function_declaration" => {
let Some(name_n) = node.child_by_field_name("name") else { return };
let fn_name = node_text(&name_n, source);
if fn_name == "constructor" { return; }
// Use the boundary-aware variant: nested function declarations inside
// method bodies must not inherit the class prefix (matches WASM behaviour).
let key = match find_parent_class_no_fn_boundary(node, source) {
Some(cls) => format!("{}.{}", cls, fn_name),
None => fn_name.to_string(),
};
store_return_type(node, &key, source, symbols);
}
"method_definition" => {
let Some(name_n) = node.child_by_field_name("name") else { return };
let method_name = node_text(&name_n, source);
if method_name == "constructor" { return; }
// method_definition is always a direct child of class_body — plain
// find_parent_class is correct here.
let key = match find_parent_class(node, source) {
Some(cls) => format!("{}.{}", cls, method_name),
None => method_name.to_string(),
};
store_return_type(node, &key, source, symbols);
}
"variable_declarator" => {
let Some(name_n) = node.child_by_field_name("name") else { return };
if name_n.kind() != "identifier" { return; }
let Some(value_n) = node.child_by_field_name("value") else { return };
// Only arrow_function, function_expression and generator_function match the TS reference;
// "function" is not a valid tree-sitter value-expression kind here.
if !matches!(value_n.kind(), "arrow_function" | "function_expression" | "generator_function") {
return;
}
let var_name = node_text(&name_n, source);
// Use the boundary-aware variant for the same reason as function_declaration.
let key = match find_parent_class_no_fn_boundary(node, source) {
Some(cls) => format!("{}.{}", cls, var_name),
None => var_name.to_string(),
};
store_return_type(&value_n, &key, source, symbols);
}
_ => {}
}
}
/// Extract the return type of `fn_node` and push it into `symbols.return_type_map`.
/// Prefers explicit return type annotation (confidence 1.0) over inferred `return new X()`
/// (confidence 0.85). Higher confidence wins on conflict.
fn store_return_type(fn_node: &Node, fn_name: &str, source: &[u8], symbols: &mut FileSymbols) {
// Explicit return type annotation
if let Some(ret_type_node) = fn_node.child_by_field_name("return_type") {
if let Some(type_name) = extract_simple_type_name(&ret_type_node, source) {
push_return_type_entry(symbols, fn_name, type_name, 1.0);
return;
}
}
// Infer from first `return new Constructor()` in body
if let Some(body) = fn_node.child_by_field_name("body") {
if let Some(type_name) = find_return_new_expr_type(&body, source) {
push_return_type_entry(symbols, fn_name, type_name, 0.85);
}
}
}
/// Scan direct children of `body` for the first `return new X()` and return the constructor name.
fn find_return_new_expr_type<'a>(body: &Node<'a>, source: &'a [u8]) -> Option<&'a str> {
for i in 0..body.child_count() {
let Some(child) = body.child(i) else { continue };
if child.kind() != "return_statement" { continue; }
for j in 0..child.child_count() {
let Some(expr) = child.child(j) else { continue };
if expr.kind() == "new_expression" {
return extract_new_expr_type_name(&expr, source);
}
}
}
None
}
/// Insert `(fn_name → type_name)` into `return_type_map`, keeping the highest-confidence entry.
fn push_return_type_entry(symbols: &mut FileSymbols, fn_name: &str, type_name: &str, confidence: f64) {
if let Some(pos) = symbols.return_type_map.iter().position(|e| e.name == fn_name) {
if symbols.return_type_map[pos].confidence >= confidence { return; }
symbols.return_type_map.swap_remove(pos);
}
symbols.return_type_map.push(TypeMapEntry {
name: fn_name.to_string(),
type_name: type_name.to_string(),
confidence,
});
}
// ── Prototype-method extraction ─────────────────────────────────────────────
/// Walk the AST collecting pre-ES6 prototype assignments.
///
/// Mirrors `extractPrototypeMethodsWalk` in `src/extractors/javascript.ts`.
///
/// Three patterns are handled:
/// 1. `Foo.prototype.bar = function(){}` → emits `Foo.bar` as a method definition
/// 2. `Foo.prototype.bar = identifier` → seeds `typeMap['Foo.bar'] = identifier`
/// 3. `Foo.prototype = { bar: fn, ... }` → same rules applied per property
fn match_js_prototype_methods(node: &Node, source: &[u8], symbols: &mut FileSymbols, _depth: usize) {
if node.kind() != "expression_statement" { return; }
let Some(expr) = node.child(0) else { return };
if expr.kind() != "assignment_expression" { return; }
let lhs = expr.child_by_field_name("left");
let rhs = expr.child_by_field_name("right");
if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
handle_js_prototype_assignment(&lhs, &rhs, source, symbols);
}
}
fn handle_js_prototype_assignment(lhs: &Node, rhs: &Node, source: &[u8], symbols: &mut FileSymbols) {
if lhs.kind() != "member_expression" { return; }
let Some(lhs_obj) = lhs.child_by_field_name("object") else { return };
let Some(lhs_prop) = lhs.child_by_field_name("property") else { return };
// Pattern 1: `Foo.prototype.bar = rhs`
// lhs.object is `Foo.prototype` (member_expression), lhs.property is `bar`
if lhs_obj.kind() == "member_expression"
&& matches!(lhs_prop.kind(), "property_identifier" | "identifier")
{
let proto_obj = lhs_obj.child_by_field_name("object");
let proto_prop = lhs_obj.child_by_field_name("property");
if let (Some(proto_obj), Some(proto_prop)) = (proto_obj, proto_prop) {
if proto_obj.kind() == "identifier"
&& node_text(&proto_prop, source) == "prototype"
&& !is_js_builtin_global(node_text(&proto_obj, source))
{
emit_js_prototype_method(
node_text(&proto_obj, source),
node_text(&lhs_prop, source),
rhs,
source,
symbols,
);
}
}
return;
}
// Pattern 2: `Foo.prototype = { bar: fn, ... }`
// lhs.object is `Foo` (identifier), lhs.property is `prototype`, rhs is object literal
if lhs_obj.kind() == "identifier"
&& node_text(&lhs_prop, source) == "prototype"
&& !is_js_builtin_global(node_text(&lhs_obj, source))
&& rhs.kind() == "object"
{
extract_js_prototype_object_literal(node_text(&lhs_obj, source), rhs, source, symbols);
}
}
/// Emit one prototype method definition or typeMap alias for `ClassName.methodName = rhs`.
///
/// Mirrors `emitPrototypeMethod` in `src/extractors/javascript.ts`.
fn emit_js_prototype_method(class_name: &str, method_name: &str, rhs: &Node, source: &[u8], symbols: &mut FileSymbols) {
let full_name = format!("{}.{}", class_name, method_name);
match rhs.kind() {
"function_expression" | "arrow_function" => {
symbols.definitions.push(Definition {
name: full_name,
kind: "method".to_string(),
line: start_line(rhs),
end_line: Some(end_line(rhs)),
decorators: None,
complexity: None,
cfg: None,
children: None,
});
}
"identifier" => {
let rhs_name = node_text(rhs, source);
if !is_js_builtin_global(rhs_name) {
push_type_map_entry(symbols, full_name, rhs_name.to_string());
}
}
_ => {}
}
}
/// Iterate over an object literal assigned to `Foo.prototype` and emit definitions/aliases.
///
/// Mirrors `extractPrototypeObjectLiteral` in `src/extractors/javascript.ts`.
fn extract_js_prototype_object_literal(class_name: &str, obj_node: &Node, source: &[u8], symbols: &mut FileSymbols) {
for i in 0..obj_node.child_count() {
let Some(child) = obj_node.child(i) else { continue };
match child.kind() {
"method_definition" => {
let Some(name_node) = child.child_by_field_name("name") else { continue };
symbols.definitions.push(Definition {
name: format!("{}.{}", class_name, node_text(&name_node, source)),
kind: "method".to_string(),
line: start_line(&child),
end_line: Some(end_line(&child)),
decorators: None,
complexity: None,
cfg: None,
children: None,
});
}
"shorthand_property_identifier" => {
let prop_name = node_text(&child, source);
if !is_js_builtin_global(prop_name) {
push_type_map_entry(
symbols,
format!("{}.{}", class_name, prop_name),
prop_name.to_string(),
);
}
}
"pair" => {
let key_node = child.child_by_field_name("key");
let value_node = child.child_by_field_name("value");
if let (Some(key_node), Some(value_node)) = (key_node, value_node) {
let method_name: &str = if key_node.kind() == "string" {
let s = node_text(&key_node, source);
// Strip exactly one matching pair of surrounding quote characters.
// `trim_matches` would also strip embedded quotes; we only want the
// outermost delimiter pair so `"it's"` stays `it's`.
s.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
.or_else(|| s.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
.unwrap_or(s)
} else {
node_text(&key_node, source)
};
if method_name.is_empty() { continue; }
emit_js_prototype_method(class_name, method_name, &value_node, source, symbols);
}
}
_ => {}
}
}
}
// ── Call-assignment extraction (Phase 8.2 parity) ───────────────────────────
/// Walk the AST recording variable assignments from call expressions into
/// `symbols.call_assignments` for cross-file return-type propagation.
/// Mirrors `recordCallAssignment` in src/extractors/javascript.ts.
fn match_js_call_assignments(node: &Node, source: &[u8], symbols: &mut FileSymbols, _depth: usize) {
if node.kind() != "variable_declarator" { return; }
let Some(name_n) = node.child_by_field_name("name") else { return };
if name_n.kind() != "identifier" { return; }
let Some(value_n) = node.child_by_field_name("value") else { return };
if value_n.kind() != "call_expression" { return; }
let var_name = node_text(&name_n, source).to_string();
let Some(fn_node) = value_n.child_by_field_name("function") else { return };
match fn_node.kind() {
"identifier" => {
symbols.call_assignments.push(NativeCallAssignment {
var_name,
callee_name: node_text(&fn_node, source).to_string(),
receiver_type_name: None,
});
}
"member_expression" => {
let Some(obj) = fn_node.child_by_field_name("object") else { return };
let Some(prop) = fn_node.child_by_field_name("property") else { return };
if obj.kind() != "identifier" { return; }
let receiver_type = symbols.type_map.iter()
.find(|e| e.name == node_text(&obj, source))
.map(|e| e.type_name.clone());
symbols.call_assignments.push(NativeCallAssignment {
var_name,
callee_name: node_text(&prop, source).to_string(),
receiver_type_name: receiver_type,
});
}
_ => {}
}
}
fn match_js_node(node: &Node, source: &[u8], symbols: &mut FileSymbols, _depth: usize) {
match node.kind() {
"function_declaration" | "generator_function_declaration" => handle_function_decl(node, source, symbols),
"class_declaration" | "abstract_class_declaration" => {
handle_class_decl(node, source, symbols)
}
"method_definition" => handle_method_def(node, source, symbols),
"interface_declaration" => handle_interface_decl(node, source, symbols),
"type_alias_declaration" => handle_type_alias(node, source, symbols),
"enum_declaration" => handle_enum_decl(node, source, symbols),
"lexical_declaration" | "variable_declaration" => handle_var_decl(node, source, symbols),
"call_expression" => handle_call_expr(node, source, symbols),
"new_expression" => handle_new_expr(node, source, symbols),
"import_statement" => handle_import_stmt(node, source, symbols),
"export_statement" => handle_export_stmt(node, source, symbols),
"expression_statement" => handle_expr_stmt(node, source, symbols),
_ => {}
}
}
// ── Per-node-kind handlers for walk_node_depth ───────────────────────────────
fn handle_function_decl(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
if let Some(name_node) = node.child_by_field_name("name") {
let children = extract_js_parameters(node, source);
symbols.definitions.push(Definition {
name: node_text(&name_node, source).to_string(),
kind: "function".to_string(),
line: start_line(node),
end_line: Some(end_line(node)),
decorators: None,
complexity: compute_all_metrics(node, source, "javascript"),
cfg: build_function_cfg(node, "javascript", source),
children: opt_children(children),
});
}
}
fn handle_class_decl(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let Some(name_node) = node.child_by_field_name("name") else { return };
let class_name = node_text(&name_node, source).to_string();
let children = extract_js_class_properties(node, source);
symbols.definitions.push(Definition {
name: class_name.clone(),
kind: "class".to_string(),
line: start_line(node),
end_line: Some(end_line(node)),
decorators: None,
complexity: None,
cfg: None,
children: opt_children(children),
});
// Heritage: extends + implements
let heritage = node
.child_by_field_name("heritage")
.or_else(|| find_child(node, "class_heritage"));
if let Some(heritage) = heritage {
if let Some(super_name) = extract_superclass(&heritage, source) {
symbols.classes.push(ClassRelation {
name: class_name.clone(),
extends: Some(super_name),
implements: None,
line: start_line(node),
});
}
for iface in extract_implements(&heritage, source) {
symbols.classes.push(ClassRelation {
name: class_name.clone(),
extends: None,
implements: Some(iface),
line: start_line(node),
});
}
}
}
fn handle_method_def(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
if let Some(name_node) = node.child_by_field_name("name") {
let method_name = node_text(&name_node, source);
let parent_class = find_parent_class(node, source);
let full_name = match parent_class {
Some(cls) => format!("{}.{}", cls, method_name),
None => method_name.to_string(),
};
let children = extract_js_parameters(node, source);
symbols.definitions.push(Definition {
name: full_name,
kind: "method".to_string(),
line: start_line(node),
end_line: Some(end_line(node)),
decorators: None,
complexity: compute_all_metrics(node, source, "javascript"),
cfg: build_function_cfg(node, "javascript", source),
children: opt_children(children),
});
}
}
fn handle_interface_decl(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let Some(name_node) = node.child_by_field_name("name") else { return };
let iface_name = node_text(&name_node, source).to_string();
symbols.definitions.push(Definition {
name: iface_name.clone(),
kind: "interface".to_string(),
line: start_line(node),
end_line: Some(end_line(node)),
decorators: None,
complexity: None,
cfg: None,
children: None,
});
// Extract interface methods
let body = node
.child_by_field_name("body")
.or_else(|| find_child(node, "interface_body"))
.or_else(|| find_child(node, "object_type"));
if let Some(body) = body {
extract_interface_methods(&body, &iface_name, source, &mut symbols.definitions);
}
}
fn handle_type_alias(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
if let Some(name_node) = node.child_by_field_name("name") {
symbols.definitions.push(Definition {
name: node_text(&name_node, source).to_string(),
kind: "type".to_string(),
line: start_line(node),
end_line: Some(end_line(node)),
decorators: None,
complexity: None,
cfg: None,
children: None,
});
}
}
fn handle_enum_decl(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
if let Some(name_node) = node.child_by_field_name("name") {
let enum_name = node_text(&name_node, source).to_string();
let children = extract_ts_enum_members(node, source);
symbols.definitions.push(Definition {
name: enum_name,
kind: "enum".to_string(),
line: start_line(node),
end_line: Some(end_line(node)),
decorators: None,
complexity: None,
cfg: None,
children: opt_children(children),
});
}
}
fn handle_var_decl(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let is_const = node.child(0)
.map(|c| node_text(&c, source) == "const")
.unwrap_or(false);
for i in 0..node.child_count() {
let Some(declarator) = node.child(i) else { continue };
if declarator.kind() != "variable_declarator" { continue; }
let name_n = declarator.child_by_field_name("name");
let value_n = declarator.child_by_field_name("value");
let (Some(name_n), Some(value_n)) = (name_n, value_n) else { continue };
let vt = value_n.kind();
if vt == "arrow_function" || vt == "function_expression" || vt == "function" || vt == "generator_function" {
let children = extract_js_parameters(&value_n, source);
symbols.definitions.push(Definition {
name: node_text(&name_n, source).to_string(),
kind: "function".to_string(),
line: start_line(node),
end_line: Some(end_line(&value_n)),
decorators: None,
complexity: compute_all_metrics(&value_n, source, "javascript"),
cfg: build_function_cfg(&value_n, "javascript", source),
children: opt_children(children),
});
} else if is_const && name_n.kind() == "object_pattern"
&& find_parent_of_types(node, &[
"function_declaration", "arrow_function",
"function_expression", "method_definition",
"generator_function_declaration", "generator_function",
]).is_none()
{
// Parity with TS query path (extractDestructuredBindingsWalk):
// skip destructured const bindings inside function scopes so the
// Rust walk path matches FUNCTION_SCOPE_TYPES behaviour.
extract_destructured_bindings(&name_n, source, start_line(node), end_line(node), &mut symbols.definitions);
} else if is_const && is_js_literal(&value_n)
&& find_parent_of_types(node, &[
"function_declaration", "arrow_function",
"function_expression", "method_definition",
"generator_function_declaration", "generator_function",
]).is_none()
{
symbols.definitions.push(Definition {
name: node_text(&name_n, source).to_string(),
kind: "constant".to_string(),
line: start_line(node),
end_line: Some(end_line(node)),
decorators: None,
complexity: None,
cfg: None,
children: None,
});
} else if name_n.kind() == "identifier" && value_n.kind() == "identifier" {
// Phase 8.3: `const alias = handler` — record for pts analysis.
// Mirror the JS BUILTIN_GLOBALS guard: skip well-known JS globals so
// they are never seeded as pts targets (e.g. `const a = Array`).
let rhs_text = node_text(&value_n, source);
if !JS_BUILTIN_GLOBALS.contains(&rhs_text) {
symbols.fn_ref_bindings.push(FnRefBinding {
lhs: node_text(&name_n, source).to_string(),
rhs: rhs_text.to_string(),
rhs_receiver: None,
});
}
} else if name_n.kind() == "identifier" && value_n.kind() == "member_expression" {
// Phase 8.3: `const alias = obj.method` — record for pts analysis.
// Mirror the JS BUILTIN_GLOBALS guard: skip bindings where the
// receiver object is a well-known JS global (e.g. `const fn = Math.random`).
if let (Some(obj), Some(prop)) = (
value_n.child_by_field_name("object"),
value_n.child_by_field_name("property"),
) {
let obj_text = node_text(&obj, source);
if !JS_BUILTIN_GLOBALS.contains(&obj_text) {
symbols.fn_ref_bindings.push(FnRefBinding {
lhs: node_text(&name_n, source).to_string(),
rhs: node_text(&prop, source).to_string(),
rhs_receiver: Some(obj_text.to_string()),
});
}
}
}
}
}
fn handle_call_expr(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let Some(fn_node) = node.child_by_field_name("function") else { return };
if fn_node.kind() == "import" {
handle_dynamic_import(node, &fn_node, source, symbols);
return;
}
if let Some(call_info) = extract_call_info(&fn_node, node, source) {
symbols.calls.push(call_info);
}
if let Some(cb_def) = extract_callback_definition(node, source) {
symbols.definitions.push(cb_def);
}
extract_callback_reference_calls(node, source, &mut symbols.calls);
}
fn handle_new_expr(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let ctor = node.child_by_field_name("constructor")
.or_else(|| node.child(1));
let Some(ctor) = ctor else { return };
match ctor.kind() {
"identifier" => {
push_simple_call(symbols, node, node_text(&ctor, source).to_string());
}
"member_expression" => {
if let Some(call_info) = extract_call_info(&ctor, node, source) {
symbols.calls.push(call_info);
}
}
_ => {}
}
}
fn handle_dynamic_import(node: &Node, _fn_node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let args = node.child_by_field_name("arguments")
.or_else(|| find_child(node, "arguments"));
let Some(args) = args else { return };
let str_node = find_child(&args, "string")
.or_else(|| find_child(&args, "template_string"));
if let Some(str_node) = str_node {
let mod_path = node_text(&str_node, source)
.replace(&['\'', '"', '`'][..], "");
let names = extract_dynamic_import_names(node, source);
let mut imp = Import::new(mod_path, names, start_line(node));
imp.dynamic_import = Some(true);
symbols.imports.push(imp);
}
}
fn handle_import_stmt(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let text = node_text(node, source);
let is_type_only = text.starts_with("import type");
let source_node = node
.child_by_field_name("source")
.or_else(|| find_child(node, "string"));
if let Some(source_node) = source_node {
let mod_path = node_text(&source_node, source)
.replace(&['\'', '"'][..], "");
let names = extract_import_names(node, source);
let mut imp = Import::new(mod_path, names, start_line(node));
if is_type_only {
imp.type_only = Some(true);
}
symbols.imports.push(imp);
}
}
fn handle_export_stmt(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let decl = node.child_by_field_name("declaration");
if let Some(decl) = &decl {
handle_export_declaration(node, decl, source, symbols);
}
let source_node = node
.child_by_field_name("source")
.or_else(|| find_child(node, "string"));
if source_node.is_some() && decl.is_none() {
handle_reexport(node, &source_node.unwrap(), source, symbols);
}
}
fn handle_export_declaration(node: &Node, decl: &Node, source: &[u8], symbols: &mut FileSymbols) {
let (kind_str, field) = match decl.kind() {
"function_declaration" | "generator_function_declaration" => ("function", "name"),
"class_declaration" | "abstract_class_declaration" => ("class", "name"),
"interface_declaration" => ("interface", "name"),
"type_alias_declaration" => ("type", "name"),
_ => return,
};
if let Some(n) = decl.child_by_field_name(field) {
symbols.exports.push(ExportInfo {
name: node_text(&n, source).to_string(),
kind: kind_str.to_string(),
line: start_line(node),
});
}
}
fn handle_reexport(node: &Node, source_node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let mod_path = node_text(source_node, source)
.replace(&['\'', '"'][..], "");
let reexport_names = extract_import_names(node, source);
let text = node_text(node, source);
let is_wildcard = text.contains("export *") || text.contains("export*");
let mut imp = Import::new(mod_path, reexport_names.clone(), start_line(node));
imp.reexport = Some(true);
if is_wildcard && reexport_names.is_empty() {
imp.wildcard_reexport = Some(true);
}
symbols.imports.push(imp);
}
fn handle_expr_stmt(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let Some(expr) = node.child(0) else { return };
if expr.kind() != "assignment_expression" { return; }
let left = expr.child_by_field_name("left");
let right = expr.child_by_field_name("right");
let (Some(left), Some(right)) = (left, right) else { return };
let left_text = node_text(&left, source);
if !left_text.starts_with("module.exports") && left_text != "exports" { return; }
if right.kind() == "call_expression" {
handle_require_reexport(&right, node, source, symbols);
}
if right.kind() == "object" {
handle_spread_require_reexports(&right, node, source, symbols);
}
}
fn handle_require_reexport(right: &Node, node: &Node, source: &[u8], symbols: &mut FileSymbols) {
let fn_node = right.child_by_field_name("function");
let args = right
.child_by_field_name("arguments")