-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparser.rs
More file actions
2430 lines (2283 loc) · 91 KB
/
Copy pathparser.rs
File metadata and controls
2430 lines (2283 loc) · 91 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 crate::types::SymbolKind;
pub struct ParsedSymbol {
pub qualified_name: String,
pub name: String,
pub kind: SymbolKind,
pub language: String,
pub path: String,
pub line_start: usize,
pub line_end: usize,
pub signature: String,
pub docstring: String,
pub name_tokens: String,
pub is_entry_point: bool,
/// Best-effort "this is a test function" signal (rust `#[test]`/
/// `#[tokio::test]`, python `test_*` under a test path, go `Test*` with a
/// `*testing.T` param, java `@Test`). Used to exempt tests from dead-code
/// analysis — they have no in-repo callers by design, invoked externally
/// by the test harness just like `is_entry_point` symbols.
pub is_test: bool,
/// Enclosing class/impl type name for methods (`None` for free functions).
/// Drives tier-2 method resolution.
pub class_context: Option<String>,
/// McCabe cyclomatic complexity (1 = no branches). Always 1 for
/// languages without a real parse tree — see `branch_node_kinds`.
pub complexity: i64,
}
use crate::graph::tokenize::tokenize_identifier;
use crate::indexer::lang_constants::get_lang_constants;
/// Map a tree-sitter node kind and context to the correct `SymbolKind`.
/// `in_class` is true when the node is a direct child of a class/impl scope,
/// which upgrades plain function definitions to Method.
fn node_kind_to_symbol_kind(node_kind: &str, in_class: bool) -> SymbolKind {
match node_kind {
"class_definition" | "class_declaration" => SymbolKind::Class,
"struct_item" => SymbolKind::Struct,
"trait_item" => SymbolKind::Trait,
// Reachable only if `resolve_name_node` ever grows an `impl_item` case (it
// currently doesn't: `impl_item` has no `name` field, only `type`/`trait`).
// `impl_item` stays in Rust's `function_node_types` purely so its children
// get `class_context` via `class_node_types` below — emitting impl blocks
// themselves as symbols would add one noisy duplicate-named entry per
// `impl`/`impl Trait for` block without a corresponding consumer.
"impl_item" => SymbolKind::Impl,
"interface_declaration" => SymbolKind::Interface,
// Go's `type_declaration` and TS's `type_alias_declaration` are
// distinct grammar node kinds for the same concept (a named type),
// so both map to the one SymbolKind here.
"type_declaration" | "type_alias_declaration" => SymbolKind::Type,
// Explicit method nodes are always Method regardless of scope.
"method_declaration" | "method_definition" => SymbolKind::Method,
// JS/TS `const foo = () => {}` — treated as a variable holding a function.
"lexical_declaration" => SymbolKind::Variable,
// Plain function nodes: Method when inside a class/impl, Function otherwise.
_ => {
if in_class {
SymbolKind::Method
} else {
SymbolKind::Function
}
}
}
}
/// Parse `source` for a tier-0 `language` into a tree-sitter tree, or `None` if
/// the language is unsupported or parsing fails. Single source of the per-language
/// grammar mapping.
pub fn parse_tree(source: &str, language: &str) -> Option<tree_sitter::Tree> {
let lang: tree_sitter::Language = match language {
"python" => tree_sitter_python::LANGUAGE.into(),
"rust" => tree_sitter_rust::LANGUAGE.into(),
"go" => tree_sitter_go::LANGUAGE.into(),
"javascript" => tree_sitter_javascript::LANGUAGE.into(),
"typescript" => tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
"java" => tree_sitter_java::LANGUAGE.into(),
// Tier-0.5: optional grammar crates, each gated by a Cargo feature.
#[cfg(feature = "lang-ruby")]
"ruby" => tree_sitter_ruby::LANGUAGE.into(),
#[cfg(feature = "lang-php")]
"php" => tree_sitter_php::LANGUAGE_PHP.into(),
// kotlin and swift: lang-kotlin / lang-swift are no-op feature stubs;
// their tree-sitter crates use incompatible API versions. These languages
// always fall back to regex extraction in extract_file_data.
#[cfg(feature = "lang-csharp")]
"csharp" => tree_sitter_c_sharp::LANGUAGE.into(),
#[cfg(feature = "lang-shell")]
"shell" | "bash" => tree_sitter_bash::LANGUAGE.into(),
#[cfg(feature = "lang-c")]
"c" => tree_sitter_c::LANGUAGE.into(),
#[cfg(feature = "lang-cpp")]
"cpp" => tree_sitter_cpp::LANGUAGE.into(),
_ => return None,
};
let mut parser = tree_sitter::Parser::new();
parser.set_language(&lang).ok()?;
parser.parse(source, None)
}
pub fn extract_symbols(
source: &str,
language: &str,
path: &str,
) -> Result<Vec<ParsedSymbol>, String> {
let tree = parse_tree(source, language).ok_or("Failed to parse")?;
Ok(extract_symbols_from_tree(&tree, source, language, path))
}
/// Same as [`extract_symbols`] but against an already-parsed tree, so callers
/// that need multiple extractions from one file (symbols, calls, imports,
/// types, aliases) can share a single tree-sitter parse instead of re-parsing
/// the same source once per extraction.
pub fn extract_symbols_from_tree(
tree: &tree_sitter::Tree,
source: &str,
language: &str,
path: &str,
) -> Vec<ParsedSymbol> {
let Some(lang_consts) = get_lang_constants(language) else {
return Vec::new();
};
let mut symbols = Vec::new();
walk_symbols(
tree.root_node(),
source,
&lang_consts,
language,
path,
None,
&mut symbols,
);
symbols
}
/// Resolve the name node for `node`. Most `function_node_types` expose `name`
/// directly via `lc.name_field`, but a few wrap the name on a nested child:
/// Go `type_declaration` holds it on a `type_spec` child, and JS/TS
/// `lexical_declaration` holds it on a `variable_declarator` child (only
/// followed when the declarator's value is itself a function literal, so
/// plain `const x = 5` is not treated as a symbol).
fn resolve_name_node<'a>(
node: tree_sitter::Node<'a>,
lc: &crate::indexer::lang_constants::LangConstants,
) -> Option<tree_sitter::Node<'a>> {
if let Some(n) = node.child_by_field_name(lc.name_field) {
return Some(n);
}
match node.kind() {
"type_declaration" => {
let mut cursor = node.walk();
node.children(&mut cursor)
.find(|c| c.kind() == "type_spec")
.and_then(|spec| spec.child_by_field_name("name"))
}
"lexical_declaration" => {
let mut cursor = node.walk();
node.children(&mut cursor).find_map(|decl| {
if decl.kind() != "variable_declarator" {
return None;
}
let value = decl.child_by_field_name("value")?;
if matches!(
value.kind(),
"arrow_function" | "function_expression" | "function"
) {
decl.child_by_field_name("name")
} else {
None
}
})
}
// C and C++ function_definition: the function name is not in a direct
// "name" field but nested inside a declarator chain:
// function_definition
// declarator: function_declarator | pointer_declarator | ...
// declarator: ... (recursively) → identifier
// Walk the chain until we reach an identifier node.
"function_definition" => {
fn find_ident_in_declarator(n: tree_sitter::Node) -> Option<tree_sitter::Node> {
if n.kind() == "identifier" || n.kind() == "field_identifier" {
return Some(n);
}
if let Some(inner) = n.child_by_field_name("declarator") {
return find_ident_in_declarator(inner);
}
None
}
node.child_by_field_name("declarator")
.and_then(find_ident_in_declarator)
}
_ => None,
}
}
/// Walks backward through contiguous same-kind comment siblings immediately
/// preceding `node` — no blank-line gap between any two, nor between the
/// last one and `node` itself — and joins them in source order. Line-
/// comment doc conventions (Rust `///`, Go `//`, Shell/C `#`) parse each
/// line as its *own* tree-sitter node, so taking only the single immediate
/// `prev_named_sibling()` (the old behavior) silently captured just the
/// *last* line of a multi-line doc comment and dropped the rest. Block-
/// comment conventions (`/** */`) are already one node spanning every line,
/// so they pass through unaffected — the loop just finds nothing above them
/// to merge, same net result as before.
///
/// Adjacency check: a `line_comment` node's `end_position().row` already
/// lands on the *following* line (tree-sitter's rust grammar folds the
/// terminating newline into the token), so two nodes are immediately
/// adjacent when `earlier.end_position().row == later.start_position().row`
/// — no `+ 1` needed (confirmed by walking the real parse tree; an earlier
/// version of this got that off by one and matched nothing).
fn collect_doc_comment_lines(node: tree_sitter::Node, source: &str, doc_type: &str) -> String {
let mut lines: Vec<String> = Vec::new();
let mut current = node.prev_named_sibling();
let mut expected_row = node.start_position().row;
while let Some(n) = current {
if n.kind() != doc_type || n.end_position().row != expected_row {
break;
}
lines.push(source[n.byte_range()].trim().to_string());
expected_row = n.start_position().row;
current = n.prev_named_sibling();
}
lines.reverse();
lines.join("\n")
}
/// Recursive symbol walk tracking the enclosing class/impl so methods record
/// their `class_context`.
fn walk_symbols(
node: tree_sitter::Node,
source: &str,
lc: &crate::indexer::lang_constants::LangConstants,
language: &str,
path: &str,
enclosing_class: Option<String>,
out: &mut Vec<ParsedSymbol>,
) {
// A symbol defined here belongs to the class we are currently inside.
if lc.function_node_types.contains(&node.kind())
&& let Some(name_node) = resolve_name_node(node, lc)
{
let name = source[name_node.byte_range()].to_string();
let mut docstring = String::new();
if language == "python" {
if let Some(body) = node.child_by_field_name("body")
&& body.kind() == "block"
&& let Some(expr) = body.child(0)
&& expr.kind() == "expression_statement"
{
let raw_doc = source[expr.byte_range()].trim();
docstring = raw_doc.trim_matches(|c| c == '"' || c == '\'').to_string();
}
} else if let Some(doc_type) = lc.docstring_type {
docstring = collect_doc_comment_lines(node, source, doc_type);
}
let sig_end = source[node.start_byte()..]
.find('{')
.or_else(|| source[node.start_byte()..].find(':'))
.map(|pos| node.start_byte() + pos + 1)
.unwrap_or(node.end_byte());
let signature = source[node.start_byte()..sig_end].trim().to_string();
let name_tokens = tokenize_identifier(&name);
// Go has no class scope: a method's "class" is its receiver type.
let class_context = if language == "go" && node.kind() == "method_declaration" {
go_receiver_type(node, source)
} else {
enclosing_class.clone()
};
let is_entry_point = detect_entry_point(node, source, language, &name, &signature);
let is_test = detect_is_test(node, source, language, &name, &signature, path);
let complexity = compute_cyclomatic_complexity(node, language);
out.push(ParsedSymbol {
qualified_name: name.clone(),
name,
kind: node_kind_to_symbol_kind(node.kind(), enclosing_class.is_some()),
language: language.to_string(),
path: path.to_string(),
line_start: node.start_position().row + 1,
line_end: node.end_position().row + 1,
signature,
docstring,
name_tokens,
is_entry_point,
is_test,
complexity,
class_context,
});
}
// Entering a class/impl sets the context for its descendants. Rust's
// `trait_item` names itself via field `name` (a `type_identifier`) — it
// does not share `impl_item`'s `class_name_field` ("type", the Self
// type) — so the field to read can't come from the single
// per-language `class_name_field` constant alone for this node kind.
let child_class = if lc.class_node_types.contains(&node.kind()) {
let name_field = if node.kind() == "trait_item" {
"name"
} else {
lc.class_name_field
};
node.child_by_field_name(name_field)
.map(|n| source[n.byte_range()].to_string())
.or_else(|| enclosing_class.clone())
} else {
enclosing_class.clone()
};
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
walk_symbols(child, source, lc, language, path, child_class.clone(), out);
}
}
/// The receiver type of a Go `method_declaration` (`func (s *Service) M()` → `Service`).
fn go_receiver_type(node: tree_sitter::Node, source: &str) -> Option<String> {
let receiver = node.child_by_field_name("receiver")?;
let mut cursor = receiver.walk();
for child in receiver.children(&mut cursor) {
if child.kind() == "parameter_declaration"
&& let Some(ty) = child.child_by_field_name("type")
{
// Strip pointer/qualifier; keep the trailing bare type identifier.
let bare: String = source[ty.byte_range()]
.rsplit(['.', '*', ' '])
.next()
.unwrap_or("")
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
if !bare.is_empty() {
return Some(bare);
}
}
}
None
}
/// Decorator/attribute sibling node kind(s) that may precede a definition, per
/// language. Java needs two: `@Foo` parses as `marker_annotation`, `@Foo(...)`
/// as `annotation`.
fn decorator_node_kinds(language: &str) -> &'static [&'static str] {
match language {
"python" => &["decorator"],
"rust" => &["attribute_item"],
"java" => &["marker_annotation", "annotation"],
_ => &[],
}
}
/// Source text of every decorator/attribute immediately preceding `node` (innermost first).
fn collect_decorators<'a>(
node: tree_sitter::Node,
source: &'a str,
kinds: &[&str],
) -> Vec<&'a str> {
let mut out = Vec::new();
let mut sib = node.prev_named_sibling();
while let Some(s) = sib {
if !kinds.contains(&s.kind()) {
break;
}
out.push(source[s.byte_range()].trim());
sib = s.prev_named_sibling();
}
out
}
/// Per-language entry-point convention: known framework decorators/attributes,
/// `main`/`init` functions, and `export default`.
fn detect_entry_point(
node: tree_sitter::Node,
source: &str,
language: &str,
name: &str,
signature: &str,
) -> bool {
let decorators = collect_decorators(node, source, decorator_node_kinds(language));
match language {
"python" => {
const HOOKS: &[&str] = &[
".route(",
".command(",
".get(",
".post(",
".put(",
".delete(",
".patch(",
];
// Dunder methods (`__init__`, `__str__`, `__eq__`, `__iter__`, ...)
// are invoked by Python's data model via protocol dispatch
// (`str(x)` calls `__str__`, `for v in x` calls `__iter__`, a
// constructor call `X()` calls `__init__`) — never by their
// literal name at a call site, so a name-based call-graph can
// never see a "caller" for them regardless of real usage.
(name.len() > 4 && name.starts_with("__") && name.ends_with("__"))
|| decorators
.iter()
.any(|d| HOOKS.iter().any(|h| d.contains(h)))
}
"rust" => {
// Any non-trivial attribute macro on a function/method is a
// strong, general signal that something other than an ordinary
// call site invokes or registers it — route/tool/RPC
// registration, FFI export, a plugin/handler framework, etc.
// (see `NON_DISPATCH_ATTRS` for the small set of modifier
// attributes that don't imply this).
const NON_DISPATCH_ATTRS: &[&str] = &[
"allow",
"deny",
"warn",
"forbid",
"must_use",
"deprecated",
"inline",
"cold",
"cfg",
"cfg_attr",
"doc",
"track_caller",
"non_exhaustive",
"repr",
"should_panic",
"ignore",
"test",
"derive",
"automatically_derived",
];
// Common std/core trait methods dispatched via operator or
// protocol syntax (`x.into()`, `x == y`, `for v in x`,
// `x.clone()`, ...) rather than by their literal name at a call
// site — invisible to a name-based call-graph regardless of how
// many places genuinely invoke them through the trait.
const TRAIT_DISPATCH_NAMES: &[&str] = &[
"from",
"try_from",
"fmt",
"drop",
"deref",
"deref_mut",
"default",
"clone",
"eq",
"ne",
"partial_cmp",
"cmp",
"hash",
"next",
"into_iter",
"index",
"index_mut",
"add",
"sub",
"mul",
"div",
"rem",
"neg",
"not",
"bitand",
"bitor",
"bitxor",
"as_ref",
"as_mut",
"borrow",
"borrow_mut",
"deserialize",
"serialize",
];
name == "main"
|| TRAIT_DISPATCH_NAMES.contains(&name)
|| decorators.iter().any(|d| {
let inner = d.trim_start_matches("#[").trim_end_matches(']');
let path = inner.split('(').next().unwrap_or(inner).trim();
path == "main"
|| path.ends_with("::main")
|| !NON_DISPATCH_ATTRS.contains(&path)
})
}
"go" => node.kind() == "function_declaration" && (name == "main" || name == "init"),
"java" => signature.contains("public static void main"),
"javascript" | "typescript" => {
name == "main"
|| node
.parent()
.map(|p| {
p.kind() == "export_statement"
&& source[p.byte_range()]
.trim_start()
.starts_with("export default")
})
.unwrap_or(false)
}
_ => false,
}
}
/// Source text of every `annotation`/`marker_annotation` on `node`. Unlike
/// Rust's `#[attr]` (a preceding sibling of the item), tree-sitter-java parses
/// `@Foo` as a direct CHILD of the declaration node — either directly, or
/// nested one level inside a `modifiers` child — so this walks children
/// instead of `collect_decorators`'s prev-sibling walk.
fn collect_java_annotations<'a>(node: tree_sitter::Node, source: &'a str) -> Vec<&'a str> {
fn is_annotation(kind: &str) -> bool {
kind == "annotation" || kind == "marker_annotation"
}
let mut out = Vec::new();
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if is_annotation(child.kind()) {
out.push(source[child.byte_range()].trim());
} else if child.kind() == "modifiers" {
let mut mod_cursor = child.walk();
for grandchild in child.children(&mut mod_cursor) {
if is_annotation(grandchild.kind()) {
out.push(source[grandchild.byte_range()].trim());
}
}
}
}
out
}
/// McCabe cyclomatic complexity: 1 (baseline path) + 1 per decision-point
/// node in `node`'s subtree (see `branch_node_kinds`). Walks the full
/// subtree, so a nested function/closure defined inside `node` contributes
/// to the enclosing symbol's count too, in addition to getting its own
/// separate `ParsedSymbol` entry — this over-counts relative to some
/// stricter McCabe implementations that stop at nested function boundaries,
/// but keeps the walk simple and still gives a useful relative signal
/// ("this symbol's body, including anything defined inline in it, branches
/// a lot").
fn compute_cyclomatic_complexity(node: tree_sitter::Node, language: &str) -> i64 {
let branch_kinds = crate::indexer::lang_constants::branch_node_kinds(language);
if branch_kinds.is_empty() {
return 1;
}
let mut complexity = 1i64;
count_branch_nodes(node, branch_kinds, &mut complexity);
complexity
}
fn count_branch_nodes(node: tree_sitter::Node, branch_kinds: &[&str], complexity: &mut i64) {
if branch_kinds.contains(&node.kind()) {
*complexity += 1;
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
count_branch_nodes(child, branch_kinds, complexity);
}
}
/// Best-effort "is this a test function" signal, per language. Feeds
/// `is_test` on `ParsedSymbol` so dead-code analysis can exempt tests —
/// they have no in-repo callers by design (invoked by the test harness),
/// which otherwise makes every test function look like high-confidence
/// dead code. Javascript/typescript are not covered: Jest/Mocha tests are
/// anonymous callbacks passed to `it(`/`test(`, not named top-level symbols
/// the extractor would see here.
fn detect_is_test(
node: tree_sitter::Node,
source: &str,
language: &str,
name: &str,
signature: &str,
path: &str,
) -> bool {
match language {
"rust" => {
let decorators = collect_decorators(node, source, decorator_node_kinds(language));
decorators.iter().any(|d| {
let inner = d.trim_start_matches("#[").trim_end_matches(']');
let attr_path = inner.split('(').next().unwrap_or(inner).trim();
attr_path == "test" || attr_path == "rstest" || attr_path.ends_with("::test")
})
}
"python" => {
let file_name = path.rsplit('/').next().unwrap_or(path);
let test_path = file_name.starts_with("test_")
|| file_name.ends_with("_test.py")
|| path.contains("/tests/")
|| path.contains("/test/");
name.starts_with("test_") && test_path
}
"go" => {
path.ends_with("_test.go")
&& name.starts_with("Test")
&& name.len() > 4
&& name[4..5].chars().next().is_some_and(|c| c.is_uppercase())
&& signature.contains("*testing.T")
}
"java" => {
let decorators = collect_java_annotations(node, source);
decorators.iter().any(|d| {
let inner = d.trim_start_matches('@');
let ann_path = inner.split('(').next().unwrap_or(inner).trim();
ann_path == "Test" || ann_path.ends_with(".Test")
})
}
_ => false,
}
}
/// A raw call site discovered in source, attributed to its enclosing function.
///
/// `enclosing_name`/`enclosing_line` identify the caller symbol; `enclosing_class`
/// is the class it lives in (for `self`/`this` resolution); `receiver` is the
/// object of a method call (`recv.method()`), enabling tier-2 type resolution.
pub struct RawCall {
pub enclosing_name: String,
pub enclosing_line: usize,
pub enclosing_class: Option<String>,
pub callee: String,
pub receiver: Option<String>,
/// True when `receiver` came from a `Type::method()` scoped-path call
/// (the path segment immediately before the last `::`) rather than a
/// `recv.method()` field access. `receiver` is then already the type
/// name itself — resolution must scope directly to that class, not go
/// through the variable→type lookup a `.`-receiver needs.
pub receiver_is_type_path: bool,
/// True when this whole call expression is immediately `?`-tried
/// (`foo.bar()?`) or immediately `.unwrap()`/`.expect(..)`-chained
/// (`foo.bar().unwrap()`) — a cheap, sound (not heuristic-guessy)
/// syntactic signal that the call's return type is `Option<_>`/`Result<_,_>`.
/// Rust won't compile otherwise, so this is provable from the parse tree
/// alone, no type inference needed. Used by `rebuild_graph` to drop
/// bare-name fan-out candidates whose own signature can't possibly be
/// `Option`/`Result` — see its `MAX_CALLEE_CANDIDATES` fallback.
pub looks_option_or_result_chained: bool,
/// The immediate module-path segment just before the callee, when the
/// whole callee expression is a lowercase-qualified `::`-path
/// (`crate::telemetry::timed_tool` → `Some("telemetry")`) with no `use`
/// bringing the name into `file_symbols`/`import_map` — see
/// `module_hint_of`. `None` for a `.`-receiver call, a type-qualified
/// `Type::method()` call (already carried via `receiver`), or a bare
/// unqualified name.
pub module_hint: Option<String>,
pub line: usize,
}
/// Keep the leading identifier of a segment (drop generics/parens/whitespace).
fn leading_ident(seg: &str) -> Option<String> {
let ident: String = seg
.trim()
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
if ident.is_empty() { None } else { Some(ident) }
}
/// Split a callee expression into (immediate receiver, method/callee name,
/// whether that receiver is a type-path segment rather than a variable).
///
/// `self.method` → (Some("self"), "method", false);
/// `a.b.method` → (Some("b"), "method", false);
/// `HashMap::new` → (Some("HashMap"), "new", true) — the segment before the
/// last `::` is kept (not discarded) when it looks like a type name, since
/// that's the class an associated-function call like `Type::method()` must
/// resolve against; `mod::func` → (None, "func", false) — a lowercase
/// segment reads as a module, not a type (see `is_type_like`).
fn split_receiver_callee(raw: &str) -> Option<(Option<String>, String, bool)> {
if let Some(dot) = raw.rfind('.') {
let (left, right) = raw.split_at(dot);
let callee = leading_ident(&right[1..])?;
// Immediate receiver = last segment of the left side.
let recv = left.rsplit(['.', ':']).next().and_then(leading_ident);
Some((recv, callee, false))
} else if let Some(idx) = raw.rfind("::") {
let (left, right) = raw.split_at(idx);
let callee = leading_ident(&right[2..])?;
let recv = left.rsplit("::").next().and_then(leading_ident);
let is_type = recv.as_deref().is_some_and(is_type_like);
Some((if is_type { recv } else { None }, callee, is_type))
} else {
Some((None, leading_ident(raw)?, false))
}
}
/// The module-path segment `split_receiver_callee` discards for a lowercase
/// (non-type-like) `::`-qualified callee, e.g. `crate::telemetry::timed_tool`
/// or `telemetry::timed_tool` → `Some("telemetry")`.
///
/// Without this, a fully-qualified call to a module-level function with no
/// `use` importing it is textually indistinguishable from a bare unqualified
/// call of the same name — `resolve_tier1` matches purely on bare name, and
/// `rebuild_graph`'s same-file preference (see its doc comment) can then bind
/// to an unrelated same-named symbol that merely happens to share the
/// caller's own file, silently misresolving the edge (in the worst case, to
/// a phantom self-recursive edge on the caller itself) instead of the module
/// actually named in the source. Preserved separately from `receiver` so
/// tier-2 method resolution (which expects a variable/type name, not a
/// module) is unaffected — this is consumed only by `rebuild_graph`'s
/// candidate selection, as a same-strength-as-`same_file` tiebreak that
/// takes priority when present, since an explicit qualifier in the source
/// text is stronger evidence than incidental file collocation.
fn module_hint_of(raw: &str) -> Option<String> {
if raw.contains('.') {
return None; // dot-form's own receiver already covers this call
}
let idx = raw.rfind("::")?;
let (left, _) = raw.split_at(idx);
let seg = left.rsplit("::").next().and_then(leading_ident)?;
if is_type_like(&seg) {
None // type-qualified — already carried via `receiver`/`receiver_is_type_path`
} else {
Some(seg)
}
}
/// Heuristic: a path segment is "type-like" when it starts with an uppercase
/// letter, matching Rust/C#/Java/Kotlin/Swift convention for types/classes
/// (vs. snake_case modules or lowerCamelCase namespaces/packages). Not
/// perfect — code that doesn't follow the convention won't benefit — but a
/// false negative here just falls back to the pre-existing unscoped
/// resolution behavior, so the cost of missing one is low; a false positive
/// (treating a module as a type) just means a class-scoped lookup that
/// finds nothing, same as today.
fn is_type_like(segment: &str) -> bool {
segment.chars().next().is_some_and(|c| c.is_uppercase())
}
/// True if `call_node` (a whole `recv.method(..)`/`Type::method(..)` call
/// expression) is immediately `?`-tried, or immediately followed by
/// `.unwrap()`/`.expect(..)`/`.unwrap_or*(..)`. Only Rust's grammar defines
/// `try_expression`; other languages' `call_node` never has one as a parent,
/// so this is always `false` there — harmless, not a Rust-only code path.
///
/// This is deliberately narrow (direct parent only, not an arbitrary walk up
/// the chain) — it only needs to be *sound* (no false "yes"), not complete.
/// A missed case just falls back to today's behavior; a wrong "yes" would
/// incorrectly drop a real candidate in `rebuild_graph`.
fn looks_option_or_result_chained(call_node: tree_sitter::Node, source: &str) -> bool {
const UNWRAP_LIKE: &[&str] = &[
"unwrap",
"expect",
"unwrap_or",
"unwrap_or_default",
"unwrap_or_else",
];
let Some(parent) = call_node.parent() else {
return false;
};
if parent.kind() == "try_expression" {
return true;
}
if parent.kind() == "field_expression" {
// Confirm `call_node` is the receiver (`value`) of this field access, not
// some unrelated sibling — and that the field name is one of the
// unwrap-like methods, and that the field access is itself being called
// (`.unwrap()`, not just referenced as `.unwrap`).
let is_value = parent
.child_by_field_name("value")
.is_some_and(|v| v.id() == call_node.id());
let field_name = parent
.child_by_field_name("field")
.map(|f| &source[f.byte_range()]);
let is_invoked = parent.parent().is_some_and(|gp| {
gp.kind() == "call_expression"
&& gp
.child_by_field_name("function")
.is_some_and(|f| f.id() == parent.id())
});
if is_value && matches!(field_name, Some(f) if UNWRAP_LIKE.contains(&f)) && is_invoked {
return true;
}
}
// `.and_then(|x| EXPR)` — sound (not heuristic) one-level closure peel:
// `Option::and_then`/`Result::and_then` require the closure's return type
// to equal the *outer* Option/Result's own inner type, so if the whole
// `.and_then(..)` call is itself provably Option/Result-chained (recurse),
// then a single-expression closure body passed to it must be too — the
// code wouldn't type-check otherwise. Restricted to `and_then` specifically
// (not `.map(..)`, whose closure returns a plain value, not an `Option`/
// `Result` — recursing there would be unsound) and to a closure whose body
// *is* the call (single-expression closures only, not a `{ .. }` block
// that merely contains it somewhere).
if parent.kind() == "closure_expression"
&& parent
.child_by_field_name("body")
.is_some_and(|b| b.id() == call_node.id())
&& let Some(and_then_call) = parent.parent().and_then(|args| args.parent())
&& and_then_call.kind() == "call_expression"
&& let Some(fn_node) = and_then_call.child_by_field_name("function")
&& fn_node.kind() == "field_expression"
&& fn_node
.child_by_field_name("field")
.is_some_and(|f| &source[f.byte_range()] == "and_then")
{
return looks_option_or_result_chained(and_then_call, source);
}
false
}
/// Walk the AST collecting call sites, tracking the nearest enclosing function
/// and class.
fn walk_calls(
node: tree_sitter::Node,
source: &str,
consts: &crate::indexer::lang_constants::LangConstants,
enclosing: Option<(String, usize)>,
enclosing_class: Option<String>,
out: &mut Vec<RawCall>,
) {
let mut current = enclosing;
if consts.function_node_types.contains(&node.kind())
&& let Some(name_node) = node.child_by_field_name(consts.name_field)
{
current = Some((
source[name_node.byte_range()].to_string(),
node.start_position().row + 1,
));
}
let child_class = if consts.class_node_types.contains(&node.kind()) {
node.child_by_field_name(consts.class_name_field)
.map(|n| source[n.byte_range()].to_string())
.or_else(|| enclosing_class.clone())
} else {
enclosing_class.clone()
};
if consts.call_node_types.contains(&node.kind())
&& let Some((enc_name, enc_line)) = ¤t
&& let Some(fn_node) = node.child_by_field_name(consts.call_function_field)
&& let Some((receiver, callee, receiver_is_type_path)) =
split_receiver_callee(&source[fn_node.byte_range()])
{
out.push(RawCall {
enclosing_name: enc_name.clone(),
enclosing_line: *enc_line,
enclosing_class: child_class.clone(),
callee,
receiver,
receiver_is_type_path,
module_hint: module_hint_of(&source[fn_node.byte_range()]),
looks_option_or_result_chained: looks_option_or_result_chained(node, source),
line: node.start_position().row + 1,
});
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
walk_calls(
child,
source,
consts,
current.clone(),
child_class.clone(),
out,
);
}
}
/// Extract call sites from a source file, each attributed to its enclosing function.
/// Top-level calls (outside any function) are skipped — they have no caller symbol.
pub fn extract_calls(source: &str, language: &str, _path: &str) -> Result<Vec<RawCall>, String> {
let tree = parse_tree(source, language).ok_or("Failed to parse")?;
Ok(extract_calls_from_tree(&tree, source, language))
}
/// Same as [`extract_calls`] but against an already-parsed tree (see
/// [`extract_symbols_from_tree`]).
pub fn extract_calls_from_tree(
tree: &tree_sitter::Tree,
source: &str,
language: &str,
) -> Vec<RawCall> {
let Some(consts) = get_lang_constants(language) else {
return Vec::new();
};
let mut out = Vec::new();
walk_calls(tree.root_node(), source, &consts, None, None, &mut out);
out
}
/// File-local alias map (`x = helper` → `x` ↦ `helper`) via the conservative
/// resolver, so calls through simple aliases resolve to the real target.
///
/// The full `FileContext` (file_symbols + import_map + type_map) is supplied so
/// the resolver's multi-assignment and symbol/import/type guards apply.
pub fn extract_file_aliases(
source: &str,
language: &str,
ctx: &crate::resolver::FileContext,
) -> std::collections::HashMap<String, String> {
let Some(tree) = parse_tree(source, language) else {
return std::collections::HashMap::new();
};
extract_file_aliases_from_tree(&tree, source, language, ctx)
}
/// Same as [`extract_file_aliases`] but against an already-parsed tree (see
/// [`extract_symbols_from_tree`]).
pub fn extract_file_aliases_from_tree(
tree: &tree_sitter::Tree,
source: &str,
language: &str,
ctx: &crate::resolver::FileContext,
) -> std::collections::HashMap<String, String> {
crate::resolver::conservative::ConservativeResolver::new().extract_aliases(
tree.root_node(),
source.as_bytes(),
language,
ctx,
)
}
/// Best-effort `name → type` map from explicit annotations: typed parameters
/// plus Rust `let` and Go `var` bindings, across every tier-0 language that has
/// them. Used by the resolver as an alias guard and for tier-2 method resolution.
///
/// JavaScript (dynamic) yields an empty map. Go shares one type across several
/// names (`x, y Foo`), so each name is mapped.
pub fn extract_type_map(source: &str, language: &str) -> std::collections::HashMap<String, String> {
let Some(tree) = parse_tree(source, language) else {
return std::collections::HashMap::new();
};
extract_type_map_from_tree(&tree, source, language)
}
/// Same as [`extract_type_map`] but against an already-parsed tree (see
/// [`extract_symbols_from_tree`]).
pub fn extract_type_map_from_tree(
tree: &tree_sitter::Tree,
source: &str,
language: &str,
) -> std::collections::HashMap<String, String> {
let mut map = std::collections::HashMap::new();
// Node kinds carrying a `name(s): type` (or `name(s) type`) binding.
let binding_kinds: &[&str] = match language {
"python" => &["typed_parameter"],
"typescript" => &["required_parameter", "optional_parameter"],
"rust" => &["parameter", "let_declaration"],
"go" => &["parameter_declaration", "var_spec"],
"java" => &["formal_parameter"],
_ => return map, // javascript: no static annotations
};
let mut stack = vec![tree.root_node()];
while let Some(node) = stack.pop() {
if binding_kinds.contains(&node.kind()) {
for (name, ty) in binding_names_and_type(node, source, language) {
map.insert(name, ty);
}
}
// Rust constructor inference: `let x = Foo::new(...)`, `Foo::default()`,
// or `Foo { .. }` binds x to type Foo even without a type annotation.
if language == "rust"
&& node.kind() == "let_declaration"
&& node.child_by_field_name("type").is_none()
&& let Some(pat) = node.child_by_field_name("pattern")
&& pat.kind() == "identifier"
&& let Some(value) = node.child_by_field_name("value")
&& let Some(ty) = rust_constructor_type(value, source)
{
map.insert(source[pat.byte_range()].to_string(), ty);
}
// Rust reassignment inference: `let mut x;` declares `x` with no
// initializer (so the `let_declaration` case above never fires), and
// its type only becomes apparent at a later `x = Foo::Variant;` /
// `x = Foo::new(..);` assignment — typically one arm of an `if`/`match`
// that builds up a state-machine-style value across branches (e.g.
// this crate's own `EdgeConfidence` confidence variable in
// `pipeline.rs::extract_file_data`). Every matching assignment for the
// same `x` inserts the same type, which is what makes this safe across
// multiple branches: whichever one the walk visits first or last,
// `map[x]` ends up the same value.
if language == "rust"
&& node.kind() == "assignment_expression"
&& let Some(lhs) = node.child_by_field_name("left")
&& lhs.kind() == "identifier"
&& let Some(rhs) = node.child_by_field_name("right")
&& let Some(ty) = rust_constructor_type(rhs, source)
{
map.insert(source[lhs.byte_range()].to_string(), ty);
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
stack.push(child);
}
}
map
}
/// The type constructed by a Rust expression used as a `let` initializer (or,
/// via `assignment_expression` in `extract_type_map_from_tree`, a later
/// reassignment): `Foo::new(..)` / `Foo::default()` / `Foo::with_x(..)` ->
/// `Foo`; `Foo { .. }` (struct literal) -> `Foo`; a bare enum-variant path
/// `Foo::Variant` (no call parens) -> `Foo`. Returns `None` for anything else.
fn rust_constructor_type(value: tree_sitter::Node, source: &str) -> Option<String> {
match value.kind() {
// Foo::new(...) -- a call whose function is a scoped identifier.
"call_expression" => {
let func = value.child_by_field_name("function")?;
if func.kind() != "scoped_identifier" {