-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathjavascript.rs
More file actions
1585 lines (1470 loc) · 62.1 KB
/
javascript.rs
File metadata and controls
1585 lines (1470 loc) · 62.1 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};
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);
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" => {
ctor.child_by_field_name("property").map(|p| node_text(&p, 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 takes priority
if let Some(type_anno) = find_child(node, "type_annotation") {
if let Some(type_name) = extract_simple_type_name(&type_anno, source) {
symbols.type_map.push(TypeMapEntry {
name: var_name.to_string(),
type_name: type_name.to_string(),
});
return; // Skip new_expression check — annotation wins
}
}
// Fall back to new expression inference
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(),
});
}
}
}
}
}
}
"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) {
symbols.type_map.push(TypeMapEntry {
name: node_text(&name_node, source).to_string(),
type_name: type_name.to_string(),
});
}
}
}
}
}
_ => {}
}
}
fn match_js_node(node: &Node, source: &[u8], symbols: &mut FileSymbols, _depth: usize) {
match node.kind() {
"function_declaration" => handle_function_decl(node, source, symbols),
"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" {
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 && 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,
});
}
}
}
fn handle_call_expr(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
if let Some(fn_node) = node.child_by_field_name("function") {
if fn_node.kind() == "import" {
handle_dynamic_import(node, &fn_node, source, symbols);
} else 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);
}
}
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" => {
symbols.calls.push(Call {
name: node_text(&ctor, source).to_string(),
line: start_line(node),
dynamic: None,
receiver: None,
});
}
"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" => ("function", "name"),
"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")
.or_else(|| find_child(right, "arguments"));
if let (Some(fn_node), Some(args)) = (fn_node, args) {
if node_text(&fn_node, source) == "require" {
if let Some(str_arg) = find_child(&args, "string") {
let mod_path = node_text(&str_arg, source)
.replace(&['\'', '"'][..], "");
let mut imp = Import::new(mod_path, vec![], start_line(node));
imp.reexport = Some(true);
imp.wildcard_reexport = Some(true);
symbols.imports.push(imp);
}
}
}
}
fn handle_spread_require_reexports(right: &Node, node: &Node, source: &[u8], symbols: &mut FileSymbols) {
for ci in 0..right.child_count() {
let Some(child) = right.child(ci) else { continue };
if child.kind() != "spread_element" { continue; }
let spread_expr = child.child(1)
.or_else(|| child.child_by_field_name("value"));
let Some(spread_expr) = spread_expr else { continue };
if spread_expr.kind() != "call_expression" { continue; }
let fn2 = spread_expr.child_by_field_name("function");
let args2 = spread_expr
.child_by_field_name("arguments")
.or_else(|| find_child(&spread_expr, "arguments"));
let (Some(fn2), Some(args2)) = (fn2, args2) else { continue };
if node_text(&fn2, source) != "require" { continue; }
if let Some(str_arg2) = find_child(&args2, "string") {
let mod_path2 = node_text(&str_arg2, source)
.replace(&['\'', '"'][..], "");
let mut imp = Import::new(mod_path2, vec![], start_line(node));
imp.reexport = Some(true);
imp.wildcard_reexport = Some(true);
symbols.imports.push(imp);
}
}
}
// ── AST node extraction (new / throw / await / string / regex) ──────────────
const TEXT_MAX: usize = 200;
/// Walk the tree collecting new/throw/await/string/regex AST nodes.
fn walk_ast_nodes(node: &Node, source: &[u8], ast_nodes: &mut Vec<AstNode>) {
walk_ast_nodes_depth(node, source, ast_nodes, 0);
}
fn walk_ast_nodes_depth(node: &Node, source: &[u8], ast_nodes: &mut Vec<AstNode>, depth: usize) {
if depth >= MAX_WALK_DEPTH {
return;
}
match node.kind() {
"new_expression" => {
let name = extract_new_name(node, source);
let text = truncate(node_text(node, source), TEXT_MAX);
ast_nodes.push(AstNode {
kind: "new".to_string(),
name,
line: start_line(node),
text: Some(text),
receiver: None,
});
// Don't recurse — we already captured this node
return;
}
"throw_statement" => {
let name = extract_throw_name(node, source);
let text = extract_expression_text(node, source);
ast_nodes.push(AstNode {
kind: "throw".to_string(),
name,
line: start_line(node),
text,
receiver: None,
});
// Don't recurse — prevents double-counting `throw new Error`
return;
}
"await_expression" => {
let name = extract_await_name(node, source);
let text = extract_expression_text(node, source);
ast_nodes.push(AstNode {
kind: "await".to_string(),
name,
line: start_line(node),
text,
receiver: None,
});
// Recurse into children to capture nested calls (e.g. await fetch(url))
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
walk_ast_nodes_depth(&child, source, ast_nodes, depth + 1);
}
}
return;
}
"string" | "template_string" => {
let raw = node_text(node, source);
// Strip quotes to get content
let content = raw
.trim_start_matches(|c| c == '\'' || c == '"' || c == '`')
.trim_end_matches(|c| c == '\'' || c == '"' || c == '`');
if content.len() < 2 {
// Still recurse children (template_string may have nested expressions)
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
walk_ast_nodes_depth(&child, source, ast_nodes, depth + 1);
}
}
return;
}
let name = truncate(content, 100);
let text = truncate(raw, TEXT_MAX);
ast_nodes.push(AstNode {
kind: "string".to_string(),
name,
line: start_line(node),
text: Some(text),
receiver: None,
});
// Do recurse children for strings
}
"regex" => {
let raw = node_text(node, source);
let name = if raw.is_empty() { "?".to_string() } else { raw.to_string() };
let text = truncate(raw, TEXT_MAX);
ast_nodes.push(AstNode {
kind: "regex".to_string(),
name,
line: start_line(node),
text: Some(text),
receiver: None,
});
// Do recurse children for regex
}
_ => {}
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
walk_ast_nodes_depth(&child, source, ast_nodes, depth + 1);
}
}
}
/// Extract constructor name from a `new_expression` node.
/// Handles `new Foo()`, `new a.Foo()`, `new Foo.Bar()`.
fn extract_new_name(node: &Node, source: &[u8]) -> String {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "identifier" {
return node_text(&child, source).to_string();
}
if child.kind() == "member_expression" {
return node_text(&child, source).to_string();
}
}
}
// Fallback: text before '(' minus 'new '
let raw = node_text(node, source);
raw.split('(')
.next()
.unwrap_or(raw)
.replace("new ", "")
.trim()
.to_string()
}
/// Extract name from a `throw_statement`.
/// `throw new Error(...)` → "Error"; `throw x` → "x"
fn extract_throw_name(node: &Node, source: &[u8]) -> String {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
match child.kind() {
"new_expression" => return extract_new_name(&child, source),
"call_expression" => {
if let Some(fn_node) = child.child_by_field_name("function") {
return node_text(&fn_node, source).to_string();
}
let text = node_text(&child, source);
return text.split('(').next().unwrap_or("?").to_string();
}
"identifier" => return node_text(&child, source).to_string(),
_ => {}
}
}
}
truncate(node_text(node, source), TEXT_MAX)
}
/// Extract name from an `await_expression`.
/// `await fetch(...)` → "fetch"; `await this.foo()` → "this.foo"
fn extract_await_name(node: &Node, source: &[u8]) -> String {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
match child.kind() {
"call_expression" => {
if let Some(fn_node) = child.child_by_field_name("function") {
return node_text(&fn_node, source).to_string();
}
let text = node_text(&child, source);
return text.split('(').next().unwrap_or("?").to_string();
}
"identifier" | "member_expression" => {
return node_text(&child, source).to_string();
}
_ => {}
}
}
}
truncate(node_text(node, source), TEXT_MAX)
}
/// Extract expression text from throw/await — skip the keyword child.
fn extract_expression_text(node: &Node, source: &[u8]) -> Option<String> {
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
// Skip the keyword token itself
if child.kind() != "throw" && child.kind() != "await" {
return Some(truncate(node_text(&child, source), TEXT_MAX));
}
}
}
Some(truncate(node_text(node, source), TEXT_MAX))
}
// ── Extended kinds helpers ──────────────────────────────────────────────────
fn extract_js_parameters(node: &Node, source: &[u8]) -> Vec<Definition> {
let mut params = Vec::new();
let params_node = node.child_by_field_name("parameters")
.or_else(|| find_child(node, "formal_parameters"));
if let Some(params_node) = params_node {
for i in 0..params_node.child_count() {
if let Some(child) = params_node.child(i) {
match child.kind() {
"identifier" => {
params.push(child_def(
node_text(&child, source).to_string(),
"parameter",
start_line(&child),
));
}
"required_parameter" | "optional_parameter" => {
// TS parameters: pattern field holds the identifier;
// fall back to left field or first child for edge cases
let name_node = child.child_by_field_name("pattern")
.or_else(|| child.child_by_field_name("left"))
.or_else(|| child.child(0));
if let Some(name_node) = name_node {
if name_node.kind() == "identifier"
|| name_node.kind() == "shorthand_property_identifier_pattern"
{
params.push(child_def(
node_text(&name_node, source).to_string(),
"parameter",
start_line(&child),
));
}
}
}
"assignment_pattern" => {
if let Some(left) = child.child_by_field_name("left") {
if left.kind() == "identifier" {
params.push(child_def(
node_text(&left, source).to_string(),
"parameter",
start_line(&child),
));
}
}
}
"rest_pattern" | "rest_element" => {
for j in 0..child.child_count() {
if let Some(inner) = child.child(j) {
if inner.kind() == "identifier" {
params.push(child_def(
node_text(&inner, source).to_string(),
"parameter",
start_line(&child),
));
}
}
}
}
_ => {}
}
}
}
}
params
}
fn extract_js_class_properties(node: &Node, source: &[u8]) -> Vec<Definition> {
let mut props = Vec::new();
let body = node.child_by_field_name("body")
.or_else(|| find_child(node, "class_body"));
if let Some(body) = body {
for i in 0..body.child_count() {
if let Some(child) = body.child(i) {
match child.kind() {
"field_definition" | "public_field_definition" | "property_definition" => {
let prop = child.child_by_field_name("property")
.or_else(|| child.child_by_field_name("name"))
.or_else(|| find_child(&child, "property_identifier"));
if let Some(prop) = prop {
let kind = prop.kind();
if kind == "property_identifier" || kind == "identifier"
|| kind == "private_property_identifier"
{
props.push(child_def(
node_text(&prop, source).to_string(),
"property",
start_line(&child),
));
}
}
}
_ => {}
}
}
}
}
props
}
fn extract_ts_enum_members(node: &Node, source: &[u8]) -> Vec<Definition> {
let mut members = Vec::new();
let body = node.child_by_field_name("body")
.or_else(|| find_child(node, "enum_body"));
if let Some(body) = body {
for i in 0..body.child_count() {
if let Some(child) = body.child(i) {
if child.kind() == "enum_assignment" || child.kind() == "property_identifier" {
let name = child.child_by_field_name("name")
.unwrap_or(child);
members.push(child_def(
node_text(&name, source).to_string(),
"constant",
start_line(&child),
));
}
}
}
}
members
}
fn is_js_literal(node: &Node) -> bool {
matches!(node.kind(),
"number" | "string" | "true" | "false" | "null" | "undefined"
| "template_string" | "regex" | "array" | "object"
| "unary_expression" | "binary_expression" | "new_expression"
)
}
// ── Existing helpers ────────────────────────────────────────────────────────
fn extract_interface_methods(
body: &Node,
iface_name: &str,
source: &[u8],
definitions: &mut Vec<Definition>,
) {
for i in 0..body.child_count() {
if let Some(child) = body.child(i) {
if child.kind() == "method_signature" || child.kind() == "property_signature" {
if let Some(name_node) = child.child_by_field_name("name") {
definitions.push(Definition {
name: format!("{}.{}", iface_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,
});
}
}
}
}
}
fn extract_implements(heritage: &Node, source: &[u8]) -> Vec<String> {
let mut interfaces = Vec::new();
for i in 0..heritage.child_count() {
if let Some(child) = heritage.child(i) {
if node_text(&child, source) == "implements" {
for j in (i + 1)..heritage.child_count() {
if let Some(next) = heritage.child(j) {
if next.kind() == "identifier" || next.kind() == "type_identifier" {
interfaces.push(node_text(&next, source).to_string());
}
if next.child_count() > 0 {
extract_implements_from_node(&next, source, &mut interfaces);
}
}
}
break;
}
if child.kind() == "implements_clause" {
extract_implements_from_node(&child, source, &mut interfaces);
}
}
}
interfaces
}
fn extract_implements_from_node(node: &Node, source: &[u8], result: &mut Vec<String>) {
extract_implements_depth(node, source, result, 0);
}
fn extract_implements_depth(node: &Node, source: &[u8], result: &mut Vec<String>, depth: usize) {
if depth >= MAX_WALK_DEPTH {
return;
}
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
if child.kind() == "identifier" || child.kind() == "type_identifier" {
result.push(node_text(&child, source).to_string());
}
if child.child_count() > 0 {
extract_implements_depth(&child, source, result, depth + 1);
}
}
}
}
fn extract_call_info(fn_node: &Node, call_node: &Node, source: &[u8]) -> Option<Call> {
match fn_node.kind() {
"identifier" => Some(Call {
name: node_text(fn_node, source).to_string(),
line: start_line(call_node),
dynamic: None,
receiver: None,
}),
"member_expression" => {
let obj = fn_node.child_by_field_name("object");
let prop = fn_node.child_by_field_name("property");
let prop = prop?;
let prop_text = node_text(&prop, source);
if prop_text == "call" || prop_text == "apply" || prop_text == "bind" {
if let Some(obj) = &obj {
if obj.kind() == "identifier" {
return Some(Call {
name: node_text(obj, source).to_string(),
line: start_line(call_node),
dynamic: Some(true),
receiver: None,
});
}
if obj.kind() == "member_expression" {
if let Some(inner_prop) = obj.child_by_field_name("property") {
return Some(Call {
name: node_text(&inner_prop, source).to_string(),
line: start_line(call_node),
dynamic: Some(true),
receiver: None,
});
}
}
}
}
if prop.kind() == "string" || prop.kind() == "string_fragment" {
let method_name = node_text(&prop, source).replace(&['\'', '"'][..], "");
if !method_name.is_empty() {
let receiver = fn_node.child_by_field_name("object")
.map(|obj| node_text(&obj, source).to_string());
return Some(Call {
name: method_name,
line: start_line(call_node),
dynamic: Some(true),
receiver,
});
}
}
let receiver = fn_node.child_by_field_name("object")
.map(|obj| node_text(&obj, source).to_string());
Some(Call {
name: prop_text.to_string(),
line: start_line(call_node),
dynamic: None,
receiver,
})
}
"subscript_expression" => {
let index = fn_node.child_by_field_name("index");
if let Some(index) = index {
if index.kind() == "string" || index.kind() == "template_string" {
let method_name = node_text(&index, source)
.replace(&['\'', '"', '`'][..], "");
if !method_name.is_empty() && !method_name.contains('$') {
let receiver = fn_node.child_by_field_name("object")
.map(|obj| node_text(&obj, source).to_string());
return Some(Call {
name: method_name,
line: start_line(call_node),
dynamic: Some(true),
receiver,
});
}
}
}
None
}
_ => None,
}
}
fn find_anonymous_callback<'a>(args_node: &Node<'a>) -> Option<Node<'a>> {
for i in 0..args_node.child_count() {
if let Some(child) = args_node.child(i) {
if child.kind() == "arrow_function" || child.kind() == "function_expression" {
return Some(child);
}
}
}
None
}
fn find_first_string_arg<'a>(args_node: &Node<'a>, source: &'a [u8]) -> Option<String> {
for i in 0..args_node.child_count() {
if let Some(child) = args_node.child(i) {
if child.kind() == "string" {
return Some(node_text(&child, source).replace(&['\'', '"'][..], ""));
}
}
}
None
}
fn walk_call_chain<'a>(start_node: &Node<'a>, method_name: &str, source: &[u8]) -> Option<Node<'a>> {
let mut current = Some(*start_node);
while let Some(node) = current {
if node.kind() == "call_expression" {
if let Some(fn_node) = node.child_by_field_name("function") {
if fn_node.kind() == "member_expression" {
if let Some(prop) = fn_node.child_by_field_name("property") {
if node_text(&prop, source) == method_name {
return Some(node);
}
}
}
}
}
current = match node.kind() {
"member_expression" => node.child_by_field_name("object"),
"call_expression" => node.child_by_field_name("function"),
_ => None,
};
}
None
}
fn is_express_method(method: &str) -> bool {
matches!(
method,
"get" | "post" | "put" | "delete" | "patch" | "options" | "head" | "all" | "use"
)
}