Repository navigation
Expand file tree
/
Copy pathextractors.rs
More file actions
2191 lines (2074 loc) · 94.1 KB
/
Copy pathextractors.rs
File metadata and controls
2191 lines (2074 loc) · 94.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
//! The extract_* family — continuation of the Walker impl (see mod.rs for the
//! porting contract). Each function mirrors its namesake in
//! src/extraction/tree-sitter.ts; TS-file line references are as of the R2
//! port. Bug-for-bug fidelity is deliberate — fix the TS side first.
use crate::textutil as util;
use super::{
body_of, is_builtin_type, is_host_global_root, is_literal_receiver, is_object_member_function,
is_react_hoc, is_static_object_key, is_variable_type, is_vue_collection_name, Extra, Scope, Walker,
};
use crate::buffers::edge_kind_index;
use std::collections::HashSet;
use tree_sitter::Node;
impl<'t> Walker<'t> {
// --- extractFunction --------------------------------------------------------
pub(super) fn extract_function(&mut self, node: Node<'t>, name_override: Option<String>) {
let mut name = name_override
.clone()
.unwrap_or_else(|| self.extract_name(node));
// Arrow/function-expression values: resolve the name from the parent
// variable_declarator (`export const useAuth = () => {}`), or from a
// CommonJS export assignment (`exports.getItems = async () => {}`,
// #1675). Mirrors TreeSitterExtractor.extractFunction.
let mut common_js_export = false;
if name_override.is_none()
&& name == "<anonymous>"
&& matches!(node.kind(), "arrow_function" | "function_expression" | "generator_function")
{
if let Some(parent) = node.parent() {
if parent.kind() == "variable_declarator" {
if let Some(var_name) = parent.child_by_field_name("name") {
name = self.text(var_name).to_string();
}
} else if parent.kind() == "assignment_expression" {
if let Some(export_name) = self.common_js_export_name(parent, node) {
name = export_name;
common_js_export = true;
}
}
}
}
if name == "<anonymous>" {
// Still walk the body: module wrappers hold named inner functions
// and calls that would otherwise be lost (#528).
let body = body_of(node);
self.visit_parameter_defaults(node, body);
if let Some(body) = body {
self.visit_function_body(body);
}
return;
}
let extra = Extra {
docstring: crate::docstring::preceding_docstring(node, self.src),
signature: self.signature_of(node),
visibility: self.visibility_of(node),
is_exported: Some(common_js_export || self.is_exported(node)),
is_async: Some(self.is_async(node)),
is_static: self.is_static(node),
..Extra::default()
};
let Some(row) = self.create_node("function", &name, node, extra) else {
return;
};
self.extract_type_annotations(node, row);
self.extract_decorators_for(node, row);
self.stack.push(Scope { row, kind: "function", name });
let body = body_of(node);
self.visit_parameter_defaults(node, body);
if let Some(body) = body {
self.visit_function_body(body);
}
self.stack.pop();
}
/// A parameter's default value is code the function runs, each time a
/// call leaves that argument out (#2588). Each default, and a computed key
/// in a destructured parameter, is walked as the body is, with the same
/// scope on the stack; the names a parameter binds and its type annotation
/// are not. A function with no body never runs. Mirrors
/// TreeSitterExtractor.visitParameterDefaults.
fn visit_parameter_defaults(&mut self, func: Node<'t>, body: Option<Node<'t>>) {
let Some(body) = body else { return };
// A class field holds its function: `onPick = (item = first()) => {…}`.
let owner = if matches!(func.kind(), "public_field_definition" | "field_definition") {
body.parent()
} else {
Some(func)
};
if let Some(params) = owner.and_then(|o| o.child_by_field_name("parameters")) {
self.visit_pattern_defaults(params);
}
}
/// The defaults in a parameter list or a destructuring pattern, in source
/// order. Mirrors TreeSitterExtractor.visitPatternDefaults.
fn visit_pattern_defaults(&mut self, node: Node<'t>) {
stack_guard!();
match node.kind() {
"formal_parameters" | "object_pattern" | "array_pattern" | "rest_pattern" => {
for i in 0..node.named_child_count() {
if let Some(child) = node.named_child(i) {
self.visit_pattern_defaults(child);
}
}
}
"required_parameter" | "optional_parameter" => {
if let Some(pattern) = node.child_by_field_name("pattern") {
self.visit_pattern_defaults(pattern);
}
if let Some(value) = node.child_by_field_name("value") {
self.visit_function_body(value);
}
}
"assignment_pattern" | "object_assignment_pattern" => {
if let Some(left) = node.child_by_field_name("left") {
self.visit_pattern_defaults(left);
}
if let Some(right) = node.child_by_field_name("right") {
self.visit_function_body(right);
}
}
"pair_pattern" => {
if let Some(key) = node.child_by_field_name("key").filter(|k| k.kind() == "computed_property_name") {
self.visit_function_body(key);
}
if let Some(value) = node.child_by_field_name("value") {
self.visit_pattern_defaults(value);
}
}
_ => {}
}
}
/// The property a CommonJS export assignment binds a function to —
/// `exports.NAME = <node>` / `module.exports.NAME = <node>`, or the same
/// with the name in quotes, `exports["NAME"] = <node>` — or None for any
/// other assignment. The node must be the assignment's whole right-hand
/// side. Mirrors TreeSitterExtractor.commonJsExportName.
fn common_js_export_name(&self, assignment: Node<'t>, value: Node<'t>) -> Option<String> {
let right = assignment.child_by_field_name("right")?;
if right.start_byte() != value.start_byte() || right.end_byte() != value.end_byte() {
return None;
}
let left = assignment.child_by_field_name("left")?;
if !matches!(left.kind(), "member_expression" | "subscript_expression") {
return None;
}
let object = left.child_by_field_name("object")?;
if !matches!(self.text(object), "exports" | "module.exports") {
return None;
}
if left.kind() == "subscript_expression" {
return self.quoted_identifier(left.child_by_field_name("index")?).map(str::to_string);
}
let property = left.child_by_field_name("property")?;
if property.kind() != "property_identifier" {
return None;
}
Some(self.text(property).to_string())
}
/// The name a string literal spells when it is a plain identifier: `'svc'`
/// or `"getItems"` → the text between the quotes. None for anything else,
/// including a string with an escape or a character no identifier can
/// hold. Mirrors quotedIdentifier in tree-sitter.ts.
fn quoted_identifier(&self, node: Node<'t>) -> Option<&'t str> {
if node.kind() != "string" {
return None;
}
let text = self.text(node);
let quoted = text.len() >= 2
&& (text.starts_with('\'') || text.starts_with('"'))
&& text.ends_with(&text[..1]);
if !quoted {
return None;
}
let key = &text[1..text.len() - 1];
let mut chars = key.chars();
let first = chars.next()?;
if !(first.is_ascii_alphabetic() || first == '_' || first == '$')
|| !chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
{
return None;
}
Some(key)
}
// --- reactComponentHoc / extractReactComponentNode (#841) --------------------
/// Some(inner) when the initializer is a recognized component wrapper —
/// inner is the inline render function, or None for `styled.x`/`memo(Ref)`.
/// Outer None = not a component wrapper.
fn react_component_hoc(&self, value: Node<'t>) -> Option<Option<Node<'t>>> {
if self.is_typed_styled_template(value) {
return Some(None);
}
if value.kind() != "call_expression" {
return None;
}
let callee = value.child_by_field_name("function")?;
let callee_text = self.text(callee);
if util::styled_callee().is_match(callee_text) {
return Some(None);
}
if !is_react_hoc(callee_text) {
return None;
}
let mut inner: Option<Node> = None;
if let Some(args) = value.child_by_field_name("arguments") {
for i in 0..args.named_child_count() {
if let Some(a) = args.named_child(i) {
if matches!(a.kind(), "arrow_function" | "function_expression") {
inner = Some(a);
break;
}
}
}
}
Some(inner)
}
/// A typed styled tag, `styled.div<Props>` before a template literal, which
/// parses as comparisons: `(styled.div < Props) > template`. The leftmost
/// operand is the `styled` tag against a `<`; the rightmost is the
/// template_string against a `>` (`>>` when the type argument ends in its
/// own `<…>`). Mirrors TreeSitterExtractor.isTypedStyledTemplate.
fn is_typed_styled_template(&self, value: Node<'t>) -> bool {
if value.kind() != "binary_expression" {
return false;
}
let (mut tag_parent, mut tag) = (value, value.child_by_field_name("left"));
while let Some(t) = tag.filter(|t| t.kind() == "binary_expression") {
(tag_parent, tag) = (t, t.child_by_field_name("left"));
}
let (mut template_parent, mut template) = (value, value.child_by_field_name("right"));
while let Some(t) = template.filter(|t| t.kind() == "binary_expression") {
(template_parent, template) = (t, t.child_by_field_name("right"));
}
let (Some(tag), Some(template)) = (tag, template) else {
return false;
};
let operator = |n: Node<'t>| n.child_by_field_name("operator").map(|o| o.kind()).unwrap_or("");
let closing = operator(template_parent);
template.kind() == "template_string"
&& operator(tag_parent) == "<"
&& !closing.is_empty()
&& closing.bytes().all(|b| b == b'>')
&& util::styled_callee().is_match(self.text(tag))
}
fn extract_react_component_node(
&mut self,
name: &str,
declarator: Node<'t>,
inner_fn: Option<Node<'t>>,
extra: Extra,
) {
let Some(row) = self.create_node("component", name, declarator, extra) else {
return;
};
self.stack.push(Scope { row, kind: "component", name: name.to_string() });
match inner_fn {
Some(inner) => {
let body = body_of(inner);
self.visit_parameter_defaults(inner, body);
if let Some(body) = body {
self.visit_function_body(body);
}
}
// Without a render function, the initializer is walked instead.
None => {
if let Some(value) = declarator.child_by_field_name("value") {
self.walk_component_wrapper(value);
}
}
}
self.stack.pop();
}
/// A wrapper with no render function of its own (`styled.div\`…\``,
/// `styled(Base).attrs(…)<P>\`…\``, `styled(Base)(styles)`, `memo(Base)`),
/// walked with its component on the stack as a constant's initializer is
/// (#693): the template's interpolations and the `.attrs()` / options /
/// style-function / comparator arguments are the component's code. The
/// wrapper's own chain (`styled`, `styled.div`, `.attrs`, `memo`) is not
/// recorded, the component it wraps is left to the JSX synthesizer (it is
/// what this one renders), and a typed tag's type operands are not walked.
/// Mirrors TreeSitterExtractor.walkComponentWrapper.
fn walk_component_wrapper(&mut self, link: Node<'t>) {
stack_guard!();
match link.kind() {
"binary_expression" => {
// `(styled(Base) < Props) > \`…\``: the tag is the leftmost
// operand and the template the rightmost; between is the type.
let mut tag = Some(link);
while let Some(t) = tag.filter(|t| t.kind() == "binary_expression") {
tag = t.child_by_field_name("left");
}
let mut template = Some(link);
while let Some(t) = template.filter(|t| t.kind() == "binary_expression") {
template = t.child_by_field_name("right");
}
if let Some(tag) = tag {
self.walk_component_wrapper(tag);
}
if let Some(template) = template {
self.visit_function_body(template);
}
}
"call_expression" => {
let callee = link.child_by_field_name("function");
if let Some(c) = callee {
self.walk_component_wrapper(c);
}
let Some(args) = link.child_by_field_name("arguments") else { return };
// A tagged template's argument is its template: the styles.
if args.kind() != "arguments" {
self.visit_function_body(args);
return;
}
// `styled(Base)`, `memo(Base)`: the first argument is the
// component wrapped, or a wrapper around it.
let callee_text = callee.map(|c| self.text(c)).unwrap_or("");
let root = callee_text == "styled" || is_react_hoc(callee_text);
let base = args
.named_child(0)
.filter(|f| root && matches!(f.kind(), "identifier" | "member_expression"));
for i in 0..args.named_child_count() {
let Some(arg) = args.named_child(i) else { continue };
if base.map(|b| b.start_byte() == arg.start_byte()).unwrap_or(false) {
continue;
}
if root && i == 0 && arg.kind() == "call_expression" && self.is_component_wrapper_call(arg) {
self.walk_component_wrapper(arg);
} else if matches!(arg.kind(), "arrow_function" | "function_expression") {
// A style or `.attrs()` function runs as the component's
// code: its body is walked, the function never named.
let body = body_of(arg);
self.visit_parameter_defaults(arg, body);
if let Some(body) = body {
self.visit_function_body(body);
}
} else {
self.visit_function_body(arg);
}
}
self.capture_wrapper_argument_refs(args, base);
}
"member_expression" | "subscript_expression" => {
if let Some(object) = link.child_by_field_name("object") {
self.walk_component_wrapper(object);
}
}
"non_null_expression" | "parenthesized_expression" | "instantiation_expression" => {
// `styled.div<{ open: boolean }>` error-recovers into a call on
// `non_null_expression(instantiation_expression(styled.div, …))`.
if let Some(inner) = link.child_by_field_name("function").or_else(|| link.named_child(0)) {
self.walk_component_wrapper(inner);
}
}
_ => {}
}
}
/// A call reactComponentHoc reads as a component wrapper: `styled…(…)`,
/// `memo(…)`, `forwardRef(…)`. Mirrors isComponentWrapperCall.
fn is_component_wrapper_call(&self, call: Node<'t>) -> bool {
let Some(callee) = call.child_by_field_name("function") else { return false };
let text = self.text(callee);
util::styled_callee().is_match(text) || is_react_hoc(text)
}
/// Function-as-value candidates (#756) among a wrapper call's arguments,
/// attributed to the component — never the component the call wraps.
/// Mirrors captureWrapperArgumentRefs.
fn capture_wrapper_argument_refs(&mut self, args: Node<'t>, base: Option<Node<'t>>) {
let Some(mode) = super::fnref::dispatch(args.kind()) else { return };
if self.stack.is_empty() {
return;
}
let from = self.top_row();
for (cand, _mode) in super::fnref::capture(args, mode, self.src) {
if base.map(|b| b.start_byte() == cand.column_byte).unwrap_or(false) {
continue;
}
self.fn_ref_cands.push((from, cand));
}
}
// --- extractClass ------------------------------------------------------------
pub(super) fn extract_class(&mut self, node: Node<'t>) {
let resolved_body = body_of(node); // skipBodilessClass unset for TS/JS
let name = self.extract_name(node);
// A class expression's name is bound inside the expression alone:
// never exported by it, and its head is its signature, which a
// declaration lacks (#2499). Mirrors TreeSitterExtractor.extractClass.
let expression = node.kind() == "class";
let extra = Extra {
docstring: crate::docstring::preceding_docstring(node, self.src),
visibility: self.visibility_of(node),
is_exported: Some(!expression && self.is_exported(node)),
signature: if expression { resolved_body.map(|body| class_expression_head(self.src, node, body)) } else { None },
..Extra::default()
};
let Some(row) = self.create_node("class", &name, node, extra) else {
return;
};
self.extract_inheritance(node, row);
self.extract_decorators_for(node, row);
self.stack.push(Scope { row, kind: "class", name });
let body = resolved_body.unwrap_or(node);
for i in 0..body.named_child_count() {
if let Some(c) = body.named_child(i) {
self.visit_node(c);
}
}
self.stack.pop();
}
// --- extractMethod -------------------------------------------------------------
pub(super) fn extract_method(&mut self, node: Node<'t>) {
if !self.inside_class_like() {
// Object-literal methods are ephemeral: walk the body only.
if let Some(parent) = node.parent() {
if matches!(parent.kind(), "object" | "object_expression") {
let body = body_of(node);
self.visit_parameter_defaults(node, body);
if let Some(body) = body {
self.visit_function_body(body);
}
return;
}
}
self.extract_function(node, None);
return;
}
let name = self.extract_name(node);
let extra = Extra {
docstring: crate::docstring::preceding_docstring(node, self.src),
signature: self.signature_of(node),
visibility: self.visibility_of(node),
is_async: Some(self.is_async(node)),
is_static: self.is_static(node),
..Extra::default() // methods carry no isExported (mirrors extractMethod)
};
let Some(row) = self.create_node("method", &name, node, extra) else {
return;
};
self.extract_type_annotations(node, row);
self.extract_decorators_for(node, row);
self.stack.push(Scope { row, kind: "method", name });
let body = body_of(node);
self.visit_parameter_defaults(node, body);
if let Some(body) = body {
self.visit_function_body(body);
}
self.stack.pop();
}
// --- extractInterface / extractEnum / members -----------------------------------
pub(super) fn extract_interface(&mut self, node: Node<'t>) {
let name = self.extract_name(node);
let extra = Extra {
docstring: crate::docstring::preceding_docstring(node, self.src),
is_exported: Some(self.is_exported(node)),
..Extra::default()
};
let Some(row) = self.create_node("interface", &name, node, extra) else {
return;
};
self.extract_inheritance(node, row);
self.stack.push(Scope { row, kind: "interface", name });
let body = body_of(node).unwrap_or(node);
for i in 0..body.named_child_count() {
if let Some(c) = body.named_child(i) {
self.visit_node(c);
}
}
self.stack.pop();
}
pub(super) fn extract_enum(&mut self, node: Node<'t>) {
let Some(body) = body_of(node) else { return };
let name = self.extract_name(node);
let extra = Extra {
docstring: crate::docstring::preceding_docstring(node, self.src),
visibility: self.visibility_of(node),
is_exported: Some(self.is_exported(node)),
..Extra::default()
};
let Some(row) = self.create_node("enum", &name, node, extra) else {
return;
};
self.extract_inheritance(node, row);
self.stack.push(Scope { row, kind: "enum", name });
for i in 0..body.named_child_count() {
let Some(child) = body.named_child(i) else { continue };
if matches!(child.kind(), "property_identifier" | "enum_assignment") {
self.extract_enum_members(child);
} else {
self.visit_node(child);
}
}
self.stack.pop();
}
fn extract_enum_members(&mut self, node: Node<'t>) {
if let Some(name_node) = node.child_by_field_name("name") {
let name = self.text(name_node).to_string();
self.create_node("enum_member", &name, node, Extra::default());
return;
}
let mut found = false;
for i in 0..node.named_child_count() {
if let Some(child) = node.named_child(i) {
if matches!(child.kind(), "simple_identifier" | "identifier" | "property_identifier") {
let name = self.text(child).to_string();
self.create_node("enum_member", &name, child, Extra::default());
found = true;
}
}
}
if !found && node.named_child_count() == 0 {
let name = self.text(node).to_string();
self.create_node("enum_member", &name, node, Extra::default());
}
}
// --- extractProperty (#808 property-classified class fields) ---------------------
pub(super) fn extract_property(&mut self, node: Node<'t>) -> Option<(u32, String)> {
let docstring = crate::docstring::preceding_docstring(node, self.src);
let visibility = self.visibility_of(node);
let is_static = Some(self.is_static(node).unwrap_or(false)); // `?? false` — always present
let name_node = node
.child_by_field_name("name")
.or_else(|| node.child_by_field_name("property"))
.or_else(|| {
(0..node.named_child_count())
.filter_map(|i| node.named_child(i))
.find(|c| c.kind() == "identifier")
})?;
let name = self.text(name_node).to_string();
// TS/JS field definitions carry an explicit `type` field; the generic
// scan is for other languages (#808). A `property_signature` (an
// interface member, #1638) carries a `type` field and no value, so it
// reads the type field too: the generic scan's exclusion list covers
// `identifier` but not the `property_identifier` an interface member is
// named with, so it would stop on the name and make the signature repeat
// it (`counts counts`) instead of naming the type. Mirrors
// extractProperty's isTsJsField.
let is_ts_js_field = matches!(
node.kind(),
"public_field_definition" | "field_definition" | "property_signature"
);
let type_node = if is_ts_js_field {
node.child_by_field_name("type")
} else {
(0..node.named_child_count()).filter_map(|i| node.named_child(i)).find(|c| {
!matches!(
c.kind(),
"modifier"
| "modifiers"
| "identifier"
| "accessor_list"
| "accessors"
| "equals_value_clause"
)
})
};
let type_text = type_node.map(|t| {
let raw = self.text(t);
raw.strip_prefix(':').unwrap_or(raw).trim_start().to_string()
});
let signature = match &type_text {
Some(t) => format!("{t} {name}"),
None => name.clone(),
};
let row = self.create_node(
"property",
&name,
node,
Extra { docstring, signature: Some(signature), visibility, is_static, ..Extra::default() },
)?;
self.extract_decorators_for(node, row);
self.extract_type_annotations(node, row);
Some((row, name))
}
// --- extractVariable (TS/JS branch) ------------------------------------------------
/// A top-level binding exported by a LATER statement rather than at its
/// declaration: `export default NAME`, `export { NAME }`, `export { NAME as
/// default }`. The declaration's own `is_exported` (an `export_statement`
/// ancestor) cannot see these. One anchored regex over the file source.
/// Mirrors TreeSitterExtractor.isExportedLater.
pub(super) fn is_exported_later(&self, name: &str) -> bool {
if name.is_empty()
|| !name.chars().next().map(|c| c.is_ascii_alphabetic() || c == '_' || c == '$').unwrap_or(false)
|| !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
{
return false;
}
let n = regex::escape(name);
// `R` (CRLF mode): JS's multiline `^`/`$` treat `\r` as a line end as
// well as `\n`; `(?m)` alone sees only `\n`, and would miss `export
// default NAME;\r\n` on every Windows autocrlf checkout.
// Inside `{ … }` the name is bounded by a character that can't
// continue an identifier, not by `\b`, which takes a `$` for a
// separator. The crate has no look-around, so the bounds consume.
// ASCII classes, not `\w`: this crate's `\w` is Unicode, JS's is not.
let pattern = format!(
r"(?mR)^[ \t]*export\s+(?:default\s+{n}\s*;?[ \t]*$|\{{(?:[^}}]*[^0-9A-Za-z_$}}])?{n}(?:[^0-9A-Za-z_$}}][^}}]*)?\}})",
n = n
);
match regex::Regex::new(&pattern) {
Ok(re) => re.is_match(self.src),
Err(_) => false,
}
}
/// Returns the initializers it walked under the symbol they declare — a
/// constant's or a variable's (#693), a component wrapper's — whose fn-ref
/// candidates that walk already took for the symbol (the caller's scan of
/// the declaration skips them; it would take each again for the file).
/// Mirrors TreeSitterExtractor.extractVariable.
pub(super) fn extract_variable(&mut self, node: Node<'t>) -> Option<HashSet<usize>> {
let mut walked: Option<HashSet<usize>> = None;
let is_const = self.is_const_decl(node);
let kind: &'static str = if is_const { "constant" } else { "variable" };
let docstring = crate::docstring::preceding_docstring(node, self.src);
let is_exported = self.is_exported(node); // `?? false` — always present
for i in 0..node.named_child_count() {
let Some(child) = node.named_child(i) else { continue };
if child.kind() != "variable_declarator" {
continue;
}
let Some(name_node) = child.child_by_field_name("name") else { continue };
let value = child.child_by_field_name("value");
// Destructured patterns mint no node — except RTK Query generated
// hooks (`export const { useGetXQuery } = api`).
if matches!(name_node.kind(), "object_pattern" | "array_pattern") {
if name_node.kind() == "object_pattern"
&& value.map(|v| v.kind() == "identifier").unwrap_or(false)
{
self.extract_rtk_hook_bindings(name_node, is_exported);
}
// The initializer (and any default in the pattern) still runs:
// walk the declarator as a function body walks it, with the
// enclosing scope on the stack (#2340). Mirrors
// TreeSitterExtractor.extractVariable.
self.visit_function_body(child);
continue;
}
let name = self.text(name_node).to_string();
// Arrow/function/generator values extract as functions, named by the declarator.
if let Some(v) = value {
if matches!(v.kind(), "arrow_function" | "function_expression" | "generator_function") {
self.extract_function(v, None);
continue;
}
}
let init_signature = value.map(|v| util::init_signature(self.text(v)));
// React HOC-wrapped components (#841), PascalCase-gated.
if let Some(v) = value {
if util::pascal_case().is_match(&name) {
if let Some(inner) = self.react_component_hoc(v) {
self.extract_react_component_node(
&name,
child,
inner,
Extra {
docstring: docstring.clone(),
signature: init_signature.clone(),
is_exported: Some(is_exported),
..Extra::default()
},
);
if inner.is_none() {
walked.get_or_insert_with(HashSet::new).insert(v.id());
}
continue;
}
}
}
let var_row = self.create_node(
kind,
&name,
child,
Extra {
docstring: docstring.clone(),
signature: init_signature.clone(),
is_exported: Some(is_exported),
..Extra::default()
},
);
if let Some(row) = var_row {
self.extract_variable_type_annotation(child, row);
}
// A named object literal owns its function members, exported or
// not (#2300): `const api = { load() {…} }` gives `api::load`. The
// rest of the literal is walked under the owner (#693). Mirrors
// the ownedObject branch of TreeSitterExtractor.extractVariable.
if let (Some(row), Some(obj)) = (var_row, self.owned_object_value(value)) {
self.extract_owned_object_members(obj, row, kind, &name, true, false);
walked.get_or_insert_with(HashSet::new).insert(obj.id());
continue;
}
// Exported const object-of-functions / store shapes.
let object_of_fns: Option<Node> = match value {
Some(v) if matches!(v.kind(), "object" | "object_expression") => Some(v),
Some(v) if v.kind() == "call_expression" => self.find_initializer_returned_object(v, 0),
_ => None,
};
let has_inline_fns = object_of_fns
.map(|o| self.object_has_inline_functions(o))
.unwrap_or(false);
// "Exported" includes the two-statement form `const useStore =
// create(…)` … `export default useStore` (is_exported_later), the
// shape most React Native stores are written in. Mirrors
// TreeSitterExtractor.isExportedLater.
let extract_object_methods =
(is_exported || self.is_exported_later(&name)) && object_of_fns.is_some() && has_inline_fns;
let rtk_endpoints = match value {
Some(v) if v.kind() == "call_expression" => self.find_rtk_endpoints_object(v),
_ => None,
};
let pinia_setup = match value {
Some(v) if v.kind() == "call_expression" => self.find_pinia_setup_fn(v),
_ => None,
};
let mut store_collections: Vec<Node> = Vec::new();
if let Some(v) = value {
if matches!(v.kind(), "call_expression" | "new_expression") {
store_collections.extend(self.find_vue_store_collection_objects(v));
}
}
if let Some(obj) = object_of_fns {
if !extract_object_methods
&& is_vue_collection_name(&name)
&& self.looks_like_vue_store_file()
{
store_collections.push(obj);
}
}
// Walk the initializer for calls, ATTRIBUTED to the declared symbol
// (#693) — except the object/store shapes whose members are
// extracted method-by-method below (walking those too would
// double-count each member arrow's calls). Before this the walk ran
// with only the FILE on the stack (`const cfg = load()` recorded the
// file as load's caller) and object literals were skipped outright.
let members_extracted_separately = extract_object_methods
|| rtk_endpoints.is_some()
|| pinia_setup.is_some()
|| !store_collections.is_empty();
if let Some(v) = value {
if !members_extracted_separately {
match var_row {
Some(row) => {
self.stack.push(Scope { row, kind, name: name.clone() });
self.visit_function_body(v);
self.stack.pop();
walked.get_or_insert_with(HashSet::new).insert(v.id());
}
None => self.visit_function_body(v),
}
}
}
if extract_object_methods {
if let Some(obj) = object_of_fns {
self.extract_object_literal_functions(obj);
}
}
if let Some(rtk) = rtk_endpoints {
self.extract_rtk_endpoints(rtk);
}
if let Some(setup) = pinia_setup {
self.extract_pinia_setup_body(setup);
}
for coll in store_collections {
self.extract_object_literal_functions(coll);
}
}
walked
}
/// extractRtkHookBindings — `export const { useGetXQuery } = api`.
fn extract_rtk_hook_bindings(&mut self, pattern: Node<'t>, is_exported: bool) {
for i in 0..pattern.named_child_count() {
let Some(binding) = pattern.named_child(i) else { continue };
if binding.kind() != "shorthand_property_identifier_pattern" {
continue;
}
let name = self.text(binding).to_string();
if !util::rtk_hook_name().is_match(&name) {
continue;
}
self.create_node(
"function",
&name,
binding,
Extra {
is_exported: Some(is_exported),
signature: Some("= RTK Query generated hook".to_string()),
..Extra::default()
},
);
}
}
// --- owned object literals (#2300) ------------------------------------------------
/// ownsObjectLiterals: a generated or minified bundle — named so or not —
/// keeps the old shape. (Every tsjs variant is TS/JS, so only that check
/// remains; it is computed once per file.)
fn owns_object_literals(&self) -> bool {
self.owns_objects
}
/// ownedMemberFunction: the function an owned literal's member becomes,
/// named by its static key — `load() {…}`, `load: () => {…}`,
/// `load: function () {…}`, `load: function* () {…}`. None for every other
/// member (a computed key, a value, a shorthand, a spread).
fn owned_member_function(&self, member: Node<'t>) -> Option<(Node<'t>, String)> {
if member.kind() == "method_definition" {
let key = member.child_by_field_name("name")?;
if !is_static_object_key(key.kind()) {
return None;
}
return Some((member, util::object_key_name(self.text(key))));
}
if member.kind() != "pair" {
return None;
}
let key = member.child_by_field_name("key")?;
let value = member.child_by_field_name("value")?;
if !is_static_object_key(key.kind()) || !is_object_member_function(value.kind()) {
return None;
}
Some((value, util::object_key_name(self.text(key))))
}
/// ownedObjectValue: `value` when it is an object literal owning at least
/// one function member.
pub(super) fn owned_object_value(&self, value: Option<Node<'t>>) -> Option<Node<'t>> {
let value = value?;
if !matches!(value.kind(), "object" | "object_expression") || !self.owns_object_literals() {
return None;
}
for i in 0..value.named_child_count() {
if let Some(member) = value.named_child(i) {
if self.owned_member_function(member).is_some() {
return Some(value);
}
}
}
None
}
/// Put an owner on the stack — on top of the file alone for one on the
/// global object — returning what was set aside for leave_owner.
fn enter_owner(&mut self, row: u32, kind: &'static str, name: &str, global: bool) -> Vec<Scope> {
let rest = if global { self.stack.split_off(1) } else { Vec::new() };
self.stack.push(Scope { row, kind, name: name.to_string() });
rest
}
fn leave_owner(&mut self, rest: Vec<Scope>) {
self.stack.pop();
self.stack.extend(rest);
}
/// extractOwnedObjectMembers: each function member becomes its own node,
/// qualified under the owner (at file scope for one on the global object).
/// Every other member runs where the literal is written: under the owner
/// for a module-scope declaration (`values_under_owner`, #693), under the
/// enclosing scope for a local or an assignment. The literal's shorthand
/// members go to the function-as-value capture the same way.
fn extract_owned_object_members(&mut self, obj: Node<'t>, row: u32, kind: &'static str, name: &str, values_under_owner: bool, global: bool) {
let held = values_under_owner.then(|| self.enter_owner(row, kind, name, global));
self.maybe_capture_fn_refs(obj);
for i in 0..obj.named_child_count() {
let Some(member) = obj.named_child(i) else { continue };
if let Some((func, member_name)) = self.owned_member_function(member) {
if values_under_owner {
self.extract_function(func, Some(member_name));
} else {
let rest = self.enter_owner(row, kind, name, global);
self.extract_function(func, Some(member_name));
self.leave_owner(rest);
}
} else {
self.visit_function_body(member);
}
}
if let Some(rest) = held {
self.leave_owner(rest);
}
}
/// extractLocalObjectOwner: `const api = { load() {…} }` in a function body
/// or an IIFE gets the node a module-scope declaration would, with its
/// members under it. False when the declarator holds no owned literal.
pub(super) fn extract_local_object_owner(&mut self, declarator: Node<'t>) -> bool {
let Some(name_node) = declarator.child_by_field_name("name") else { return false };
if name_node.kind() != "identifier" {
return false;
}
let Some(obj) = self.owned_object_value(declarator.child_by_field_name("value")) else {
return false;
};
let is_const = declarator.parent().map(|d| self.is_const_decl(d)).unwrap_or(false);
let kind: &'static str = if is_const { "constant" } else { "variable" };
let name = self.text(name_node).to_string();
// A local: never the target of another scope's value read.
let extra = Extra {
docstring: crate::docstring::preceding_docstring(declarator, self.src),
signature: Some(util::init_signature(self.text(obj))),
is_exported: Some(false),
not_value_target: true,
..Extra::default()
};
let Some(row) = self.create_node(kind, &name, declarator, extra) else { return false };
self.extract_variable_type_annotation(declarator, row);
self.extract_owned_object_members(obj, row, kind, &name, false, false);
true
}
/// extractAssignedObjectOwner: `window.App = {…}` / `App.utils = {…}` /
/// `dw_page = {…}`. A plain identifier target is qualified like a
/// declaration. A path's owner is named by its last link and qualified by
/// the path as written, and so are its members (`window.App::init`); a
/// path on the global object is global wherever it is written, so it is
/// contained by the file. False (nothing extracted) for any other assignment.
pub(super) fn extract_assigned_object_owner(&mut self, node: Node<'t>, module_level: bool) -> bool {
let Some(obj) = self.owned_object_value(node.child_by_field_name("right")) else { return false };
let Some(path) = self.object_owner_path(node.child_by_field_name("left")) else { return false };
// A plain name assigned at module level is a global (`dw_page = {…}`);
// in a function it is a local being reassigned.
if path.len() == 1 && !module_level {
return false;
}
let qualified_name = (path.len() > 1).then(|| path.join("."));
let global = path.len() > 1 && is_host_global_root(&path[0]);
let rest = if global { self.stack.split_off(1) } else { Vec::new() };
let statement = node.parent().filter(|p| p.kind() == "expression_statement").unwrap_or(node);
let name = path.last().cloned().unwrap_or_default();
// `App.utils` is read as `App.utils`, never as a bare `utils`.
let extra = Extra {
docstring: crate::docstring::preceding_docstring(statement, self.src),
signature: Some(util::init_signature(self.text(obj))),
is_exported: Some(false),
qualified_name: qualified_name.clone(),
not_value_target: !(path.len() == 1 || global),
..Extra::default()
};
let row = self.create_node("variable", &name, node, extra);
self.stack.extend(rest);
let Some(row) = row else { return false };
if let Some(qualified_name) = qualified_name {
self.object_path_owners.insert(row, qualified_name);
}
self.extract_owned_object_members(obj, row, "variable", &name, false, global);
true
}
/// objectOwnerPath: an assignment target's links written as plain names
/// (`dw_page` → [dw_page], `App.utils.dom` → [App, utils, dom]), or None
/// for anything else — `this.x`, `a[k]`, a call, CommonJS's
/// `module.exports` / `exports.x`, or a prototype.
fn object_owner_path(&self, left: Option<Node<'t>>) -> Option<Vec<String>> {
let mut path: Vec<String> = Vec::new();