Skip to main content

brokk_bifrost_cpp/
structural.rs

1//! C++ structural spec for `query_code`.
2
3use brokk_bifrost_core::analyzer::Language;
4use brokk_bifrost_core::analyzer::structural::adapter_helpers::{
5    attach_positional_argument_roles, attach_role_with_derived_name, attach_terminal_callee,
6    first_named_child,
7};
8use brokk_bifrost_core::analyzer::structural::callable::{
9    CallKind, CallShapeCoverage, CallSiteContext, CallSiteFacts,
10};
11use brokk_bifrost_core::analyzer::structural::edges::{
12    INVERSE_REFERENCE_EDGE_SUPPORT, ReferenceEdgeSupport,
13};
14use brokk_bifrost_core::analyzer::structural::facts::Span;
15use brokk_bifrost_core::analyzer::structural::kinds::{NormalizedKind, Role};
16use brokk_bifrost_core::analyzer::structural::materialization::{
17    CPP_MATERIALIZATION_SUPPORT, DeclarationMaterializationSupport,
18};
19use brokk_bifrost_core::analyzer::structural::occurrences::{
20    NO_OCCURRENCE_ROLE_SUPPORT, OccurrenceRoleSupport,
21};
22use brokk_bifrost_core::analyzer::structural::resolution::{
23    CALLABLE_APPLICABILITY_ONLY_SUPPORT, LexicalEnvironmentSupport,
24};
25use brokk_bifrost_core::analyzer::structural::routes::{
26    IdentityAxis, IdentityRouteSupport, RouteHopKind,
27};
28use brokk_bifrost_core::analyzer::structural::spec::{RoleSink, StructuralSpec};
29use brokk_bifrost_core::hash::HashSet;
30use tree_sitter::Node;
31
32#[derive(Debug, Default)]
33pub struct CppStructuralSpec;
34
35pub static CPP_STRUCTURAL_SPEC: CppStructuralSpec = CppStructuralSpec;
36
37pub const CPP_KIND_TABLE: &[(&str, NormalizedKind)] = &[
38    ("call_expression", NormalizedKind::Call),
39    ("new_expression", NormalizedKind::Call),
40    ("field_expression", NormalizedKind::FieldAccess),
41    ("function_definition", NormalizedKind::Function),
42    ("lambda_expression", NormalizedKind::Lambda),
43    ("class_specifier", NormalizedKind::Class),
44    ("struct_specifier", NormalizedKind::Class),
45    ("union_specifier", NormalizedKind::Class),
46    ("alias_declaration", NormalizedKind::Declaration),
47    ("assignment_expression", NormalizedKind::Assignment),
48    ("init_declarator", NormalizedKind::Assignment),
49    ("preproc_include", NormalizedKind::Import),
50    ("identifier", NormalizedKind::Identifier),
51    ("field_identifier", NormalizedKind::Identifier),
52    ("namespace_identifier", NormalizedKind::Identifier),
53    ("qualified_identifier", NormalizedKind::Identifier),
54    ("type_identifier", NormalizedKind::Identifier),
55    ("template_function", NormalizedKind::Identifier),
56    ("template_method", NormalizedKind::Identifier),
57    ("template_type", NormalizedKind::Identifier),
58    ("dependent_name", NormalizedKind::Identifier),
59    ("destructor_name", NormalizedKind::Identifier),
60    ("operator_name", NormalizedKind::Identifier),
61    ("primitive_type", NormalizedKind::Identifier),
62    ("char_literal", NormalizedKind::StringLiteral),
63    ("string_literal", NormalizedKind::StringLiteral),
64    ("raw_string_literal", NormalizedKind::StringLiteral),
65    ("number_literal", NormalizedKind::NumericLiteral),
66    ("true", NormalizedKind::BooleanLiteral),
67    ("false", NormalizedKind::BooleanLiteral),
68    ("null", NormalizedKind::NullLiteral),
69    ("return_statement", NormalizedKind::Return),
70    ("throw_statement", NormalizedKind::Throw),
71    ("catch_clause", NormalizedKind::Catch),
72    ("if_statement", NormalizedKind::If),
73    ("for_statement", NormalizedKind::Loop),
74    ("while_statement", NormalizedKind::WhileLoop),
75    ("do_statement", NormalizedKind::WhileLoop),
76];
77
78/// Whether tree-sitter recovered `.field = value` as a declaration child pair:
79/// an `ERROR` containing only the anonymous dot immediately followed by an
80/// `init_declarator` whose declarator is a real identifier.
81///
82/// This is intentionally narrower than rejecting declarators below `ERROR` in
83/// general: macro-decorated declarations and ordinary comma-separated initialized
84/// declarations also use recovery nodes and remain real declarations.
85pub fn is_recovered_designator_init_declarator(node: Node<'_>) -> bool {
86    if node.kind() != "init_declarator" {
87        return false;
88    }
89    let Some(identifier) = node.child_by_field_name("declarator") else {
90        return false;
91    };
92    if identifier.kind() != "identifier" || identifier.is_missing() {
93        return false;
94    }
95    let Some(previous) = node.prev_named_sibling() else {
96        return false;
97    };
98    if previous.kind() != "ERROR"
99        || previous.named_child_count() != 0
100        || previous.child_count() != 1
101        || previous.end_byte() != node.start_byte()
102    {
103        return false;
104    }
105    previous.child(0).is_some_and(|child| {
106        child.kind() == "."
107            && !child.is_named()
108            && child.start_byte() == previous.start_byte()
109            && child.end_byte() == previous.end_byte()
110    })
111}
112
113fn last_named_field_child<'tree>(node: Node<'tree>, field: &str) -> Option<Node<'tree>> {
114    let mut cursor = node.walk();
115    node.children_by_field_name(field, &mut cursor)
116        .filter(|child| child.is_named())
117        .last()
118}
119
120fn declarator_name_node<'tree>(declarator: Node<'tree>) -> Option<Node<'tree>> {
121    let mut current = declarator;
122    loop {
123        match current.kind() {
124            "identifier"
125            | "field_identifier"
126            | "namespace_identifier"
127            | "type_identifier"
128            | "destructor_name"
129            | "operator_name"
130            | "primitive_type" => return Some(current),
131            "qualified_identifier" => current = last_named_field_child(current, "name")?,
132            "dependent_name" | "template_function" | "template_method" | "template_type" => {
133                current = current.child_by_field_name("name")?;
134            }
135            "function_declarator"
136            | "pointer_declarator"
137            | "array_declarator"
138            | "init_declarator" => current = current.child_by_field_name("declarator")?,
139            "reference_declarator" | "parenthesized_declarator" => {
140                current = first_named_child(current)?;
141            }
142            _ => return None,
143        }
144    }
145}
146
147fn expression_name_node<'tree>(expression: Node<'tree>) -> Option<Node<'tree>> {
148    let mut current = expression;
149    loop {
150        match current.kind() {
151            "identifier"
152            | "field_identifier"
153            | "namespace_identifier"
154            | "type_identifier"
155            | "destructor_name"
156            | "operator_name"
157            | "primitive_type"
158            | "this" => return Some(current),
159            "qualified_identifier" => current = last_named_field_child(current, "name")?,
160            "dependent_name" | "template_function" | "template_method" | "template_type" => {
161                current = current.child_by_field_name("name")?;
162            }
163            "field_expression" => current = current.child_by_field_name("field")?,
164            "call_expression" => current = current.child_by_field_name("function")?,
165            "new_expression" => current = current.child_by_field_name("type")?,
166            "parenthesized_expression" => current = first_named_child(current)?,
167            _ => return declarator_name_node(current),
168        }
169    }
170}
171
172fn attach_qualified_scope_receiver(sink: &mut RoleSink<'_>, function: Node<'_>) {
173    if function.kind() != "qualified_identifier" {
174        return;
175    }
176    if let Some(scope) = function.child_by_field_name("scope") {
177        attach_role_with_derived_name(sink, Role::Receiver, scope, expression_name_node);
178    }
179}
180
181fn qualified_declarator_node(mut node: Node<'_>) -> Option<Node<'_>> {
182    loop {
183        if node.kind() == "qualified_identifier" {
184            return Some(node);
185        }
186        node = node
187            .child_by_field_name("declarator")
188            .or_else(|| node.child_by_field_name("name"))
189            .or_else(|| first_named_child(node))?;
190    }
191}
192
193fn node_text<'source>(node: Node<'_>, source: &'source str) -> Option<&'source str> {
194    node.utf8_text(source.as_bytes()).ok()
195}
196
197fn scoped_function_definition(node: Node<'_>) -> Option<Node<'_>> {
198    node.child_by_field_name("declarator")
199        .and_then(qualified_declarator_node)
200        .and_then(|qualified| qualified.child_by_field_name("scope"))
201}
202
203fn is_constructor_definition(node: Node<'_>, source: &str) -> bool {
204    node.child_by_field_name("declarator")
205        .and_then(qualified_declarator_node)
206        .and_then(|qualified| {
207            Some((
208                expression_name_node(qualified.child_by_field_name("scope")?)?,
209                expression_name_node(last_named_field_child(qualified, "name")?)?,
210            ))
211        })
212        .is_some_and(|(scope, name)| node_text(scope, source) == node_text(name, source))
213}
214
215fn unquoted_include_span(node: Node<'_>) -> Option<Span> {
216    if !matches!(node.kind(), "string_literal" | "system_lib_string") {
217        return None;
218    }
219    let start = node.start_byte().checked_add(1)?;
220    let end = node.end_byte().checked_sub(1)?;
221    (start <= end).then_some(Span {
222        start_byte: start,
223        end_byte: end,
224    })
225}
226
227/// The names of every function-like macro this translation unit defines, read
228/// from `preproc_function_def` name fields.
229///
230/// The walk is iterative and descends only through preprocessor conditional
231/// blocks, which is where a definition can nest. A `#define` written inside a
232/// function body is not collected; that is a known and stated boundary, not an
233/// approximation of one.
234fn function_like_macro_names(root: Node<'_>, source: &str) -> HashSet<String> {
235    let mut names = HashSet::default();
236    let mut stack = vec![root];
237    while let Some(node) = stack.pop() {
238        for index in 0..node.named_child_count() {
239            let Some(child) = node.named_child(index) else {
240                continue;
241            };
242            match child.kind() {
243                "preproc_function_def" => {
244                    if let Some(name) = child.child_by_field_name("name") {
245                        names.insert(source[name.start_byte()..name.end_byte()].to_owned());
246                    }
247                }
248                "preproc_if" | "preproc_ifdef" | "preproc_else" | "preproc_elif"
249                | "preproc_elifdef" => stack.push(child),
250                _ => {}
251            }
252        }
253    }
254    names
255}
256
257impl StructuralSpec for CppStructuralSpec {
258    fn language(&self) -> Language {
259        Language::Cpp
260    }
261
262    fn kind_table(&self) -> &'static [(&'static str, NormalizedKind)] {
263        CPP_KIND_TABLE
264    }
265
266    fn refine_kind(
267        &self,
268        node: Node<'_>,
269        kind: NormalizedKind,
270        enclosing: Option<NormalizedKind>,
271        source: &str,
272        _context: &CallSiteContext,
273    ) -> NormalizedKind {
274        if kind == NormalizedKind::Function
275            && (enclosing == Some(NormalizedKind::Class)
276                || scoped_function_definition(node).is_some())
277        {
278            if is_constructor_definition(node, source) {
279                NormalizedKind::Constructor
280            } else {
281                NormalizedKind::Method
282            }
283        } else {
284            kind
285        }
286    }
287
288    fn supports_kind(&self, kind: NormalizedKind) -> bool {
289        matches!(kind, NormalizedKind::Method | NormalizedKind::Constructor)
290            || self
291                .kind_table()
292                .iter()
293                .any(|(_, fact_kind)| fact_kind.satisfies(kind))
294    }
295
296    fn supports_role(&self, role: Role) -> bool {
297        !matches!(role, Role::Kwarg | Role::Decorator)
298    }
299
300    fn call_site_context(&self, root: Node<'_>, source: &str) -> CallSiteContext {
301        CallSiteContext::with_macro_derived_callees(function_like_macro_names(root, source))
302    }
303
304    /// A `new_expression` is a constructor call, and a call whose callee names
305    /// a function-like macro of this translation unit has an argument list
306    /// that belongs to the macro, not to the callable that finally runs
307    /// (#1478). `CALL_TWICE(2)` parses as an ordinary call of two source
308    /// arguments even when the expansion calls a three-parameter callable, so
309    /// the honest answer is unknown coverage and no argument rows at all —
310    /// never a fabricated list an exact-arity assertion could read as clean.
311    ///
312    /// The boundary is deliberate: only macros defined in this file are
313    /// known here, because that is what this file's parse tree contains. A
314    /// macro defined in an included header leaves the site exact, which is
315    /// the same answer the analyzer gives today.
316    fn call_site_facts(
317        &self,
318        node: Node<'_>,
319        source: &str,
320        context: &CallSiteContext,
321    ) -> Option<CallSiteFacts> {
322        if node.kind() == "new_expression" {
323            return Some(CallSiteFacts::of_kind(CallKind::Constructor));
324        }
325        let callee = node.child_by_field_name("function")?;
326        (callee.kind() == "identifier"
327            && context.is_macro_derived_callee(&source[callee.start_byte()..callee.end_byte()]))
328        .then(|| CallSiteFacts::of_coverage(CallShapeCoverage::UnknownMacroDerived))
329    }
330
331    /// C++ has not learned occurrence-role classification yet (#1473).
332    /// The empty table is the honest answer: queries and assertions that ask
333    /// for an occurrence role here report incomplete rather than clean-empty.
334    fn occurrence_role_support(&self) -> &OccurrenceRoleSupport {
335        &NO_OCCURRENCE_ROLE_SUPPORT
336    }
337
338    fn lexical_environment_support(&self) -> &LexicalEnvironmentSupport {
339        // C and C++ classify no scopes, binding intervals, import binders or
340        // package clause, but the call seams report per-candidate callable
341        // applicability (#1478 M3). The per-axis table states exactly that.
342        &CALLABLE_APPLICABILITY_ONLY_SUPPORT
343    }
344
345    fn materialization_support(&self) -> &DeclarationMaterializationSupport {
346        &CPP_MATERIALIZATION_SUPPORT
347    }
348
349    fn reference_edge_support(&self) -> &ReferenceEdgeSupport {
350        &INVERSE_REFERENCE_EDGE_SUPPORT
351    }
352
353    fn identity_route_support(&self) -> &IdentityRouteSupport {
354        // C++'s occurrence adapter is shallow, so it claims no path axes. Its
355        // declaration layer keeps prototype/body occurrences distinct, which
356        // the physical-grouping axis carries; the declaration-definition peer
357        // *relation* stays unclaimed until a producer emits typed peer rows
358        // rather than merged ranges (see the #1475 ExecPlan Decision Log, M6,
359        // and its follow-up issue).
360        static SUPPORT: IdentityRouteSupport = IdentityRouteSupport::NONE
361            .supported_axis(IdentityAxis::CanonicalIdentity)
362            .supported_axis(IdentityAxis::PhysicalGrouping)
363            .supported_relation(RouteHopKind::NestedOwner);
364        &SUPPORT
365    }
366
367    fn extract(&self, node: Node<'_>, kind: NormalizedKind, sink: &mut RoleSink<'_>) {
368        match kind {
369            NormalizedKind::Call => {
370                let function_field = if node.kind() == "new_expression" {
371                    "type"
372                } else {
373                    "function"
374                };
375                if let Some(function) = node.child_by_field_name(function_field) {
376                    attach_terminal_callee(sink, function, expression_name_node(function));
377                    if function.kind() == "field_expression"
378                        && let Some(argument) = function.child_by_field_name("argument")
379                    {
380                        attach_role_with_derived_name(
381                            sink,
382                            Role::Receiver,
383                            argument,
384                            expression_name_node,
385                        );
386                    }
387                    attach_qualified_scope_receiver(sink, function);
388                }
389                if let Some(arguments) = node.child_by_field_name("arguments") {
390                    attach_positional_argument_roles(sink, arguments, expression_name_node);
391                }
392            }
393            NormalizedKind::FieldAccess => {
394                if let Some(field) = node.child_by_field_name("field") {
395                    attach_role_with_derived_name(sink, Role::Field, field, expression_name_node);
396                    if let Some(name) = expression_name_node(field) {
397                        sink.set_name(name);
398                    }
399                }
400                if let Some(argument) = node.child_by_field_name("argument") {
401                    attach_role_with_derived_name(
402                        sink,
403                        Role::Object,
404                        argument,
405                        expression_name_node,
406                    );
407                }
408            }
409            NormalizedKind::Function | NormalizedKind::Method | NormalizedKind::Constructor => {
410                if let Some(name) = node
411                    .child_by_field_name("declarator")
412                    .and_then(declarator_name_node)
413                {
414                    sink.set_name(name);
415                }
416            }
417            NormalizedKind::Class | NormalizedKind::Declaration => {
418                if let Some(name) = node
419                    .child_by_field_name("name")
420                    .and_then(declarator_name_node)
421                    .or_else(|| node.child_by_field_name("name"))
422                {
423                    sink.set_name(name);
424                }
425            }
426            NormalizedKind::Assignment => match node.kind() {
427                "init_declarator" => {
428                    if let Some(declarator) = node.child_by_field_name("declarator") {
429                        attach_role_with_derived_name(
430                            sink,
431                            Role::Left,
432                            declarator,
433                            declarator_name_node,
434                        );
435                        if let Some(name) = declarator_name_node(declarator) {
436                            sink.set_name(name);
437                        }
438                    }
439                    if let Some(value) = node.child_by_field_name("value") {
440                        attach_role_with_derived_name(
441                            sink,
442                            Role::Right,
443                            value,
444                            expression_name_node,
445                        );
446                    }
447                }
448                "assignment_expression" => {
449                    if let Some(left) = node.child_by_field_name("left") {
450                        attach_role_with_derived_name(sink, Role::Left, left, expression_name_node);
451                    }
452                    if let Some(right) = node.child_by_field_name("right") {
453                        attach_role_with_derived_name(
454                            sink,
455                            Role::Right,
456                            right,
457                            expression_name_node,
458                        );
459                    }
460                }
461                _ => {}
462            },
463            NormalizedKind::Import => {
464                if let Some(path) = node.child_by_field_name("path") {
465                    if let Some(name) = unquoted_include_span(path) {
466                        sink.role_named_span(Role::Module, path, name);
467                    } else {
468                        attach_role_with_derived_name(
469                            sink,
470                            Role::Module,
471                            path,
472                            expression_name_node,
473                        );
474                    }
475                }
476            }
477            NormalizedKind::Identifier => match expression_name_node(node) {
478                Some(name) => sink.set_name(name),
479                None => sink.set_name(node),
480            },
481            _ => {}
482        }
483    }
484}