aft-parse 0.67.1

Syntax parsing, imports and call resolution for Agent Foundational Toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! The call-graph extractor: one walk over each file's syntax tree.
//!
//! A [`SyntaxIndex`] walks the tree once; every pass of the extraction reads
//! the nodes, kinds and neighbours it recorded instead of walking the tree
//! again or asking tree-sitter to search for a parent. The passes are the
//! ones the extractor always ran, with the same rules; only how they find
//! their nodes changed. `CallgraphBlob::extract_reference` keeps the
//! extractor this replaced, for the extraction gate.
//!
//! This module also parses for extraction, including incremental reparsing
//! after an edit.

use std::borrow::Cow;
use std::collections::HashMap;
use std::path::Path;

use super::syntax_index::SyntaxIndex;
use super::{
    assign_ordinals, blob_imports, blob_refs, blob_symbols, dispatch, language_id, structural_ref,
    AstPreorderNode, BlobRef, BlobRefKind, CallgraphBlob, ManifestJoinError, ParseBlob, Parser,
};
use crate::callgraph;
use crate::callgraph_store::facts::{FactPaths, NoProjectFacts};
use crate::parser::LangId;

test_support_visibility! {
/// Parses `source` as `language` and extracts its parse output.
pub(super) fn extract(
    source: &str,
    language: &str,
    extractor_version: String,
) -> Result<CallgraphBlob, ManifestJoinError> {
    let lang = language_id(language)
        .ok_or_else(|| ManifestJoinError::UnsupportedLanguage(language.to_string()))?;
    let tree = parse_source(source, lang)?;
    extract_tree(source, language, extractor_version, &tree, None)
}
}

/// Extracts the parse output of `source` from `tree`, its syntax tree in
/// `language`. With `outline`, also fills it with the file's symbols as the
/// parser extracts them, before the call graph changes any.
pub(super) fn extract_tree(
    source: &str,
    language: &str,
    extractor_version: String,
    tree: &tree_sitter::Tree,
    outline: Option<&mut Vec<crate::symbols::Symbol>>,
) -> Result<CallgraphBlob, ManifestJoinError> {
    let lang = language_id(language)
        .ok_or_else(|| ManifestJoinError::UnsupportedLanguage(language.to_string()))?;
    let root = tree.root_node();
    let index = SyntaxIndex::new(root);
    let ast_nodes = ast_preorder_nodes(&index);
    let line_index = crate::callgraph_store::LineIndex::new(source);
    let mut data = callgraph::build_file_data_from_index(
        Path::new("__callgraph_blob__"),
        source,
        lang,
        tree,
        &line_index,
        &index,
        outline,
    )
    .map_err(|error| ManifestJoinError::Parse(error.to_string()))?;
    if lang == LangId::Rust {
        crate::callgraph_store::extend_rust_imports_from_uses(
            source,
            index
                .preorder_kinds()
                .filter(|(_, kind)| *kind == "use_declaration")
                .map(|(node, _)| node),
            &mut data,
        );
    }
    let mut symbols = blob_symbols(&data);
    let mut imports = blob_imports(&data);
    let mut refs = blob_refs(&line_index, &data);
    if lang == LangId::Luau {
        refs.extend(
            crate::luau::exports(source, root)
                .into_iter()
                .map(|(name, export)| BlobRef {
                    ordinal: 0,
                    kind: BlobRefKind::ExportAlias,
                    caller_symbol: None,
                    short_name: None,
                    full_ref: Some(name.clone()),
                    module_path: None,
                    line: 1,
                    byte_start: 0,
                    byte_end: source.len(),
                    path_override: None,
                    local_name: Some(name),
                    requested_name: Some(export.symbol),
                    namespace_alias: None,
                    wildcard: false,
                    import_kind: Some("export_alias".to_string()),
                }),
        );
    }
    if lang == LangId::Rust {
        refs.extend(rust_module_refs(source, &index));
    }
    let paths = FactPaths {
        root: Path::new("/"),
        facts: &NoProjectFacts,
    };
    let file = Path::new("/__callgraph_blob__");
    let mut structural = crate::callgraph_store::collect_reexport_refs_with_line_index(
        paths.root,
        file,
        "__callgraph_blob__",
        source,
        lang,
        &crate::callgraph::ModuleResolutionMemo::default(),
        &paths,
        &line_index,
        Some(root),
    )
    .raw_refs;
    structural.extend(
        crate::callgraph_store::collect_source_less_export_alias_refs_with_line_index(
            "__callgraph_blob__",
            source,
            &line_index,
        )
        .raw_refs,
    );
    if lang == LangId::Rust {
        structural.extend(
            crate::callgraph_store::collect_rust_pub_use_reexport_refs(
                paths.root,
                file,
                "__callgraph_blob__",
                &data.import_block.imports,
                &line_index,
                &paths,
            )
            .raw_refs,
        );
    }
    refs.extend(structural.into_iter().map(structural_ref));
    assign_ordinals(
        &ast_nodes,
        &line_index,
        &mut symbols,
        &mut imports,
        &mut refs,
    );
    let mut exported_symbols = data.exported_symbols.clone();
    exported_symbols.sort();
    let mut callable_symbols = data.calls_by_symbol.keys().cloned().collect::<Vec<_>>();
    callable_symbols.sort();
    refs.sort_by(|left, right| {
        (
            left.ordinal,
            left.kind,
            left.byte_start,
            left.byte_end,
            left.full_ref.as_deref(),
            left.caller_symbol.as_deref(),
        )
            .cmp(&(
                right.ordinal,
                right.kind,
                right.byte_start,
                right.byte_end,
                right.full_ref.as_deref(),
                right.caller_symbol.as_deref(),
            ))
    });
    refs.dedup_by(|left, right| {
        left.ordinal == right.ordinal
            && left.kind == right.kind
            && left.byte_start == right.byte_start
            && left.byte_end == right.byte_end
            && left.full_ref == right.full_ref
            && left.caller_symbol == right.caller_symbol
    });

    let mut parse = ParseBlob {
        entry_point_symbols: data
            .symbol_metadata
            .iter()
            .filter(|(_, meta)| meta.entry_point_attribute.is_some())
            .map(|(name, _)| name.clone())
            .collect(),
        dispatch: dispatch::DispatchFacts::default(),
        extractor_version,
        language: language.to_string(),
        ast_nodes,
        symbols,
        default_export_symbol: data.default_export_symbol,
        exported_symbols,
        callable_symbols,
        imports,
        python_bindings: data.python_bindings,
        refs,
    };
    parse.entry_point_symbols.sort();
    parse.dispatch = dispatch::extract_with(source, lang, root, &mut parse, &index)?;
    Ok(CallgraphBlob::Parse(parse))
}

/// Every node's kind and span in preorder, numbered by position.
fn ast_preorder_nodes(index: &SyntaxIndex<'_>) -> Vec<AstPreorderNode> {
    index
        .preorder_kinds()
        .enumerate()
        .map(|(ordinal, (node, kind))| AstPreorderNode {
            ordinal: ordinal as u32,
            kind: Cow::Borrowed(kind),
            byte_start: node.start_byte(),
            byte_end: node.end_byte(),
        })
        .collect()
}

/// A reference for each `mod name;` declaration (a module whose body is in
/// another file).
fn rust_module_refs(source: &str, index: &SyntaxIndex<'_>) -> Vec<BlobRef> {
    let mut refs = Vec::new();
    for (node, kind) in index.preorder_kinds() {
        if kind != "mod_item"
            || node
                .named_children(&mut node.walk())
                .any(|child| child.kind() == "declaration_list")
        {
            continue;
        }
        let Some(name) = node.child_by_field_name("name") else {
            continue;
        };
        let module_name = source[name.byte_range()].to_string();
        refs.push(BlobRef {
            ordinal: 0,
            kind: BlobRefKind::Module,
            caller_symbol: None,
            short_name: Some(module_name.clone()),
            full_ref: Some(
                if crate::callgraph_store::rust_module_has_macro_use_with(source, node, index) {
                    format!("#[macro_use] mod {module_name};")
                } else {
                    module_name.clone()
                },
            ),
            module_path: Some(module_name),
            line: node.start_position().row as u32 + 1,
            byte_start: node.start_byte(),
            byte_end: node.end_byte(),
            path_override: crate::callgraph_store::rust_module_path_override_with(
                source, node, index,
            )
            .map(str::to_string),
            local_name: None,
            requested_name: None,
            namespace_alias: None,
            wildcard: false,
            import_kind: None,
        });
    }
    refs
}

/// Parses `source` as `lang` for extraction, reusing a header's tree when
/// its language was chosen by parsing it. Markdown nested too deeply for its
/// grammar is refused (see [`crate::parser::markdown_too_deep_to_parse`]).
pub fn parse_source(source: &str, lang: LangId) -> Result<tree_sitter::Tree, ManifestJoinError> {
    refuse_unsafe_markdown(source, lang)?;
    if let Some(tree) = crate::parser::cached_header_tree(source, lang) {
        return Ok(tree);
    }
    with_parser(lang, |parser| {
        crate::parser::parse_with_parser(
            parser,
            std::path::Path::new("<index-content>"),
            source,
            lang,
            None,
        )
        .map_err(super::extraction_error)
    })
}

/// Fails for Markdown the Markdown grammar cannot parse without aborting
/// the process.
fn refuse_unsafe_markdown(source: &str, lang: LangId) -> Result<(), ManifestJoinError> {
    if crate::parser::markdown_too_deep_to_parse(lang, source) {
        return Err(ManifestJoinError::Parse(
            crate::parser::MARKDOWN_TOO_DEEP.to_string(),
        ));
    }
    Ok(())
}

/// Parses `source` as `lang` after an edit from `previous_source`, whose
/// tree in the same language is `previous`. The edit given to tree-sitter is
/// the span between the texts' common prefix and common suffix; tree-sitter
/// reuses every subtree the edit does not touch, and the tree it returns is
/// the tree a fresh parse of `source` gives.
pub fn reparse_source(
    previous_source: &str,
    previous: &tree_sitter::Tree,
    source: &str,
    lang: LangId,
) -> Result<tree_sitter::Tree, ManifestJoinError> {
    refuse_unsafe_markdown(source, lang)?;
    let Some(edit) = text_edit(previous_source.as_bytes(), source.as_bytes()) else {
        return Ok(previous.clone());
    };
    let mut tree = previous.clone();
    tree.edit(&edit);
    with_parser(lang, |parser| {
        crate::parser::parse_with_parser(
            parser,
            std::path::Path::new("<index-content>"),
            source,
            lang,
            Some(&tree),
        )
        .map_err(super::extraction_error)
    })
}

test_support_visibility! {
/// The single edit that turns `old` into `new`: everything between their
/// common prefix and their common suffix. `None` when they are equal.
fn text_edit(old: &[u8], new: &[u8]) -> Option<tree_sitter::InputEdit> {
    if old == new {
        return None;
    }
    let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
    let longest_suffix = old.len().min(new.len()) - prefix;
    let suffix = old
        .iter()
        .rev()
        .zip(new.iter().rev())
        .take(longest_suffix)
        .take_while(|(a, b)| a == b)
        .count();
    // Tree-sitter counts rows by '\n' and columns in bytes.
    let point = |text: &[u8], byte: usize| {
        let before = &text[..byte];
        let row = before.iter().filter(|&&b| b == b'\n').count();
        let line_start = before
            .iter()
            .rposition(|&b| b == b'\n')
            .map_or(0, |i| i + 1);
        tree_sitter::Point::new(row, byte - line_start)
    };
    Some(tree_sitter::InputEdit {
        start_byte: prefix,
        old_end_byte: old.len() - suffix,
        new_end_byte: new.len() - suffix,
        start_position: point(old, prefix),
        old_end_position: point(old, old.len() - suffix),
        new_end_position: point(new, new.len() - suffix),
    })
}
}

thread_local! {
    // A parser is mutable and not shareable, so each extraction thread keeps
    // one per grammar instead of building one per file.
    static EXTRACTION_PARSERS: std::cell::RefCell<HashMap<LangId, Parser>> =
        std::cell::RefCell::new(HashMap::new());
}

#[cfg(all(
    any(test, feature = "test-support"),
    feature = "test-hooks",
    feature = "wasm-grammars"
))]
pub fn install_luau_parser_for_test(parser: Parser) {
    EXTRACTION_PARSERS.with(|parsers| {
        parsers.borrow_mut().insert(LangId::Luau, parser);
    });
}

#[cfg(all(
    any(test, feature = "test-support"),
    feature = "test-hooks",
    feature = "wasm-grammars"
))]
pub fn retains_luau_parser_for_test() -> bool {
    EXTRACTION_PARSERS.with(|parsers| parsers.borrow().contains_key(&LangId::Luau))
}

fn with_parser(
    lang: LangId,
    parse: impl FnOnce(&mut Parser) -> Result<tree_sitter::Tree, ManifestJoinError>,
) -> Result<tree_sitter::Tree, ManifestJoinError> {
    EXTRACTION_PARSERS.with(|parsers| {
        let mut parsers = parsers.borrow_mut();
        let mut parser = match parsers.remove(&lang) {
            Some(parser) => parser,
            None => {
                let mut parser = Parser::new();
                crate::parser::initialize_parser(&mut parser, lang)
                    .map_err(super::extraction_error)?;
                parser
            }
        };
        #[cfg(any(test, feature = "test-support"))]
        parser.note_parse();
        let result = parse(&mut parser);
        if result.is_ok() {
            parsers.insert(lang, parser);
        }
        result
    })
}