Skip to main content

aft_parse/
calls.rs

1//! Shared call-site extraction helpers.
2//!
3//! Extracted from `commands/zoom.rs` so both the zoom command and the
4//! call-graph engine can reuse the same AST-walking logic.
5
6use std::collections::{BTreeSet, HashSet};
7
8use rustc_hash::{FxHashMap, FxHashSet};
9
10use crate::callgraph_store::join::syntax_index::{Direct, Nav};
11use crate::parser::LangId;
12
13// Defensive recursion bound for AST walkers. Hand-written code nests only tens
14// of levels deep, but minified bundles, generated code, and very long
15// expression/type chains can produce trees thousands of nodes deep. The inspect
16// rayon pool uses bounded worker stacks, so unbounded AST recursion here can
17// overflow the stack and SIGABRT the entire bridge. Past this depth we stop
18// descending and treat the node as an opaque leaf. Kept well under the pool
19// stack budget (see dispatch.rs stack_size).
20const MAX_AST_WALK_DEPTH: u32 = 1_500;
21const MAX_RUST_MACRO_CALL_DEPTH: u32 = 32;
22
23thread_local! {
24    static RUST_FRAGMENT_PARSER: std::cell::RefCell<Option<tree_sitter::Parser>> = const { std::cell::RefCell::new(None) };
25    #[cfg(any(test, feature = "test-support"))]
26    pub static RUST_FRAGMENT_TREES: std::cell::RefCell<Option<FxHashMap<String, tree_sitter::Tree>>> = const { std::cell::RefCell::new(None) };
27    #[cfg(not(any(test, feature = "test-support")))]
28    static RUST_FRAGMENT_TREES: std::cell::RefCell<Option<FxHashMap<String, tree_sitter::Tree>>> = const { std::cell::RefCell::new(None) };
29}
30
31#[cfg(any(test, feature = "test-support"))]
32thread_local! {
33    pub static RUST_FRAGMENT_PARSER_INITIALIZATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
34    pub static RUST_FRAGMENT_PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
35}
36
37/// Keeps fragment trees only while one content record is extracted. Both the
38/// call graph and dead-code facts walk the same macros, sometimes again for
39/// nested functions; parsing depends on the fragment text, not its caller.
40pub struct RustMacroFragmentCache {
41    owner: bool,
42    _thread: std::marker::PhantomData<*mut ()>,
43}
44
45pub fn cache_rust_macro_fragments() -> RustMacroFragmentCache {
46    let owner = RUST_FRAGMENT_TREES.with(|trees| {
47        let mut trees = trees.borrow_mut();
48        if trees.is_some() {
49            false
50        } else {
51            *trees = Some(FxHashMap::default());
52            true
53        }
54    });
55    RustMacroFragmentCache {
56        owner,
57        _thread: std::marker::PhantomData,
58    }
59}
60
61impl Drop for RustMacroFragmentCache {
62    fn drop(&mut self) {
63        if self.owner {
64            // Drop on unwind too, so a worker never retains a previous file's
65            // fragments or grows a process-wide cache as it visits new files.
66            RUST_FRAGMENT_TREES.with(|trees| *trees.borrow_mut() = None);
67        }
68    }
69}
70
71/// Returns the tree-sitter node kind strings that represent call expressions
72/// for the given language.
73pub fn call_node_kinds(lang: LangId) -> &'static [&'static str] {
74    match lang {
75        LangId::TypeScript | LangId::JavaScript => &["call_expression", "new_expression"],
76        LangId::Tsx => &[
77            "call_expression",
78            "new_expression",
79            "jsx_opening_element",
80            "jsx_self_closing_element",
81        ],
82        LangId::Go => &["call_expression"],
83        LangId::Python => &["call"],
84        LangId::Rust => &["call_expression", "macro_invocation"],
85        LangId::Solidity | LangId::Scala => &["call_expression"],
86        LangId::Java => &["method_invocation"],
87        LangId::Ruby => &["call"],
88        LangId::Kotlin | LangId::Swift => &["call_expression"],
89        LangId::Php => &[
90            "function_call_expression",
91            "member_call_expression",
92            "nullsafe_member_call_expression",
93            "scoped_call_expression",
94        ],
95        LangId::Perl => &["function_call_expression", "method_call_expression"],
96        LangId::Lua | LangId::Luau => &["function_call"],
97        LangId::C | LangId::Cpp | LangId::Cuda | LangId::Metal | LangId::Zig => {
98            &["call_expression"]
99        }
100        LangId::CSharp => &["invocation_expression"],
101        LangId::Bash
102        | LangId::Scss
103        | LangId::Vue
104        | LangId::Html
105        | LangId::Markdown
106        | LangId::Json
107        | LangId::Yaml
108        | LangId::Pascal
109        | LangId::R
110        | LangId::Groovy
111        | LangId::ObjC
112        | LangId::Toml => &[],
113    }
114}
115
116test_support_visibility! {
117/// Recursively walk tree nodes looking for call expressions within a byte range.
118///
119/// Collects `(callee_name, line_number)` pairs into `results`.
120fn walk_for_calls(
121    node: tree_sitter::Node,
122    source: &str,
123    byte_start: usize,
124    byte_end: usize,
125    call_kinds: &[&str],
126    results: &mut Vec<(String, u32)>,
127) {
128    walk_for_calls_at_depth(node, source, byte_start, byte_end, call_kinds, results, 0);
129}
130}
131
132fn walk_for_calls_at_depth(
133    node: tree_sitter::Node,
134    source: &str,
135    byte_start: usize,
136    byte_end: usize,
137    call_kinds: &[&str],
138    results: &mut Vec<(String, u32)>,
139    depth: u32,
140) {
141    let node_start = node.start_byte();
142    let node_end = node.end_byte();
143
144    // Skip nodes entirely outside our range
145    if node_end <= byte_start || node_start >= byte_end {
146        return;
147    }
148
149    if call_kinds.contains(&node.kind()) && node_start >= byte_start && node_end <= byte_end {
150        if let Some(name) = extract_callee_name(&node, source) {
151            results.push((name, node.start_position().row as u32 + 1));
152        }
153    }
154
155    // Stop descending past MAX_AST_WALK_DEPTH to avoid overflowing the bounded
156    // inspect worker stack on pathologically deep trees (minified bundles,
157    // generated code, long chains). Treat the truncated subtree as an opaque
158    // leaf; calls already discovered at this node are still reported.
159    if depth >= MAX_AST_WALK_DEPTH {
160        return;
161    }
162
163    // Recurse into children
164    let mut cursor = node.walk();
165    if cursor.goto_first_child() {
166        loop {
167            walk_for_calls_at_depth(
168                cursor.node(),
169                source,
170                byte_start,
171                byte_end,
172                call_kinds,
173                results,
174                depth + 1,
175            );
176            if !cursor.goto_next_sibling() {
177                break;
178            }
179        }
180    }
181}
182
183/// Extract the callee name from a call expression node.
184///
185/// For simple calls like `foo()`, returns "foo".
186/// For member access like `this.add()` or `obj.method()`, returns the last
187/// segment ("add" / "method").
188/// For Rust macros like `println!()`, returns "println!".
189pub fn extract_callee_name(node: &tree_sitter::Node, source: &str) -> Option<String> {
190    let kind = node.kind();
191
192    if kind == "macro_invocation" {
193        // Rust macro: first child is the macro name (e.g. `println!`)
194        let first_child = node.child(0)?;
195        let text = &source[first_child.byte_range()];
196        return Some(format!("{}!", text));
197    }
198
199    let func_node = callee_node(node)?;
200
201    let func_kind = func_node.kind();
202    match func_kind {
203        // Simple identifier: foo()
204        "identifier" => Some(source[func_node.byte_range()].to_string()),
205        // Member access: obj.method() / this.method()
206        "member_expression"
207        | "field_expression"
208        | "attribute"
209        | "member_access_expression"
210        | "qualified_identifier"
211        | "generic_function"
212        | "generic_name"
213        | "template_function"
214        | "template_method" => {
215            // Last child that's a property_identifier, field_identifier, or identifier
216            extract_last_segment(&func_node, source)
217        }
218        // Computed member access: obj["method"]()
219        "subscript_expression" => extract_computed_member_name(&func_node, source)
220            .or_else(|| extract_last_segment(&func_node, source)),
221        _ => {
222            // Other callee kinds may be expressions rather than names.
223            let text = &source[func_node.byte_range()];
224            // If it contains a dot, take the last segment
225            let name = if text.contains('.') {
226                text.rsplit('.').next().map(|s| s.trim().to_string())
227            } else {
228                Some(text.trim().to_string())
229            };
230            name.filter(|name| is_name_like_callee(name))
231        }
232    }
233}
234
235/// Keep qualified names and language-specific sigils, but not the source text
236/// of an anonymous function, arrow expression, or call result.
237fn is_name_like_callee(text: &str) -> bool {
238    !text.is_empty()
239        && text.chars().all(|ch| {
240            ch.is_alphanumeric() || matches!(ch, '_' | '$' | ':' | '\\' | '@' | '?' | '!')
241        })
242}
243
244/// Extract the full callee expression from a call expression node.
245///
246/// Unlike `extract_callee_name` which returns only the last segment,
247/// this returns the full expression (e.g. "utils.foo" for `utils.foo()`).
248/// Used by the call graph engine to detect namespace-qualified calls.
249pub fn extract_full_callee(node: &tree_sitter::Node, source: &str) -> Option<String> {
250    let kind = node.kind();
251
252    if kind == "macro_invocation" {
253        let first_child = node.child(0)?;
254        let text = &source[first_child.byte_range()];
255        return Some(format!("{}!", text));
256    }
257
258    let func_node = callee_node(node)?;
259    let func_node = strip_generic_callee_wrapper(func_node);
260
261    Some(source[func_node.byte_range()].trim().to_string())
262}
263
264fn callee_node<'a>(node: &tree_sitter::Node<'a>) -> Option<tree_sitter::Node<'a>> {
265    match node.kind() {
266        "new_expression" => node
267            .child_by_field_name("constructor")
268            .or_else(|| node.named_child(0)),
269        "jsx_opening_element" | "jsx_self_closing_element" => node
270            .child_by_field_name("name")
271            .or_else(|| node.named_child(0)),
272        // Perl method call `$obj->method(...)`: the callee is the `method`
273        // field, not the leading invocant that `child(0)` would return.
274        "method_call_expression" => node
275            .child_by_field_name("method")
276            .or_else(|| node.child_by_field_name("function")),
277        _ => node
278            .child_by_field_name("function")
279            .or_else(|| node.child(0)),
280    }
281}
282
283fn strip_generic_callee_wrapper<'a>(node: tree_sitter::Node<'a>) -> tree_sitter::Node<'a> {
284    if node.kind() == "generic_function" {
285        node.child_by_field_name("function")
286            .or_else(|| node.named_child(0))
287            .unwrap_or(node)
288    } else {
289        node
290    }
291}
292
293/// The name a computed member access `obj["name"]` spells with a string
294/// literal, or `None` when its index is any other expression.
295pub fn extract_computed_member_name(node: &tree_sitter::Node, source: &str) -> Option<String> {
296    let index = node.child_by_field_name("index")?;
297    let text = source[index.byte_range()].trim();
298    computed_member_literal(text)
299}
300
301test_support_visibility! {
302fn computed_member_literal(text: &str) -> Option<String> {
303    if text.len() >= 2
304        && ((text.starts_with('"') && text.ends_with('"'))
305            || (text.starts_with('\'') && text.ends_with('\'')))
306    {
307        return Some(text[1..text.len().saturating_sub(1)].to_string());
308    }
309    None
310}
311}
312
313/// Extract the last segment of a member expression (the method/property name).
314///
315/// A name can nest in a name, as in C++'s right-nested `a::b::c`, as deep as
316/// the source writes it, so the descent is a loop rather than recursion: a
317/// stack overflow would abort the process. Every step of the descent ends
318/// in a result (the fallback always yields a segment), so following the
319/// `name` field or a generic wrapper is final, as a recursive call
320/// returning its result would be.
321fn extract_last_segment(node: &tree_sitter::Node, source: &str) -> Option<String> {
322    let mut node = *node;
323    'descend: loop {
324        node = strip_generic_callee_wrapper(node);
325        if let Some(name) = node.child_by_field_name("name") {
326            node = name;
327            continue;
328        }
329
330        let child_count = node.child_count();
331        // Walk children from the end looking for an identifier-like node
332        for i in (0..child_count).rev() {
333            if let Some(child) = node.child(i as u32) {
334                match child.kind() {
335                    "property_identifier" | "field_identifier" | "identifier" => {
336                        return Some(source[child.byte_range()].to_string());
337                    }
338                    "generic_function" | "generic_name" | "template_function"
339                    | "template_method" => {
340                        node = child;
341                        continue 'descend;
342                    }
343                    _ => {}
344                }
345            }
346        }
347        // Fallback: full text, last dot segment
348        let text = &source[node.byte_range()];
349        return text.rsplit('.').next().map(|s| s.trim().to_string());
350    }
351}
352
353/// Extract type-reference names within a byte range of the AST.
354///
355/// This is intentionally separate from call extraction. The live call graph and
356/// `aft_callgraph` commands remain call-edge-only; dead-code analysis consumes
357/// these type-position names as a side channel.
358fn extract_type_references_in_range(
359    source: &str,
360    root: tree_sitter::Node,
361    byte_start: usize,
362    byte_end: usize,
363    lang: LangId,
364) -> BTreeSet<String> {
365    let mut results = BTreeSet::new();
366    collect_type_references(root, source, byte_start, byte_end, lang, &mut results);
367    results
368}
369
370/// Extract all type-reference names in a parsed file.
371pub fn extract_type_references(
372    source: &str,
373    root: tree_sitter::Node,
374    lang: LangId,
375) -> BTreeSet<String> {
376    extract_type_references_in_range(source, root, 0, source.len(), lang)
377}
378
379test_support_visibility! {
380fn collect_type_references(
381    node: tree_sitter::Node,
382    source: &str,
383    byte_start: usize,
384    byte_end: usize,
385    lang: LangId,
386    results: &mut BTreeSet<String>,
387) {
388    collect_type_references_at_depth(node, source, byte_start, byte_end, lang, results, 0);
389}
390}
391
392fn collect_type_references_at_depth(
393    node: tree_sitter::Node,
394    source: &str,
395    byte_start: usize,
396    byte_end: usize,
397    lang: LangId,
398    results: &mut BTreeSet<String>,
399    depth: u32,
400) {
401    let node_start = node.start_byte();
402    let node_end = node.end_byte();
403
404    if node_end <= byte_start || node_start >= byte_end {
405        return;
406    }
407
408    // Stop descending past MAX_AST_WALK_DEPTH to avoid overflowing the bounded
409    // inspect worker stack on pathologically deep trees (minified bundles,
410    // generated code, long chains). Treat the truncated subtree as an opaque
411    // leaf; type references inside it are intentionally skipped.
412    if depth >= MAX_AST_WALK_DEPTH {
413        return;
414    }
415
416    if node_start >= byte_start && node_end <= byte_end {
417        collect_type_reference_fields(&node, source, lang, results);
418        if is_type_context_node(lang, node.kind()) {
419            collect_type_reference_identifiers(node, source, lang, results);
420            return;
421        }
422    }
423
424    let mut cursor = node.walk();
425    if cursor.goto_first_child() {
426        loop {
427            collect_type_references_at_depth(
428                cursor.node(),
429                source,
430                byte_start,
431                byte_end,
432                lang,
433                results,
434                depth + 1,
435            );
436            if !cursor.goto_next_sibling() {
437                break;
438            }
439        }
440    }
441}
442
443fn collect_type_reference_fields(
444    node: &tree_sitter::Node,
445    source: &str,
446    lang: LangId,
447    results: &mut BTreeSet<String>,
448) {
449    for field in ["type", "return_type", "result", "trait"] {
450        if let Some(child) = node.child_by_field_name(field) {
451            collect_type_reference_identifiers(child, source, lang, results);
452        }
453    }
454
455    if matches!(lang, LangId::TypeScript | LangId::Tsx) && node.kind() == "type_alias_declaration" {
456        if let Some(value) = node.child_by_field_name("value") {
457            collect_type_reference_identifiers(value, source, lang, results);
458        }
459    }
460
461    // Building a value with a struct literal (`ZoomResponse { .. }`) uses the
462    // type even when no annotation ever names it.
463    if lang == LangId::Rust && node.kind() == "struct_expression" {
464        if let Some(name) = node.child_by_field_name("name") {
465            collect_type_reference_identifiers(name, source, lang, results);
466        }
467    }
468}
469
470fn is_type_context_node(lang: LangId, kind: &str) -> bool {
471    match lang {
472        LangId::TypeScript | LangId::Tsx => matches!(
473            kind,
474            "type_annotation"
475                | "type_arguments"
476                | "extends_clause"
477                | "implements_clause"
478                | "satisfies_expression"
479        ),
480        LangId::JavaScript => false,
481        LangId::Python => kind == "type",
482        LangId::Rust => matches!(
483            kind,
484            "parameter"
485                | "field_declaration"
486                | "generic_type"
487                | "type_arguments"
488                | "reference_type"
489                | "array_type"
490                | "tuple_type"
491                | "bounded_type"
492        ),
493        LangId::Go => matches!(
494            kind,
495            "field_declaration"
496                | "parameter_declaration"
497                | "generic_type"
498                | "type_arguments"
499                | "type_elem"
500                | "pointer_type"
501                | "array_type"
502                | "slice_type"
503                | "map_type"
504                | "qualified_type"
505                | "channel_type"
506                | "function_type"
507        ),
508        _ => false,
509    }
510}
511
512fn collect_type_reference_identifiers(
513    node: tree_sitter::Node,
514    source: &str,
515    lang: LangId,
516    results: &mut BTreeSet<String>,
517) {
518    collect_type_reference_identifiers_at_depth(node, source, lang, results, 0);
519}
520
521fn collect_type_reference_identifiers_at_depth(
522    node: tree_sitter::Node,
523    source: &str,
524    lang: LangId,
525    results: &mut BTreeSet<String>,
526    depth: u32,
527) {
528    if is_type_reference_identifier(lang, node.kind()) {
529        let name = source[node.byte_range()].trim();
530        if let Some(name) = clean_type_reference_name(name) {
531            results.insert(name);
532        }
533    }
534
535    if depth >= MAX_AST_WALK_DEPTH {
536        return;
537    }
538
539    let mut cursor = node.walk();
540    if cursor.goto_first_child() {
541        loop {
542            collect_type_reference_identifiers_at_depth(
543                cursor.node(),
544                source,
545                lang,
546                results,
547                depth + 1,
548            );
549            if !cursor.goto_next_sibling() {
550                break;
551            }
552        }
553    }
554}
555
556fn is_type_reference_identifier(lang: LangId, kind: &str) -> bool {
557    match lang {
558        LangId::TypeScript | LangId::Tsx => matches!(kind, "type_identifier" | "identifier"),
559        LangId::Python => kind == "identifier",
560        LangId::Rust | LangId::Go => kind == "type_identifier",
561        _ => false,
562    }
563}
564
565fn clean_type_reference_name(name: &str) -> Option<String> {
566    let name = name
567        .rsplit(['.', ':'])
568        .find(|segment| !segment.is_empty())
569        .unwrap_or(name)
570        .trim()
571        .trim_start_matches('?');
572
573    if name.is_empty()
574        || !name
575            .chars()
576            .next()
577            .is_some_and(|c| c == '_' || c.is_alphabetic())
578    {
579        return None;
580    }
581
582    Some(name.to_string())
583}
584
585/// Extract Go expression references, including callbacks and package variables.
586/// Resolution rejects identifiers that do not name indexed package symbols.
587pub fn extract_go_value_references(source: &str, root: tree_sitter::Node) -> Vec<CallTuple> {
588    // A work stack of (node, its parent) instead of recursion: an expression
589    // can nest tens of thousands of levels deep, and a stack overflow aborts
590    // the process. Carrying the parent also spares a `parent()` lookup per
591    // node, which tree-sitter answers by descending from the root. Children
592    // are pushed in reverse, so references come out in source order.
593    let mut results = Vec::new();
594    let mut pending = vec![(root, root.parent())];
595    while let Some((node, parent)) = pending.pop() {
596        let is_callee = parent.is_some_and(|p| {
597            p.kind() == "call_expression" && p.child_by_field_name("function") == Some(node)
598        });
599        let is_value = node.kind() == "selector_expression"
600            || (node.kind() == "identifier"
601                && parent.is_some_and(|p| {
602                    matches!(
603                        p.kind(),
604                        "argument_list"
605                            | "expression_list"
606                            | "return_statement"
607                            | "binary_expression"
608                            | "unary_expression"
609                            | "parenthesized_expression"
610                            | "keyed_element"
611                            | "literal_element"
612                    )
613                }));
614        if is_value && !is_callee {
615            let full = source[node.byte_range()].to_string();
616            let short = full.rsplit('.').next().unwrap_or(&full).to_string();
617            results.push((
618                full,
619                short,
620                node.start_position().row as u32 + 1,
621                node.start_byte(),
622                node.end_byte(),
623            ));
624        }
625        // A dotted name is one reference, but a fluent selector's receiver can
626        // contain calls with callback arguments. Walk that computed receiver
627        // without inventing extra references to the names in a pure dotted path.
628        if node.kind() == "selector_expression" {
629            let mut selector = node;
630            let mut operand = node.child_by_field_name("operand");
631            while let Some(base) = operand {
632                if base.kind() == "selector_expression" {
633                    selector = base;
634                    operand = base.child_by_field_name("operand");
635                } else {
636                    if !matches!(base.kind(), "identifier" | "package_identifier") {
637                        pending.push((base, Some(selector)));
638                    }
639                    break;
640                }
641            }
642        } else {
643            let start = pending.len();
644            pending.extend(
645                node.named_children(&mut node.walk())
646                    .map(|child| (child, Some(node))),
647            );
648            pending[start..].reverse();
649        }
650    }
651    results
652}
653
654/// Extract bare or namespace-qualified callback arguments, not invocation edges.
655pub fn extract_js_callback_references(
656    source: &str,
657    root: tree_sitter::Node<'_>,
658) -> Vec<(String, String, u32, usize, usize)> {
659    extract_js_callback_references_with(source, root, Direct)
660}
661
662/// [`extract_js_callback_references`], walking and looking up with `nav`.
663pub fn extract_js_callback_references_with<'tree>(
664    source: &str,
665    root: tree_sitter::Node<'tree>,
666    nav: impl Nav<'tree>,
667) -> Vec<(String, String, u32, usize, usize)> {
668    let mut results = Vec::new();
669    // Callbacks in one scope ask the same scopes the same questions; each
670    // scope's bindings are read once.
671    let mut scopes = FxHashMap::default();
672    nav.walk_named(root, |node, kind| {
673        if kind == "arguments" {
674            for argument in node.named_children(&mut node.walk()) {
675                if matches!(nav.kind(argument), "identifier" | "member_expression") {
676                    let full = source[argument.byte_range()].trim();
677                    let root_name = full.split('.').next().unwrap_or(full);
678                    if !js_callback_is_shadowed(source, argument, root_name, nav, &mut scopes) {
679                        results.push((
680                            full.to_string(),
681                            full.rsplit('.').next().unwrap_or(full).to_string(),
682                            argument.start_position().row as u32 + 1,
683                            argument.start_byte(),
684                            argument.end_byte(),
685                        ));
686                    }
687                }
688            }
689        }
690        true
691    });
692    results.sort_by_key(|site| site.3);
693    results
694}
695
696/// The bindings of one JavaScript scope that can shadow a callback name.
697struct JsScopeBindings<'source> {
698    /// The text of every identifier among the scope's parameters.
699    parameters: FxHashSet<&'source str>,
700    /// For a block or program: the first `let`, `const` or `var` binding of
701    /// each name, and whether it shadows (it does unless its value is a
702    /// function).
703    declarations: FxHashMap<&'source str, bool>,
704}
705
706fn js_scope_bindings<'tree, 'source>(
707    source: &'source str,
708    scope: tree_sitter::Node<'tree>,
709    nav: impl Nav<'tree>,
710) -> JsScopeBindings<'source> {
711    let mut bindings = JsScopeBindings {
712        parameters: FxHashSet::default(),
713        declarations: FxHashMap::default(),
714    };
715    if let Some(parameters) = scope.child_by_field_name("parameters") {
716        nav.walk_named(parameters, |node, kind| {
717            if kind == "identifier" {
718                bindings.parameters.insert(&source[node.byte_range()]);
719            }
720            true
721        });
722    }
723    if matches!(nav.kind(scope), "statement_block" | "program") {
724        for declaration in scope.named_children(&mut scope.walk()) {
725            if !matches!(
726                declaration.kind(),
727                "lexical_declaration" | "variable_declaration"
728            ) {
729                continue;
730            }
731            for binding in declaration.named_children(&mut declaration.walk()) {
732                if let Some(name) = binding.child_by_field_name("name") {
733                    let shadows = !binding.child_by_field_name("value").is_some_and(|value| {
734                        matches!(value.kind(), "arrow_function" | "function_expression")
735                    });
736                    bindings
737                        .declarations
738                        .entry(&source[name.byte_range()])
739                        .or_insert(shadows);
740                }
741            }
742        }
743    }
744    bindings
745}
746
747/// Whether a parameter or a preceding scope's declaration binds `name` where
748/// `argument` is passed. The innermost scope that binds it decides; among
749/// a block's declarations the first one does.
750fn js_callback_is_shadowed<'tree, 'source>(
751    source: &'source str,
752    argument: tree_sitter::Node<'tree>,
753    name: &str,
754    nav: impl Nav<'tree>,
755    scopes: &mut FxHashMap<usize, JsScopeBindings<'source>>,
756) -> bool {
757    let mut ancestor = nav.parent(argument);
758    while let Some(scope) = ancestor {
759        let bindings = scopes
760            .entry(scope.id())
761            .or_insert_with(|| js_scope_bindings(source, scope, nav));
762        if bindings.parameters.contains(name) {
763            return true;
764        }
765        if let Some(&shadows) = bindings.declarations.get(name) {
766            return shadows;
767        }
768        ancestor = nav.parent(scope);
769    }
770    false
771}
772
773/// Extract Rust function paths used as values rather than called directly.
774///
775/// The call graph stores these separately from calls so execution trees remain
776/// call-only while reverse dependencies and dead-code reachability follow callbacks passed to APIs
777/// such as `map` and `unwrap_or_else`.
778pub fn extract_rust_value_references(
779    source: &str,
780    root: tree_sitter::Node,
781) -> Vec<(String, String, u32, usize, usize)> {
782    extract_rust_value_references_with(source, root, Direct)
783}
784
785/// [`extract_rust_value_references`], walking and looking up with `nav`.
786pub fn extract_rust_value_references_with<'tree>(
787    source: &str,
788    root: tree_sitter::Node<'tree>,
789    nav: impl Nav<'tree>,
790) -> Vec<(String, String, u32, usize, usize)> {
791    #[cfg(any(test, feature = "test-support"))]
792    if LEGACY_VALUE_REFERENCES.with(|legacy| legacy.get()) {
793        let mut results = Vec::new();
794        collect_rust_value_references(root, source, &mut results, 0);
795        return results;
796    }
797    let mut walk = RustValueWalk {
798        source,
799        nav,
800        ancestors: Vec::new(),
801        blocks: FxHashMap::default(),
802        results: Vec::new(),
803    };
804    // Callers may pass a subtree. Capture its outside ancestry once, rather
805    // than asking tree-sitter to rediscover it for every identifier.
806    let mut parent = nav.parent(root);
807    while let Some(node) = parent {
808        walk.ancestors.push(node);
809        parent = nav.parent(node);
810    }
811    walk.ancestors.reverse();
812    for node in &walk.ancestors {
813        if nav.kind(*node) == "block" {
814            walk.blocks
815                .insert(node.id(), rust_block_bindings(*node, source));
816        }
817    }
818    walk.visit(root, 0);
819    walk.results
820}
821
822#[cfg(any(test, feature = "test-support"))]
823thread_local! {
824    static LEGACY_VALUE_REFERENCES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
825    pub static VALUE_BINDING_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
826}
827
828struct RustValueWalk<'tree, 'source, N> {
829    source: &'source str,
830    nav: N,
831    ancestors: Vec<tree_sitter::Node<'tree>>,
832    // The first declaration end for a name is enough: the legacy rule asks
833    // whether *any* preceding let binds it, not which binding supplies a type.
834    blocks: FxHashMap<usize, FxHashMap<&'source str, usize>>,
835    results: Vec<(String, String, u32, usize, usize)>,
836}
837
838fn rust_block_bindings<'source>(
839    block: tree_sitter::Node<'_>,
840    source: &'source str,
841) -> FxHashMap<&'source str, usize> {
842    let mut bindings = FxHashMap::default();
843    let mut cursor = block.walk();
844    for child in block.children(&mut cursor) {
845        #[cfg(any(test, feature = "test-support"))]
846        VALUE_BINDING_WORK.with(|work| work.set(work.get() + 1));
847        if child.kind() != "let_declaration" {
848            continue;
849        }
850        if let Some(pattern) = child.child_by_field_name("pattern") {
851            let mut pending = vec![pattern];
852            while let Some(node) = pending.pop() {
853                #[cfg(any(test, feature = "test-support"))]
854                VALUE_BINDING_WORK.with(|work| work.set(work.get() + 1));
855                if node.kind() == "identifier" {
856                    bindings
857                        .entry(&source[node.byte_range()])
858                        .or_insert(child.end_byte());
859                }
860                let mut pattern_cursor = node.walk();
861                pending.extend(node.children(&mut pattern_cursor));
862            }
863        }
864    }
865    bindings
866}
867
868impl<'tree, N: Nav<'tree>> RustValueWalk<'tree, '_, N> {
869    fn visit(&mut self, node: tree_sitter::Node<'tree>, depth: u32) {
870        let nav = self.nav;
871        let kind = nav.kind(node);
872        if kind == "block" {
873            self.blocks
874                .insert(node.id(), rust_block_bindings(node, self.source));
875        }
876        let nested = self.ancestors.last().is_some_and(|parent| {
877            matches!(
878                nav.kind(*parent),
879                "scoped_identifier" | "scoped_type_identifier" | "generic_function"
880            )
881        });
882        if matches!(kind, "identifier" | "scoped_identifier")
883            && !nested
884            && self.is_value_position(node)
885        {
886            let full = self.source[node.byte_range()].trim();
887            let short = full.rsplit("::").next().unwrap_or(full).trim();
888            if !full.is_empty()
889                && !short.is_empty()
890                && (kind != "identifier" || !self.is_shadowed(node))
891            {
892                self.results.push((
893                    full.to_string(),
894                    short.to_string(),
895                    node.start_position().row as u32 + 1,
896                    node.start_byte(),
897                    node.end_byte(),
898                ));
899            }
900        }
901        if depth < MAX_AST_WALK_DEPTH {
902            self.ancestors.push(node);
903            nav.for_each_child(node, |child| self.visit(child, depth + 1));
904            self.ancestors.pop();
905        }
906        if kind == "block" {
907            self.blocks.remove(&node.id());
908        }
909    }
910
911    fn is_value_position(&self, node: tree_sitter::Node<'_>) -> bool {
912        let mut current = node;
913        for parent in self.ancestors.iter().rev() {
914            let selected = |field: &str| {
915                parent
916                    .child_by_field_name(field)
917                    .is_some_and(|child| same_node(&child, &current))
918            };
919            let parent_kind = self.nav.kind(*parent);
920            if parent_kind == "call_expression" && selected("function") {
921                return false;
922            }
923            match parent_kind {
924                "block"
925                    if parent.named_child(parent.named_child_count().saturating_sub(1) as u32)
926                        == Some(current) =>
927                {
928                    return true
929                }
930                "match_arm" if selected("value") => return true,
931                "arguments" | "array_expression" | "tuple_expression" => return true,
932                "let_declaration" if selected("value") => return true,
933                "assignment_expression" if selected("right") => return true,
934                "field_initializer" if selected("value") => return true,
935                // Reading a static through a receiver or index runs its lazy
936                // initializer. The member name itself is not a value use.
937                "field_expression" if selected("value") => return true,
938                "index_expression" => return true,
939                "shorthand_field_initializer" | "return_expression" | "break_expression" => {
940                    return true
941                }
942                "parenthesized_expression"
943                | "reference_expression"
944                | "unary_expression"
945                | "await_expression"
946                | "try_expression" => current = *parent,
947                _ => return false,
948            }
949        }
950        false
951    }
952
953    fn is_shadowed(&self, node: tree_sitter::Node<'_>) -> bool {
954        let name = &self.source[node.byte_range()];
955        let mut current = node;
956        for parent in self.ancestors.iter().rev() {
957            match self.nav.kind(*parent) {
958                "function_item" | "closure_expression" => {
959                    if parent
960                        .child_by_field_name("parameters")
961                        .is_some_and(|parameters| {
962                            rust_pattern_binds_name(parameters, self.source, name)
963                        })
964                    {
965                        return true;
966                    }
967                }
968                "match_arm" => {
969                    if parent
970                        .child_by_field_name("pattern")
971                        .is_some_and(|pattern| rust_pattern_binds_name(pattern, self.source, name))
972                    {
973                        return true;
974                    }
975                }
976                "for_expression" => {
977                    if parent
978                        .child_by_field_name("body")
979                        .is_some_and(|body| node_contains(&body, &node))
980                        && parent
981                            .child_by_field_name("pattern")
982                            .is_some_and(|pattern| {
983                                rust_pattern_binds_name(pattern, self.source, name)
984                            })
985                    {
986                        return true;
987                    }
988                }
989                "if_expression" | "while_expression" => {
990                    if parent
991                        .child_by_field_name("consequence")
992                        .or_else(|| parent.child_by_field_name("body"))
993                        .is_some_and(|body| node_contains(&body, &node))
994                        && parent
995                            .child_by_field_name("condition")
996                            .is_some_and(|condition| {
997                                rust_let_condition_binds_name(condition, self.source, name)
998                            })
999                    {
1000                        return true;
1001                    }
1002                }
1003                "block" => {
1004                    #[cfg(any(test, feature = "test-support"))]
1005                    VALUE_BINDING_WORK.with(|work| work.set(work.get() + 1));
1006                    if self
1007                        .blocks
1008                        .get(&parent.id())
1009                        .and_then(|bindings| bindings.get(name))
1010                        .is_some_and(|end| *end <= current.start_byte())
1011                    {
1012                        return true;
1013                    }
1014                }
1015                _ => {}
1016            }
1017            current = *parent;
1018        }
1019        false
1020    }
1021}
1022
1023#[cfg(any(test, feature = "test-support"))]
1024pub fn legacy_rust_value_references(
1025    source: &str,
1026    root: tree_sitter::Node,
1027) -> Vec<(String, String, u32, usize, usize)> {
1028    let mut results = Vec::new();
1029    collect_rust_value_references(root, source, &mut results, 0);
1030    results
1031}
1032
1033#[cfg(any(test, feature = "test-support"))]
1034fn collect_rust_value_references(
1035    node: tree_sitter::Node,
1036    source: &str,
1037    results: &mut Vec<(String, String, u32, usize, usize)>,
1038    depth: u32,
1039) {
1040    if matches!(node.kind(), "identifier" | "scoped_identifier")
1041        && !rust_path_is_nested(&node)
1042        && rust_path_is_value_position(&node)
1043    {
1044        let full = source[node.byte_range()].trim();
1045        let short = full.rsplit("::").next().unwrap_or(full).trim();
1046        if !full.is_empty()
1047            && !short.is_empty()
1048            && (node.kind() != "identifier" || !rust_bare_identifier_is_shadowed(&node, source))
1049        {
1050            results.push((
1051                full.to_string(),
1052                short.to_string(),
1053                node.start_position().row as u32 + 1,
1054                node.start_byte(),
1055                node.end_byte(),
1056            ));
1057        }
1058    }
1059
1060    if depth >= MAX_AST_WALK_DEPTH {
1061        return;
1062    }
1063
1064    let mut cursor = node.walk();
1065    if cursor.goto_first_child() {
1066        loop {
1067            collect_rust_value_references(cursor.node(), source, results, depth + 1);
1068            if !cursor.goto_next_sibling() {
1069                break;
1070            }
1071        }
1072    }
1073}
1074
1075#[cfg(any(test, feature = "test-support"))]
1076fn rust_path_is_nested(node: &tree_sitter::Node<'_>) -> bool {
1077    node.parent().is_some_and(|parent| {
1078        matches!(
1079            parent.kind(),
1080            "scoped_identifier" | "scoped_type_identifier" | "generic_function"
1081        )
1082    })
1083}
1084
1085#[cfg(any(test, feature = "test-support"))]
1086fn rust_path_is_value_position(node: &tree_sitter::Node<'_>) -> bool {
1087    let mut current = *node;
1088    while let Some(parent) = current.parent() {
1089        if parent.kind() == "call_expression"
1090            && parent
1091                .child_by_field_name("function")
1092                .is_some_and(|function| same_node(&function, &current))
1093        {
1094            return false;
1095        }
1096
1097        let is_selected_field = |field: &str| {
1098            parent
1099                .child_by_field_name(field)
1100                .is_some_and(|child| same_node(&child, &current))
1101        };
1102        match parent.kind() {
1103            "block"
1104                if parent.named_child(parent.named_child_count().saturating_sub(1) as u32)
1105                    == Some(current) =>
1106            {
1107                return true
1108            }
1109            "match_arm" if is_selected_field("value") => return true,
1110            "arguments" | "array_expression" | "tuple_expression" => return true,
1111            "let_declaration" if is_selected_field("value") => return true,
1112            "assignment_expression" if is_selected_field("right") => return true,
1113            "field_initializer" if is_selected_field("value") => return true,
1114            "field_expression" if is_selected_field("value") => return true,
1115            "index_expression" => return true,
1116            "shorthand_field_initializer" => return true,
1117            "return_expression" | "break_expression" => return true,
1118            "parenthesized_expression"
1119            | "reference_expression"
1120            | "unary_expression"
1121            | "await_expression"
1122            | "try_expression" => current = parent,
1123            _ => return false,
1124        }
1125    }
1126    false
1127}
1128
1129#[cfg(any(test, feature = "test-support"))]
1130fn rust_bare_identifier_is_shadowed(node: &tree_sitter::Node<'_>, source: &str) -> bool {
1131    rust_name_is_shadowed_at(*node, source, &source[node.byte_range()])
1132}
1133
1134/// Whether a binding shadows this name at an expression. Parameters, match/loop
1135/// patterns, let conditions and preceding lets in enclosing blocks count;
1136/// sibling scopes and later lets do not.
1137pub fn rust_name_is_shadowed_at(node: tree_sitter::Node<'_>, source: &str, name: &str) -> bool {
1138    let mut current = node;
1139
1140    while let Some(parent) = current.parent() {
1141        match parent.kind() {
1142            "function_item" | "closure_expression" => {
1143                if parent
1144                    .child_by_field_name("parameters")
1145                    .is_some_and(|parameters| rust_pattern_binds_name(parameters, source, name))
1146                {
1147                    return true;
1148                }
1149            }
1150            "match_arm" => {
1151                if parent
1152                    .child_by_field_name("pattern")
1153                    .is_some_and(|pattern| rust_pattern_binds_name(pattern, source, name))
1154                {
1155                    return true;
1156                }
1157            }
1158            "for_expression" => {
1159                if parent
1160                    .child_by_field_name("pattern")
1161                    .is_some_and(|pattern| rust_pattern_binds_name(pattern, source, name))
1162                    && parent
1163                        .child_by_field_name("body")
1164                        .is_some_and(|body| node_contains(&body, &node))
1165                {
1166                    return true;
1167                }
1168            }
1169            "if_expression" | "while_expression" => {
1170                let body = parent
1171                    .child_by_field_name("consequence")
1172                    .or_else(|| parent.child_by_field_name("body"));
1173                if body.is_some_and(|body| node_contains(&body, &node))
1174                    && parent
1175                        .child_by_field_name("condition")
1176                        .is_some_and(|condition| {
1177                            rust_let_condition_binds_name(condition, source, name)
1178                        })
1179                {
1180                    return true;
1181                }
1182            }
1183            "block" => {
1184                let mut sibling = current.prev_named_sibling();
1185                while let Some(previous) = sibling {
1186                    #[cfg(any(test, feature = "test-support"))]
1187                    VALUE_BINDING_WORK.with(|work| work.set(work.get() + 1));
1188                    if previous.kind() == "let_declaration"
1189                        && previous
1190                            .child_by_field_name("pattern")
1191                            .is_some_and(|pattern| rust_pattern_binds_name(pattern, source, name))
1192                    {
1193                        return true;
1194                    }
1195                    sibling = previous.prev_named_sibling();
1196                }
1197            }
1198            _ => {}
1199        }
1200        current = parent;
1201    }
1202
1203    false
1204}
1205
1206/// Whether a `let` condition anywhere in `condition` (itself included) binds
1207/// `name`. The search keeps its pending nodes on the heap rather than
1208/// recursing, so a deeply nested condition cannot overflow the stack.
1209fn rust_let_condition_binds_name(
1210    condition: tree_sitter::Node<'_>,
1211    source: &str,
1212    name: &str,
1213) -> bool {
1214    let mut pending = vec![condition];
1215    while let Some(node) = pending.pop() {
1216        if node.kind() == "let_condition"
1217            && node
1218                .child_by_field_name("pattern")
1219                .or_else(|| node.named_child(0))
1220                .is_some_and(|pattern| rust_pattern_binds_name(pattern, source, name))
1221        {
1222            return true;
1223        }
1224        pending.extend(node.children(&mut node.walk()));
1225    }
1226    false
1227}
1228
1229/// Whether an identifier `name` occurs anywhere in `node` (itself
1230/// included). The search keeps its pending nodes on the heap rather than
1231/// recursing, so a deeply nested pattern cannot overflow the stack.
1232fn rust_pattern_binds_name(node: tree_sitter::Node<'_>, source: &str, name: &str) -> bool {
1233    let mut pending = vec![node];
1234    while let Some(node) = pending.pop() {
1235        if node.kind() == "identifier" && &source[node.byte_range()] == name {
1236            return true;
1237        }
1238        pending.extend(node.children(&mut node.walk()));
1239    }
1240    false
1241}
1242
1243fn same_node(left: &tree_sitter::Node<'_>, right: &tree_sitter::Node<'_>) -> bool {
1244    left.id() == right.id()
1245}
1246
1247fn node_contains(container: &tree_sitter::Node<'_>, node: &tree_sitter::Node<'_>) -> bool {
1248    container.start_byte() <= node.start_byte() && node.end_byte() <= container.end_byte()
1249}
1250
1251/// Extract call expression names within a byte range of the AST.
1252///
1253/// Walks all nodes in the tree, finds call_expression/call/macro_invocation
1254/// nodes whose byte range falls within [byte_start, byte_end], and extracts
1255/// the callee name (last segment for member access like `obj.method()`).
1256///
1257/// Returns (callee_name, line_number) pairs.
1258pub fn extract_calls_in_range(
1259    source: &str,
1260    root: tree_sitter::Node,
1261    byte_start: usize,
1262    byte_end: usize,
1263    lang: LangId,
1264) -> Vec<(String, u32)> {
1265    let mut results = Vec::new();
1266    let call_kinds = call_node_kinds(lang);
1267    walk_for_calls(
1268        root,
1269        source,
1270        byte_start,
1271        byte_end,
1272        &call_kinds,
1273        &mut results,
1274    );
1275    results
1276}
1277
1278/// Extract calls with full callee expressions (including namespace qualifiers).
1279///
1280/// Returns `(full_callee, short_name, line, byte_start, byte_end)` tuples.
1281/// `full_callee` is e.g. "utils.foo", `short_name` is "foo".
1282pub fn extract_calls_full(
1283    source: &str,
1284    root: tree_sitter::Node,
1285    byte_start: usize,
1286    byte_end: usize,
1287    lang: LangId,
1288) -> Vec<(String, String, u32, usize, usize)> {
1289    extract_calls_full_with(source, root, byte_start, byte_end, lang, Direct)
1290}
1291
1292/// [`extract_calls_full`], walking with `nav`.
1293pub fn extract_calls_full_with<'tree>(
1294    source: &str,
1295    root: tree_sitter::Node<'tree>,
1296    byte_start: usize,
1297    byte_end: usize,
1298    lang: LangId,
1299    nav: impl Nav<'tree>,
1300) -> Vec<(String, String, u32, usize, usize)> {
1301    if lang == LangId::Rust {
1302        return extract_rust_calls_with_macro_facts_with(source, root, byte_start, byte_end, nav).0;
1303    }
1304    let mut results = Vec::new();
1305    let call_kinds = call_node_kinds(lang);
1306    if call_kinds.is_empty() {
1307        // A grammar without call nodes has no calls to find.
1308        return results;
1309    }
1310    collect_calls_full_with(
1311        root,
1312        source,
1313        byte_start,
1314        byte_end,
1315        &call_kinds,
1316        &mut results,
1317        nav,
1318    );
1319    if lang == LangId::Luau {
1320        for (full, short, _, _, _) in &mut results {
1321            if let Some(name) = full.rsplit(['.', ':']).next() {
1322                *short = name.to_string();
1323            }
1324        }
1325    }
1326    results
1327}
1328
1329/// Call-site tuple shared by the extraction helpers:
1330/// `(full_callee, short_name, line, byte_start, byte_end)`.
1331pub type CallTuple = (String, String, u32, usize, usize);
1332
1333/// Upper bound on unanalyzed macro mentions recorded for one file. A file full
1334/// of DSL macros (SQL, HTML templates) would otherwise record every word in
1335/// them; past this many the note on `callers` output is already clear enough.
1336const MAX_UNPARSED_MACRO_MENTIONS_PER_FILE: usize = 512;
1337
1338/// The template of one `macro_rules!` arm, located in the original source.
1339#[derive(Debug, Clone, PartialEq, Eq)]
1340pub struct RustMacroBody {
1341    /// Macro name without the `!`.
1342    pub name: String,
1343    /// Byte range strictly inside the arm's template delimiters.
1344    pub byte_start: usize,
1345    pub byte_end: usize,
1346}
1347
1348/// What call extraction learned about Rust macros beyond the calls themselves.
1349#[derive(Debug, Clone, Default)]
1350pub struct RustMacroFacts {
1351    /// Every `macro_rules!` arm template that was re-parsed for calls.
1352    pub bodies: Vec<RustMacroBody>,
1353    /// Identifiers inside macro token trees that tree-sitter could not parse
1354    /// as Rust, excluding names that were still recognized as callees. Each is
1355    /// a `CallTuple` whose full and short names are the identifier. A call
1356    /// hidden in such a region is invisible to the call graph, so `callers`
1357    /// reports these mentions instead of claiming there are no callers.
1358    /// Only one mention of each name per file is kept: one location per
1359    /// file is enough to point a reader at the macro, and macro-heavy
1360    /// files would otherwise record every local variable many times over.
1361    pub unparsed_mentions: Vec<CallTuple>,
1362    mention_names: HashSet<String>,
1363}
1364
1365impl RustMacroFacts {
1366    fn push_mention(&mut self, mention: CallTuple) {
1367        if self.unparsed_mentions.len() < MAX_UNPARSED_MACRO_MENTIONS_PER_FILE
1368            && self.mention_names.insert(mention.1.clone())
1369        {
1370            self.unparsed_mentions.push(mention);
1371        }
1372    }
1373}
1374
1375/// Rust call extraction including calls written inside macro token trees:
1376/// invocation arguments (`vec![f(x)]`, `tokio::select! { .. }`) and
1377/// `macro_rules!` templates, which tree-sitter keeps as opaque tokens. Each
1378/// token tree is parsed again on its own as Rust; tree-sitter's error recovery
1379/// still yields the calls in most macro argument shapes. Returns the calls
1380/// sorted by position, plus the macro facts gathered on the way.
1381pub fn extract_rust_calls_with_macro_facts(
1382    source: &str,
1383    root: tree_sitter::Node,
1384    byte_start: usize,
1385    byte_end: usize,
1386) -> (Vec<CallTuple>, RustMacroFacts) {
1387    extract_rust_calls_with_macro_facts_with(source, root, byte_start, byte_end, Direct)
1388}
1389
1390/// [`extract_rust_calls_with_macro_facts`], walking the outer tree with
1391/// `nav`. Macro token trees are parsed on their own, so their trees are
1392/// walked directly.
1393pub fn extract_rust_calls_with_macro_facts_with<'tree>(
1394    source: &str,
1395    root: tree_sitter::Node<'tree>,
1396    byte_start: usize,
1397    byte_end: usize,
1398    nav: impl Nav<'tree>,
1399) -> (Vec<CallTuple>, RustMacroFacts) {
1400    let mut results = Vec::new();
1401    let call_kinds = call_node_kinds(LangId::Rust);
1402    collect_calls_full_with(
1403        root,
1404        source,
1405        byte_start,
1406        byte_end,
1407        &call_kinds,
1408        &mut results,
1409        nav,
1410    );
1411    let mut facts = RustMacroFacts::default();
1412    collect_rust_macro_calls_with(
1413        root,
1414        source,
1415        byte_start,
1416        byte_end,
1417        0,
1418        &mut results,
1419        &mut facts,
1420        nav,
1421    );
1422    results.sort_by_key(|(_, _, _, start, end)| (*start, *end));
1423    results.dedup();
1424    facts
1425        .unparsed_mentions
1426        .sort_by_key(|(_, _, _, start, end)| (*start, *end));
1427    (results, facts)
1428}
1429
1430fn collect_rust_macro_calls(
1431    node: tree_sitter::Node<'_>,
1432    source: &str,
1433    byte_start: usize,
1434    byte_end: usize,
1435    depth: u32,
1436    results: &mut Vec<CallTuple>,
1437    facts: &mut RustMacroFacts,
1438) {
1439    collect_rust_macro_calls_with(
1440        node, source, byte_start, byte_end, depth, results, facts, Direct,
1441    );
1442}
1443
1444#[allow(clippy::too_many_arguments)]
1445fn collect_rust_macro_calls_with<'tree>(
1446    node: tree_sitter::Node<'tree>,
1447    source: &str,
1448    byte_start: usize,
1449    byte_end: usize,
1450    depth: u32,
1451    results: &mut Vec<CallTuple>,
1452    facts: &mut RustMacroFacts,
1453    nav: impl Nav<'tree>,
1454) {
1455    // The reparse-depth bound does not bound ordinary AST nesting. The walk
1456    // keeps that traversal off the native stack without dropping nested facts.
1457    nav.walk(node, |node, _| {
1458        visit_rust_macro_node(node, source, byte_start, byte_end, depth, results, facts)
1459    });
1460}
1461
1462fn visit_rust_macro_node(
1463    node: tree_sitter::Node<'_>,
1464    source: &str,
1465    byte_start: usize,
1466    byte_end: usize,
1467    depth: u32,
1468    results: &mut Vec<CallTuple>,
1469    facts: &mut RustMacroFacts,
1470) -> bool {
1471    if depth >= MAX_RUST_MACRO_CALL_DEPTH
1472        || node.end_byte() <= byte_start
1473        || node.start_byte() >= byte_end
1474    {
1475        return false;
1476    }
1477
1478    match node.kind() {
1479        "macro_invocation" => {
1480            let mut cursor = node.walk();
1481            if cursor.goto_first_child() {
1482                loop {
1483                    let child = cursor.node();
1484                    if child.kind() == "token_tree" {
1485                        collect_rust_token_tree_calls(child, source, depth, results, facts);
1486                        break;
1487                    }
1488                    if !cursor.goto_next_sibling() {
1489                        break;
1490                    }
1491                }
1492            }
1493            return false;
1494        }
1495        // A `macro_rules!` template is code that runs wherever the macro is
1496        // expanded. Whole method families are sometimes written inside one,
1497        // so its calls are extracted like any other; the body ranges let the
1498        // call graph tell which calls came from which macro.
1499        "macro_definition" => {
1500            let name = node
1501                .child_by_field_name("name")
1502                .and_then(|name| source.get(name.byte_range()))
1503                .map(str::to_string);
1504            let mut cursor = node.walk();
1505            for rule in node.children(&mut cursor) {
1506                if rule.kind() != "macro_rule" {
1507                    continue;
1508                }
1509                let Some(right) = rule.child_by_field_name("right") else {
1510                    continue;
1511                };
1512                if let Some(name) = &name {
1513                    let range = right.byte_range();
1514                    if range.end > range.start + 1 {
1515                        facts.bodies.push(RustMacroBody {
1516                            name: name.clone(),
1517                            byte_start: range.start + 1,
1518                            byte_end: range.end - 1,
1519                        });
1520                    }
1521                }
1522                collect_rust_token_tree_calls(right, source, depth, results, facts);
1523            }
1524            return false;
1525        }
1526        _ => {}
1527    }
1528
1529    true
1530}
1531
1532test_support_visibility! {
1533fn parse_rust_macro_fragment(fragment: &str) -> Option<tree_sitter::Tree> {
1534    if let Some(tree) = RUST_FRAGMENT_TREES.with(|trees| {
1535        trees
1536            .borrow()
1537            .as_ref()
1538            .and_then(|trees| trees.get(fragment).cloned())
1539    }) {
1540        return Some(tree);
1541    }
1542    // Release the parser borrow before walking the owned tree: nested macros
1543    // can then reuse the same parser without recursive RefCell borrowing.
1544    let tree = RUST_FRAGMENT_PARSER.with(|cached| {
1545        let mut cached = cached.borrow_mut();
1546        if cached.is_none() {
1547            let mut parser = tree_sitter::Parser::new();
1548            parser
1549                .set_language(&crate::parser::grammar_for(LangId::Rust).ok()?)
1550                .ok()?;
1551            #[cfg(any(test, feature = "test-support"))]
1552            RUST_FRAGMENT_PARSER_INITIALIZATIONS.with(|count| count.set(count.get() + 1));
1553            *cached = Some(parser);
1554        }
1555        #[cfg(any(test, feature = "test-support"))]
1556        RUST_FRAGMENT_PARSES.with(|count| count.set(count.get() + 1));
1557        cached.as_mut()?.parse(fragment, None)
1558    })?;
1559    RUST_FRAGMENT_TREES.with(|trees| {
1560        if let Some(trees) = trees.borrow_mut().as_mut() {
1561            trees.insert(fragment.to_string(), tree.clone());
1562        }
1563    });
1564    Some(tree)
1565}
1566}
1567
1568fn collect_rust_token_tree_calls(
1569    token_tree: tree_sitter::Node<'_>,
1570    source: &str,
1571    depth: u32,
1572    results: &mut Vec<CallTuple>,
1573    facts: &mut RustMacroFacts,
1574) {
1575    let range = token_tree.byte_range();
1576    if range.end <= range.start + 1 {
1577        return;
1578    }
1579    let inner_start = range.start + 1;
1580    let inner_end = range.end - 1;
1581    let Some(fragment) = source.get(inner_start..inner_end) else {
1582        return;
1583    };
1584
1585    let Some(tree) = parse_rust_macro_fragment(fragment) else {
1586        return;
1587    };
1588
1589    let mut fragment_calls = Vec::new();
1590    let mut fragment_facts = RustMacroFacts::default();
1591    collect_calls_full(
1592        tree.root_node(),
1593        fragment,
1594        0,
1595        fragment.len(),
1596        &call_node_kinds(LangId::Rust),
1597        &mut fragment_calls,
1598    );
1599    collect_rust_macro_calls(
1600        tree.root_node(),
1601        fragment,
1602        0,
1603        fragment.len(),
1604        depth + 1,
1605        &mut fragment_calls,
1606        &mut fragment_facts,
1607    );
1608    // A call on a macro metavariable (`$value.len()`, `$f(x)`) names nothing
1609    // until the macro is expanded, so it is dropped rather than recorded as a
1610    // call a name-based resolver could bind to an unrelated function.
1611    // `$crate::path` is the exception: in a macro template `$crate` names the
1612    // crate that defines the macro, which is the crate of this file, so it is
1613    // rewritten to the ordinary `crate::path` the resolver understands.
1614    fragment_calls.retain_mut(|(full, _, _, _, _)| {
1615        if full.contains("$crate::") {
1616            *full = full.replace("$crate::", "crate::");
1617        }
1618        !full.contains('$')
1619    });
1620    if tree.root_node().has_error() {
1621        collect_unparsed_mentions(
1622            tree.root_node(),
1623            fragment,
1624            &fragment_calls,
1625            &mut fragment_facts,
1626        );
1627    }
1628
1629    let token_start_row = token_tree.start_position().row as u32;
1630    let remap = |(full, short, line, start, end): CallTuple| {
1631        (
1632            full,
1633            short,
1634            token_start_row + line,
1635            inner_start + start,
1636            inner_start + end,
1637        )
1638    };
1639    results.extend(fragment_calls.into_iter().map(remap));
1640    facts
1641        .bodies
1642        .extend(fragment_facts.bodies.into_iter().map(|body| RustMacroBody {
1643            name: body.name,
1644            byte_start: inner_start + body.byte_start,
1645            byte_end: inner_start + body.byte_end,
1646        }));
1647    for mention in fragment_facts.unparsed_mentions {
1648        facts.push_mention(remap(mention));
1649    }
1650}
1651
1652/// Record the identifiers tree-sitter had to put in `ERROR` nodes while
1653/// re-parsing one macro token tree. Names that were recognized as callees
1654/// anyway are skipped: the call graph already has those calls.
1655fn collect_unparsed_mentions(
1656    root: tree_sitter::Node<'_>,
1657    fragment: &str,
1658    fragment_calls: &[CallTuple],
1659    facts: &mut RustMacroFacts,
1660) {
1661    let callee_names: BTreeSet<&str> = fragment_calls
1662        .iter()
1663        .map(|(_, short, _, _, _)| short.as_str())
1664        .collect();
1665    // Explicit stack instead of recursion: fragments come from arbitrary
1666    // macro input and can nest deeply.
1667    let mut pending = vec![(root, false)];
1668    while let Some((node, in_error)) = pending.pop() {
1669        if facts.unparsed_mentions.len() >= MAX_UNPARSED_MACRO_MENTIONS_PER_FILE {
1670            return;
1671        }
1672        let in_error = in_error || node.is_error();
1673        if in_error && node.kind() == "identifier" {
1674            if let Some(name) = fragment.get(node.byte_range()) {
1675                if !callee_names.contains(name) {
1676                    facts.push_mention((
1677                        name.to_string(),
1678                        name.to_string(),
1679                        node.start_position().row as u32 + 1,
1680                        node.start_byte(),
1681                        node.end_byte(),
1682                    ));
1683                }
1684            }
1685            continue;
1686        }
1687        // Only subtrees that contain an error can hold an unparsed mention.
1688        if !in_error && !node.has_error() {
1689            continue;
1690        }
1691        let mut cursor = node.walk();
1692        for child in node.children(&mut cursor) {
1693            pending.push((child, in_error));
1694        }
1695    }
1696}
1697
1698fn collect_calls_full(
1699    node: tree_sitter::Node,
1700    source: &str,
1701    byte_start: usize,
1702    byte_end: usize,
1703    call_kinds: &[&str],
1704    results: &mut Vec<(String, String, u32, usize, usize)>,
1705) {
1706    collect_calls_full_with(
1707        node, source, byte_start, byte_end, call_kinds, results, Direct,
1708    );
1709}
1710
1711fn collect_calls_full_with<'tree>(
1712    node: tree_sitter::Node<'tree>,
1713    source: &str,
1714    byte_start: usize,
1715    byte_end: usize,
1716    call_kinds: &[&str],
1717    results: &mut Vec<(String, String, u32, usize, usize)>,
1718    nav: impl Nav<'tree>,
1719) {
1720    // Preserve preorder and range pruning while allowing generated expressions
1721    // to nest beyond the refresh worker's native stack capacity.
1722    nav.walk(node, |node, kind| {
1723        let node_start = node.start_byte();
1724        let node_end = node.end_byte();
1725        let overlaps = node_end > byte_start && node_start < byte_end;
1726        if overlaps
1727            && call_kinds.contains(&kind)
1728            && node_start >= byte_start
1729            && node_end <= byte_end
1730        {
1731            if let (Some(full), Some(short)) = (
1732                extract_full_callee(&node, source),
1733                extract_callee_name(&node, source),
1734            ) {
1735                results.push((
1736                    full,
1737                    short,
1738                    node.start_position().row as u32 + 1,
1739                    node_start,
1740                    node_end,
1741                ));
1742            }
1743        }
1744        overlaps
1745    });
1746}