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
414
415
416
417
418
419
420
421
422
423
//! In-memory Rust declaration and lexical-binding indexes. Graph producers
//! reuse their existing return and receiver fact fields; no index is serialized.

// Every map here is looked up, never iterated in an order that shows in
// the output, so a fast hash serves them.
use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
use std::ops::Range;
use tree_sitter::Node;

use super::join::syntax_index::Nav;

test_support_visibility! {
#[derive(Clone, Debug)]
pub(super) struct Declaration {
    pub symbol: String,
    pub owner: Option<String>,
    pub return_type: Option<String>,
    pub bytes: Range<usize>,
}
}

pub(super) fn has_self_parameter(node: Node<'_>, source: &str) -> bool {
    node.child_by_field_name("parameters")
        .is_some_and(|parameters| {
            parameters
                .named_children(&mut parameters.walk())
                .any(|parameter| {
                    parameter.kind() == "self_parameter"
                        || parameter
                            .child_by_field_name("pattern")
                            .is_some_and(|pattern| {
                                text(pattern, source).trim_start_matches("mut ") == "self"
                            })
                })
        })
}

test_support_visibility! {
#[derive(Clone, Debug)]
pub(super) enum Initializer {
    Call { callee: String },
    Nominal(String),
}
}

test_support_visibility! {
#[derive(Clone, Debug)]
pub(super) struct Binding {
    start: usize,
    scope: Range<usize>,
    pub annotation: Option<String>,
    pub initializer: Option<Initializer>,
}
}

test_support_visibility! {
#[derive(Default)]
pub(super) struct RustBindings {
    declarations: HashMap<String, Option<usize>>,
    symbols: HashMap<usize, usize>,
    records: Vec<Declaration>,
    calls: HashMap<usize, usize>,
    bindings: HashMap<(usize, String), Vec<Binding>>,
    bounds: HashMap<(usize, String), String>,
    parameters: HashSet<(usize, String)>,
    generic_functions: HashSet<usize>,
    unit_structs: HashMap<String, bool>,
}
}

fn text<'a>(node: Node<'_>, source: &'a str) -> &'a str {
    &source[node.byte_range()]
}

fn names(pattern: Node<'_>, source: &str) -> Vec<String> {
    let mut names = Vec::new();
    let mut stack = vec![pattern];
    while let Some(node) = stack.pop() {
        if node.kind() == "identifier" {
            names.push(text(node, source).to_string());
        }
        stack.extend(node.named_children(&mut node.walk()));
    }
    names
}

fn identity<'tree>(
    node: Node<'tree>,
    source: &str,
    types: &HashSet<String>,
    nav: impl Nav<'tree>,
) -> Option<(String, Option<String>)> {
    let name = text(node.child_by_field_name("name")?, source);
    let mut scope = Vec::new();
    let mut owner = None;
    let mut parent = nav.parent(node);
    let mut implementation = false;
    let mut qualify = false;
    while let Some(ancestor) = parent {
        let ancestor_kind = nav.kind(ancestor);
        if ancestor_kind == "impl_item" && !implementation {
            let ty = text(ancestor.child_by_field_name("type")?, source);
            let base = ty.split('<').next().unwrap_or(ty);
            let local = types.contains(&crate::callgraph::rust_module_qualified_name(
                ancestor, source, base, nav,
            ));
            qualify = local
                || ancestor
                    .child_by_field_name("trait")
                    .is_some_and(|trait_node| {
                        let name = text(trait_node, source)
                            .split('<')
                            .next()
                            .unwrap_or_default();
                        types.contains(&crate::callgraph::rust_module_qualified_name(
                            ancestor, source, name, nav,
                        ))
                    });
            let generic =
                ancestor
                    .child_by_field_name("type_parameters")
                    .is_some_and(|parameters| {
                        parameters
                            .named_children(&mut parameters.walk())
                            .any(|parameter| {
                                parameter
                                    .child_by_field_name("name")
                                    .is_some_and(|name| text(name, source) == ty)
                            })
                    });
            owner = (local && !generic)
                .then(|| crate::callgraph::rust_module_qualified_name(ancestor, source, ty, nav));
            scope.push(
                if let Some(trait_node) = ancestor.child_by_field_name("trait") {
                    format!("{} for {ty}", text(trait_node, source))
                } else {
                    ty.to_string()
                },
            );
            implementation = true;
            parent = nav.parent(ancestor);
            continue;
        }
        if ancestor_kind == "mod_item" && (!implementation || qualify)
            || ancestor_kind == "trait_item" && !implementation
        {
            let name = text(ancestor.child_by_field_name("name")?, source).to_string();
            if ancestor_kind == "trait_item" {
                owner = Some(crate::callgraph::rust_module_qualified_name(
                    ancestor, source, &name, nav,
                ));
            }
            scope.push(name);
        }
        parent = nav.parent(ancestor);
    }
    scope.reverse();
    scope.push(name.to_string());
    Some((scope.join("::"), owner))
}

impl RustBindings {
    #[cfg(any(test, feature = "test-support"))]
    pub fn new(source: &str, root: Node<'_>) -> Self {
        Self::new_with(source, root, super::join::syntax_index::Direct)
    }

    #[cfg(any(test, feature = "test-support"))]
    pub fn unit_struct(&self, symbol: &str) -> bool {
        self.unit_structs.get(symbol).copied() == Some(true)
    }

    /// [`RustBindings::new`], walking and looking up with `nav`.
    pub fn new_with<'tree>(source: &str, root: Node<'tree>, nav: impl Nav<'tree>) -> Self {
        let mut result = Self::default();
        let mut types = HashSet::default();
        nav.walk_named(root, |node, kind| {
            if matches!(
                kind,
                "struct_item" | "enum_item" | "trait_item" | "type_item"
            ) {
                if let Some(name) = node.child_by_field_name("name") {
                    types.insert(crate::callgraph::rust_module_qualified_name(
                        node,
                        source,
                        text(name, source),
                        nav,
                    ));
                }
            }
            true
        });
        let mut stack = vec![(root, None, root.byte_range())];
        while let Some((node, mut callable, mut scope)) = stack.pop() {
            let kind = nav.kind(node);
            if kind == "struct_item" {
                if let Some(name) = node.child_by_field_name("name") {
                    let mut parts = vec![text(name, source).to_string()];
                    let mut parent = nav.parent(node);
                    while let Some(ancestor) = parent {
                        if nav.kind(ancestor) == "mod_item" {
                            if let Some(name) = ancestor.child_by_field_name("name") {
                                parts.push(text(name, source).to_string());
                            }
                        }
                        parent = nav.parent(ancestor);
                    }
                    parts.reverse();
                    result
                        .unit_structs
                        .entry(parts.join("::"))
                        .and_modify(|unit| *unit = false)
                        .or_insert(node.child_by_field_name("body").is_none());
                }
            }
            if matches!(kind, "function_item" | "closure_expression") {
                callable = Some(node.start_byte());
                scope = node.byte_range();
                if let Some(parameters) = node.child_by_field_name("parameters") {
                    for name in names(parameters, source) {
                        result
                            .bindings
                            .entry((node.start_byte(), name))
                            .or_default()
                            .push(Binding {
                                start: parameters.start_byte(),
                                scope: scope.clone(),
                                annotation: None,
                                initializer: None,
                            });
                    }
                }
                if let Some(parameters) = node.child_by_field_name("type_parameters") {
                    result.generic_functions.insert(node.start_byte());
                    for parameter in parameters.named_children(&mut parameters.walk()) {
                        if let Some(name) = parameter.child_by_field_name("name") {
                            result
                                .parameters
                                .insert((node.start_byte(), text(name, source).to_string()));
                        }
                        if let (Some(name), Some(bounds)) = (
                            parameter.child_by_field_name("name"),
                            parameter.child_by_field_name("bounds"),
                        ) {
                            result.bounds.insert(
                                (node.start_byte(), text(name, source).to_string()),
                                text(bounds, source).to_string(),
                            );
                        }
                    }
                }
                let mut parent = nav.parent(node);
                while let Some(ancestor) = parent {
                    if nav.kind(ancestor) == "impl_item" {
                        if let Some(parameters) = ancestor.child_by_field_name("type_parameters") {
                            result.generic_functions.insert(node.start_byte());
                            for parameter in parameters.named_children(&mut parameters.walk()) {
                                if let Some(name) = parameter.child_by_field_name("name") {
                                    let key = (node.start_byte(), text(name, source).to_string());
                                    if result.parameters.insert(key.clone()) {
                                        if let Some(bounds) =
                                            parameter.child_by_field_name("bounds")
                                        {
                                            result
                                                .bounds
                                                .insert(key, text(bounds, source).to_string());
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    }
                    parent = nav.parent(ancestor);
                }
            }
            if kind == "block" {
                scope = node.byte_range();
            }
            if matches!(kind, "function_item" | "function_signature_item") {
                if let Some((symbol, owner)) = identity(node, source, &types, nav) {
                    let declaration = Declaration {
                        symbol: symbol.clone(),
                        owner,
                        return_type: node
                            .child_by_field_name("return_type")
                            .map(|n| text(n, source).to_string()),
                        bytes: node.byte_range(),
                    };
                    let position = result.records.len();
                    result.symbols.insert(node.start_byte(), position);
                    result
                        .declarations
                        .entry(symbol)
                        .and_modify(|old| *old = None)
                        .or_insert(Some(position));
                    result.records.push(declaration);
                }
            }
            if let Some(callable) = callable {
                if kind == "call_expression" {
                    result.calls.insert(node.start_byte(), callable);
                }
                if kind == "let_declaration" || kind == "parameter" {
                    if let Some(pattern) = node.child_by_field_name("pattern") {
                        let simple = matches!(pattern.kind(), "identifier" | "mut_pattern");
                        let initializer = simple
                            .then(|| node.child_by_field_name("value"))
                            .flatten()
                            .and_then(|value| match value.kind() {
                                "call_expression" => Some(Initializer::Call {
                                    callee: crate::calls::extract_full_callee(&value, source)?,
                                }),
                                "struct_expression" => Some(Initializer::Nominal(
                                    text(value.child_by_field_name("name")?, source).to_string(),
                                )),
                                "identifier"
                                    if text(value, source)
                                        .chars()
                                        .next()
                                        .is_some_and(char::is_uppercase) =>
                                {
                                    Some(Initializer::Nominal(text(value, source).to_string()))
                                }
                                _ => None,
                            });
                        let binding = Binding {
                            start: node.start_byte(),
                            scope: scope.clone(),
                            annotation: node
                                .child_by_field_name("type")
                                .map(|n| text(n, source).to_string()),
                            initializer,
                        };
                        for name in names(pattern, source) {
                            result
                                .bindings
                                .entry((callable, name))
                                .or_default()
                                .push(binding.clone());
                        }
                    }
                } else if !matches!(kind, "function_item" | "closure_expression") {
                    if let Some(pattern) = node.child_by_field_name("pattern") {
                        let mut binding_scope = node;
                        if kind == "let_condition" {
                            while !matches!(
                                nav.kind(binding_scope),
                                "if_expression" | "while_expression"
                            ) {
                                let Some(parent) = nav.parent(binding_scope) else {
                                    break;
                                };
                                binding_scope = parent;
                            }
                        }
                        for name in names(pattern, source) {
                            result
                                .bindings
                                .entry((callable, name))
                                .or_default()
                                .push(Binding {
                                    start: pattern.start_byte(),
                                    scope: binding_scope.byte_range(),
                                    annotation: None,
                                    initializer: None,
                                });
                        }
                    }
                }
            }
            nav.for_each_named_child(node, |child| stack.push((child, callable, scope.clone())));
        }
        for bindings in result.bindings.values_mut() {
            bindings.sort_by_key(|b| b.start);
        }
        result
    }

    pub fn declaration(&self, symbol: &str) -> Option<&Declaration> {
        self.records.get((*self.declarations.get(symbol)?)?)
    }

    /// Extraction retains every positional declaration, even when duplicate
    /// names cannot supply a unique binding for a call.
    pub fn declaration_at(&self, byte: usize) -> Option<&Declaration> {
        self.records.get(*self.symbols.get(&byte)?)
    }

    pub fn symbol_at(&self, byte: usize) -> Option<&str> {
        let declaration = self.declaration_at(byte)?;
        self.declaration(&declaration.symbol)
            .map(|d| d.symbol.as_str())
    }

    pub fn binding(&self, name: &str, call_byte: usize) -> Option<&Binding> {
        let callable = self.calls.get(&call_byte)?;
        let bindings = self.bindings.get(&(*callable, name.to_string()))?;
        let end = bindings.partition_point(|b| b.start < call_byte);
        bindings[..end]
            .iter()
            .rev()
            .find(|b| b.scope.contains(&call_byte))
    }

    pub fn bound(&self, name: &str, call_byte: usize) -> Option<&str> {
        self.bounds
            .get(&(*self.calls.get(&call_byte)?, name.to_string()))
            .map(String::as_str)
    }

    pub fn type_parameter(&self, name: &str, call_byte: usize) -> bool {
        self.calls
            .get(&call_byte)
            .is_some_and(|callable| self.parameters.contains(&(*callable, name.to_string())))
    }

    pub fn generic_callable(&self, call_byte: usize) -> bool {
        self.calls
            .get(&call_byte)
            .is_some_and(|callable| self.generic_functions.contains(callable))
    }
}