1use std::borrow::Cow;
4use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
5
6use serde::{Deserialize, Serialize};
7use tree_sitter::Node;
8
9use super::super::rust_bindings::{Initializer, RustBindings};
10use super::syntax_index::{Direct, Nav};
11use super::{BlobRef, BlobRefKind, BlobSymbol, ManifestJoinError, ParseBlob};
12use crate::parser::LangId;
13
14pub fn python_reexports(parse: &ParseBlob) -> Vec<(String, Vec<String>)> {
17 parse
18 .refs
19 .iter()
20 .filter(|reference| reference.kind == BlobRefKind::Reexport && !reference.wildcard)
21 .filter_map(|reference| {
22 let module = reference.module_path.clone()?;
23 let mut names =
24 crate::callgraph_store::parse_reexport_names(reference.full_ref.as_deref()?)
25 .into_iter()
26 .map(|(local, source)| format!("{source} as {local}"))
27 .collect::<Vec<_>>();
28 names.sort();
29 Some((module, names))
30 })
31 .collect()
32}
33
34#[path = "dispatch/projected.rs"]
35pub mod projected;
36#[path = "dispatch/smart_pointer.rs"]
37pub(super) mod smart_pointer;
38#[path = "dispatch/static_receiver.rs"]
39mod static_receiver;
40#[path = "dispatch/typescript.rs"]
41mod typescript;
42pub(super) use static_receiver::STATIC_IMPORT_PREFIX;
43pub use static_receiver::{CSharpProjects, StaticFacts, StaticSiteEvidence};
44test_support_visibility! {
45#[path = "dispatch/view.rs"]
46mod view;
47}
48
49pub fn complete_typescript_symbols<'tree>(
52 source: &str,
53 lang: LangId,
54 root: Node<'tree>,
55 symbols: &mut Vec<crate::symbols::Symbol>,
56 nav: impl Nav<'tree>,
57) -> Vec<Node<'tree>> {
58 if matches!(lang, LangId::TypeScript | LangId::Tsx) {
59 let nodes = nav.reverse_named_preorder(root);
60 typescript::complete_symbols(&nodes, source, symbols, nav);
61 nodes
62 } else {
63 Vec::new()
64 }
65}
66
67pub fn typescript_objects_from_data(
70 source: &str,
71 lang: LangId,
72 nodes: &[Node<'_>],
73 data: &crate::callgraph::FileCallData,
74) -> Option<ParseBlob> {
75 if !matches!(lang, LangId::TypeScript | LangId::Tsx) {
76 return None;
77 }
78 let mut profile = crate::stage_timer::StageTimer::new("typescript_facts");
79 let mut refs = Vec::new();
80 for (caller, calls) in &data.calls_by_symbol {
81 for call in calls.iter().filter(|call| {
82 call.kind == crate::callgraph::CallSiteKind::Call && call.full_callee.contains('.')
83 }) {
84 refs.push(BlobRef {
85 ordinal: refs.len() as u32,
86 kind: BlobRefKind::Call,
87 caller_symbol: Some(caller.clone()),
88 short_name: Some(call.callee_name.clone()),
89 full_ref: Some(call.full_callee.clone()),
90 module_path: None,
91 line: call.line,
92 byte_start: call.byte_start,
93 byte_end: call.byte_end,
94 path_override: None,
95 local_name: None,
96 requested_name: None,
97 namespace_alias: None,
98 wildcard: false,
99 import_kind: None,
100 });
101 }
102 }
103 let mut parse = ParseBlob {
104 entry_point_symbols: Vec::new(),
105 dispatch: DispatchFacts::default(),
106 extractor_version: String::new(),
107 language: if lang == LangId::Tsx {
108 "tsx"
109 } else {
110 "typescript"
111 }
112 .into(),
113 ast_nodes: Vec::new(),
114 symbols: super::blob_symbols(data),
115 default_export_symbol: data.default_export_symbol.clone(),
116 exported_symbols: data.exported_symbols.clone(),
117 callable_symbols: Vec::new(),
118 imports: super::blob_imports(data),
119 python_bindings: Vec::new(),
120 refs,
121 };
122 profile.finish(
123 "inputs",
124 format_args!("nodes={} refs={}", nodes.len(), parse.refs.len()),
125 );
126 let objects = typescript::Objects::new_objects_only(nodes, source, &parse, Direct);
130 profile.finish("index", format_args!("nodes={}", nodes.len()));
131 let mut facts = DispatchFacts::default();
132 objects.extract(&mut facts);
133 facts.methods.extend_from_slice(objects.methods());
134 profile.finish(
135 "facts",
136 format_args!(
137 "methods={} types={}",
138 facts.methods.len(),
139 facts.types.len()
140 ),
141 );
142 let call_kinds = crate::calls::call_node_kinds(lang);
143 let calls = nodes
144 .iter()
145 .filter(|node| call_kinds.contains(&node.kind()))
146 .map(|node| ((node.start_byte(), node.end_byte()), *node))
147 .collect::<HashMap<_, _>>();
148 profile.finish("calls", format_args!("calls={}", calls.len()));
149 for reference in &parse.refs {
150 let Some(&call) = calls.get(&(reference.byte_start, reference.byte_end)) else {
151 continue;
152 };
153 let Some(callee) = field(call, &["function", "name"]) else {
154 continue;
155 };
156 if field(callee, &["property"]).is_none() {
157 continue;
158 }
159 let Some(receiver) = field(callee, &["object"]) else {
160 continue;
161 };
162 let ty = if text(receiver, source) == "this" {
163 Direct
164 .enclosing(call, FUNCTIONS)
165 .filter(|function| function.kind() == "method_definition")
166 .and_then(|function| typescript::object_member(function, source, Direct))
167 .map(|(object, _)| typescript::object_identity(object))
168 } else {
169 objects.object_receiver(receiver, call)
170 };
171 if !ty.as_ref().is_some_and(|ty| {
172 ty.starts_with("@object:") || ty.starts_with("@return:") || ty.starts_with("@field:")
173 }) {
174 continue;
175 }
176 facts.sites.push(SiteHint {
177 ordinal: reference.ordinal,
178 caller: reference.caller_symbol.clone(),
179 line: reference.line,
180 member: field(callee, &["property"]).map(|member| text(member, source).to_string()),
181 receiver: ty,
182 dynamic: false,
183 });
184 }
185 if facts.methods.is_empty() && facts.sites.is_empty() && facts.returns.is_empty() {
186 profile.finish("sites", format_args!("sites=0"));
187 return None;
188 }
189 profile.finish("sites", format_args!("sites={}", facts.sites.len()));
190 let site_ordinals = facts
191 .sites
192 .iter()
193 .map(|site| site.ordinal)
194 .collect::<HashSet<_>>();
195 parse
196 .refs
197 .retain(|reference| site_ordinals.contains(&reference.ordinal));
198 for symbol in &mut parse.symbols {
201 symbol.signature = None;
202 }
203 for reference in &mut parse.refs {
204 reference.caller_symbol = None;
205 reference.short_name = None;
206 reference.full_ref = None;
207 }
208 parse.dispatch = facts;
209 Some(parse)
210}
211
212#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
213pub struct DispatchFacts {
214 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub static_facts: Option<Box<StaticFacts>>,
216 #[serde(default)]
219 pub go_package: Option<String>,
220 pub types: Vec<TypeHint>,
221 pub methods: Vec<MethodHint>,
222 pub sites: Vec<SiteHint>,
223 #[serde(default)]
224 pub fields: Vec<FieldHint>,
225 #[serde(default)]
226 pub returns: Vec<ReturnHint>,
227}
228
229#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
230pub struct FieldHint {
231 pub owner: String,
232 pub name: String,
233 pub ty: String,
234}
235
236#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
237pub struct ReturnHint {
238 pub symbol: String,
239 pub ty: String,
240}
241
242#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
243pub struct TypeHint {
244 pub name: String,
245 pub bases: Vec<String>,
246 pub interface: bool,
247 pub closed: bool,
248}
249
250#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
251pub struct MethodHint {
252 pub owner: String,
253 pub trait_name: Option<String>,
254 pub name: String,
255 pub symbol: String,
256 pub has_body: bool,
257 pub shape: String,
258 pub private: bool,
259}
260
261#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
262pub struct SiteHint {
263 pub ordinal: u32,
264 pub caller: Option<String>,
265 pub line: u32,
266 pub member: Option<String>,
267 pub receiver: Option<String>,
268 pub dynamic: bool,
269}
270
271fn text<'a>(node: Node<'_>, source: &'a str) -> &'a str {
272 source.get(node.byte_range()).unwrap_or_default()
273}
274fn field<'a>(node: Node<'a>, names: &[&str]) -> Option<Node<'a>> {
275 names.iter().find_map(|name| node.child_by_field_name(name))
276}
277test_support_visibility! {
278fn descendants(node: Node<'_>) -> Vec<Node<'_>> {
279 let mut result = Vec::new();
280 let mut cursor = node.walk();
281 let mut depth = 0;
282 loop {
283 result.push(cursor.node());
284 if cursor.goto_last_child() {
287 while !cursor.node().is_named() && cursor.goto_previous_sibling() {}
288 if cursor.node().is_named() {
289 depth += 1;
290 continue;
291 }
292 cursor.goto_parent();
293 }
294 loop {
295 if depth == 0 {
296 return result;
297 }
298 let mut previous = cursor.goto_previous_sibling();
299 while previous && !cursor.node().is_named() {
300 previous = cursor.goto_previous_sibling();
301 }
302 if previous {
303 break;
304 }
305 cursor.goto_parent();
306 depth -= 1;
307 }
308 }
309}
310}
311fn method_shape(node: Node<'_>, source: &str, language: &str) -> String {
312 let parameters = field(node, &["parameters"])
313 .map(|p| {
314 descendants(p)
315 .into_iter()
316 .filter(|n| n.kind() == "parameter_declaration")
317 .filter_map(|n| field(n, &["type"]).map(|t| text(t, source)))
318 .collect::<Vec<_>>()
319 .join(",")
320 })
321 .unwrap_or_default();
322 let result = field(node, &["result", "return_type"])
323 .map(|n| text(n, source).split_whitespace().collect::<String>())
324 .unwrap_or_default();
325 let receiver = if language == "rust" {
326 if super::super::rust_bindings::has_self_parameter(node, source) {
327 "self;"
328 } else {
329 "static;"
330 }
331 } else {
332 ""
333 };
334 format!("{receiver}{parameters}->{result}")
335}
336
337fn rust_receiver_shape(shape: &str) -> Option<bool> {
338 if shape.starts_with("self;") {
341 Some(true)
342 } else if shape.starts_with("static;") {
343 Some(false)
344 } else {
345 None
346 }
347}
348
349pub fn associated_reference(full: &str) -> bool {
350 super::super::parse_method_dispatch(full).is_some_and(|(_, _, _, associated)| associated)
351}
352fn type_name(raw: &str) -> String {
353 raw.trim()
354 .trim_start_matches(':')
355 .trim()
356 .trim_start_matches('&')
357 .trim_start_matches("mut ")
358 .trim_start_matches('*')
359 .trim_start_matches("dyn ")
360 .trim_start_matches("impl ")
361 .split(['<', '[', '?'])
362 .next()
363 .unwrap_or_default()
364 .trim()
365 .to_string()
366}
367
368fn receiver_projection<'a>(
369 language: &str,
370 receiver: &'a str,
371 member: &str,
372) -> std::borrow::Cow<'a, str> {
373 if language == "rust" && receiver.starts_with("@field:") {
374 format!("@method:{receiver}|{member}").into()
375 } else {
376 receiver.into()
377 }
378}
379const TYPES: &[&str] = &[
380 "class_declaration",
381 "class_definition",
382 "interface_declaration",
383 "trait_item",
384 "struct_item",
385 "type_spec",
386 "object_declaration",
387];
388test_support_visibility! {
389const FUNCTIONS: &[&str] = &[
390 "function_declaration",
391 "function_definition",
392 "function_item",
393 "method_definition",
394 "method_signature",
395 "method_spec",
396 "method_elem",
397 "method_declaration",
398 "function_signature_item",
399 "arrow_function",
400 "function_expression",
401 "generator_function",
402 "lambda_expression",
403];
404}
405fn named<'tree>(node: Node<'tree>, source: &str, nav: impl Nav<'tree>) -> Option<String> {
406 if let Some((_, name)) = typescript::object_member(node, source, nav) {
407 return Some(name);
408 }
409 field(node, &["name"])
410 .or_else(|| {
411 node.named_children(&mut node.walk()).find(|n| {
412 ["identifier", "simple_identifier", "type_identifier"].contains(&n.kind())
413 })
414 })
415 .map(|name| text(name, source).to_string())
416}
417fn owner<'tree>(
418 node: Node<'tree>,
419 source: &str,
420 language: &str,
421 nav: impl Nav<'tree>,
422) -> Option<(String, Option<String>)> {
423 if typescript::supported(language) {
424 if let Some((object, _)) = typescript::object_member(node, source, nav) {
425 return Some((typescript::object_identity(object), None));
426 }
427 if matches!(nav.kind(node), "function_expression" | "generator_function") {
428 return None;
429 }
430 }
431 if language == "rust" {
432 if let Some(implementation) = nav.enclosing(node, &["impl_item"]) {
433 return Some((
434 type_name(text(field(implementation, &["type"])?, source)),
435 field(implementation, &["trait"]).map(|n| type_name(text(n, source))),
436 ));
437 }
438 }
439 if language == "go" {
440 if let Some(method) = nav.enclosing(node, &["method_declaration"]) {
441 let receiver = field(method, &["receiver"])?;
442 let parameter = descendants(receiver)
443 .into_iter()
444 .find(|n| n.kind() == "parameter_declaration")?;
445 return Some((type_name(text(field(parameter, &["type"])?, source)), None));
446 }
447 }
448 nav.enclosing(node, TYPES)
449 .and_then(|n| named(n, source, nav))
450 .map(|n| (n, None))
451}
452
453fn complete_members<'tree>(
457 source: &str,
458 lang: LangId,
459 all: &[Node<'tree>],
460 parse: &mut ParseBlob,
461 spans: &SpanOrdinals,
462 rust_bindings: Option<&RustBindings>,
463 nav: impl Nav<'tree>,
464) -> Result<(), ManifestJoinError> {
465 let mut identities = HashMap::new();
468 for symbol in &parse.symbols {
469 identities
470 .entry((symbol.end_line, symbol.end_col, symbol.name.clone()))
471 .or_insert_with(|| symbol.scoped_name.clone());
472 }
473 let mut scoped_names = parse
474 .symbols
475 .iter()
476 .map(|s| s.scoped_name.clone())
477 .collect::<HashSet<_>>();
478 let mut callers = symbol_callers(parse);
479 for &node in all {
480 if !FUNCTIONS.contains(&nav.kind(node)) {
481 continue;
482 }
483 let Some((owner, _)) = owner(node, source, &parse.language, nav) else {
484 continue;
485 };
486 let Some(name) = named(node, source, nav) else {
487 continue;
488 };
489 let position = (
490 node.start_position().row as u32,
491 node.start_position().column as u32,
492 );
493 let identity = (
494 node.end_position().row as u32,
495 node.end_position().column as u32,
496 name.clone(),
497 );
498 let rust_symbol = rust_bindings.and_then(|index| index.symbol_at(node.start_byte()));
499 if let Some(symbol) = rust_symbol {
500 if scoped_names.contains(symbol) {
501 callers
502 .entry(position)
503 .or_insert_with(|| symbol.to_string());
504 continue;
505 }
506 }
507 if let Some(symbol) = identities.get(&identity) {
508 callers.entry(position).or_insert_with(|| symbol.clone());
509 continue;
510 }
511 let mut scoped_name = rust_symbol
512 .or_else(|| {
513 rust_bindings
514 .and_then(|index| index.declaration_at(node.start_byte()))
515 .map(|declaration| declaration.symbol.as_str())
516 })
517 .map(str::to_string)
518 .unwrap_or_else(|| format!("{owner}::{name}"));
519 let ordinal = spans
520 .get(&(node.start_byte(), node.end_byte()))
521 .copied()
522 .unwrap_or_default();
523 if scoped_names.contains(&scoped_name) {
524 scoped_name = format!("{scoped_name}@{ordinal}");
525 }
526 scoped_names.insert(scoped_name.clone());
527 identities.insert(identity, scoped_name.clone());
528 callers
529 .entry(position)
530 .or_insert_with(|| scoped_name.clone());
531 parse.symbols.push(BlobSymbol {
532 is_test: None,
533 ordinal,
534 name,
535 scoped_name: scoped_name.clone(),
536 kind: "method".into(),
537 exported: false,
538 is_default_export: false,
539 start_line: node.start_position().row as u32,
540 start_col: node.start_position().column as u32,
541 end_line: node.end_position().row as u32,
542 end_col: node.end_position().column as u32,
543 signature: Some(
544 text(node, source)
545 .split('{')
546 .next()
547 .unwrap_or_default()
548 .trim()
549 .to_string(),
550 ),
551 program_start: false,
552 entry_attribute: None,
553 });
554 if field(node, &["body"]).is_some() {
555 parse.callable_symbols.push(scoped_name);
556 }
557 }
558 let mut call_ordinals = parse
559 .refs
560 .iter()
561 .enumerate()
562 .filter(|(_, r)| r.kind == BlobRefKind::Call)
563 .map(|(index, r)| (r.ordinal, index))
564 .collect::<HashMap<_, _>>();
565 for &call in all
566 .iter()
567 .filter(|n| crate::calls::call_node_kinds(lang).contains(&nav.kind(**n)))
568 {
569 let callee = field(call, &["function", "name"]).or_else(|| {
570 if parse.language == "kotlin" {
571 call.named_child(0)
572 } else {
573 None
574 }
575 });
576 let Some(callee) = callee else {
577 continue;
578 };
579 let Some(&ordinal) = spans.get(&(call.start_byte(), call.end_byte())) else {
580 continue;
581 };
582 if let Some(&index) = call_ordinals.get(&ordinal) {
583 if typescript::supported(&parse.language) {
584 if let Some(function) = nav.enclosing(call, FUNCTIONS) {
585 if typescript::object_member(function, source, nav).is_some() {
586 if let Some(caller) = callers.get(&(
587 function.start_position().row as u32,
588 function.start_position().column as u32,
589 )) {
590 parse.refs[index].caller_symbol = Some(caller.clone());
591 }
592 }
593 }
594 }
595 continue;
596 }
597 let caller = nav.enclosing(call, FUNCTIONS).and_then(|function| {
598 callers
599 .get(&(
600 function.start_position().row as u32,
601 function.start_position().column as u32,
602 ))
603 .cloned()
604 });
605 if caller.is_none() {
606 continue;
607 }
608 call_ordinals.insert(ordinal, parse.refs.len());
609 let full = text(callee, source).to_string();
610 let short = full
611 .rsplit(['.', ':'])
612 .next()
613 .unwrap_or_default()
614 .to_string();
615 parse.refs.push(BlobRef {
616 ordinal,
617 kind: BlobRefKind::Call,
618 caller_symbol: caller,
619 short_name: Some(short),
620 full_ref: Some(full),
621 module_path: None,
622 line: call.start_position().row as u32 + 1,
623 byte_start: call.start_byte(),
624 byte_end: call.end_byte(),
625 path_override: None,
626 local_name: None,
627 requested_name: None,
628 namespace_alias: None,
629 wildcard: false,
630 import_kind: None,
631 });
632 }
633 parse.refs.sort_by_key(|r| (r.ordinal, r.kind));
634 parse.symbols.sort_by_key(|s| s.ordinal);
635 parse.callable_symbols.sort();
636 parse.callable_symbols.dedup();
637 Ok(())
638}
639
640pub fn extract(
642 source: &str,
643 lang: LangId,
644 root: Node<'_>,
645 parse: &mut ParseBlob,
646) -> Result<DispatchFacts, ManifestJoinError> {
647 extract_with(source, lang, root, parse, Direct)
648}
649
650pub fn extract_with<'tree>(
652 source: &str,
653 lang: LangId,
654 root: Node<'tree>,
655 parse: &mut ParseBlob,
656 nav: impl Nav<'tree>,
657) -> Result<DispatchFacts, ManifestJoinError> {
658 let all = nav.reverse_named_preorder(root);
659 let spans = exact_ordinals(parse);
662 let rust_bindings = (lang == LangId::Rust).then(|| RustBindings::new_with(source, root, nav));
665 complete_members(
666 source,
667 lang,
668 &all,
669 parse,
670 &spans,
671 rust_bindings.as_ref(),
672 nav,
673 )?;
674 let language = parse.language.as_str();
675 let index_receivers = language == "rust";
676 #[cfg(any(test, feature = "test-support"))]
677 let index_receivers = index_receivers && !UNINDEXED_RECEIVERS.with(|mode| mode.get());
678 let receiver_index = index_receivers
679 .then(|| RustReceiverIndex::new(&all, source, rust_bindings.as_ref().unwrap(), nav));
680 let rust_bindings = rust_bindings.as_ref();
681 let smart_fields = (language == "rust").then(|| smart_pointer::Fields::new(&all, source, nav));
682 let class_fields = ClassFieldMemo::default();
683 let go_index = (language == "go")
684 .then(|| crate::callgraph_store::go_dispatch::SourceIndex::new(root, source, false));
685 let callers = symbol_callers(parse);
686 let mut symbols_by_name_line = HashMap::new();
687 for symbol in &parse.symbols {
688 symbols_by_name_line
689 .entry((symbol.name.as_str(), symbol.start_line))
690 .or_insert(symbol);
691 }
692 let mut functions = HashMap::<(u32, u32), Node<'_>>::new();
693 let mut functions_by_end = HashMap::new();
694 for &node in all.iter().filter(|n| FUNCTIONS.contains(&nav.kind(**n))) {
695 functions_by_end.insert(node.end_byte(), node);
696 let key = (
697 node.end_position().row as u32,
698 node.end_position().column as u32,
699 );
700 functions
701 .entry(key)
702 .and_modify(|previous| {
703 if node.end_byte() - node.start_byte() < previous.end_byte() - previous.start_byte()
704 {
705 *previous = node;
706 }
707 })
708 .or_insert(node);
709 }
710 let mut facts = DispatchFacts::default();
711 facts.go_package = go_index.as_ref().and_then(|index| index.package.clone());
712 let ts_objects =
713 typescript::supported(language).then(|| typescript::Objects::new(&all, source, parse, nav));
714 if let Some(objects) = &ts_objects {
715 objects.extract(&mut facts);
716 }
717 if language == "rust" {
718 for node in &all {
719 if nav.kind(*node) == "field_declaration" {
720 if let (Some(container), Some(name), Some(ty)) = (
721 nav.enclosing(*node, &["struct_item"]),
722 field(*node, &["name"]),
723 field(*node, &["type"]),
724 ) {
725 if let Some(owner) = named(container, source, nav) {
726 facts.fields.push(FieldHint {
727 owner: crate::callgraph::rust_module_qualified_name(
728 container, source, &owner, nav,
729 ),
730 name: text(name, source).to_string(),
731 ty: smart_fields.as_ref().unwrap().field_type(ty, source, nav),
732 });
733 }
734 }
735 }
736 }
737 for symbol in &parse.symbols {
738 if let Some(&node) = rust_bindings
739 .as_ref()
740 .and_then(|index| index.declaration(&symbol.scoped_name))
741 .and_then(|declaration| functions_by_end.get(&declaration.bytes.end))
742 {
743 if let Some(ty) = field(node, &["return_type"]) {
744 let mut ty = type_name(text(ty, source));
745 if ty == "Self" {
746 ty = rust_bindings
747 .as_ref()
748 .and_then(|index| index.declaration_at(node.start_byte()))
749 .and_then(|declaration| declaration.owner.as_ref())
750 .map(|owner| type_name(owner))
751 .or_else(|| owner(node, source, language, nav).map(|(owner, _)| owner))
752 .unwrap_or(ty);
753 }
754 facts.returns.push(ReturnHint {
755 symbol: symbol.scoped_name.clone(),
756 ty,
757 });
758 }
759 }
760 }
761 }
762 for node in &all {
763 let kind = nav.kind(*node);
764 if !TYPES.contains(&kind) {
765 continue;
766 }
767 if language == "go" && nav.enclosing(*node, FUNCTIONS).is_some() {
768 continue;
769 }
770 let Some(mut name) = named(*node, source, nav) else {
771 continue;
772 };
773 if language == "rust" {
774 name = crate::callgraph::rust_module_qualified_name(*node, source, &name, nav);
775 }
776 let body = field(*node, &["body", "type"]);
777 let interface = kind.contains("interface")
778 || kind == "trait_item"
779 || body.is_some_and(|n| n.kind() == "interface_type")
780 || text(*node, source)
781 .split('{')
782 .next()
783 .unwrap_or_default()
784 .split_whitespace()
785 .any(|w| w == "abstract")
786 || (language == "python" && text(*node, source).contains("@abstractmethod"));
787 let mut bases = Vec::new();
788 for child in node.named_children(&mut node.walk()) {
789 if language != "python"
790 && [
791 "class_heritage",
792 "superclasses",
793 "super_interfaces",
794 "superclass",
795 "delegation_specifiers",
796 ]
797 .contains(&child.kind())
798 {
799 for base in descendants(child) {
800 if ["type_identifier", "identifier", "user_type"].contains(&base.kind()) {
801 bases.push(type_name(text(base, source)));
802 }
803 }
804 }
805 }
806 if language == "python" {
807 if let Some(arguments) = field(*node, &["superclasses"]) {
808 bases.extend(
809 arguments
810 .named_children(&mut arguments.walk())
811 .filter(|n| n.kind() != "keyword_argument")
812 .map(|n| type_name(text(n, source))),
813 );
814 }
815 }
816 if language == "go" {
817 if let Some(body) = body {
818 for member in descendants(body) {
819 if member.kind() == "field_declaration" && field(member, &["name"]).is_none() {
820 if let Some(t) = field(member, &["type"]) {
821 bases.push(type_name(text(t, source)));
822 }
823 }
824 }
825 }
826 }
827 bases.retain(|name| !name.is_empty());
828 if language != "python" {
829 bases.sort();
830 bases.dedup();
831 }
832 let header = text(*node, source).split('{').next().unwrap_or_default();
833 facts.types.push(TypeHint {
834 name,
835 bases,
836 interface,
837 closed: header
838 .split_whitespace()
839 .any(|w| w == "final" || w == "sealed"),
840 });
841 }
842 for symbol in &parse.symbols {
843 let node = functions
844 .get(&(symbol.end_line, symbol.end_col))
845 .or_else(|| {
846 (language == "rust")
847 .then(|| {
848 rust_bindings
849 .as_ref()
850 .and_then(|index| index.declaration(&symbol.scoped_name))
851 .and_then(|declaration| functions_by_end.get(&declaration.bytes.end))
852 })
853 .flatten()
854 });
855 let Some(&node) = node else {
856 continue;
857 };
858 if !["method", "function"].contains(&symbol.kind.as_str()) {
859 continue;
860 }
861 let Some((mut owner, mut trait_name)) = owner(node, source, language, nav) else {
862 continue;
863 };
864 if ts_objects.as_ref().is_some_and(|objects| {
865 typescript::object_member(node, source, nav).is_some_and(|(object, name)| {
866 name != symbol.name || !objects.unambiguous_member(object, &name)
867 })
868 }) {
869 continue;
870 }
871 if language == "rust" {
872 if let Some(declared) = rust_bindings
873 .as_ref()
874 .and_then(|index| index.declaration_at(node.start_byte()))
875 .and_then(|declaration| declaration.owner.as_ref())
876 {
877 owner = type_name(declared);
878 }
879 if let Some(name) = &trait_name {
880 let qualified =
881 crate::callgraph::rust_module_qualified_name(node, source, name, nav);
882 if facts
883 .types
884 .iter()
885 .any(|ty| ty.interface && ty.name == qualified)
886 {
887 trait_name = Some(qualified);
888 }
889 }
890 }
891 facts.methods.push(MethodHint {
894 owner,
895 trait_name,
896 name: symbol.name.clone(),
897 symbol: symbol.scoped_name.clone(),
898 has_body: field(node, &["body"]).is_some(),
899 shape: if typescript::supported(language) {
900 String::new()
901 } else {
902 method_shape(node, source, language)
903 },
904 private: text(node, source)
905 .split('{')
906 .next()
907 .unwrap_or_default()
908 .split_whitespace()
909 .any(|w| ["private", "protected", "pub(crate)"].contains(&w)),
910 });
911 }
912 if language == "cpp" {
913 for symbol in &parse.symbols {
917 if !matches!(symbol.kind.as_str(), "method" | "function") {
918 continue;
919 }
920 let Some((owner, _)) = symbol.scoped_name.rsplit_once("::") else {
921 continue;
922 };
923 facts.methods.push(MethodHint {
924 owner: owner.to_string(),
925 trait_name: None,
926 name: symbol.name.clone(),
927 symbol: symbol.scoped_name.clone(),
928 has_body: functions
929 .get(&(symbol.end_line, symbol.end_col))
930 .is_some_and(|node| field(*node, &["body"]).is_some()),
931 shape: String::new(),
932 private: false,
933 });
934 }
935 }
936 let mut method_names = facts
939 .methods
940 .iter()
941 .map(|m| (m.owner.clone(), m.name.clone(), m.trait_name.clone()))
942 .collect::<HashSet<_>>();
943 for node in &all {
944 if ![
945 "method_signature",
946 "function_signature_item",
947 "method_spec",
948 "method_declaration",
949 ]
950 .contains(&nav.kind(*node))
951 {
952 continue;
953 }
954 let Some((mut owner, trait_name)) = owner(*node, source, language, nav) else {
955 continue;
956 };
957 if language == "rust" {
958 if let Some(declared) = rust_bindings
959 .as_ref()
960 .and_then(|index| index.declaration_at(node.start_byte()))
961 .and_then(|declaration| declaration.owner.as_ref())
962 {
963 owner = type_name(declared);
964 }
965 }
966 let Some(name) = named(*node, source, nav) else {
967 continue;
968 };
969 if method_names.contains(&(owner.clone(), name.clone(), trait_name.clone())) {
970 continue;
971 }
972 if let Some(symbol) =
973 symbols_by_name_line.get(&(name.as_str(), node.start_position().row as u32))
974 {
975 let symbol = symbol.scoped_name.clone();
976 method_names.insert((owner.clone(), name.clone(), trait_name.clone()));
977 facts.methods.push(MethodHint {
978 owner,
979 trait_name,
980 name,
981 symbol,
982 has_body: field(*node, &["body"]).is_some(),
983 shape: if typescript::supported(language) {
984 String::new()
985 } else {
986 method_shape(*node, source, language)
987 },
988 private: text(*node, source)
989 .split('{')
990 .next()
991 .unwrap_or_default()
992 .split_whitespace()
993 .any(|w| ["private", "protected", "pub(crate)"].contains(&w)),
994 });
995 }
996 }
997 if language == "rust" {
998 let mut type_indices = HashMap::new();
999 for (index, ty) in facts.types.iter().enumerate() {
1000 type_indices.entry(ty.name.clone()).or_insert(index);
1001 }
1002 for implementation in all.iter().filter(|n| nav.kind(**n) == "impl_item") {
1005 if let (Some(ty), Some(trait_node)) = (
1006 field(*implementation, &["type"]),
1007 field(*implementation, &["trait"]),
1008 ) {
1009 let ty = crate::callgraph::rust_module_qualified_name(
1010 *implementation,
1011 source,
1012 &type_name(text(ty, source)),
1013 nav,
1014 );
1015 let mut trait_name = type_name(text(trait_node, source));
1016 let qualified = crate::callgraph::rust_module_qualified_name(
1017 *implementation,
1018 source,
1019 &trait_name,
1020 nav,
1021 );
1022 if type_indices.contains_key(&qualified) {
1023 trait_name = qualified;
1024 }
1025 if let Some(t) = type_indices.get(&ty).map(|&i| &mut facts.types[i]) {
1026 if !t.bases.contains(&trait_name) {
1027 t.bases.push(trait_name);
1028 }
1029 }
1030 }
1031 }
1032 }
1033 let call_kinds = crate::calls::call_node_kinds(lang);
1034 let calls = all
1035 .iter()
1036 .copied()
1037 .filter(|n| call_kinds.contains(&nav.kind(*n)))
1038 .collect::<Vec<_>>();
1039 let call_ranges = calls
1040 .iter()
1041 .map(|n| (n.start_byte(), n.end_byte()))
1042 .collect::<Vec<_>>();
1043 let references = parse
1044 .refs
1045 .iter()
1046 .enumerate()
1047 .filter(|(_, r)| r.kind == BlobRefKind::Call)
1048 .collect::<Vec<_>>();
1049 let queries = references
1050 .iter()
1051 .map(|(_, r)| (r.byte_start, r.byte_end))
1052 .collect::<Vec<_>>();
1053 let targets = super::extraction_index::range_minima(
1054 &call_ranges,
1055 &queries,
1056 super::extraction_index::LookupWork::Dispatch,
1057 );
1058 let mut namespace_imports = parse
1059 .imports
1060 .iter()
1061 .filter_map(|i| i.namespace_import.as_deref())
1062 .collect::<HashSet<_>>();
1063 if language == "python" {
1068 namespace_imports.extend(parse.imports.iter().filter_map(|i| {
1069 let namespace = i.namespace_import.as_deref()?;
1070 i.module_path
1071 .strip_prefix(namespace)?
1072 .starts_with('.')
1073 .then_some(i.module_path.as_str())
1074 }));
1075 }
1076 let local_rust_types = facts
1077 .types
1078 .iter()
1079 .map(|ty| ty.name.as_str())
1080 .collect::<HashSet<_>>();
1081 let templates = all
1084 .iter()
1085 .copied()
1086 .filter(|node| language == "rust" && nav.kind(*node) == "macro_definition")
1087 .collect::<Vec<_>>();
1088 let reference_keys = if templates.is_empty() {
1089 Vec::new()
1090 } else {
1091 parse.reference_keys()
1092 };
1093 let mut static_receivers = static_receiver::Index::new(&all, source, parse, &functions, nav);
1094 for ((position, reference), target) in references.into_iter().zip(targets) {
1095 let Some(call) = target.map(|i| calls[i]) else {
1096 if let Some(site) = template_self_site(
1097 reference,
1098 reference_keys.get(position).copied(),
1099 &templates,
1100 &parse.symbols,
1101 ) {
1102 facts.sites.push(site);
1103 }
1104 continue;
1105 };
1106 let Some(callee) = field(call, &["function", "name", "macro"]).or_else(|| {
1107 if language == "kotlin" {
1108 call.named_child(0)
1109 } else {
1110 None
1111 }
1112 }) else {
1113 continue;
1114 };
1115 let callee = if language == "rust" && callee.kind() == "generic_function" {
1116 field(callee, &["function"]).unwrap_or(callee)
1117 } else {
1118 callee
1119 };
1120 if language == "cpp" && callee.kind() == "field_expression" {
1121 if let Some(site) = cpp_typed_site(call, callee, reference, source, root, nav) {
1122 facts.sites.push(site);
1123 }
1124 continue;
1125 }
1126 let associated = language == "rust"
1127 && callee.kind() == "scoped_identifier"
1128 && field(callee, &["name"]).is_some_and(|name| text(name, source) == "new");
1129 if associated {
1130 let Some(path) = field(callee, &["path"]) else {
1131 continue;
1132 };
1133 let owner = type_name(text(path, source));
1134 if owner == "Self"
1135 || local_rust_types.contains(owner.as_str())
1136 || !owner
1137 .rsplit("::")
1138 .next()
1139 .is_some_and(|name| name.chars().next().is_some_and(char::is_uppercase))
1140 {
1141 continue;
1142 }
1143 }
1144 let dynamic = syntactic_dynamic(callee, source, language);
1145 if !dynamic
1150 && matches!(language, "javascript" | "typescript" | "tsx")
1151 && callee.kind() == "subscript_expression"
1152 {
1153 continue;
1154 }
1155 let receiver_node = field(
1156 callee,
1157 &["object", "value", "operand", "expression", "receiver"],
1158 )
1159 .or_else(|| {
1160 if callee.kind() == "navigation_expression" {
1161 callee.named_child(0)
1162 } else {
1163 None
1164 }
1165 });
1166 let receiver_node = receiver_node.or_else(|| field(call, &["object"]));
1168 let receiver_node =
1169 receiver_node.or_else(|| associated.then(|| field(callee, &["path"])).flatten());
1170 if !dynamic && receiver_node.is_none() {
1171 if language == "rust"
1175 && call.kind() == "macro_invocation"
1176 && reference
1177 .full_ref
1178 .as_deref()
1179 .is_some_and(|name| name.contains('.'))
1180 {
1181 facts.sites.push(SiteHint {
1182 ordinal: reference.ordinal,
1183 caller: reference.caller_symbol.clone(),
1184 line: reference.line,
1185 member: reference.short_name.clone(),
1186 receiver: None,
1187 dynamic: false,
1188 });
1189 }
1190 continue;
1191 }
1192 if receiver_node.is_some_and(|n| namespace_imports.contains(text(n, source)))
1193 && go_index
1194 .as_ref()
1195 .and_then(|index| index.receiver(call.start_byte(), call.end_byte()))
1196 .is_none()
1197 {
1198 continue;
1201 }
1202 let receiver = if let Some(index) = &go_index {
1203 index
1204 .receiver(call.start_byte(), call.end_byte())
1205 .map(str::to_string)
1206 } else {
1207 receiver_node.and_then(|receiver| {
1208 if let Some(objects) = &ts_objects {
1209 if !matches!(text(receiver, source), "this" | "super") {
1210 return objects.receiver(receiver, call);
1211 }
1212 }
1213 if associated {
1214 return Some(text(receiver, source).to_string());
1215 }
1216 receiver_type(
1217 receiver,
1218 call,
1219 source,
1220 language,
1221 &facts,
1222 receiver_index.as_ref(),
1223 &class_fields,
1224 nav,
1225 )
1226 })
1227 };
1228 if let Some(index) = &mut static_receivers {
1229 let written = (!dynamic && receiver.is_none())
1230 .then_some(receiver_node)
1231 .flatten();
1232 index.site(reference.ordinal, written, call, |identifier| {
1233 ts_objects.as_ref().map_or((None, None, false), |objects| {
1234 let scope = objects.binding_scope(identifier);
1235 (
1236 objects.binding(identifier),
1237 scope,
1238 objects.class_binding_written(identifier, scope),
1239 )
1240 })
1241 });
1242 }
1243 facts.sites.push(SiteHint {
1244 ordinal: reference.ordinal,
1245 caller: if language == "python" {
1246 reference.caller_symbol.clone()
1249 } else {
1250 nav.enclosing(call, FUNCTIONS)
1251 .and_then(|function| {
1252 callers
1253 .get(&(
1254 function.start_position().row as u32,
1255 function.start_position().column as u32,
1256 ))
1257 .cloned()
1258 })
1259 .or_else(|| reference.caller_symbol.clone())
1260 },
1261 line: reference.line,
1262 member: if dynamic {
1263 None
1264 } else {
1265 field(callee, &["property", "field", "name"])
1266 .or_else(|| {
1267 if language == "kotlin" {
1268 callee.named_children(&mut callee.walk()).last()
1269 } else {
1270 None
1271 }
1272 })
1273 .or_else(|| {
1274 if language == "java" {
1275 field(call, &["name"])
1276 } else {
1277 None
1278 }
1279 })
1280 .map(|n| text(n, source).trim_start_matches('.').to_string())
1281 .or_else(|| reference.short_name.clone())
1282 },
1283 receiver,
1284 dynamic,
1285 });
1286 }
1287 facts.static_facts = static_receivers.and_then(static_receiver::Index::finish);
1288 let mut site_ordinals = facts
1290 .sites
1291 .iter()
1292 .map(|s| s.ordinal)
1293 .collect::<HashSet<_>>();
1294 let callable_symbols = parse
1295 .symbols
1296 .iter()
1297 .filter(|s| ["method", "function"].contains(&s.kind.as_str()))
1298 .collect::<Vec<_>>();
1299 let symbol_lines = callable_symbols
1300 .iter()
1301 .map(|s| (s.start_line as usize, s.end_line as usize))
1302 .collect::<Vec<_>>();
1303 let call_lines = calls
1304 .iter()
1305 .map(|n| (n.start_position().row, n.end_position().row))
1306 .collect::<Vec<_>>();
1307 let dynamic_callers = super::extraction_index::range_minima(
1308 &symbol_lines,
1309 &call_lines,
1310 super::extraction_index::LookupWork::Dispatch,
1311 );
1312 for (call, caller) in calls.iter().zip(dynamic_callers) {
1313 let Some(callee) = field(*call, &["function", "name"]).or_else(|| {
1314 if language == "kotlin" {
1315 call.named_child(0)
1316 } else {
1317 None
1318 }
1319 }) else {
1320 continue;
1321 };
1322 if !syntactic_dynamic(callee, source, language) {
1323 continue;
1324 }
1325 let ordinal = spans
1326 .get(&(call.start_byte(), call.end_byte()))
1327 .copied()
1328 .unwrap_or_default();
1329 if !site_ordinals.insert(ordinal) {
1330 continue;
1331 }
1332 let caller = caller.map(|i| callable_symbols[i].scoped_name.clone());
1333 facts.sites.push(SiteHint {
1334 ordinal,
1335 caller,
1336 line: call.start_position().row as u32 + 1,
1337 member: None,
1338 receiver: None,
1339 dynamic: true,
1340 });
1341 }
1342 if language == "python" {
1343 facts
1346 .sites
1347 .sort_by(|a, b| (a.ordinal, &a.caller).cmp(&(b.ordinal, &b.caller)));
1348 facts
1349 .sites
1350 .dedup_by(|a, b| a.ordinal == b.ordinal && a.caller == b.caller);
1351 } else {
1352 facts.sites.sort_by_key(|s| s.ordinal);
1353 facts.sites.dedup_by_key(|s| s.ordinal);
1354 }
1355 facts.methods.sort_by(|a, b| a.symbol.cmp(&b.symbol));
1356 facts.methods.dedup();
1357 Ok(facts)
1358}
1359
1360type SpanOrdinals = rustc_hash::FxHashMap<(usize, usize), u32>;
1362
1363fn exact_ordinals(parse: &ParseBlob) -> SpanOrdinals {
1364 let mut spans = SpanOrdinals::default();
1365 for node in &parse.ast_nodes {
1366 spans
1367 .entry((node.byte_start, node.byte_end))
1368 .or_insert(node.ordinal);
1369 }
1370 spans
1371}
1372
1373fn symbol_callers(parse: &ParseBlob) -> HashMap<(u32, u32), String> {
1374 let mut callers = HashMap::new();
1375 for symbol in &parse.symbols {
1376 callers
1377 .entry((symbol.start_line, symbol.start_col))
1378 .or_insert_with(|| symbol.scoped_name.clone());
1379 }
1380 callers
1381}
1382fn cpp_typed_site<'tree>(
1391 call: Node<'tree>,
1392 callee: Node<'tree>,
1393 reference: &BlobRef,
1394 source: &str,
1395 root: Node<'tree>,
1396 nav: impl Nav<'tree>,
1397) -> Option<SiteHint> {
1398 if field(callee, &["operator"]).map(|operator| text(operator, source)) != Some(".") {
1399 return None;
1400 }
1401 let receiver = field(callee, &["argument"]).filter(|node| node.kind() == "identifier")?;
1402 let member = field(callee, &["field"]).filter(|node| node.kind() == "field_identifier")?;
1403 let scope = nav
1404 .enclosing(call, &["function_definition"])
1405 .unwrap_or(root);
1406 let receiver_type = super::super::infer_cpp_receiver_type_from_scope(
1407 scope,
1408 source,
1409 text(receiver, source),
1410 reference.line.max(1),
1411 )?;
1412 Some(SiteHint {
1413 ordinal: reference.ordinal,
1414 caller: reference.caller_symbol.clone(),
1415 line: reference.line,
1416 member: Some(text(member, source).to_string()),
1417 receiver: Some(receiver_type),
1418 dynamic: false,
1419 })
1420}
1421
1422pub const TEMPLATE_SELF_RECEIVER: &str = "@template-self:";
1430
1431fn template_self_site(
1438 reference: &BlobRef,
1439 key: Option<u32>,
1440 templates: &[Node<'_>],
1441 symbols: &[BlobSymbol],
1442) -> Option<SiteHint> {
1443 let caller = reference
1446 .caller_symbol
1447 .as_deref()
1448 .filter(|caller| !caller.ends_with('!'))?;
1449 let member = reference.full_ref.as_deref()?.strip_prefix("self.")?;
1450 if member.is_empty() || !member.chars().all(|ch| ch == '_' || ch.is_alphanumeric()) {
1451 return None;
1452 }
1453 let template = templates.iter().find(|template| {
1454 template.start_byte() <= reference.byte_start && reference.byte_end <= template.end_byte()
1455 })?;
1456 let (first, last) = (
1457 template.start_position().row as u32,
1458 template.end_position().row as u32,
1459 );
1460 let mut defined = symbols.iter().filter(|symbol| {
1461 symbol.name == member
1462 && matches!(symbol.kind.as_str(), "function" | "method")
1463 && symbol.scoped_name != caller
1464 && !symbol.scoped_name.ends_with('!')
1465 && first <= symbol.start_line
1466 && symbol.end_line <= last
1467 });
1468 let target = defined.next()?;
1469 if defined.next().is_some() {
1470 return None;
1471 }
1472 Some(SiteHint {
1473 ordinal: key?,
1474 caller: Some(caller.to_string()),
1475 line: reference.line,
1476 member: Some(member.to_string()),
1477 receiver: Some(format!("{TEMPLATE_SELF_RECEIVER}{}", target.scoped_name)),
1478 dynamic: false,
1479 })
1480}
1481
1482fn syntactic_dynamic(callee: Node<'_>, source: &str, language: &str) -> bool {
1483 match language {
1484 "javascript" | "typescript" | "tsx" => {
1485 callee.kind() == "subscript_expression"
1486 && crate::calls::extract_computed_member_name(&callee, source).is_none()
1487 }
1488 "python" => {
1489 callee.kind() == "call"
1490 && field(callee, &["function"]).is_some_and(|n| text(n, source) == "getattr")
1491 }
1492 _ => false,
1493 }
1494}
1495
1496test_support_visibility! {
1497struct RustReceiverIndex<'nodes, 'tree> {
1501 nodes: &'nodes [Node<'tree>],
1502 functions: HashMap<usize, (usize, usize)>,
1503 constructors: HashSet<String>,
1504 bindings: &'nodes RustBindings,
1505}
1506}
1507
1508impl<'nodes, 'tree> RustReceiverIndex<'nodes, 'tree> {
1509 test_support_visibility! {
1510 fn new(
1511 nodes: &'nodes [Node<'tree>],
1512 source: &str,
1513 bindings: &'nodes RustBindings,
1514 nav: impl Nav<'tree>,
1515 ) -> Self {
1516 #[cfg(any(test, feature = "test-support"))]
1517 super::extraction_work::note(|work| {
1518 work.receiver_index_passes += 1;
1519 work.receiver_index_nodes += nodes.len();
1520 });
1521 let mut index = Self {
1522 nodes,
1523 functions: HashMap::new(),
1524 constructors: HashSet::new(),
1525 bindings,
1526 };
1527 let mut ancestors = Vec::<(Node<'tree>, usize, usize)>::new();
1528 for (position, &node) in nodes.iter().enumerate() {
1529 while ancestors
1532 .last()
1533 .is_some_and(|(_, _, remaining)| *remaining == 0)
1534 {
1535 let (ancestor, start, _) = ancestors.pop().unwrap();
1536 if FUNCTIONS.contains(&nav.kind(ancestor)) {
1537 index.functions.insert(ancestor.id(), (start, position));
1538 }
1539 }
1540 if let Some((_, _, remaining)) = ancestors.last_mut() {
1541 *remaining -= 1;
1542 }
1543 ancestors.push((node, position, node.named_child_count()));
1544 if nav.kind(node) == "function_item"
1545 && named(node, source, nav).as_deref() == Some("new")
1546 {
1547 if let Some((owner, _)) = owner(node, source, "rust", nav) {
1548 if field(node, &["return_type"])
1549 .is_some_and(|ty| ["Self", owner.as_str()].contains(&text(ty, source)))
1550 {
1551 index.constructors.insert(owner);
1552 }
1553 }
1554 }
1555 }
1556 for (ancestor, start, _) in ancestors {
1557 if FUNCTIONS.contains(&nav.kind(ancestor)) {
1558 index.functions.insert(ancestor.id(), (start, nodes.len()));
1559 }
1560 }
1561 index
1562 }
1563 }
1564
1565 test_support_visibility! {
1566 fn function_nodes(&self, function: Node<'tree>) -> Option<&'nodes [Node<'tree>]> {
1567 let &(start, end) = self.functions.get(&function.id())?;
1568 self.nodes.get(start..end)
1569 }
1570
1571 }
1572}
1573
1574#[cfg(any(test, feature = "test-support"))]
1575thread_local! {
1576 static UNINDEXED_RECEIVERS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1577 pub static UNMEMOIZED_CLASS_FIELDS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1580}
1581
1582type ClassFieldMemo<'tree> = std::cell::RefCell<HashMap<usize, Vec<Node<'tree>>>>;
1590
1591fn class_field_declarations<'tree, N: Nav<'tree>>(class: Node<'tree>, nav: N) -> Vec<Node<'tree>> {
1595 #[cfg(any(test, feature = "test-support"))]
1596 super::extraction_work::note(|work| work.receiver_class_walks += 1);
1597 nav.reverse_named_preorder(class)
1598 .into_iter()
1599 .filter(|n| {
1600 [
1601 "field_declaration",
1602 "variable_declarator",
1603 "property_declaration",
1604 ]
1605 .contains(&nav.kind(*n))
1606 && nav.enclosing(*n, FUNCTIONS).is_none()
1607 })
1608 .collect()
1609}
1610
1611fn unindexed_constructor_present(
1612 function: Node<'_>,
1613 source: &str,
1614 language: &str,
1615 ty: &str,
1616) -> Option<bool> {
1617 let constructor_nodes = descendants(Direct.enclosing(function, &["source_file"])?);
1618 #[cfg(any(test, feature = "test-support"))]
1619 super::extraction_work::note(|work| {
1620 work.receiver_constructor_scans += 1;
1621 work.receiver_constructor_nodes += constructor_nodes.len();
1622 });
1623 Some(constructor_nodes.into_iter().any(|node| {
1624 node.kind() == "function_item"
1625 && named(node, source, Direct).as_deref() == Some("new")
1626 && owner(node, source, language, Direct).is_some_and(|(owner, _)| owner == ty)
1627 && field(node, &["return_type"])
1628 .is_some_and(|result| ["Self", ty].contains(&text(result, source)))
1629 }))
1630}
1631
1632#[allow(clippy::too_many_arguments)]
1633fn receiver_type<'tree, N: Nav<'tree>>(
1634 receiver: Node<'tree>,
1635 call: Node<'tree>,
1636 source: &str,
1637 language: &str,
1638 facts: &DispatchFacts,
1639 rust_index: Option<&RustReceiverIndex<'_, 'tree>>,
1640 class_fields: &ClassFieldMemo<'tree>,
1641 nav: N,
1642) -> Option<String> {
1643 #[cfg(any(test, feature = "test-support"))]
1644 super::extraction_work::note(|work| work.receiver_type_calls += 1);
1645 let value = text(receiver, source);
1646 let function = nav.enclosing(call, FUNCTIONS)?;
1647 #[cfg(any(test, feature = "test-support"))]
1648 let unindexed = (language == "rust" && rust_index.is_none()).then(|| {
1649 let mut root = call;
1650 while let Some(parent) = root.parent() {
1651 root = parent;
1652 }
1653 super::extraction_work::note(|work| {
1654 work.receiver_function_nodes += descendants(function).len()
1655 });
1656 RustBindings::new(source, root)
1657 });
1658 let rust_bindings = rust_index.map(|index| index.bindings);
1659 #[cfg(any(test, feature = "test-support"))]
1660 let rust_bindings = rust_bindings.or(unindexed.as_ref());
1661 let current_owner = rust_bindings
1662 .and_then(|index| {
1663 index
1664 .symbol_at(function.start_byte())
1665 .and_then(|symbol| index.declaration(symbol))
1666 })
1667 .and_then(|declaration| declaration.owner.as_ref())
1668 .map(|owner| type_name(owner))
1669 .or_else(|| owner(function, source, language, nav).map(|(o, _)| o));
1670 if language == "rust" {
1671 if receiver.kind() == "call_expression" {
1672 return field(receiver, &["function"]).map(|n| format!("@return:{}", text(n, source)));
1673 }
1674 if receiver.kind() == "field_expression" {
1675 let mut members = Vec::new();
1680 let mut base = receiver;
1681 while base.kind() == "field_expression" {
1682 members.push(field(base, &["field"]));
1683 base = field(base, &["value"])?;
1684 }
1685 let mut typed = receiver_type(
1686 base,
1687 call,
1688 source,
1689 language,
1690 facts,
1691 rust_index,
1692 class_fields,
1693 nav,
1694 )?;
1695 for member in members.into_iter().rev() {
1696 let member = text(member?, source);
1697 typed = format!("@field:{typed}|{member}");
1698 }
1699 return Some(typed);
1700 }
1701 }
1702 match language {
1703 "typescript" | "tsx" | "javascript" | "java" | "csharp" | "kotlin" if value == "this" => {
1704 if current_owner
1705 .as_ref()
1706 .is_some_and(|name| name.starts_with("@object:"))
1707 && function.kind() != "method_definition"
1708 {
1709 return None;
1710 }
1711 return current_owner;
1712 }
1713 "python" if value == "self" => return current_owner,
1714 "python" if value == "cls" => {
1715 let decorated = nav
1716 .parent(function)
1717 .filter(|p| nav.kind(*p) == "decorated_definition")?;
1718 if text(decorated, source).contains("@classmethod") {
1719 return current_owner;
1720 }
1721 return None;
1722 }
1723 "rust" if value == "self" => return current_owner,
1724 "typescript" | "tsx" | "javascript" | "java" | "csharp" | "kotlin" if value == "super" => {
1725 return facts
1726 .types
1727 .iter()
1728 .find(|t| Some(&t.name) == current_owner.as_ref())?
1729 .bases
1730 .first()
1731 .cloned()
1732 }
1733 "python" if value == "super()" => {
1734 return current_owner.map(|name| format!("@super:{name}"));
1737 }
1738 "go" => {
1739 if let Some(receiver) = field(function, &["receiver"]) {
1740 for parameter in descendants(receiver) {
1741 if parameter.kind() == "parameter_declaration"
1742 && field(parameter, &["name"]).is_some_and(|n| text(n, source) == value)
1743 {
1744 return field(parameter, &["type"]).map(|n| type_name(text(n, source)));
1745 }
1746 }
1747 }
1748 }
1749 _ => {}
1750 }
1751 if ![
1752 "typescript",
1753 "tsx",
1754 "javascript",
1755 "python",
1756 "rust",
1757 "go",
1758 "java",
1759 "csharp",
1760 "kotlin",
1761 ]
1762 .contains(&language)
1763 {
1764 return None;
1765 }
1766 if !["identifier", "simple_identifier", "self"].contains(&receiver.kind()) {
1767 return None;
1768 }
1769 if language == "rust" {
1770 let bindings = rust_bindings?;
1771 let binding = bindings.binding(value, call.start_byte())?;
1772 if let Some(annotation) = &binding.annotation {
1773 let annotation_name = type_name(annotation);
1774 if let Some(bound) = bindings.bound(&annotation_name, call.start_byte()) {
1775 return Some(type_name(bound.split('+').next().unwrap_or_default()));
1776 }
1777 if bindings.type_parameter(&annotation_name, call.start_byte())
1778 || annotation.contains('<') && bindings.generic_callable(call.start_byte())
1779 || annotation_name.contains("::")
1780 && !annotation_name
1781 .split("::")
1782 .next()
1783 .is_some_and(|name| name.chars().next().is_some_and(char::is_lowercase))
1784 {
1785 return None;
1786 }
1787 return Some(annotation_name);
1788 }
1789 return match binding.initializer.as_ref()? {
1790 Initializer::Nominal(name) => Some(type_name(name)),
1791 Initializer::Call { callee, .. } => {
1792 if let Some((ty, "new")) = callee.split_once("::") {
1793 if bindings.declaration(callee).is_some_and(|declaration| {
1794 declaration.return_type.as_deref() == Some("Self")
1795 && declaration.owner.as_deref() == Some(ty)
1796 }) {
1797 return Some(type_name(ty));
1798 }
1799 }
1800 let expression = if let Some(member) = callee
1801 .strip_prefix("self.")
1802 .or_else(|| callee.strip_prefix("Self::"))
1803 {
1804 format!("{}::{member}", current_owner?)
1805 } else {
1806 callee.clone()
1807 };
1808 Some(format!("@return:{expression}"))
1809 }
1810 };
1811 }
1812 let indexed_nodes = rust_index.and_then(|index| index.function_nodes(function));
1815 let mut nodes: Cow<'_, [Node<'tree>]> = match indexed_nodes {
1816 Some(nodes) => Cow::Borrowed(nodes),
1817 None => Cow::Owned(nav.reverse_named_preorder(function)),
1818 };
1819 if ["java", "csharp", "kotlin"].contains(&language) {
1820 if let Some(class) = nav.enclosing(function, TYPES) {
1821 #[cfg(any(test, feature = "test-support"))]
1822 if UNMEMOIZED_CLASS_FIELDS.with(std::cell::Cell::get) {
1823 class_fields.borrow_mut().remove(&class.id());
1824 }
1825 let mut memo = class_fields.borrow_mut();
1826 let fields = memo
1827 .entry(class.id())
1828 .or_insert_with(|| class_field_declarations(class, nav));
1829 nodes.to_mut().extend(fields.iter().copied());
1830 }
1831 }
1832 #[cfg(any(test, feature = "test-support"))]
1833 if indexed_nodes.is_none() {
1834 super::extraction_work::note(|work| work.receiver_function_nodes += nodes.len());
1835 }
1836 for declaration in nodes.iter() {
1837 if ![
1838 "required_parameter",
1839 "optional_parameter",
1840 "typed_parameter",
1841 "typed_default_parameter",
1842 "parameter",
1843 "parameter_declaration",
1844 "formal_parameter",
1845 "variable_declarator",
1846 "variable_declaration",
1847 "let_declaration",
1848 "var_spec",
1849 "short_var_declaration",
1850 "assignment",
1851 "local_variable_declaration",
1852 "property_declaration",
1853 ]
1854 .contains(&nav.kind(*declaration))
1855 {
1856 continue;
1857 }
1858 let binding = field(*declaration, &["name", "pattern", "left"]).or_else(|| {
1859 if language == "kotlin" {
1860 return declaration
1861 .named_children(&mut declaration.walk())
1862 .find(|n| n.kind() == "simple_identifier");
1863 }
1864 if language == "python" && declaration.kind() == "typed_parameter" {
1865 declaration.named_child(0)
1866 } else {
1867 None
1868 }
1869 });
1870 let Some(binding) = binding else {
1871 continue;
1872 };
1873 let binding_text = text(binding, source).trim();
1874 if binding_text != value && !binding_text.strip_suffix(':').is_some_and(|s| s == value) {
1875 continue;
1876 }
1877 if language == "python" && nav.enclosing(*declaration, FUNCTIONS) != Some(function) {
1878 continue;
1879 }
1880 if let Some(annotation) = field(*declaration, &["type"])
1881 .or_else(|| {
1882 nav.parent(*declaration)
1883 .filter(|p| {
1884 [
1885 "variable_declaration",
1886 "local_variable_declaration",
1887 "field_declaration",
1888 ]
1889 .contains(&nav.kind(*p))
1890 })
1891 .and_then(|p| field(p, &["type"]))
1892 })
1893 .or_else(|| {
1894 if language == "kotlin" {
1895 declaration
1896 .named_children(&mut declaration.walk())
1897 .find(|n| n.kind() == "user_type")
1898 } else {
1899 None
1900 }
1901 })
1902 {
1903 if language != "javascript"
1904 && !["var", "val"].contains(&text(annotation, source).trim())
1905 {
1906 let raw_annotation = text(annotation, source);
1907 let annotation = type_name(raw_annotation);
1908 if let Some(parameter) = nodes.iter().find(|n| {
1909 ["type_parameter", "type_parameter_declaration"].contains(&nav.kind(**n))
1910 && named(**n, source, nav).as_deref() == Some(&annotation)
1911 }) {
1912 if language == "rust" {
1913 return field(*parameter, &["bounds"]).map(|bounds| {
1917 type_name(text(bounds, source).split('+').next().unwrap_or_default())
1918 });
1919 }
1920 return None;
1921 }
1922 if language == "rust" {
1923 if raw_annotation.contains('<')
1927 && nodes.iter().any(|n| nav.kind(*n) == "type_parameter")
1928 || annotation.contains("::")
1929 && !annotation
1930 .split("::")
1931 .next()
1932 .is_some_and(|s| s.chars().next().is_some_and(char::is_lowercase))
1933 {
1934 return None;
1935 }
1936 }
1937 return Some(annotation);
1938 }
1939 }
1940 if language == "typescript" || language == "tsx" {
1942 if let Some(annotation) = declaration
1943 .named_children(&mut declaration.walk())
1944 .find(|n| n.kind() == "type_annotation")
1945 {
1946 let annotation = type_name(text(annotation, source));
1947 if nodes.iter().any(|n| {
1948 nav.kind(*n) == "type_parameter"
1949 && named(*n, source, nav).as_deref() == Some(&annotation)
1950 }) {
1951 return None;
1952 }
1953 return Some(annotation);
1954 }
1955 }
1956 if declaration.start_byte() > call.start_byte() {
1957 continue;
1958 }
1959 let assignments = nodes
1960 .iter()
1961 .filter(|n| {
1962 [
1963 "assignment_expression",
1964 "augmented_assignment_expression",
1965 "assignment",
1966 "augmented_assignment",
1967 "assignment_statement",
1968 "short_var_declaration",
1969 "update_expression",
1970 ]
1971 .contains(&nav.kind(**n))
1972 && field(**n, &["left", "argument"])
1973 .is_some_and(|lhs| text(lhs, source).trim() == value)
1974 && (language != "python" || nav.enclosing(**n, FUNCTIONS) == Some(function))
1975 })
1976 .count();
1977 if (language == "python" || language == "go") && assignments > 1
1978 || !["python", "go"].contains(&language) && assignments > 0
1979 {
1980 return None;
1981 }
1982 let initializer = field(*declaration, &["value", "right"]).or_else(|| {
1983 if language == "csharp" {
1984 descendants(*declaration)
1985 .into_iter()
1986 .find(|n| n.kind() == "object_creation_expression")
1987 } else {
1988 None
1989 }
1990 })?;
1991 let initializer = if initializer.kind() == "expression_list" {
1992 initializer.named_child(0)?
1993 } else {
1994 initializer
1995 };
1996 match language {
1997 "typescript" | "tsx" | "javascript" | "java" | "csharp" | "kotlin"
1998 if initializer.kind() == "new_expression"
1999 || initializer.kind() == "object_creation_expression" =>
2000 {
2001 return field(initializer, &["constructor", "type"])
2002 .map(|n| type_name(text(n, source)))
2003 }
2004 "python" if initializer.kind() == "call" => {
2005 let constructor = field(initializer, &["function"])?;
2006 let candidate = text(constructor, source);
2007 if facts.types.iter().any(|t| t.name == candidate) {
2008 return Some(candidate.to_string());
2009 }
2010 }
2011 "go" => {
2012 if let Some(literal) = descendants(initializer)
2013 .into_iter()
2014 .find(|n| n.kind() == "composite_literal")
2015 {
2016 return field(literal, &["type"]).map(|n| type_name(text(n, source)));
2017 }
2018 }
2019 "rust" => {
2020 if initializer.kind() == "identifier"
2021 && text(initializer, source)
2022 .chars()
2023 .next()
2024 .is_some_and(char::is_uppercase)
2025 {
2026 return Some(text(initializer, source).to_string());
2027 }
2028 if initializer.kind() == "struct_expression" {
2029 return field(initializer, &["name"]).map(|n| type_name(text(n, source)));
2030 }
2031 if initializer.kind() == "call_expression" {
2032 let name = text(field(initializer, &["function"])?, source);
2033 let Some((ty, method)) = name.split_once("::") else {
2034 return Some(format!("@return:{name}"));
2035 };
2036 if method != "new" {
2037 return Some(format!("@return:{name}"));
2038 }
2039 let valid = match (rust_index, indexed_nodes) {
2040 (Some(index), Some(_)) => index.constructors.contains(ty),
2041 _ => unindexed_constructor_present(function, source, language, ty)?,
2042 };
2043 if valid {
2044 return Some(ty.to_string());
2045 }
2046 }
2047 }
2048 _ => {}
2049 }
2050 }
2051 None
2052}
2053
2054#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
2055pub struct Target {
2056 pub file: String,
2057 pub symbol: String,
2058 pub provenance: &'static str,
2059}
2060#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
2061pub struct Resolution {
2062 pub targets: BTreeSet<Target>,
2063 pub protected: BTreeSet<(String, String)>,
2064 pub unresolved: usize,
2065 pub external: usize,
2066 pub dynamic: usize,
2067}
2068
2069macro_rules! census_exit {
2072 ($resolver:expr, $exit:literal, $answer:expr) => {{
2073 let answer = $answer;
2074 #[cfg(feature = "callgraph-shape-census")]
2075 $resolver.census_exit.set($exit);
2076 answer
2077 }};
2078}
2079
2080type NamedMethods<'a> = std::sync::Arc<Vec<(String, view::MethodGroup<'a>, &'a MethodHint)>>;
2082
2083#[derive(Clone)]
2088pub struct SharedMethods<'a> {
2089 member: String,
2090 methods: NamedMethods<'a>,
2091}
2092
2093impl SharedMethods<'_> {
2094 pub fn len(&self) -> usize {
2096 self.methods.len()
2097 }
2098}
2099
2100pub trait DispatchFiles<'a> {
2104 fn file(&'a self, path: &str) -> Option<&'a ParseBlob>;
2106 fn files_with_method(&self, name: &str) -> Vec<String>;
2109 fn files_with_static_type(&self, key: &str) -> Vec<String>;
2111 fn files_in(&self, directory: &str) -> Vec<String>;
2114 fn go_files_requiring(&self, name: &str) -> Vec<String>;
2117 fn import_target(&self, file: &str, module: &str) -> Option<String>;
2119 fn type_target(&self, file: &str, name: &str) -> Option<(String, String)>;
2121 fn associated_site(&self, file: &str, ordinal: u32) -> bool;
2123 fn projections(&'a self) -> Option<&'a (dyn projected::Projections + 'a)> {
2128 None
2129 }
2130}
2131
2132pub struct Resolver<'a> {
2136 pub files: BTreeMap<String, &'a ParseBlob>,
2137 pub import_targets: BTreeMap<(String, String), String>,
2138 pub type_targets: BTreeMap<(String, String), (String, String)>,
2139 associated_sites: HashSet<(String, u32)>,
2140 source: Option<&'a (dyn DispatchFiles<'a> + 'a)>,
2143 csharp_projects: Option<&'a CSharpProjects>,
2144 methods_by_name: std::cell::OnceCell<HashMap<&'a str, NamedMethods<'a>>>,
2148 methods_loaded: std::cell::RefCell<HashMap<String, NamedMethods<'a>>>,
2151 dependencies: std::cell::RefCell<BTreeSet<String>>,
2154 #[cfg(feature = "callgraph-shape-census")]
2155 pub census_exit: std::cell::Cell<&'static str>,
2156 #[cfg(any(test, feature = "test-support"))]
2157 pub file_visits: std::cell::Cell<usize>,
2158}
2159
2160pub mod dependency {
2174 pub fn file(path: &str) -> String {
2175 format!("r:{path}")
2176 }
2177 pub fn method(name: &str) -> String {
2178 format!("m:{name}")
2179 }
2180 pub fn type_name(path: &str, name: &str) -> String {
2181 format!("t:{path}\t{name}")
2182 }
2183 pub fn field(path: &str, owner: &str, name: &str) -> String {
2184 format!("f:{path}\t{owner}\t{name}")
2185 }
2186 pub fn return_hint(path: &str, symbol: &str) -> String {
2187 format!("ret:{path}\t{symbol}")
2188 }
2189 pub fn directory_type(file: &str, name: &str) -> String {
2190 format!("{}\t{name}", directory(file))
2191 }
2192 pub fn directory(file: &str) -> String {
2193 format!(
2194 "d:{}",
2195 std::path::Path::new(file)
2196 .parent()
2197 .map(|parent| parent.to_string_lossy())
2198 .unwrap_or_default()
2199 )
2200 }
2201 pub const GO_INTERFACES: &str = "g:";
2202}
2203impl<'a> Resolver<'a> {
2204 pub fn new(files: BTreeMap<String, &'a ParseBlob>) -> Self {
2205 let associated_sites = files
2206 .iter()
2207 .filter(|(_, parse)| parse.language == "rust")
2208 .flat_map(|(file, parse)| {
2209 parse
2210 .refs
2211 .iter()
2212 .filter(|reference| {
2213 reference
2214 .full_ref
2215 .as_deref()
2216 .is_some_and(associated_reference)
2217 })
2218 .map(move |reference| (file.clone(), reference.ordinal))
2219 })
2220 .collect();
2221 Self {
2222 files,
2223 import_targets: BTreeMap::new(),
2224 type_targets: BTreeMap::new(),
2225 associated_sites,
2226 source: None,
2227 csharp_projects: None,
2228 methods_by_name: std::cell::OnceCell::new(),
2229 methods_loaded: Default::default(),
2230 dependencies: Default::default(),
2231 #[cfg(feature = "callgraph-shape-census")]
2232 census_exit: Default::default(),
2233 #[cfg(any(test, feature = "test-support"))]
2234 file_visits: std::cell::Cell::new(0),
2235 }
2236 }
2237 pub fn note_associated_site(&mut self, file: &str, ordinal: u32) {
2238 self.associated_sites.insert((file.to_string(), ordinal));
2239 }
2240 pub fn with_parts(
2244 files: BTreeMap<String, &'a ParseBlob>,
2245 import_targets: BTreeMap<(String, String), String>,
2246 type_targets: BTreeMap<(String, String), (String, String)>,
2247 associated_sites: HashSet<(String, u32)>,
2248 ) -> Self {
2249 Self {
2250 files,
2251 import_targets,
2252 type_targets,
2253 associated_sites,
2254 source: None,
2255 csharp_projects: None,
2256 methods_by_name: std::cell::OnceCell::new(),
2257 methods_loaded: Default::default(),
2258 dependencies: Default::default(),
2259 #[cfg(feature = "callgraph-shape-census")]
2260 census_exit: Default::default(),
2261 #[cfg(any(test, feature = "test-support"))]
2262 file_visits: std::cell::Cell::new(0),
2263 }
2264 }
2265 pub fn over(source: &'a (dyn DispatchFiles<'a> + 'a)) -> Self {
2267 let mut resolver = Self::with_parts(
2268 BTreeMap::new(),
2269 BTreeMap::new(),
2270 BTreeMap::new(),
2271 HashSet::new(),
2272 );
2273 resolver.source = Some(source);
2274 resolver
2275 }
2276
2277 pub fn with_csharp_projects(mut self, projects: &'a CSharpProjects) -> Self {
2278 self.csharp_projects = Some(projects);
2279 self
2280 }
2281 pub fn into_parts(
2284 self,
2285 ) -> (
2286 BTreeMap<(String, String), String>,
2287 BTreeMap<(String, String), (String, String)>,
2288 HashSet<(String, u32)>,
2289 ) {
2290 (
2291 self.import_targets,
2292 self.type_targets,
2293 self.associated_sites,
2294 )
2295 }
2296 fn associated_site(&self, file: &str, ordinal: u32) -> bool {
2297 match self.source {
2298 Some(source) => source.associated_site(file, ordinal),
2299 None => self.associated_sites.contains(&(file.to_string(), ordinal)),
2300 }
2301 }
2302 fn lookup(&self, path: &str) -> Option<&'a ParseBlob> {
2304 match self.source {
2305 Some(source) => source.file(path),
2306 None => self.files.get(path).copied(),
2307 }
2308 }
2309 fn directory_files<'r>(
2311 &'r self,
2312 file: &str,
2313 name: &'r str,
2314 ) -> Vec<(String, view::Directory<'r, 'a>)> {
2315 self.depend(dependency::directory_type(file, name));
2316 let directory = std::path::Path::new(file).parent();
2317 match self.source {
2318 Some(source) => {
2319 let directory_name = directory
2320 .map(|parent| parent.to_string_lossy().into_owned())
2321 .unwrap_or_default();
2322 source
2323 .files_in(&directory_name)
2324 .into_iter()
2325 .filter_map(|path| {
2326 source
2327 .file(&path)
2328 .map(|parse| (path, view::Directory::new(parse, name)))
2329 })
2330 .collect()
2331 }
2332 None => self
2333 .files
2334 .iter()
2335 .filter(|(f, _)| std::path::Path::new(f).parent() == directory)
2336 .map(|(f, p)| (f.clone(), view::Directory::new(p, name)))
2337 .collect(),
2338 }
2339 }
2340 test_support_visibility! {
2341 fn go_interface_requires(&self, name: &str, shape: &str) -> bool {
2344 self.depend(dependency::GO_INTERFACES.to_string());
2345 let requires = |p: &ParseBlob| view::go_interface_requires(self, p, name, shape);
2346 match self.source {
2347 Some(source) => source
2348 .go_files_requiring(name)
2349 .iter()
2350 .filter_map(|path| source.file(path))
2351 .any(requires),
2352 None => self.files.values().any(|p| requires(p)),
2353 }
2354 }
2355 }
2356 fn import_target(&self, file: &str, module: &str) -> Option<String> {
2357 match self.source {
2358 Some(source) => source.import_target(file, module),
2359 None => self
2360 .import_targets
2361 .get(&(file.to_string(), module.to_string()))
2362 .cloned(),
2363 }
2364 }
2365 pub fn take_dependencies(&self) -> BTreeSet<String> {
2367 std::mem::take(&mut *self.dependencies.borrow_mut())
2368 }
2369 fn depend(&self, key: String) {
2370 self.dependencies.borrow_mut().insert(key);
2371 }
2372 fn file<'r>(&'r self, path: &'r str) -> Option<view::File<'r, 'a>> {
2373 self.depend(dependency::file(path));
2374 self.lookup(path)
2375 .map(|parse| view::File::new(self, path, parse))
2376 }
2377 fn known_file<'r>(&'r self, path: &'r str) -> view::File<'r, 'a> {
2380 self.file(path).expect("resolved file has facts")
2381 }
2382 fn type_target(&self, file: &str, name: &str) -> Option<(String, String)> {
2383 self.depend(dependency::file(file));
2384 self.depend(dependency::type_name(file, name));
2385 match self.source {
2386 Some(source) => source.type_target(file, name),
2387 None => self
2388 .type_targets
2389 .get(&(file.to_string(), name.to_string()))
2390 .cloned(),
2391 }
2392 }
2393 fn load_methods(
2396 &self,
2397 source: &'a (dyn DispatchFiles<'a> + 'a),
2398 member: &str,
2399 ) -> NamedMethods<'a> {
2400 let mut methods = Vec::new();
2401 for file in source.files_with_method(member) {
2402 self.note_file_visit();
2403 let Some(parse) = source.file(&file) else {
2404 continue;
2405 };
2406 for (group, method) in view::methods(parse).filter(|(_, m)| m.name == member) {
2407 methods.push((file.clone(), group, method));
2408 }
2409 }
2410 std::sync::Arc::new(methods)
2411 }
2412 pub fn share_methods(&self, member: &str) -> Option<SharedMethods<'a>> {
2418 let source = self.source?;
2419 Some(SharedMethods {
2420 member: member.to_string(),
2421 methods: self.load_methods(source, member),
2422 })
2423 }
2424 pub fn use_shared_methods(&self, shared: &SharedMethods<'a>) {
2428 self.methods_loaded.borrow_mut().insert(
2429 shared.member.clone(),
2430 std::sync::Arc::clone(&shared.methods),
2431 );
2432 }
2433 test_support_visibility! {
2434 fn methods_named(&self, member: &str) -> NamedMethods<'a> {
2435 self.depend(dependency::method(member));
2436 if let Some(source) = self.source {
2437 if let Some(found) = self.methods_loaded.borrow().get(member) {
2438 return std::sync::Arc::clone(found);
2439 }
2440 let methods = self.load_methods(source, member);
2441 self.methods_loaded
2442 .borrow_mut()
2443 .insert(member.to_string(), std::sync::Arc::clone(&methods));
2444 return methods;
2445 }
2446 let index = self.methods_by_name.get_or_init(|| {
2447 let mut index: HashMap<&'a str, Vec<(String, view::MethodGroup<'a>, &'a MethodHint)>> =
2448 HashMap::new();
2449 for (file, parse) in &self.files {
2450 self.note_file_visit();
2451 let parse: &'a ParseBlob = parse;
2452 for (group, method) in view::methods(parse) {
2453 index.entry(method.name.as_str()).or_default().push((
2454 file.clone(),
2455 group,
2456 method,
2457 ));
2458 }
2459 }
2460 index
2461 .into_iter()
2462 .map(|(name, methods)| (name, std::sync::Arc::new(methods)))
2463 .collect()
2464 });
2465 index.get(member).cloned().unwrap_or_default()
2466 }
2467 }
2468 test_support_visibility! {
2469 fn project_type(&self, file: &str, name: &str) -> Option<(String, &TypeHint)> {
2470 if let Some(projections) = self.projections() {
2471 return self.replay_projection(projections, file, name);
2472 }
2473 self.project_type_at_depth(file, name, 0)
2474 }
2475 }
2476 fn note_file_visit(&self) {
2477 #[cfg(any(test, feature = "test-support"))]
2478 self.file_visits.set(self.file_visits.get() + 1);
2479 }
2480 fn project_type_at_depth(
2481 &self,
2482 file: &str,
2483 name: &str,
2484 depth: usize,
2485 ) -> Option<(String, &TypeHint)> {
2486 if depth > 16 {
2487 return None;
2488 }
2489 if let Some(expression) = name.strip_prefix("@method:") {
2490 let (receiver, member) = expression.rsplit_once('|')?;
2491 return self.project_field_type(file, receiver, depth, Some(member));
2492 }
2493 if name.starts_with("@field:") {
2494 return self.project_field_type(file, name, depth, None);
2495 }
2496 if let Some(expression) = name.strip_prefix("@return:") {
2497 let local;
2498 let target;
2499 let (target_file, symbol) = if let Some(found) = self.type_target(file, expression) {
2500 target = found;
2501 (&target.0, &target.1)
2502 } else {
2503 self.file(file)?.return_hint(expression)?;
2504 local = (file.to_string(), expression.to_string());
2505 (&local.0, &local.1)
2506 };
2507 let returned = self.file(target_file)?.return_hint(symbol)?;
2508 return self.project_type_at_depth(target_file, &returned.ty, depth + 1);
2509 }
2510 let parse = self.file(file)?;
2511 if parse.language() == "go" && parse.go_package().is_none() {
2512 return None;
2513 }
2514 if let Some(t) = parse.type_named(name) {
2515 return Some((file.to_string(), t));
2516 }
2517 if let Some((target_file, symbol)) = self.type_target(file, name) {
2518 let (target_file, symbol) = (&target_file, &symbol);
2519 if let Some(ty) = self.file(target_file)?.type_named(symbol) {
2520 return Some((target_file.clone(), ty));
2521 }
2522 }
2523 if ["go", "java", "csharp"].contains(&parse.language()) {
2524 self.depend(dependency::directory(file));
2525 let in_directory = self.directory_files(file, name);
2526 let mut candidates = in_directory
2527 .iter()
2528 .filter(|(f, p)| {
2529 self.note_file_visit();
2530 p.language() == parse.language()
2531 && (parse.language() != "go"
2532 || (p.go_package() == parse.go_package()
2533 && (file.ends_with("_test.go") || !f.ends_with("_test.go"))))
2534 })
2535 .flat_map(|(f, p)| p.types_named().map(move |t| (f.clone(), t)));
2536 if let Some(candidate) = candidates.next() {
2537 if candidates.next().is_none() {
2538 return Some(candidate);
2539 }
2540 }
2541 }
2542 for import in parse.imports_naming(name) {
2545 let imported_name = import.imported.unwrap_or(name);
2546 if let Some(target) = parse.import_target(name, import.module) {
2549 if let Some(candidate) = self.file(&target) {
2550 let wanted = if import.default {
2551 candidate.default_export().unwrap_or(imported_name)
2552 } else {
2553 imported_name
2554 };
2555 if let Some(t) = candidate.type_named(wanted) {
2556 return Some((target.clone(), t));
2557 }
2558 }
2559 }
2560 if !import.module.starts_with('.') {
2561 return None;
2562 }
2563 let parent = std::path::Path::new(file).parent()?;
2564 let mut parts = Vec::new();
2565 let joined = parent.join(import.module);
2566 for c in joined.components() {
2567 match c {
2568 std::path::Component::ParentDir => {
2569 parts.pop();
2570 }
2571 std::path::Component::Normal(p) => parts.push(p.to_string_lossy().to_string()),
2572 _ => {}
2573 }
2574 }
2575 let base = parts.join("/");
2576 let mut candidates = std::iter::once(base.clone())
2579 .chain(
2580 ["ts", "tsx", "js", "py", "rs", "go"]
2581 .iter()
2582 .map(|ext| format!("{base}.{ext}")),
2583 )
2584 .collect::<Vec<_>>();
2585 candidates.sort();
2586 for path in candidates {
2587 let Some(candidate) = self.file(&path) else {
2588 continue;
2589 };
2590 let path = &path;
2591 self.note_file_visit();
2592 if candidate.language() != parse.language() {
2593 continue;
2594 }
2595 if parse.language() == "go" && candidate.go_package().is_none() {
2596 continue;
2597 }
2598 if let Some(t) = candidate.type_named(imported_name) {
2599 return Some((path.clone(), t));
2600 }
2601 }
2602 return None;
2603 }
2604 None
2605 }
2606 fn project_field_type(
2607 &self,
2608 file: &str,
2609 receiver: &str,
2610 depth: usize,
2611 member: Option<&str>,
2612 ) -> Option<(String, &TypeHint)> {
2613 let expression = receiver.strip_prefix("@field:")?;
2614 let (base, field_name) = expression.rsplit_once('|')?;
2615 let (base_file, ty) = self.project_type_at_depth(file, base, depth + 1)?;
2616 let field = self.known_file(&base_file).field(&ty.name, field_name)?;
2617 self.project_smart_field(&base_file, &field.ty, depth + 1, member)
2618 }
2619
2620 fn project_smart_field(
2621 &self,
2622 file: &str,
2623 name: &str,
2624 depth: usize,
2625 member: Option<&str>,
2626 ) -> Option<(String, &TypeHint)> {
2627 if depth > 16 {
2628 return None;
2629 }
2630 let Some((wrapper, outer, inner)) = smart_pointer::parts(name) else {
2631 return self.project_type_at_depth(file, name, depth);
2632 };
2633 if let Some(found) = self.project_type_at_depth(file, outer, depth) {
2635 return Some(found);
2636 }
2637 if member.is_some_and(|member| smart_pointer::owns_method(wrapper, member)) {
2638 return None;
2639 }
2640 self.project_smart_field(file, inner, depth + 1, member)
2641 }
2642 fn methods(&self, file: &str, owner: &str, name: &str, associated: bool) -> Vec<Target> {
2643 let language = self.known_file(file).language();
2644 self.methods_named(name)
2645 .iter()
2646 .filter(|(method_file, p, m)| {
2647 p.language() == language
2648 && (language != "rust"
2649 || associated
2650 || rust_receiver_shape(&m.shape) != Some(false))
2651 && self
2652 .project_type(method_file, &m.owner)
2653 .is_some_and(|(f, t)| f == file && t.name == owner)
2654 })
2655 .map(|(method_file, _, m)| Target {
2656 file: method_file.clone(),
2657 symbol: m.symbol.clone(),
2658 provenance: "exact",
2659 })
2660 .collect()
2661 }
2662 fn nearest(
2663 &self,
2664 file: &str,
2665 ty: &TypeHint,
2666 name: &str,
2667 seen: &mut BTreeSet<(String, String)>,
2668 associated: bool,
2669 ) -> Vec<Target> {
2670 if !seen.insert((file.to_string(), ty.name.clone())) {
2671 return Vec::new();
2672 }
2673 let direct = self.methods(file, &ty.name, name, associated);
2674 if !direct.is_empty() {
2675 return direct;
2676 }
2677 let mut frontier = ty
2678 .bases
2679 .iter()
2680 .filter_map(|base| self.project_type(file, base))
2681 .collect::<Vec<_>>();
2682 while !frontier.is_empty() {
2683 let mut hits = Vec::new();
2684 let mut next = Vec::new();
2685 for (file, ty) in frontier {
2686 if !seen.insert((file.clone(), ty.name.clone())) {
2687 continue;
2688 }
2689 hits.extend(self.methods(&file, &ty.name, name, associated));
2690 next.extend(
2691 ty.bases
2692 .iter()
2693 .filter_map(|base| self.project_type(&file, base)),
2694 );
2695 }
2696 if !hits.is_empty() {
2697 return hits;
2698 }
2699 frontier = next;
2700 }
2701 Vec::new()
2702 }
2703 fn subtype(
2704 &self,
2705 file: &str,
2706 ty: &TypeHint,
2707 base_file: &str,
2708 base: &str,
2709 seen: &mut BTreeSet<(String, String)>,
2710 ) -> bool {
2711 if !seen.insert((file.to_string(), ty.name.clone())) {
2712 return false;
2713 }
2714 ty.bases
2715 .iter()
2716 .filter_map(|b| self.project_type(file, b))
2717 .any(|(f, t)| {
2718 (f == base_file && t.name == base) || self.subtype(&f, t, base_file, base, seen)
2719 })
2720 }
2721 test_support_visibility! {
2722 fn python_base_type(&self, file: &str, name: &str) -> Option<(String, &TypeHint)> {
2723 let mut file = file.to_string();
2724 let mut name = name.to_string();
2725 let mut visited = BTreeSet::new();
2726 loop {
2727 if !visited.insert((file.clone(), name.clone())) {
2728 return None;
2729 }
2730 let parse = self.file(&file)?;
2731 if parse.language() != "python" {
2732 return None;
2733 }
2734 if let Some(ty) = parse.type_named(&name) {
2735 return Some((file, ty));
2736 }
2737 let imports = parse.python_imports_naming(&name);
2738 let mut targets = BTreeSet::new();
2739 for (module, names) in imports {
2740 for specifier in names {
2741 if crate::imports::specifier_local_name(&specifier) != name {
2742 continue;
2743 }
2744 for candidate in crate::callgraph_store::python_module_candidates(
2745 std::path::Path::new(""),
2746 std::path::Path::new(&file),
2747 &module,
2748 ) {
2749 let path = candidate.to_string_lossy().replace('\\', "/");
2750 if self.file(&path).is_some() {
2753 targets.insert((
2754 path,
2755 crate::imports::specifier_imported_name(&specifier).to_string(),
2756 ));
2757 break;
2758 }
2759 }
2760 }
2761 }
2762 if targets.len() != 1 {
2763 return None;
2764 }
2765 (file, name) = targets.into_iter().next()?;
2766 }
2767 }
2768 }
2769
2770 fn python_mro(
2771 &self,
2772 file: &str,
2773 ty: &TypeHint,
2774 active: &mut BTreeSet<(String, String)>,
2775 memo: &mut BTreeMap<(String, String), Vec<(String, String)>>,
2776 ) -> Option<Vec<(String, String)>> {
2777 let key = (file.to_string(), ty.name.clone());
2778 if let Some(mro) = memo.get(&key) {
2779 return Some(mro.clone());
2780 }
2781 if !active.insert(key.clone()) {
2782 return None;
2783 }
2784 let mut sequences = Vec::new();
2785 let mut bases = Vec::new();
2786 for base in &ty.bases {
2787 if let Some((base_file, base_ty)) = self.python_base_type(file, base) {
2788 bases.push((base_file.clone(), base_ty.name.clone()));
2789 sequences.push(self.python_mro(&base_file, base_ty, active, memo)?);
2790 } else {
2791 let key = if base == "object" {
2794 (String::new(), "object".to_string())
2795 } else {
2796 (file.to_string(), format!("@unknown:{base}"))
2797 };
2798 bases.push(key.clone());
2799 sequences.push(vec![key]);
2800 }
2801 }
2802 if bases.is_empty() {
2803 bases.push((String::new(), "object".to_string()));
2804 sequences.push(bases.clone());
2805 }
2806 sequences.push(bases);
2807 let mut mro = vec![key.clone()];
2808 while sequences.iter().any(|sequence| !sequence.is_empty()) {
2811 let head = sequences
2812 .iter()
2813 .filter_map(|sequence| sequence.first())
2814 .find(|head| {
2815 !sequences
2816 .iter()
2817 .any(|sequence| sequence.iter().skip(1).any(|item| item == *head))
2818 })?
2819 .clone();
2820 for sequence in &mut sequences {
2821 if sequence.first() == Some(&head) {
2822 sequence.remove(0);
2823 }
2824 }
2825 mro.push(head);
2826 }
2827 active.remove(&key);
2828 memo.insert(key, mro.clone());
2829 Some(mro)
2830 }
2831
2832 fn python_super(&self, file: &str, owner: &str, member: &str) -> Resolution {
2833 let Some((owner_file, ty)) = self.project_type(file, owner) else {
2834 return self.unknown("python", member);
2835 };
2836 let mro = match self.projections() {
2837 Some(projections) => self.replay_mro(projections, file, owner),
2838 None => self.python_mro(&owner_file, ty, &mut BTreeSet::new(), &mut BTreeMap::new()),
2839 };
2840 let Some(mro) = mro else {
2841 return self.unknown("python", member);
2842 };
2843 for (base_file, base) in mro.into_iter().skip(1) {
2844 if base.starts_with("@unknown:") {
2845 return Resolution {
2848 external: 1,
2849 ..Resolution::default()
2850 };
2851 }
2852 if base_file.is_empty() {
2853 continue;
2854 }
2855 let targets = self.methods(&base_file, &base, member, false);
2856 if !targets.is_empty() {
2857 return Resolution {
2858 targets: targets.into_iter().collect(),
2859 ..Resolution::default()
2860 };
2861 }
2862 }
2863 Resolution {
2864 external: 1,
2865 ..Resolution::default()
2866 }
2867 }
2868
2869 fn cpp_type_match(
2875 &self,
2876 file: &str,
2877 caller: Option<&str>,
2878 receiver: &str,
2879 member: &str,
2880 ) -> Resolution {
2881 let exact = format!("{receiver}::{member}");
2882 let nested = format!("::{exact}");
2883 let targets = self
2884 .methods_named(member)
2885 .iter()
2886 .filter(|(candidate_file, candidate, method)| {
2887 candidate.language() == "cpp"
2888 && (method.symbol == exact || method.symbol.ends_with(&nested))
2889 && !(candidate_file.as_str() == file && caller == Some(method.symbol.as_str()))
2890 })
2891 .map(|(candidate_file, _, method)| Target {
2892 file: candidate_file.clone(),
2893 symbol: method.symbol.clone(),
2894 provenance: super::super::PROVENANCE_TYPE_MATCH,
2895 })
2896 .collect::<BTreeSet<_>>();
2897 match targets.len() {
2898 0 => Resolution {
2899 external: 1,
2900 ..Resolution::default()
2901 },
2902 1 => Resolution {
2903 targets,
2904 ..Resolution::default()
2905 },
2906 _ => Resolution {
2907 unresolved: 1,
2908 ..Resolution::default()
2909 },
2910 }
2911 }
2912 test_support_visibility! {
2913 fn unknown(&self, language: &str, member: &str) -> Resolution {
2914 let protected: BTreeSet<_> = self
2917 .methods_named(member)
2918 .iter()
2919 .filter(|(_, parse, _)| parse.language() == language)
2920 .map(|(file, _, method)| (file.clone(), method.symbol.clone()))
2921 .collect();
2922 if ["go", "python"].contains(&language) {
2923 return Resolution {
2924 unresolved: usize::from(!protected.is_empty()),
2925 external: usize::from(protected.is_empty()),
2926 protected,
2927 ..Resolution::default()
2928 };
2929 }
2930 let targets = protected
2931 .iter()
2932 .filter(|(file, symbol)| {
2933 let parse = self.known_file(file);
2934 parse
2935 .methods_named_here(member)
2936 .into_iter()
2937 .find(|m| &m.symbol == symbol)
2938 .is_some_and(|m| {
2939 m.trait_name.is_some()
2940 || self.project_type(file, &m.owner).is_some_and(|(_, t)| {
2941 t.interface
2942 || t.bases.iter().any(|base| {
2943 self.project_type(file, base)
2944 .is_some_and(|(_, b)| b.interface)
2945 })
2946 })
2947 || language == "go" && self.go_interface_requires(&m.name, &m.shape)
2948 })
2949 })
2950 .map(|(file, symbol)| Target {
2951 file: file.clone(),
2952 symbol: symbol.clone(),
2953 provenance: "name_match",
2954 })
2955 .collect();
2956 Resolution {
2957 targets,
2958 unresolved: usize::from(!protected.is_empty()),
2959 external: usize::from(protected.is_empty()),
2960 protected,
2961 ..Resolution::default()
2962 }
2963 }
2964 }
2965 pub fn resolve(&self, file: &str, site: &SiteHint) -> Resolution {
2970 self.resolve_static(file, site)
2971 .unwrap_or_else(|| self.resolve_nonstatic(file, site))
2972 }
2973
2974 pub fn resolve_static(&self, file: &str, site: &SiteHint) -> Option<Resolution> {
2977 if site.dynamic || site.receiver.is_some() {
2978 return None;
2979 }
2980 let parse = self.lookup(file)?;
2981 let facts = parse.dispatch.static_facts.as_deref()?;
2982 let answer = self.static_call(
2983 file,
2984 &parse.language,
2985 facts,
2986 facts.site_key(site.ordinal)?,
2987 site.member.as_deref()?,
2988 )?;
2989 #[cfg(feature = "callgraph-shape-census")]
2990 self.census_exit.set(if answer.external == 0 {
2991 "exact"
2992 } else {
2993 "missing_type"
2994 });
2995 Some(answer)
2996 }
2997
2998 pub fn resolve_nonstatic(&self, file: &str, site: &SiteHint) -> Resolution {
3001 let parse = self.lookup(file).expect("resolved file has facts");
3002 if site.dynamic {
3003 return census_exit!(
3004 self,
3005 "dynamic",
3006 Resolution {
3007 dynamic: 1,
3008 ..Resolution::default()
3009 }
3010 );
3011 }
3012 let Some(member) = &site.member else {
3013 return census_exit!(self, "missing_member", Resolution::default());
3014 };
3015 if parse.language == "go" && parse.dispatch.go_package.is_none() {
3016 return census_exit!(self, "unknown_go_package", self.unknown("go", member));
3017 }
3018 let Some(receiver) = &site.receiver else {
3019 return census_exit!(self, "unknown", self.unknown(&parse.language, member));
3020 };
3021 if parse.language == "rust" {
3022 if let Some(symbol) = receiver.strip_prefix(TEMPLATE_SELF_RECEIVER) {
3023 return census_exit!(
3024 self,
3025 "rust_template_self",
3026 Resolution {
3027 targets: BTreeSet::from([Target {
3028 file: file.to_string(),
3029 symbol: symbol.to_string(),
3030 provenance: "name_match",
3031 }]),
3032 ..Resolution::default()
3033 }
3034 );
3035 }
3036 }
3037 if parse.language == "cpp" {
3038 return census_exit!(
3039 self,
3040 "cpp_type_match",
3041 self.cpp_type_match(file, site.caller.as_deref(), receiver, member)
3042 );
3043 }
3044 if parse.language == "python" {
3045 if let Some(owner) = receiver.strip_prefix("@super:") {
3046 return census_exit!(self, "python_super", self.python_super(file, owner, member));
3047 }
3048 }
3049 let projection = receiver_projection(&parse.language, receiver, member);
3050 let Some((type_file, ty)) = self.project_type(file, &projection) else {
3051 return census_exit!(
3052 self,
3053 "missing_type",
3054 Resolution {
3055 external: 1,
3056 ..Resolution::default()
3057 }
3058 );
3059 };
3060 let associated = parse.language == "rust" && self.associated_site(file, site.ordinal);
3061 let mut exact = self.nearest(&type_file, ty, member, &mut BTreeSet::new(), associated);
3062 if parse.language == "rust" {
3063 if !associated
3066 && exact.iter().any(|target| {
3067 self.known_file(&target.file)
3068 .methods_named_here(member)
3069 .into_iter()
3070 .find(|method| method.symbol == target.symbol)
3071 .is_some_and(|method| rust_receiver_shape(&method.shape).is_none())
3072 })
3073 {
3074 return census_exit!(
3075 self,
3076 "rust_legacy_shape",
3077 Resolution {
3078 unresolved: 1,
3079 protected: self
3080 .methods_named(member)
3081 .iter()
3082 .filter(|(_, parse, _)| parse.language() == "rust")
3083 .map(|(file, _, method)| (file.clone(), method.symbol.clone()))
3084 .collect(),
3085 ..Resolution::default()
3086 }
3087 );
3088 }
3089 let methods = self
3090 .known_file(&type_file)
3091 .methods_named_here(member)
3092 .into_iter()
3093 .filter(|m| {
3094 m.owner == ty.name
3095 && m.name == *member
3096 && (associated || rust_receiver_shape(&m.shape) != Some(false))
3097 })
3098 .collect::<Vec<_>>();
3099 let inherent = methods
3100 .iter()
3101 .filter(|m| m.trait_name.is_none())
3102 .collect::<Vec<_>>();
3103 if !inherent.is_empty() {
3104 exact = inherent
3105 .iter()
3106 .map(|m| Target {
3107 file: type_file.clone(),
3108 symbol: m.symbol.clone(),
3109 provenance: "exact",
3110 })
3111 .collect();
3112 } else if !ty.interface {
3113 exact.retain(|target| {
3114 let Some(method) = self
3115 .known_file(&target.file)
3116 .methods_named_here(member)
3117 .into_iter()
3118 .find(|m| m.symbol == target.symbol)
3119 else {
3120 return false;
3121 };
3122 let trait_name = method.trait_name.as_deref().unwrap_or(&method.owner);
3123 if site
3124 .caller
3125 .as_deref()
3126 .and_then(|name| name.rsplit_once("::"))
3127 .map(|(scope, _)| scope)
3128 == method.symbol.rsplit_once("::").map(|(scope, _)| scope)
3129 {
3130 return true;
3131 }
3132 let Some((trait_file, declaration)) =
3133 self.project_type(&target.file, trait_name)
3134 else {
3135 return false;
3136 };
3137 let caller_name = trait_name.rsplit("::").next().unwrap_or(trait_name);
3138 self.project_type(file, caller_name).is_some_and(
3139 |(caller_file, caller_trait)| {
3140 caller_file == trait_file && caller_trait.name == declaration.name
3141 },
3142 )
3143 });
3144 if exact.len() > 1 {
3145 return census_exit!(
3146 self,
3147 "unknown_rust_ambiguous",
3148 self.unknown(&parse.language, member)
3149 );
3150 }
3151 }
3152 }
3153 if parse.language == "go" && exact.len() > 1 {
3154 return census_exit!(
3155 self,
3156 "unknown_go_ambiguous",
3157 self.unknown(&parse.language, member)
3158 );
3159 }
3160 let mut targets = exact
3161 .into_iter()
3162 .filter(|target| {
3163 parse.language != "go"
3164 || file.ends_with("_test.go")
3165 || !target.file.ends_with("_test.go")
3166 })
3167 .collect::<BTreeSet<_>>();
3168 if ty.interface || (!ty.closed && !["rust", "go"].contains(&parse.language.as_str())) {
3169 for (candidate_file, candidate, method) in self.methods_named(member).iter() {
3170 let (candidate_file, candidate, method) = (candidate_file, *candidate, *method);
3171 if candidate.language() != parse.language {
3172 continue;
3173 }
3174 if parse.language == "go" && candidate.go_package().is_none() {
3175 continue;
3176 }
3177 if parse.language == "rust"
3178 && !associated
3179 && rust_receiver_shape(&method.shape) != Some(true)
3180 {
3181 continue;
3182 }
3183 {
3184 let implements = method.trait_name.as_deref().is_some_and(|name| {
3185 self.project_type(candidate_file, name)
3186 .is_some_and(|(f, t)| f == type_file && t.name == ty.name)
3187 }) || candidate
3188 .owner_type(self, candidate_file, &method.owner)
3189 .is_some_and(|sub| {
3190 self.subtype(
3191 candidate_file,
3192 sub,
3193 &type_file,
3194 &ty.name,
3195 &mut BTreeSet::new(),
3196 )
3197 })
3198 || (parse.language == "go" && ty.interface && {
3199 let required = self
3200 .known_file(&type_file)
3201 .go_methods()
3202 .iter()
3203 .filter(|m| m.owner == ty.name)
3204 .map(|m| (m.name.as_str(), m.shape.as_str()))
3205 .collect::<BTreeSet<_>>();
3206 !required.is_empty() && candidate.implements(&method.owner, &required)
3207 });
3208 if implements && !(candidate_file == &type_file && method.owner == ty.name) {
3209 targets.insert(Target {
3210 file: candidate_file.clone(),
3211 symbol: method.symbol.clone(),
3212 provenance: "dispatch",
3213 });
3214 }
3215 }
3216 }
3217 }
3218 let external = usize::from(targets.is_empty());
3219 let answer = Resolution {
3220 targets,
3221 external,
3222 ..Resolution::default()
3223 };
3224 #[cfg(feature = "callgraph-shape-census")]
3225 self.census_exit.set(
3226 if ty.interface || (!ty.closed && !["rust", "go"].contains(&parse.language.as_str())) {
3227 "open_type"
3228 } else {
3229 "exact"
3230 },
3231 );
3232 answer
3233 }
3234}
3235
3236pub struct MemoizedResolver<'r, 'a> {
3240 resolver: &'r Resolver<'a>,
3241 resolved: std::cell::RefCell<BTreeMap<ResolutionKey, MemoizedResolution>>,
3242}
3243
3244struct MemoizedResolution {
3247 resolved: std::sync::Arc<Resolution>,
3248 dependencies: std::rc::Rc<BTreeSet<String>>,
3249 #[cfg(feature = "callgraph-shape-census")]
3250 census_exit: &'static str,
3251}
3252
3253#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
3257pub struct ResolutionKey {
3258 pub scope: String,
3262 pub receiver: Option<String>,
3263 pub static_receiver: Option<u32>,
3264 pub member: Option<String>,
3265 pub dynamic: bool,
3266 pub associated: bool,
3267 pub caller_scope: Option<String>,
3268}
3269
3270impl Resolver<'_> {
3271 pub fn resolution_key(&self, file: &str, site: &SiteHint) -> ResolutionKey {
3275 let parse = self.lookup(file).expect("resolved file has facts");
3276 let language = &parse.language;
3277 let static_receiver = parse
3278 .dispatch
3279 .static_facts
3280 .as_deref()
3281 .and_then(|facts| facts.site_key(site.ordinal));
3282 ResolutionKey {
3283 scope: if site.receiver.is_none() && static_receiver.is_none() {
3287 language.clone()
3288 } else {
3289 file.to_string()
3290 },
3291 receiver: site.receiver.clone(),
3292 static_receiver,
3293 member: site.member.clone(),
3294 dynamic: site.dynamic,
3295 associated: language == "rust" && self.associated_site(file, site.ordinal),
3296 caller_scope: match language.as_str() {
3297 "rust" if site.receiver.is_some() => site
3298 .caller
3299 .as_deref()
3300 .and_then(|name| name.rsplit_once("::"))
3301 .map(|(scope, _)| scope.to_string()),
3302 "cpp" => site.caller.clone(),
3304 _ => None,
3305 },
3306 }
3307 }
3308}
3309
3310impl<'r, 'a> MemoizedResolver<'r, 'a> {
3311 pub fn new(resolver: &'r Resolver<'a>) -> Self {
3312 Self {
3313 resolver,
3314 resolved: Default::default(),
3315 }
3316 }
3317
3318 pub fn resolve(&self, file: &str, site: &SiteHint) -> std::sync::Arc<Resolution> {
3319 let key = self.resolver.resolution_key(file, site);
3320 self.resolve_key(file, site, key)
3321 }
3322
3323 fn resolve_key(
3324 &self,
3325 file: &str,
3326 site: &SiteHint,
3327 key: ResolutionKey,
3328 ) -> std::sync::Arc<Resolution> {
3329 if let Some(answer) = self.resolved.borrow().get(&key) {
3330 self.resolver
3331 .dependencies
3332 .borrow_mut()
3333 .extend(answer.dependencies.iter().cloned());
3334 #[cfg(feature = "callgraph-shape-census")]
3336 self.resolver.census_exit.set(answer.census_exit);
3337 return answer.resolved.clone();
3338 }
3339 let outer = self.resolver.take_dependencies();
3340 let resolved = if key.static_receiver.is_some() {
3341 if let Some(answer) = self.resolver.resolve_static(file, site) {
3342 std::sync::Arc::new(answer)
3343 } else {
3344 let mut fallback = key.clone();
3345 fallback.static_receiver = None;
3346 fallback.scope = self
3347 .resolver
3348 .lookup(file)
3349 .expect("resolved file has facts")
3350 .language
3351 .clone();
3352 self.resolve_key(file, site, fallback)
3353 }
3354 } else {
3355 std::sync::Arc::new(self.resolver.resolve_nonstatic(file, site))
3356 };
3357 let dependencies = self.resolver.take_dependencies();
3358 {
3359 let mut recorded = self.resolver.dependencies.borrow_mut();
3360 *recorded = outer;
3361 recorded.extend(dependencies.iter().cloned());
3362 }
3363 if self.resolved.borrow().len() < 4096 {
3366 self.resolved.borrow_mut().insert(
3367 key,
3368 MemoizedResolution {
3369 resolved: resolved.clone(),
3370 dependencies: std::rc::Rc::new(dependencies),
3371 #[cfg(feature = "callgraph-shape-census")]
3372 census_exit: self.resolver.census_exit.get(),
3373 },
3374 );
3375 }
3376 resolved
3377 }
3378}
3379
3380aft_store::heap_bytes_of_fields!(DispatchFacts {
3381 static_facts,
3382 go_package,
3383 types,
3384 methods,
3385 sites,
3386 fields,
3387 returns,
3388});
3389aft_store::heap_bytes_of_fields!(FieldHint { owner, name, ty });
3390aft_store::heap_bytes_of_fields!(ReturnHint { symbol, ty });
3391aft_store::heap_bytes_of_fields!(TypeHint {
3392 name,
3393 bases,
3394 interface,
3395 closed,
3396});
3397aft_store::heap_bytes_of_fields!(MethodHint {
3398 owner,
3399 trait_name,
3400 name,
3401 symbol,
3402 has_body,
3403 shape,
3404 private,
3405});
3406aft_store::heap_bytes_of_fields!(SiteHint {
3407 ordinal,
3408 caller,
3409 line,
3410 member,
3411 receiver,
3412 dynamic,
3413});
3414aft_store::heap_bytes_of_fields!(Target {
3415 file,
3416 symbol,
3417 provenance,
3418});
3419aft_store::heap_bytes_of_fields!(Resolution {
3420 targets,
3421 protected,
3422 unresolved,
3423 external,
3424 dynamic,
3425});