Skip to main content

aft_parse/callgraph_store/
single_walk.rs

1//! The call-graph extractor: one walk over each file's syntax tree.
2//!
3//! A [`SyntaxIndex`] walks the tree once; every pass of the extraction reads
4//! the nodes, kinds and neighbours it recorded instead of walking the tree
5//! again or asking tree-sitter to search for a parent. The passes are the
6//! ones the extractor always ran, with the same rules; only how they find
7//! their nodes changed. `CallgraphBlob::extract_reference` keeps the
8//! extractor this replaced, for the extraction gate.
9//!
10//! This module also parses for extraction, including incremental reparsing
11//! after an edit.
12
13use std::borrow::Cow;
14use std::collections::HashMap;
15use std::path::Path;
16
17use super::syntax_index::SyntaxIndex;
18use super::{
19    assign_ordinals, blob_imports, blob_refs, blob_symbols, dispatch, language_id, structural_ref,
20    AstPreorderNode, BlobRef, BlobRefKind, CallgraphBlob, ManifestJoinError, ParseBlob, Parser,
21};
22use crate::callgraph;
23use crate::callgraph_store::facts::{FactPaths, NoProjectFacts};
24use crate::parser::LangId;
25
26test_support_visibility! {
27/// Parses `source` as `language` and extracts its parse output.
28pub(super) fn extract(
29    source: &str,
30    language: &str,
31    extractor_version: String,
32) -> Result<CallgraphBlob, ManifestJoinError> {
33    let lang = language_id(language)
34        .ok_or_else(|| ManifestJoinError::UnsupportedLanguage(language.to_string()))?;
35    let tree = parse_source(source, lang)?;
36    extract_tree(source, language, extractor_version, &tree, None)
37}
38}
39
40/// Extracts the parse output of `source` from `tree`, its syntax tree in
41/// `language`. With `outline`, also fills it with the file's symbols as the
42/// parser extracts them, before the call graph changes any.
43pub(super) fn extract_tree(
44    source: &str,
45    language: &str,
46    extractor_version: String,
47    tree: &tree_sitter::Tree,
48    outline: Option<&mut Vec<crate::symbols::Symbol>>,
49) -> Result<CallgraphBlob, ManifestJoinError> {
50    let lang = language_id(language)
51        .ok_or_else(|| ManifestJoinError::UnsupportedLanguage(language.to_string()))?;
52    let root = tree.root_node();
53    let index = SyntaxIndex::new(root);
54    let ast_nodes = ast_preorder_nodes(&index);
55    let line_index = crate::callgraph_store::LineIndex::new(source);
56    let mut data = callgraph::build_file_data_from_index(
57        Path::new("__callgraph_blob__"),
58        source,
59        lang,
60        tree,
61        &line_index,
62        &index,
63        outline,
64    )
65    .map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
66    if lang == LangId::Rust {
67        crate::callgraph_store::extend_rust_imports_from_uses(
68            source,
69            index
70                .preorder_kinds()
71                .filter(|(_, kind)| *kind == "use_declaration")
72                .map(|(node, _)| node),
73            &mut data,
74        );
75    }
76    let mut symbols = blob_symbols(&data);
77    let mut imports = blob_imports(&data);
78    let mut refs = blob_refs(&line_index, &data);
79    if lang == LangId::Luau {
80        refs.extend(
81            crate::luau::exports(source, root)
82                .into_iter()
83                .map(|(name, export)| BlobRef {
84                    ordinal: 0,
85                    kind: BlobRefKind::ExportAlias,
86                    caller_symbol: None,
87                    short_name: None,
88                    full_ref: Some(name.clone()),
89                    module_path: None,
90                    line: 1,
91                    byte_start: 0,
92                    byte_end: source.len(),
93                    path_override: None,
94                    local_name: Some(name),
95                    requested_name: Some(export.symbol),
96                    namespace_alias: None,
97                    wildcard: false,
98                    import_kind: Some("export_alias".to_string()),
99                }),
100        );
101    }
102    if lang == LangId::Rust {
103        refs.extend(rust_module_refs(source, &index));
104    }
105    let paths = FactPaths {
106        root: Path::new("/"),
107        facts: &NoProjectFacts,
108    };
109    let file = Path::new("/__callgraph_blob__");
110    let mut structural = crate::callgraph_store::collect_reexport_refs_with_line_index(
111        paths.root,
112        file,
113        "__callgraph_blob__",
114        source,
115        lang,
116        &crate::callgraph::ModuleResolutionMemo::default(),
117        &paths,
118        &line_index,
119        Some(root),
120    )
121    .raw_refs;
122    structural.extend(
123        crate::callgraph_store::collect_source_less_export_alias_refs_with_line_index(
124            "__callgraph_blob__",
125            source,
126            &line_index,
127        )
128        .raw_refs,
129    );
130    if lang == LangId::Rust {
131        structural.extend(
132            crate::callgraph_store::collect_rust_pub_use_reexport_refs(
133                paths.root,
134                file,
135                "__callgraph_blob__",
136                &data.import_block.imports,
137                &line_index,
138                &paths,
139            )
140            .raw_refs,
141        );
142    }
143    refs.extend(structural.into_iter().map(structural_ref));
144    assign_ordinals(
145        &ast_nodes,
146        &line_index,
147        &mut symbols,
148        &mut imports,
149        &mut refs,
150    );
151    let mut exported_symbols = data.exported_symbols.clone();
152    exported_symbols.sort();
153    let mut callable_symbols = data.calls_by_symbol.keys().cloned().collect::<Vec<_>>();
154    callable_symbols.sort();
155    refs.sort_by(|left, right| {
156        (
157            left.ordinal,
158            left.kind,
159            left.byte_start,
160            left.byte_end,
161            left.full_ref.as_deref(),
162            left.caller_symbol.as_deref(),
163        )
164            .cmp(&(
165                right.ordinal,
166                right.kind,
167                right.byte_start,
168                right.byte_end,
169                right.full_ref.as_deref(),
170                right.caller_symbol.as_deref(),
171            ))
172    });
173    refs.dedup_by(|left, right| {
174        left.ordinal == right.ordinal
175            && left.kind == right.kind
176            && left.byte_start == right.byte_start
177            && left.byte_end == right.byte_end
178            && left.full_ref == right.full_ref
179            && left.caller_symbol == right.caller_symbol
180    });
181
182    let mut parse = ParseBlob {
183        entry_point_symbols: data
184            .symbol_metadata
185            .iter()
186            .filter(|(_, meta)| meta.entry_point_attribute.is_some())
187            .map(|(name, _)| name.clone())
188            .collect(),
189        dispatch: dispatch::DispatchFacts::default(),
190        extractor_version,
191        language: language.to_string(),
192        ast_nodes,
193        symbols,
194        default_export_symbol: data.default_export_symbol,
195        exported_symbols,
196        callable_symbols,
197        imports,
198        python_bindings: data.python_bindings,
199        refs,
200    };
201    parse.entry_point_symbols.sort();
202    parse.dispatch = dispatch::extract_with(source, lang, root, &mut parse, &index)?;
203    Ok(CallgraphBlob::Parse(parse))
204}
205
206/// Every node's kind and span in preorder, numbered by position.
207fn ast_preorder_nodes(index: &SyntaxIndex<'_>) -> Vec<AstPreorderNode> {
208    index
209        .preorder_kinds()
210        .enumerate()
211        .map(|(ordinal, (node, kind))| AstPreorderNode {
212            ordinal: ordinal as u32,
213            kind: Cow::Borrowed(kind),
214            byte_start: node.start_byte(),
215            byte_end: node.end_byte(),
216        })
217        .collect()
218}
219
220/// A reference for each `mod name;` declaration (a module whose body is in
221/// another file).
222fn rust_module_refs(source: &str, index: &SyntaxIndex<'_>) -> Vec<BlobRef> {
223    let mut refs = Vec::new();
224    for (node, kind) in index.preorder_kinds() {
225        if kind != "mod_item"
226            || node
227                .named_children(&mut node.walk())
228                .any(|child| child.kind() == "declaration_list")
229        {
230            continue;
231        }
232        let Some(name) = node.child_by_field_name("name") else {
233            continue;
234        };
235        let module_name = source[name.byte_range()].to_string();
236        refs.push(BlobRef {
237            ordinal: 0,
238            kind: BlobRefKind::Module,
239            caller_symbol: None,
240            short_name: Some(module_name.clone()),
241            full_ref: Some(
242                if crate::callgraph_store::rust_module_has_macro_use_with(source, node, index) {
243                    format!("#[macro_use] mod {module_name};")
244                } else {
245                    module_name.clone()
246                },
247            ),
248            module_path: Some(module_name),
249            line: node.start_position().row as u32 + 1,
250            byte_start: node.start_byte(),
251            byte_end: node.end_byte(),
252            path_override: crate::callgraph_store::rust_module_path_override_with(
253                source, node, index,
254            )
255            .map(str::to_string),
256            local_name: None,
257            requested_name: None,
258            namespace_alias: None,
259            wildcard: false,
260            import_kind: None,
261        });
262    }
263    refs
264}
265
266/// Parses `source` as `lang` for extraction, reusing a header's tree when
267/// its language was chosen by parsing it. Markdown nested too deeply for its
268/// grammar is refused (see [`crate::parser::markdown_too_deep_to_parse`]).
269pub fn parse_source(source: &str, lang: LangId) -> Result<tree_sitter::Tree, ManifestJoinError> {
270    refuse_unsafe_markdown(source, lang)?;
271    if let Some(tree) = crate::parser::cached_header_tree(source, lang) {
272        return Ok(tree);
273    }
274    with_parser(lang, |parser| {
275        crate::parser::parse_with_parser(
276            parser,
277            std::path::Path::new("<index-content>"),
278            source,
279            lang,
280            None,
281        )
282        .map_err(super::extraction_error)
283    })
284}
285
286/// Fails for Markdown the Markdown grammar cannot parse without aborting
287/// the process.
288fn refuse_unsafe_markdown(source: &str, lang: LangId) -> Result<(), ManifestJoinError> {
289    if crate::parser::markdown_too_deep_to_parse(lang, source) {
290        return Err(ManifestJoinError::Parse(
291            crate::parser::MARKDOWN_TOO_DEEP.to_string(),
292        ));
293    }
294    Ok(())
295}
296
297/// Parses `source` as `lang` after an edit from `previous_source`, whose
298/// tree in the same language is `previous`. The edit given to tree-sitter is
299/// the span between the texts' common prefix and common suffix; tree-sitter
300/// reuses every subtree the edit does not touch, and the tree it returns is
301/// the tree a fresh parse of `source` gives.
302pub fn reparse_source(
303    previous_source: &str,
304    previous: &tree_sitter::Tree,
305    source: &str,
306    lang: LangId,
307) -> Result<tree_sitter::Tree, ManifestJoinError> {
308    refuse_unsafe_markdown(source, lang)?;
309    let Some(edit) = text_edit(previous_source.as_bytes(), source.as_bytes()) else {
310        return Ok(previous.clone());
311    };
312    let mut tree = previous.clone();
313    tree.edit(&edit);
314    with_parser(lang, |parser| {
315        crate::parser::parse_with_parser(
316            parser,
317            std::path::Path::new("<index-content>"),
318            source,
319            lang,
320            Some(&tree),
321        )
322        .map_err(super::extraction_error)
323    })
324}
325
326test_support_visibility! {
327/// The single edit that turns `old` into `new`: everything between their
328/// common prefix and their common suffix. `None` when they are equal.
329fn text_edit(old: &[u8], new: &[u8]) -> Option<tree_sitter::InputEdit> {
330    if old == new {
331        return None;
332    }
333    let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
334    let longest_suffix = old.len().min(new.len()) - prefix;
335    let suffix = old
336        .iter()
337        .rev()
338        .zip(new.iter().rev())
339        .take(longest_suffix)
340        .take_while(|(a, b)| a == b)
341        .count();
342    // Tree-sitter counts rows by '\n' and columns in bytes.
343    let point = |text: &[u8], byte: usize| {
344        let before = &text[..byte];
345        let row = before.iter().filter(|&&b| b == b'\n').count();
346        let line_start = before
347            .iter()
348            .rposition(|&b| b == b'\n')
349            .map_or(0, |i| i + 1);
350        tree_sitter::Point::new(row, byte - line_start)
351    };
352    Some(tree_sitter::InputEdit {
353        start_byte: prefix,
354        old_end_byte: old.len() - suffix,
355        new_end_byte: new.len() - suffix,
356        start_position: point(old, prefix),
357        old_end_position: point(old, old.len() - suffix),
358        new_end_position: point(new, new.len() - suffix),
359    })
360}
361}
362
363thread_local! {
364    // A parser is mutable and not shareable, so each extraction thread keeps
365    // one per grammar instead of building one per file.
366    static EXTRACTION_PARSERS: std::cell::RefCell<HashMap<LangId, Parser>> =
367        std::cell::RefCell::new(HashMap::new());
368}
369
370#[cfg(all(
371    any(test, feature = "test-support"),
372    feature = "test-hooks",
373    feature = "wasm-grammars"
374))]
375pub fn install_luau_parser_for_test(parser: Parser) {
376    EXTRACTION_PARSERS.with(|parsers| {
377        parsers.borrow_mut().insert(LangId::Luau, parser);
378    });
379}
380
381#[cfg(all(
382    any(test, feature = "test-support"),
383    feature = "test-hooks",
384    feature = "wasm-grammars"
385))]
386pub fn retains_luau_parser_for_test() -> bool {
387    EXTRACTION_PARSERS.with(|parsers| parsers.borrow().contains_key(&LangId::Luau))
388}
389
390fn with_parser(
391    lang: LangId,
392    parse: impl FnOnce(&mut Parser) -> Result<tree_sitter::Tree, ManifestJoinError>,
393) -> Result<tree_sitter::Tree, ManifestJoinError> {
394    EXTRACTION_PARSERS.with(|parsers| {
395        let mut parsers = parsers.borrow_mut();
396        let mut parser = match parsers.remove(&lang) {
397            Some(parser) => parser,
398            None => {
399                let mut parser = Parser::new();
400                crate::parser::initialize_parser(&mut parser, lang)
401                    .map_err(super::extraction_error)?;
402                parser
403            }
404        };
405        #[cfg(any(test, feature = "test-support"))]
406        parser.note_parse();
407        let result = parse(&mut parser);
408        if result.is_ok() {
409            parsers.insert(lang, parser);
410        }
411        result
412    })
413}