Skip to main content

brokk_bifrost_python/
syntax.rs

1use brokk_bifrost_core::analyzer::Range;
2use brokk_bifrost_core::cancellation::CancellationToken;
3use brokk_bifrost_core::hash::HashSet;
4use tree_sitter::Node;
5
6#[derive(Debug, Default)]
7pub struct PythonOverloadDecoratorBindings {
8    direct: HashSet<String>,
9    namespaces: HashSet<String>,
10}
11
12impl PythonOverloadDecoratorBindings {
13    pub fn collect(root: Node<'_>, source: &str) -> Self {
14        let mut bindings = Self::default();
15        let mut stack = vec![root];
16
17        while let Some(node) = stack.pop() {
18            match node.kind() {
19                "function_definition" | "class_definition" | "lambda" => continue,
20                "import_statement" => bindings.collect_namespace_imports(node, source),
21                "import_from_statement" => bindings.collect_direct_imports(node, source),
22                _ => {}
23            }
24
25            let mut cursor = node.walk();
26            let children: Vec<_> = node.named_children(&mut cursor).collect();
27            stack.extend(children.into_iter().rev());
28        }
29
30        bindings
31    }
32
33    fn collect_namespace_imports(&mut self, node: Node<'_>, source: &str) {
34        let mut cursor = node.walk();
35        for imported in node.children_by_field_name("name", &mut cursor) {
36            match imported.kind() {
37                "dotted_name" => {
38                    let module = node_text(imported, source).trim();
39                    if is_typing_module(module) {
40                        self.namespaces.insert(module.to_string());
41                    }
42                }
43                "aliased_import" => {
44                    let Some(name) = imported.child_by_field_name("name") else {
45                        continue;
46                    };
47                    if !is_typing_module(node_text(name, source).trim()) {
48                        continue;
49                    }
50                    let Some(alias) = imported.child_by_field_name("alias") else {
51                        continue;
52                    };
53                    let alias = node_text(alias, source).trim();
54                    if !alias.is_empty() {
55                        self.namespaces.insert(alias.to_string());
56                    }
57                }
58                _ => {}
59            }
60        }
61    }
62
63    fn collect_direct_imports(&mut self, node: Node<'_>, source: &str) {
64        let Some(module) = node.child_by_field_name("module_name") else {
65            return;
66        };
67        if !is_typing_module(node_text(module, source).trim()) {
68            return;
69        }
70
71        let mut cursor = node.walk();
72        for imported in node.children_by_field_name("name", &mut cursor) {
73            match imported.kind() {
74                "dotted_name" if node_text(imported, source).trim() == "overload" => {
75                    self.direct.insert("overload".to_string());
76                }
77                "aliased_import" => {
78                    let Some(name) = imported.child_by_field_name("name") else {
79                        continue;
80                    };
81                    if node_text(name, source).trim() != "overload" {
82                        continue;
83                    }
84                    let Some(alias) = imported.child_by_field_name("alias") else {
85                        continue;
86                    };
87                    let alias = node_text(alias, source).trim();
88                    if !alias.is_empty() {
89                        self.direct.insert(alias.to_string());
90                    }
91                }
92                _ => {}
93            }
94        }
95    }
96
97    pub fn decorates_as_overload(&self, function: Node<'_>, source: &str) -> bool {
98        let Some(parent) = function
99            .parent()
100            .filter(|node| node.kind() == "decorated_definition")
101        else {
102            return false;
103        };
104
105        let mut cursor = parent.walk();
106        parent
107            .named_children(&mut cursor)
108            .filter(|child| child.kind() == "decorator")
109            .filter_map(decorator_callee)
110            .any(|callee| match callee.kind() {
111                "identifier" => self.direct.contains(node_text(callee, source).trim()),
112                "attribute" => {
113                    let Some(attribute) = callee.child_by_field_name("attribute") else {
114                        return false;
115                    };
116                    if node_text(attribute, source).trim() != "overload" {
117                        return false;
118                    }
119                    let Some(object) = callee.child_by_field_name("object") else {
120                        return false;
121                    };
122                    object.kind() == "identifier"
123                        && self.namespaces.contains(node_text(object, source).trim())
124                }
125                _ => false,
126            })
127    }
128}
129
130fn is_typing_module(module: &str) -> bool {
131    matches!(module, "typing" | "typing_extensions")
132}
133
134fn node_text<'a>(node: Node<'_>, source: &'a str) -> &'a str {
135    brokk_bifrost_core::analyzer::common::node_source_text(node, source)
136}
137
138/// Return the name-bearing node of a Python expression using tree-sitter fields.
139pub fn expression_name_node<'tree>(expression: Node<'tree>) -> Option<Node<'tree>> {
140    let mut current = expression;
141    loop {
142        match current.kind() {
143            "identifier" => return Some(current),
144            "attribute" => current = current.child_by_field_name("attribute")?,
145            "call" => current = current.child_by_field_name("function")?,
146            _ => return None,
147        }
148    }
149}
150
151/// Return a decorator's callable expression, peeling an optional invocation.
152pub fn decorator_callee<'tree>(decorator: Node<'tree>) -> Option<Node<'tree>> {
153    if decorator.kind() != "decorator" {
154        return None;
155    }
156    let mut expression = decorator.named_child(0)?;
157    while expression.kind() == "call" {
158        expression = expression.child_by_field_name("function")?;
159    }
160    Some(expression)
161}
162
163/// Whether `node` is contained by a parser field that Python evaluates as an
164/// annotation rather than as an ordinary expression.
165pub fn python_node_is_in_annotation(node: Node<'_>) -> bool {
166    let start = node.start_byte();
167    let end = node.end_byte();
168    let mut current = node;
169    while let Some(parent) = current.parent() {
170        let annotation = match parent.kind() {
171            "function_definition" => parent.child_by_field_name("return_type"),
172            "typed_parameter" | "typed_default_parameter" | "assignment" => {
173                parent.child_by_field_name("type")
174            }
175            _ => None,
176        };
177        if let Some(annotation) = annotation
178            && annotation.start_byte() <= start
179            && end <= annotation.end_byte()
180        {
181            return true;
182        }
183        current = parent;
184    }
185    false
186}
187
188/// Parse one exactly mapped deferred annotation and return its identifier ranges.
189pub fn python_deferred_annotation_identifier_ranges(
190    string: Node<'_>,
191    source: &str,
192    cancellation: Option<&CancellationToken>,
193) -> Option<Vec<Range>> {
194    if string.kind() != "string"
195        || string
196            .parent()
197            .is_some_and(|parent| parent.kind() == "concatenated_string")
198        || !python_node_is_in_annotation(string)
199    {
200        return None;
201    }
202
203    let mut content = None;
204    for index in 0..string.named_child_count() {
205        let child = string.named_child(index)?;
206        match child.kind() {
207            "string_start" | "string_end" => {}
208            "string_content" if content.is_none() => content = Some(child),
209            _ => return None,
210        }
211    }
212    let content = content?;
213    let language = tree_sitter_python::LANGUAGE.into();
214    let tree = brokk_bifrost_core::analyzer::common::parse_source_range_with_cancellation(
215        &language,
216        source,
217        content.range(),
218        cancellation,
219    )?;
220    if tree.root_node().has_error() {
221        return None;
222    }
223
224    let mut ranges = Vec::new();
225    let mut stack = vec![tree.root_node()];
226    while let Some(current) = stack.pop() {
227        if cancellation.is_some_and(CancellationToken::is_cancelled) {
228            return None;
229        }
230        if current.kind() == "identifier" {
231            ranges.push(Range {
232                start_byte: current.start_byte(),
233                end_byte: current.end_byte(),
234                start_line: current.start_position().row + 1,
235                end_line: current.end_position().row + 1,
236            });
237        }
238        for index in (0..current.named_child_count()).rev() {
239            if let Some(child) = current.named_child(index) {
240                stack.push(child);
241            }
242        }
243    }
244    Some(ranges)
245}