Skip to main content

brokk_bifrost_python/
adapter.rs

1//! The Python answers behind `PythonAdapter`.
2//!
3//! `LanguageAdapter` is analysis-owned, so the trait impl itself stays in
4//! `analyzer/python/adapter.rs`; every answer it gives comes from here or from
5//! [`crate::declarations`]. `synthesize_hydrated_units` is the one exception:
6//! it mutates `FileState`, an analysis type, and stays with the shell.
7
8use brokk_bifrost_core::analyzer::cognitive_complexity;
9use std::sync::LazyLock;
10
11use crate::declarations::python_is_decorated_function_boundary;
12
13pub const PYTHON_FILE_EXTENSION: &str = "py";
14
15/// Tree-sitter node-kind mapping used by the cognitive-complexity scorer
16/// for Python. Mirrors `ai.brokk.analyzer.python.CognitiveComplexityAnalysis`.
17pub static PYTHON_COGNITIVE_CONFIG: LazyLock<cognitive_complexity::Config> =
18    LazyLock::new(|| cognitive_complexity::Config {
19        if_types: &["if_statement"],
20        alternate_if_types: &["elif_clause"],
21        loop_types: &["for_statement", "while_statement"],
22        catch_types: &["except_clause"],
23        conditional_types: &["conditional_expression"],
24        case_types: &["case_clause"],
25        binary_types: &["boolean_operator"],
26        logical_operators: &["and", "or"],
27        named_function_boundary_types: &["function_definition"],
28        anonymous_function_types: &["lambda"],
29        named_function_boundary_predicate: Some(python_is_decorated_function_boundary),
30        ..cognitive_complexity::Config::empty()
31    });
32
33pub fn python_extract_call_receiver(reference: &str) -> Option<String> {
34    brokk_bifrost_core::analyzer::common::extract_call_reference_parts(reference, &["."])
35        .map(|(receiver, _)| receiver.to_string())
36}
37
38/// Literal string data may occupy a long physical line, but replacement fields
39/// remain executable structure. Bytes and implicit concatenation use the same
40/// grammar nodes. The caller validates the finite source/tree envelope first.
41pub fn is_string_line_data(
42    node: tree_sitter::Node<'_>,
43    should_stop: &mut dyn FnMut() -> bool,
44) -> std::ops::ControlFlow<(), bool> {
45    brokk_bifrost_core::analyzer::tree_walk::is_uninterpolated_literal(
46        node,
47        &["string", "concatenated_string"],
48        &["interpolation"],
49        should_stop,
50    )
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56    use std::ops::ControlFlow;
57
58    #[test]
59    fn qs6_string_data_grammar_and_cancellation() {
60        for (literal, kind, interpolations, data) in [
61            ("u'caf\u{e9}'", "string", 0, true),
62            ("b'bytes'", "string", 0, true),
63            ("'one' 'two'", "concatenated_string", 0, true),
64            ("f'plain {{braces}}'", "string", 0, true),
65            ("f'{value:{width}}'", "string", 1, false),
66            ("'prefix' f'{value}'", "concatenated_string", 1, false),
67        ] {
68            let source = format!("value = {literal}\n");
69            let tree = crate::declarations::parse_python_tree(&source).unwrap();
70            let root = tree.root_node();
71            assert!(!root.has_error(), "{}", root.to_sexp());
72            let value = root
73                .named_child(0)
74                .unwrap()
75                .named_child(0)
76                .unwrap()
77                .child_by_field_name("right")
78                .unwrap();
79            assert_eq!(value.kind(), kind);
80            let mut stack = vec![value];
81            let mut count = 0;
82            while let Some(node) = stack.pop() {
83                assert!(!node.is_error() && !node.is_missing());
84                count += usize::from(node.kind() == "interpolation");
85                let mut cursor = node.walk();
86                stack.extend(node.named_children(&mut cursor));
87            }
88            assert_eq!(count, interpolations, "{}", value.to_sexp());
89            assert_eq!(
90                is_string_line_data(value, &mut || false),
91                ControlFlow::Continue(data)
92            );
93            let mut stops = 0;
94            assert_eq!(
95                is_string_line_data(value, &mut || {
96                    stops += 1;
97                    true
98                }),
99                ControlFlow::Break(())
100            );
101            assert_eq!(stops, 1);
102        }
103    }
104}