Skip to main content

brokk_bifrost_cpp/
structural.rs

1//! C++ structural spec for `query_code`.
2
3use brokk_bifrost_core::analyzer::common::try_node_source_text as node_text;
4use brokk_bifrost_core::analyzer::statement_facts::StatementFactKind;
5use brokk_bifrost_core::analyzer::structural::adapter_helpers::{
6    CalleeSpineStep, attach_positional_argument_roles, attach_role_with_derived_name,
7    attach_terminal_callee, field_name_in_parent, first_named_child, terminal_callee_leaf,
8    unquoted_string_content_span,
9};
10use brokk_bifrost_core::analyzer::structural::callable::{
11    CallKind, CallShapeCoverage, CallSiteContext, CallSiteFacts,
12};
13use brokk_bifrost_core::analyzer::structural::edges::{
14    INVERSE_REFERENCE_EDGE_SUPPORT, ReferenceEdgeSupport,
15};
16use brokk_bifrost_core::analyzer::structural::facts::Span;
17use brokk_bifrost_core::analyzer::structural::kinds::{NormalizedKind, Role};
18use brokk_bifrost_core::analyzer::structural::materialization::{
19    CPP_MATERIALIZATION_SUPPORT, DeclarationMaterializationSupport,
20};
21use brokk_bifrost_core::analyzer::structural::occurrences::{
22    OccurrenceRole, OccurrenceRoleSupport,
23};
24use brokk_bifrost_core::analyzer::structural::resolution::{
25    BindingActivation, BindingKind, EnvironmentAxis, HoistingClass, LexicalEnvironmentSupport,
26    ScopeFormation, default_scope_formation,
27};
28use brokk_bifrost_core::analyzer::structural::result_use::{
29    CallResultUse, CallResultUseIndex, CallResultUseOpenReason, CallResultUseSite,
30    IntentionalDiscardKind,
31};
32use brokk_bifrost_core::analyzer::structural::routes::{
33    IdentityAxis, IdentityRouteSupport, RouteHopKind,
34};
35use brokk_bifrost_core::analyzer::structural::spec::{RoleSink, StructuralSpec};
36use brokk_bifrost_core::analyzer::tree_walk::{ParentIndex, named_children_iter, node_range};
37use brokk_bifrost_core::analyzer::{Language, Range};
38use brokk_bifrost_core::hash::HashSet;
39use tree_sitter::Node;
40
41#[derive(Debug, Default)]
42pub struct CppStructuralSpec;
43
44pub static CPP_STRUCTURAL_SPEC: CppStructuralSpec = CppStructuralSpec;
45
46/// Whether this is a C++ preprocessor conditional node.
47///
48/// The linked tree-sitter-cpp grammar uses `preproc_ifdef` for both `#ifdef`
49/// and `#ifndef`; `preproc_ifndef` remains accepted for trees that expose it
50/// as a distinct node kind.
51pub(crate) fn is_cpp_preprocessor_conditional(node: Node<'_>) -> bool {
52    matches!(
53        node.kind(),
54        "preproc_if"
55            | "preproc_ifdef"
56            | "preproc_ifndef"
57            | "preproc_elif"
58            | "preproc_elifdef"
59            | "preproc_else"
60    )
61}
62
63/// Classify one exact C or C++ call expression.  The C grammar is the same
64/// parser route as C++, so the syntax classifier deliberately does not use a
65/// source-file extension or a text-search fallback.
66pub fn cpp_call_result_use(call: Node<'_>, source: &str) -> CallResultUseSite {
67    let default = if !matches!(call.kind(), "call_expression" | "new_expression")
68        || call.has_error()
69        || has_recovery_ancestor(call)
70    {
71        CallResultUse::Open(CallResultUseOpenReason::RecoveredSyntax)
72    } else if has_deferred_ancestor(call) {
73        CallResultUse::Open(CallResultUseOpenReason::DeferredContext)
74    } else {
75        let mut expression = call;
76        loop {
77            let Some(parent) = expression.parent() else {
78                break CallResultUse::Open(CallResultUseOpenReason::UnclassifiedSyntax);
79            };
80            if parent.is_error() || parent.is_missing() {
81                break CallResultUse::Open(CallResultUseOpenReason::RecoveredSyntax);
82            }
83            match parent.kind() {
84                "parenthesized_expression" | "comma_expression"
85                    if parent
86                        .named_children(&mut parent.walk())
87                        .any(|child| child.id() == expression.id()) =>
88                {
89                    expression = parent;
90                }
91                "expression_statement"
92                    if parent
93                        .named_children(&mut parent.walk())
94                        .any(|child| child.id() == expression.id()) =>
95                {
96                    break CallResultUse::Discarded;
97                }
98                "for_statement"
99                    if matches!(
100                        field_name_in_parent(parent, expression),
101                        Some("initializer" | "update")
102                    ) =>
103                {
104                    break CallResultUse::Discarded;
105                }
106                "cast_expression"
107                    if field_name_in_parent(parent, expression) == Some("value")
108                        && parent
109                            .child_by_field_name("type")
110                            .is_some_and(|type_node| cpp_type_is_void(type_node, source)) =>
111                {
112                    break CallResultUse::IntentionalDiscard(IntentionalDiscardKind::CppVoidCast);
113                }
114                "argument_list"
115                    if parent
116                        .parent()
117                        .is_some_and(|outer_call| cpp_static_cast_to_void(outer_call, source)) =>
118                {
119                    break CallResultUse::IntentionalDiscard(IntentionalDiscardKind::CppVoidCast);
120                }
121                "lambda_expression" => {
122                    break CallResultUse::Open(CallResultUseOpenReason::DeferredContext);
123                }
124                _ => break CallResultUse::Consumed,
125            }
126        }
127    };
128    CallResultUseSite::new(call.start_byte(), call.end_byte(), default)
129}
130
131fn cpp_type_is_void(type_node: Node<'_>, source: &str) -> bool {
132    let base = match type_node.kind() {
133        "type_descriptor" if type_node.child_by_field_name("declarator").is_none() => {
134            type_node.child_by_field_name("type")
135        }
136        "primitive_type" => Some(type_node),
137        _ => None,
138    };
139    base.is_some_and(|base| {
140        base.kind() == "primitive_type" && node_text(base, source) == Some("void")
141    })
142}
143
144fn has_recovery_ancestor(mut node: Node<'_>) -> bool {
145    while let Some(parent) = node.parent() {
146        if parent.is_error() || parent.is_missing() {
147            return true;
148        }
149        node = parent;
150    }
151    false
152}
153
154fn has_deferred_ancestor(mut node: Node<'_>) -> bool {
155    while let Some(parent) = node.parent() {
156        if parent.kind() == "lambda_expression" {
157            return true;
158        }
159        node = parent;
160    }
161    false
162}
163
164fn cpp_static_cast_to_void(call: Node<'_>, source: &str) -> bool {
165    if call.kind() != "call_expression" {
166        return false;
167    }
168    let Some(function) = call.child_by_field_name("function") else {
169        return false;
170    };
171    if function.kind() != "template_function"
172        || function
173            .child_by_field_name("name")
174            .and_then(|name| node_text(name, source))
175            != Some("static_cast")
176    {
177        return false;
178    }
179    function
180        .child_by_field_name("arguments")
181        .and_then(|arguments| arguments.named_child(0))
182        .is_some_and(|type_node| cpp_type_is_void(type_node, source))
183}
184
185fn cpp_cast_call(call: Node<'_>, source: &str) -> bool {
186    let Some(function) = call.child_by_field_name("function") else {
187        return false;
188    };
189    if function.kind() != "template_function" {
190        return false;
191    }
192    matches!(
193        function
194            .child_by_field_name("name")
195            .and_then(|name| node_text(name, source)),
196        Some("static_cast" | "reinterpret_cast" | "const_cast" | "dynamic_cast")
197    )
198}
199
200/// One source-snapshot index of exact C/C++ call spans.
201#[derive(Debug, Clone)]
202pub struct CppCallResultUseIndex {
203    inner: CallResultUseIndex,
204}
205
206impl CppCallResultUseIndex {
207    pub fn new(root: Node<'_>, source: &str) -> Self {
208        let mut sites = Vec::new();
209        let mut stack = vec![root];
210        while let Some(node) = stack.pop() {
211            if matches!(node.kind(), "call_expression" | "new_expression")
212                && !cpp_cast_call(node, source)
213            {
214                sites.push(cpp_call_result_use(node, source));
215            }
216            for index in (0..node.named_child_count()).rev() {
217                stack.push(node.named_child(index).expect("named child exists"));
218            }
219        }
220        Self {
221            inner: CallResultUseIndex::new(sites),
222        }
223    }
224
225    pub fn at_span(
226        &self,
227        start_byte: usize,
228        end_byte: usize,
229    ) -> Result<&CallResultUseSite, CallResultUseOpenReason> {
230        self.inner.at_span(start_byte, end_byte)
231    }
232
233    pub fn sites(&self) -> &[CallResultUseSite] {
234        self.inner.sites()
235    }
236}
237
238pub const CPP_KIND_TABLE: &[(&str, NormalizedKind)] = &[
239    ("comment", NormalizedKind::Comment),
240    ("call_expression", NormalizedKind::Call),
241    ("new_expression", NormalizedKind::Call),
242    ("field_expression", NormalizedKind::FieldAccess),
243    ("function_definition", NormalizedKind::Function),
244    ("lambda_expression", NormalizedKind::Lambda),
245    ("class_specifier", NormalizedKind::Class),
246    ("struct_specifier", NormalizedKind::Class),
247    ("union_specifier", NormalizedKind::Class),
248    ("alias_declaration", NormalizedKind::Declaration),
249    ("namespace_definition", NormalizedKind::Module),
250    ("assignment_expression", NormalizedKind::Assignment),
251    ("init_declarator", NormalizedKind::Assignment),
252    ("preproc_include", NormalizedKind::Import),
253    ("identifier", NormalizedKind::Identifier),
254    ("field_identifier", NormalizedKind::Identifier),
255    ("namespace_identifier", NormalizedKind::Identifier),
256    ("qualified_identifier", NormalizedKind::Identifier),
257    ("type_identifier", NormalizedKind::Identifier),
258    ("template_function", NormalizedKind::Identifier),
259    ("template_method", NormalizedKind::Identifier),
260    ("template_type", NormalizedKind::Identifier),
261    ("dependent_name", NormalizedKind::Identifier),
262    ("destructor_name", NormalizedKind::Identifier),
263    ("operator_name", NormalizedKind::Identifier),
264    ("primitive_type", NormalizedKind::Identifier),
265    ("char_literal", NormalizedKind::StringLiteral),
266    ("string_literal", NormalizedKind::StringLiteral),
267    ("raw_string_literal", NormalizedKind::StringLiteral),
268    ("number_literal", NormalizedKind::NumericLiteral),
269    ("true", NormalizedKind::BooleanLiteral),
270    ("false", NormalizedKind::BooleanLiteral),
271    ("null", NormalizedKind::NullLiteral),
272    ("return_statement", NormalizedKind::Return),
273    ("throw_statement", NormalizedKind::Throw),
274    ("catch_clause", NormalizedKind::Catch),
275    ("if_statement", NormalizedKind::If),
276    ("for_statement", NormalizedKind::Loop),
277    ("for_range_loop", NormalizedKind::Loop),
278    ("compound_statement", NormalizedKind::Block),
279    ("switch_statement", NormalizedKind::Switch),
280    ("case_statement", NormalizedKind::Case),
281    ("labeled_statement", NormalizedKind::Label),
282    ("goto_statement", NormalizedKind::Goto),
283    ("break_statement", NormalizedKind::Break),
284    ("continue_statement", NormalizedKind::Continue),
285    ("while_statement", NormalizedKind::WhileLoop),
286    ("do_statement", NormalizedKind::WhileLoop),
287];
288
289fn cpp_escape_codepoint(digits: &str, radix: u32, byte_escape: bool) -> Option<char> {
290    let value = u32::from_str_radix(digits, radix).ok()?;
291    if byte_escape && value > 0x7f {
292        return None;
293    }
294    char::from_u32(value)
295}
296
297fn cpp_cooked_string_escape(escape: &str) -> Option<Option<char>> {
298    let escaped = escape.strip_prefix('\\')?;
299    if matches!(escaped, "\n" | "\r\n") {
300        return Some(None);
301    }
302    let character = match escaped {
303        "a" => '\x07',
304        "b" => '\x08',
305        "f" => '\x0c',
306        "n" => '\n',
307        "r" => '\r',
308        "t" => '\t',
309        "v" => '\x0b',
310        "0" => '\0',
311        "\\" => '\\',
312        "'" => '\'',
313        "\"" => '\"',
314        "?" => '?',
315        _ if escaped.starts_with('x') => {
316            let digits = escaped.get(1..)?;
317            (!digits.is_empty()
318                && digits.len() <= 4
319                && digits.bytes().all(|byte| byte.is_ascii_hexdigit()))
320            .then_some(())?;
321            cpp_escape_codepoint(digits, 16, true)?
322        }
323        _ if escaped.starts_with('u') => {
324            let digits = escaped.get(1..)?;
325            (digits.len() == 4 && digits.bytes().all(|byte| byte.is_ascii_hexdigit()))
326                .then_some(())?;
327            cpp_escape_codepoint(digits, 16, false)?
328        }
329        _ if escaped.starts_with('U') => {
330            let digits = escaped.get(1..)?;
331            (digits.len() == 8 && digits.bytes().all(|byte| byte.is_ascii_hexdigit()))
332                .then_some(())?;
333            cpp_escape_codepoint(digits, 16, false)?
334        }
335        _ if escaped.len() <= 3 && escaped.bytes().all(|byte| (b'0'..=b'7').contains(&byte)) => {
336            cpp_escape_codepoint(escaped, 8, true)?
337        }
338        _ => return None,
339    };
340    Some(Some(character))
341}
342
343fn cpp_string_literal_value(node: Node<'_>, source: &str) -> Option<String> {
344    let spelling = node_text(node, source)?;
345    match node.kind() {
346        "string_literal" => {
347            // Wide and UTF-prefixed literals have implementation-specific code
348            // unit encodings. Only the ordinary narrow form has a portable
349            // decoded UTF-8 value for this fact axis.
350            if !spelling.starts_with('"') {
351                return None;
352            }
353            let mut decoded = String::new();
354            let mut cursor = node.walk();
355            for child in node.named_children(&mut cursor) {
356                let text = node_text(child, source)?;
357                match child.kind() {
358                    "string_content" => decoded.push_str(text),
359                    "escape_sequence" => {
360                        if let Some(character) = cpp_cooked_string_escape(text)? {
361                            decoded.push(character);
362                        }
363                    }
364                    _ => return None,
365                }
366            }
367            Some(decoded)
368        }
369        "raw_string_literal" => {
370            if !spelling.starts_with("R\"") {
371                return None;
372            }
373            let mut content = None;
374            let mut cursor = node.walk();
375            for child in node.named_children(&mut cursor) {
376                match child.kind() {
377                    "raw_string_content" => {
378                        if content.is_some() {
379                            return None;
380                        }
381                        content = Some(node_text(child, source)?);
382                    }
383                    "raw_string_delimiter" => {}
384                    _ => return None,
385                }
386            }
387            content.map(str::to_owned)
388        }
389        _ => None,
390    }
391}
392
393fn condition_expression(node: Node<'_>) -> Option<Node<'_>> {
394    let condition = node.child_by_field_name("condition")?;
395    if condition.kind() == "condition_clause" {
396        condition
397            .child_by_field_name("value")
398            .or_else(|| condition.named_child(0))
399    } else {
400        Some(condition)
401    }
402}
403
404/// Declaration evidence retained only while classifying one switch.
405#[derive(Clone, Copy)]
406struct CppSwitchDeclaration<'tree> {
407    type_node: Node<'tree>,
408    declarator: Node<'tree>,
409}
410
411fn cpp_switch_scope(node: Node<'_>) -> bool {
412    matches!(
413        node.kind(),
414        "compound_statement"
415            | "for_statement"
416            | "for_range_loop"
417            | "if_statement"
418            | "switch_statement"
419            | "while_statement"
420            | "catch_clause"
421    )
422}
423
424fn cpp_switch_local_declaration<'tree>(
425    switch: Node<'tree>,
426    name: &str,
427    source: &str,
428) -> Option<CppSwitchDeclaration<'tree>> {
429    let condition = condition_expression(switch)?;
430    let function = std::iter::successors(switch.parent(), |node| node.parent())
431        .find(|node| matches!(node.kind(), "function_definition" | "lambda_expression"))?;
432    enum Step<'tree> {
433        Enter(Node<'tree>),
434        LeaveScope,
435    }
436    enum Binding<'tree> {
437        Unknown,
438        Declaration(CppSwitchDeclaration<'tree>),
439    }
440    let mut stack = vec![Step::Enter(function)];
441    // Only the requested identifier is retained at each lexical tier.
442    let mut scopes: Vec<Option<Binding<'tree>>> = vec![None];
443    while let Some(step) = stack.pop() {
444        let node = match step {
445            Step::LeaveScope => {
446                scopes.pop().expect("entered scope");
447                continue;
448            }
449            Step::Enter(node) => node,
450        };
451        if node == condition {
452            return scopes.iter().rev().find_map(Option::as_ref).and_then(
453                |binding| match binding {
454                    Binding::Unknown => None,
455                    Binding::Declaration(declaration) => Some(*declaration),
456                },
457            );
458        }
459        if node != function
460            && matches!(
461                node.kind(),
462                "function_definition"
463                    | "lambda_expression"
464                    | "class_specifier"
465                    | "struct_specifier"
466                    | "union_specifier"
467                    | "enum_specifier"
468            )
469        {
470            continue;
471        }
472        if cpp_switch_scope(node) {
473            scopes.push(None);
474            stack.push(Step::LeaveScope);
475        }
476        if node.kind() == "declaration" {
477            for declarator in node.children_by_field_name("declarator", &mut node.walk()) {
478                if declarator_name_node(declarator).and_then(|node| node_text(node, source))
479                    == Some(name)
480                {
481                    // Prototypes and unsupported declarators also hide names.
482                    *scopes.last_mut().expect("function scope") = Some(Binding::Unknown);
483                }
484            }
485        }
486        if node.kind() == "identifier"
487            && node_text(node, source) == Some(name)
488            && let Some(owner) = cpp_binder_owner(node, |node| node.parent(), field_name_in_parent)
489        {
490            let declaration = match owner {
491                CppBinderOwner::Local(declarator) => {
492                    let owner = std::iter::successors(declarator.parent(), |node| node.parent())
493                        .find(|node| node.kind() == "declaration")
494                        .expect("local binder declaration");
495                    owner
496                        .child_by_field_name("type")
497                        .map(|type_node| CppSwitchDeclaration {
498                            type_node,
499                            declarator,
500                        })
501                }
502                CppBinderOwner::Parameter => {
503                    let owner = std::iter::successors(node.parent(), |node| node.parent())
504                        .find(|node| {
505                            matches!(
506                                node.kind(),
507                                "parameter_declaration"
508                                    | "optional_parameter_declaration"
509                                    | "variadic_parameter_declaration"
510                            )
511                        })
512                        .expect("parameter binder declaration");
513                    owner
514                        .child_by_field_name("type")
515                        .zip(owner.child_by_field_name("declarator"))
516                        .map(|(type_node, declarator)| CppSwitchDeclaration {
517                            type_node,
518                            declarator,
519                        })
520                }
521                CppBinderOwner::RangeFor(owner) => owner
522                    .child_by_field_name("type")
523                    .zip(owner.child_by_field_name("declarator"))
524                    .map(|(type_node, declarator)| CppSwitchDeclaration {
525                        type_node,
526                        declarator,
527                    }),
528                _ => None,
529            };
530            // An unknown inner binding must not fall through to a parameter.
531            *scopes.last_mut().expect("function scope") =
532                Some(declaration.map_or(Binding::Unknown, Binding::Declaration));
533        }
534        for index in (0..node.named_child_count()).rev() {
535            stack.push(Step::Enter(node.named_child(index).expect("named child")));
536        }
537    }
538    None
539}
540
541/// Search one lexical type tier, descending into a named scope only when the
542/// written qualification selects it. Aliases are barriers, not enum evidence.
543fn cpp_switch_type_in_scope<'tree>(
544    scope: Node<'tree>,
545    path: &[String],
546    before: usize,
547    source: &str,
548) -> Option<Node<'tree>> {
549    use crate::declarations::cpp_structured_type_path;
550    let mut stack = vec![(scope, 0)];
551    let mut found = None;
552    let mut unresolved_import = None;
553    while let Some((node, component)) = stack.pop() {
554        if node.start_byte() >= before {
555            continue;
556        }
557        if node != scope {
558            if node.kind() == "using_declaration" {
559                let imports_namespace = (0..node.child_count())
560                    .any(|index| node.child(index).expect("child").kind() == "namespace");
561                let imported = first_named_child(node)
562                    .and_then(declarator_name_node)
563                    .and_then(|name| node_text(name, source));
564                if imports_namespace || imported == Some(path[component].as_str()) {
565                    unresolved_import = Some(node);
566                }
567                continue;
568            }
569            let named_type = matches!(
570                node.kind(),
571                "enum_specifier"
572                    | "class_specifier"
573                    | "struct_specifier"
574                    | "union_specifier"
575                    | "namespace_definition"
576                    | "namespace_alias_definition"
577                    | "alias_declaration"
578                    | "type_definition"
579                    | "type_parameter_declaration"
580                    | "variadic_type_parameter_declaration"
581            );
582            if named_type {
583                let names = if node.kind() == "type_definition" {
584                    node.children_by_field_name("declarator", &mut node.walk())
585                        .filter_map(declarator_name_node)
586                        .filter_map(|name| cpp_structured_type_path(name, source))
587                        .collect::<Vec<_>>()
588                } else if matches!(
589                    node.kind(),
590                    "type_parameter_declaration" | "variadic_type_parameter_declaration"
591                ) {
592                    first_named_child(node)
593                        .and_then(|name| cpp_structured_type_path(name, source))
594                        .into_iter()
595                        .collect()
596                } else {
597                    node.child_by_field_name("name")
598                        .and_then(|name| {
599                            // A C++17 nested namespace has a different grammar
600                            // wrapper from a qualified type name.
601                            let mut stack = vec![name];
602                            let mut path = Vec::new();
603                            while let Some(part) = stack.pop() {
604                                if part.kind() == "nested_namespace_specifier" {
605                                    for index in (0..part.named_child_count()).rev() {
606                                        stack.push(
607                                            part.named_child(index).expect("namespace component"),
608                                        );
609                                    }
610                                } else {
611                                    path.extend(cpp_structured_type_path(part, source)?);
612                                }
613                            }
614                            Some(path)
615                        })
616                        .into_iter()
617                        .collect()
618                };
619                for name in names {
620                    if path[component..].starts_with(&name) {
621                        let next = component + name.len();
622                        if next < path.len()
623                            && let Some(body) = node.child_by_field_name("body")
624                        {
625                            stack.push((body, next));
626                        } else if found.is_none_or(|previous: Node<'_>| {
627                            previous.start_byte() < node.start_byte()
628                        }) {
629                            // An alias/forward declaration cannot supply the
630                            // rest of a qualification and must block fallback.
631                            found = Some(node);
632                        }
633                    }
634                }
635                continue;
636            }
637            if cpp_switch_scope(node)
638                || matches!(node.kind(), "function_definition" | "lambda_expression")
639            {
640                continue;
641            }
642        }
643        for index in (0..node.named_child_count()).rev() {
644            stack.push((node.named_child(index).expect("named child"), component));
645        }
646    }
647    found.or(unresolved_import)
648}
649
650fn cpp_switch_named_type<'tree>(type_node: Node<'tree>, source: &str) -> Option<Node<'tree>> {
651    use crate::declarations::cpp_structured_type_path;
652    if type_node.kind() == "enum_specifier"
653        && type_node.child_by_field_name("body").is_some()
654        && type_node.child_by_field_name("name").is_some()
655    {
656        return Some(type_node);
657    }
658    if matches!(
659        type_node.kind(),
660        "class_specifier" | "struct_specifier" | "union_specifier"
661    ) && type_node.child_by_field_name("body").is_some()
662    {
663        return Some(type_node);
664    }
665    let name = if matches!(
666        type_node.kind(),
667        "enum_specifier" | "class_specifier" | "struct_specifier" | "union_specifier"
668    ) {
669        type_node.child_by_field_name("name")?
670    } else {
671        type_node
672    };
673    // Template arguments and dependent types require semantic resolution.
674    let mut stack = vec![name];
675    while let Some(node) = stack.pop() {
676        if !matches!(
677            node.kind(),
678            "type_identifier"
679                | "identifier"
680                | "namespace_identifier"
681                | "qualified_identifier"
682                | "scoped_identifier"
683                | "scoped_type_identifier"
684        ) {
685            return None;
686        }
687        stack.extend(named_children_iter(node).filter(|node| !node.is_extra()));
688    }
689    let path = cpp_structured_type_path(name, source)?;
690    let global = name.child(0).is_some_and(|child| child.kind() == "::");
691    for scope in std::iter::successors(type_node.parent(), |node| node.parent()) {
692        if !(cpp_switch_scope(scope)
693            || matches!(
694                scope.kind(),
695                "function_definition"
696                    | "template_declaration"
697                    | "namespace_definition"
698                    | "class_specifier"
699                    | "struct_specifier"
700                    | "union_specifier"
701                    | "translation_unit"
702            ))
703            || (global && scope.kind() != "translation_unit")
704        {
705            continue;
706        }
707        if let Some(declaration) =
708            cpp_switch_type_in_scope(scope, &path, type_node.start_byte(), source)
709        {
710            return Some(declaration);
711        }
712        if !global
713            && matches!(
714                scope.kind(),
715                "class_specifier" | "struct_specifier" | "union_specifier"
716            )
717        {
718            // Inherited names and complete-class lookup can hide an outer
719            // enum even without an earlier declaration in the class body.
720            if named_children_iter(scope).any(|node| node.kind() == "base_class_clause")
721                || cpp_switch_type_in_scope(scope, &path, usize::MAX, source)
722                    .is_some_and(|declaration| declaration.start_byte() >= type_node.start_byte())
723            {
724                return None;
725            }
726        }
727        // An out-of-line definition's logical owner is not its AST parent.
728        // Resolving relative names across that boundary needs the resolver.
729        if !global
730            && (scope.kind() == "function_definition"
731                && scoped_function_definition(scope).is_some()
732                || scope
733                    .child_by_field_name("name")
734                    .is_some_and(|name| name.kind() == "qualified_identifier"))
735        {
736            return None;
737        }
738    }
739    None
740}
741
742fn cpp_switch_pointer_depth(mut declarator: Node<'_>) -> Option<usize> {
743    let mut depth = 0;
744    loop {
745        match declarator.kind() {
746            "identifier" | "field_identifier" => return Some(depth),
747            "pointer_declarator" => {
748                depth += 1;
749                declarator = declarator.child_by_field_name("declarator")?;
750            }
751            "init_declarator" => declarator = declarator.child_by_field_name("declarator")?,
752            "reference_declarator" | "parenthesized_declarator" | "attributed_declarator" => {
753                declarator = first_named_child(declarator)?
754            }
755            _ => return None,
756        }
757    }
758}
759
760fn cpp_switch_enum_type<'tree>(switch: Node<'tree>, source: &str) -> Option<Node<'tree>> {
761    let mut operand = condition_expression(switch)?;
762    let mut fields = Vec::new();
763    while operand.kind() == "field_expression" {
764        fields.push(operand);
765        operand = operand.child_by_field_name("argument")?;
766    }
767    if operand.kind() != "identifier" {
768        return None;
769    }
770    let mut declaration =
771        cpp_switch_local_declaration(switch, node_text(operand, source)?, source)?;
772    for field in fields.into_iter().rev() {
773        let operator = field.child_by_field_name("operator")?;
774        let expected_depth = match operator.kind() {
775            "." => 0,
776            "->" => 1,
777            _ => return None,
778        };
779        if cpp_switch_pointer_depth(declaration.declarator)? != expected_depth {
780            return None;
781        }
782        let record = cpp_switch_named_type(declaration.type_node, source)?;
783        if !matches!(
784            record.kind(),
785            "class_specifier" | "struct_specifier" | "union_specifier"
786        ) {
787            return None;
788        }
789        let name = node_text(field.child_by_field_name("field")?, source)?;
790        let mut member = None;
791        for field_declaration in named_children_iter(record.child_by_field_name("body")?)
792            .filter(|node| node.kind() == "field_declaration")
793        {
794            for declarator in field_declaration
795                .children_by_field_name("declarator", &mut field_declaration.walk())
796            {
797                if declarator_name_node(declarator).and_then(|name| node_text(name, source))
798                    == Some(name)
799                {
800                    member = Some(CppSwitchDeclaration {
801                        type_node: field_declaration.child_by_field_name("type")?,
802                        declarator,
803                    });
804                }
805            }
806        }
807        declaration = member?;
808    }
809    if cpp_switch_pointer_depth(declaration.declarator)? != 0 {
810        return None;
811    }
812    let enum_type = cpp_switch_named_type(declaration.type_node, source)?;
813    (enum_type.kind() == "enum_specifier").then_some(enum_type)
814}
815
816fn declarator_identifier<'tree>(node: Node<'tree>) -> Option<Node<'tree>> {
817    let mut current = node;
818    loop {
819        match current.kind() {
820            "identifier" | "field_identifier" | "statement_identifier" => return Some(current),
821            "init_declarator"
822            | "pointer_declarator"
823            | "reference_declarator"
824            | "array_declarator"
825            | "parenthesized_declarator"
826            | "attributed_declarator" => {
827                current = current.child_by_field_name("declarator")?;
828            }
829            "qualified_identifier" => current = current.child_by_field_name("name")?,
830            _ => return None,
831        }
832    }
833}
834
835fn loop_variable<'tree>(loop_node: Node<'tree>, source: &'tree str) -> Option<&'tree str> {
836    let declarator = if loop_node.kind() == "for_range_loop" {
837        loop_node.child_by_field_name("declarator")
838    } else {
839        let initializer = loop_node.child_by_field_name("initializer")?;
840        if initializer.kind() == "declaration" {
841            initializer
842                .child_by_field_name("declarator")
843                .and_then(declarator_identifier)
844        } else if initializer.kind() == "assignment_expression" {
845            initializer
846                .child_by_field_name("left")
847                .and_then(expression_name_node)
848        } else {
849            None
850        }
851    }?;
852    let name = declarator_identifier(declarator).or(Some(declarator))?;
853    node_text(name, source)
854}
855
856impl brokk_bifrost_core::analyzer::statement_facts::producer::StatementFactSyntax
857    for CppStructuralSpec
858{
859    fn supports_kind(
860        &self,
861        kind: brokk_bifrost_core::analyzer::statement_facts::StatementFactKind,
862    ) -> bool {
863        use brokk_bifrost_core::analyzer::statement_facts::StatementFactKind;
864        !matches!(
865            kind,
866            StatementFactKind::NestedIfStatements | StatementFactKind::MisleadingIndentation
867        )
868    }
869
870    fn roles<'tree>(&self, node: Node<'tree>, role: Role) -> Vec<Node<'tree>> {
871        let target = match role {
872            Role::Test if node.kind() == "case_statement" => node.child_by_field_name("value"),
873            Role::Test => condition_expression(node),
874            Role::Consequence => node.child_by_field_name("consequence"),
875            Role::Alternative => {
876                brokk_bifrost_core::analyzer::structural::body_relations::if_alternative_body(
877                    node,
878                    brokk_bifrost_core::analyzer::structural::body_relations::syntax_for(
879                        Language::Cpp,
880                    )
881                    .expect("C++ body syntax"),
882                )
883            }
884            Role::Body => node.child_by_field_name("body"),
885            Role::Operator => node.child_by_field_name("operator"),
886            Role::Left => node.child_by_field_name("left"),
887            Role::Right => node.child_by_field_name("right"),
888            Role::Label => node.child_by_field_name("label"),
889            _ => None,
890        };
891        target.into_iter().collect()
892    }
893
894    fn is_code_child(&self, node: Node<'_>) -> bool {
895        !node.is_extra() && !node.kind().starts_with("preproc_") && node.kind() != "comment"
896    }
897
898    fn loop_variable(&self, node: Node<'_>, source: &str) -> Option<String> {
899        matches!(node.kind(), "for_statement" | "for_range_loop")
900            .then(|| loop_variable(node, source).map(str::to_owned))
901            .flatten()
902    }
903
904    fn is_counted_loop(&self, node: Node<'_>) -> bool {
905        node.kind() == "for_statement"
906    }
907
908    fn loop_initializers<'tree>(&self, node: Node<'tree>) -> Vec<Node<'tree>> {
909        node.child_by_field_name("initializer")
910            .into_iter()
911            .collect()
912    }
913
914    fn is_alloca(&self, node: Node<'_>, source: &str) -> bool {
915        node.kind() == "call_expression"
916            && node
917                .child_by_field_name("function")
918                .and_then(|function| node_text(function, source))
919                .is_some_and(|name| {
920                    matches!(name, "alloca" | "__builtin_alloca" | "_alloca" | "_malloca")
921                })
922    }
923
924    fn switch_enum<'tree>(&self, node: Node<'tree>, source: &str) -> Option<Node<'tree>> {
925        cpp_switch_enum_type(node, source)
926    }
927
928    fn enumeration(
929        &self,
930        node: Node<'_>,
931        source: &str,
932    ) -> Option<(
933        brokk_bifrost_core::analyzer::statement_facts::EnumFact,
934        Vec<brokk_bifrost_core::analyzer::statement_facts::EnumeratorFact>,
935    )> {
936        use brokk_bifrost_core::analyzer::statement_facts::{EnumFact, EnumeratorFact};
937        if node.kind() != "enum_specifier" {
938            return None;
939        }
940        let range = node_range(node);
941        let name = node
942            .child_by_field_name("name")
943            .and_then(|name| node_text(name, source))
944            .map(str::to_owned);
945        let mut enumerators = Vec::new();
946        let mut stack = vec![node];
947        while let Some(current) = stack.pop() {
948            if current != node && current.kind() == "enum_specifier" {
949                continue;
950            }
951            if current.kind() == "enumerator"
952                && let Some(name) = current.child_by_field_name("name")
953                && let Some(name) = node_text(name, source)
954            {
955                enumerators.push(EnumeratorFact {
956                    range: node_range(current),
957                    enum_range: range,
958                    name: name.to_owned(),
959                });
960            }
961            stack.extend(named_children_iter(current).filter(|child| !child.is_extra()));
962        }
963        Some((EnumFact { range, name }, enumerators))
964    }
965
966    fn name<'tree>(&self, node: Node<'tree>) -> Option<Node<'tree>> {
967        expression_name_node(node)
968    }
969}
970
971/// The persisted C++ generator label and the query-time rows share one classifier.
972pub fn statement_fact_kind(node: Node<'_>, source: &str) -> Option<StatementFactKind> {
973    brokk_bifrost_core::analyzer::statement_facts::producer::StatementFacts::new(
974        &CPP_STRUCTURAL_SPEC,
975    )
976    .expect("C++ statement syntax")
977    .classify(node, source, &Default::default())
978}
979
980pub(crate) fn capture_statement_fact_rows(
981    node: Node<'_>,
982    source: &str,
983    rows: &mut brokk_bifrost_core::analyzer::statement_facts::StatementFactRows,
984) {
985    brokk_bifrost_core::analyzer::statement_facts::producer::StatementFacts::new(
986        &CPP_STRUCTURAL_SPEC,
987    )
988    .expect("C++ statement syntax")
989    .capture(node, source, &Default::default(), rows);
990}
991
992#[cfg(test)]
993fn alloca_is_in_unbounded_loop(node: Node<'_>, source: &str) -> bool {
994    statement_fact_kind(node, source) == Some(StatementFactKind::AllocaInLoop)
995}
996
997#[cfg(test)]
998fn enum_switch_is_missing_case(node: Node<'_>, source: &str) -> bool {
999    let producer = brokk_bifrost_core::analyzer::statement_facts::producer::StatementFacts::new(
1000        &CPP_STRUCTURAL_SPEC,
1001    )
1002    .unwrap();
1003    let mut rows = brokk_bifrost_core::analyzer::statement_facts::StatementFactRows::default();
1004    producer.capture(node, source, &Default::default(), &mut rows);
1005    rows.switches.iter().any(|fact| fact.missing_enum_case)
1006}
1007
1008/// Whether tree-sitter recovered `.field = value` as a declaration child pair:
1009/// an `ERROR` containing only the anonymous dot immediately followed by an
1010/// `init_declarator` whose declarator is a real identifier.
1011///
1012/// This is intentionally narrower than rejecting declarators below `ERROR` in
1013/// general: macro-decorated declarations and ordinary comma-separated initialized
1014/// declarations also use recovery nodes and remain real declarations.
1015pub fn is_recovered_designator_init_declarator(node: Node<'_>) -> bool {
1016    if node.kind() != "init_declarator" {
1017        return false;
1018    }
1019    let Some(identifier) = node.child_by_field_name("declarator") else {
1020        return false;
1021    };
1022    if identifier.kind() != "identifier" || identifier.is_missing() {
1023        return false;
1024    }
1025    let Some(previous) = node.prev_named_sibling() else {
1026        return false;
1027    };
1028    if previous.kind() != "ERROR"
1029        || previous.named_child_count() != 0
1030        || previous.child_count() != 1
1031        || previous.end_byte() != node.start_byte()
1032    {
1033        return false;
1034    }
1035    previous.child(0).is_some_and(|child| {
1036        child.kind() == "."
1037            && !child.is_named()
1038            && child.start_byte() == previous.start_byte()
1039            && child.end_byte() == previous.end_byte()
1040    })
1041}
1042
1043use brokk_bifrost_core::analyzer::tree_walk::last_named_field_child;
1044
1045/// The declared name of a `namespace_definition`.
1046///
1047/// `namespace a::b { }` spells a `nested_namespace_specifier` that nests to
1048/// the right, so the innermost specifier's last child is the terminal segment.
1049/// An anonymous namespace has no `name` field at all and stays unnamed.
1050fn namespace_name_node<'tree>(namespace: Node<'tree>) -> Option<Node<'tree>> {
1051    let mut current = namespace.child_by_field_name("name")?;
1052    while current.kind() == "nested_namespace_specifier" {
1053        current = current.named_child(current.named_child_count().checked_sub(1)?)?;
1054    }
1055    Some(current)
1056}
1057
1058pub fn declarator_name_node<'tree>(declarator: Node<'tree>) -> Option<Node<'tree>> {
1059    let mut current = declarator;
1060    loop {
1061        match current.kind() {
1062            "identifier"
1063            | "field_identifier"
1064            | "namespace_identifier"
1065            | "type_identifier"
1066            | "destructor_name"
1067            | "operator_name"
1068            | "operator_cast"
1069            | "primitive_type" => return Some(current),
1070            "qualified_identifier" => current = last_named_field_child(current, "name")?,
1071            "dependent_name" => current = first_named_child(current)?,
1072            "template_function" | "template_method" | "template_type" => {
1073                current = current.child_by_field_name("name")?;
1074            }
1075            "function_declarator"
1076            | "pointer_declarator"
1077            | "pointer_type_declarator"
1078            | "macro_modifier_declarator"
1079            | "variadic_declarator"
1080            | "array_declarator"
1081            | "init_declarator" => current = current.child_by_field_name("declarator")?,
1082            "attributed_declarator" => current = first_named_child(current)?,
1083            "reference_declarator" | "parenthesized_declarator" => {
1084                current = first_named_child(current)?;
1085            }
1086            _ => return None,
1087        }
1088    }
1089}
1090
1091/// Grammar steps for the shared call-callee spine. A value expression has no step.
1092pub fn callee_spine_step(kind: &str) -> Option<CalleeSpineStep> {
1093    use CalleeSpineStep::{Field, FieldOrOnlyChild, Name, OnlyChild};
1094    match kind {
1095        "identifier"
1096        | "field_identifier"
1097        | "type_identifier"
1098        | "operator_name"
1099        | "operator_cast"
1100        | "destructor_name"
1101        | "literal_operator_name"
1102        | "primitive_type" => Some(Name),
1103        "qualified_identifier"
1104        | "scoped_identifier"
1105        | "scoped_type_identifier"
1106        | "template_function"
1107        | "template_method"
1108        | "template_type" => Some(Field("name")),
1109        "dependent_name" => Some(OnlyChild),
1110        "field_expression" => Some(Field("field")),
1111        "pointer_expression" => Some(FieldOrOnlyChild("argument")),
1112        _ => None,
1113    }
1114}
1115
1116fn expression_name_node<'tree>(expression: Node<'tree>) -> Option<Node<'tree>> {
1117    let mut current = expression;
1118    loop {
1119        match current.kind() {
1120            "identifier"
1121            | "field_identifier"
1122            | "namespace_identifier"
1123            | "type_identifier"
1124            | "destructor_name"
1125            | "operator_name"
1126            | "primitive_type"
1127            | "this" => return Some(current),
1128            "qualified_identifier" => current = last_named_field_child(current, "name")?,
1129            "dependent_name" => current = first_named_child(current)?,
1130            "template_function" | "template_method" | "template_type" => {
1131                current = current.child_by_field_name("name")?;
1132            }
1133            "field_expression" => current = current.child_by_field_name("field")?,
1134            "call_expression" => current = current.child_by_field_name("function")?,
1135            "new_expression" => current = current.child_by_field_name("type")?,
1136            "parenthesized_expression" => current = first_named_child(current)?,
1137            _ => return declarator_name_node(current),
1138        }
1139    }
1140}
1141
1142fn attach_qualified_scope_receiver(sink: &mut RoleSink<'_>, function: Node<'_>) {
1143    if function.kind() != "qualified_identifier" {
1144        return;
1145    }
1146    if let Some(scope) = function.child_by_field_name("scope") {
1147        attach_role_with_derived_name(sink, Role::Receiver, scope, expression_name_node);
1148    }
1149}
1150
1151fn qualified_declarator_node(mut node: Node<'_>) -> Option<Node<'_>> {
1152    loop {
1153        if node.kind() == "qualified_identifier" {
1154            return Some(node);
1155        }
1156        node = node
1157            .child_by_field_name("declarator")
1158            .or_else(|| node.child_by_field_name("name"))
1159            .or_else(|| first_named_child(node))?;
1160    }
1161}
1162
1163fn scoped_function_definition(node: Node<'_>) -> Option<Node<'_>> {
1164    node.child_by_field_name("declarator")
1165        .and_then(qualified_declarator_node)
1166        .and_then(|qualified| qualified.child_by_field_name("scope"))
1167}
1168
1169pub fn constructor_scope_matches_name(scope: Node<'_>, name: Node<'_>, source: &str) -> bool {
1170    node_text(scope, source) == node_text(name, source)
1171}
1172
1173fn is_constructor_definition(node: Node<'_>, source: &str) -> bool {
1174    node.child_by_field_name("declarator")
1175        .and_then(qualified_declarator_node)
1176        .and_then(|qualified| {
1177            Some((
1178                expression_name_node(qualified.child_by_field_name("scope")?)?,
1179                expression_name_node(last_named_field_child(qualified, "name")?)?,
1180            ))
1181        })
1182        .is_some_and(|(scope, name)| constructor_scope_matches_name(scope, name, source))
1183}
1184
1185fn unquoted_include_span(node: Node<'_>) -> Option<Span> {
1186    if !matches!(node.kind(), "string_literal" | "system_lib_string") {
1187        return None;
1188    }
1189    unquoted_string_content_span(node)
1190}
1191
1192/// The names of every function-like macro this translation unit defines, read
1193/// from `preproc_function_def` name fields.
1194///
1195/// The walk is iterative and descends only through preprocessor conditional
1196/// blocks, which is where a definition can nest. A `#define` written inside a
1197/// function body is not collected; that is a known and stated boundary, not an
1198/// approximation of one.
1199fn function_like_macro_names(root: Node<'_>, source: &str) -> HashSet<String> {
1200    let mut names = HashSet::default();
1201    let mut stack = vec![root];
1202    while let Some(node) = stack.pop() {
1203        for child in named_children_iter(node) {
1204            match child.kind() {
1205                "preproc_function_def" => {
1206                    if let Some(name) = child.child_by_field_name("name") {
1207                        names.insert(source[name.start_byte()..name.end_byte()].to_owned());
1208                    }
1209                }
1210                "preproc_if" | "preproc_ifdef" | "preproc_else" | "preproc_elif"
1211                | "preproc_elifdef" => stack.push(child),
1212                _ => {}
1213            }
1214        }
1215    }
1216    names
1217}
1218
1219/// Return the one identifier-bearing node that spells a member in a C++
1220/// `field_expression`.
1221///
1222/// The grammar permits the `field` child to be a qualified name, a dependent
1223/// name, a template method, or a destructor name. `expression_name_node`
1224/// already follows those wrappers to their terminal name. Walking upward from
1225/// the candidate and comparing that terminal node keeps receiver identifiers,
1226/// declaration names, field-designator labels, and path prefixes out of the
1227/// member role without looking at source text.
1228fn cpp_member_position(node: Node<'_>) -> Option<OccurrenceRole> {
1229    if !matches!(
1230        node.kind(),
1231        "identifier" | "field_identifier" | "type_identifier" | "operator_name" | "destructor_name"
1232    ) {
1233        return None;
1234    }
1235
1236    let mut current = node;
1237    while let Some(parent) = current.parent() {
1238        if parent.kind() == "field_expression" {
1239            let field = parent.child_by_field_name("field")?;
1240            return expression_name_node(field)
1241                .filter(|name| name.id() == node.id())
1242                .map(|_| OccurrenceRole::MemberPosition);
1243        }
1244
1245        // These are the only named wrappers that can occur between the
1246        // terminal field name and its owning field expression.
1247        if matches!(
1248            parent.kind(),
1249            "qualified_identifier" | "dependent_name" | "template_method" | "destructor_name"
1250        ) {
1251            current = parent;
1252        } else {
1253            return None;
1254        }
1255    }
1256    None
1257}
1258
1259/// What declares a C or C++ binder.
1260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1261enum CppBinderOwner<'tree> {
1262    /// A parameter of a function definition, a lambda or a `catch` clause.
1263    Parameter,
1264    /// A local declaration; the node is the declarator the name completes.
1265    Local(Node<'tree>),
1266    /// A range-based `for` variable; the node is the loop.
1267    RangeFor(Node<'tree>),
1268    /// A structured binding; the node is the binding declarator.
1269    StructuredBinding(Node<'tree>),
1270    /// A lambda init-capture (`[x = y]`).
1271    InitCapture,
1272}
1273
1274/// Declarator wrappers that carry a name inward through their `declarator`
1275/// field or their single named child.
1276const CPP_DECLARATOR_WRAPPERS: &[&str] = &[
1277    "pointer_declarator",
1278    "array_declarator",
1279    "reference_declarator",
1280    "parenthesized_declarator",
1281    "attributed_declarator",
1282    "variadic_declarator",
1283];
1284
1285/// What declares `node` as a C or C++ variable, or `None` when it is not a
1286/// variable binder.
1287///
1288/// The name is found by walking up the declarator chain. A name that reaches
1289/// a function declarator without passing a pointer or reference declarator
1290/// names a function; one that does names a function pointer variable. A
1291/// parameter binds only in a function definition, a lambda or a `catch`
1292/// clause; a prototype's parameter names bind nothing. A file-scope or
1293/// member declaration names a member or a global, not a lexical binding.
1294fn cpp_binder_owner<'tree>(
1295    node: Node<'tree>,
1296    parent: impl Fn(Node<'tree>) -> Option<Node<'tree>>,
1297    mut field_name: impl FnMut(Node<'tree>, Node<'tree>) -> Option<&'static str>,
1298) -> Option<CppBinderOwner<'tree>> {
1299    if node.kind() != "identifier" {
1300        return None;
1301    }
1302    let mut child = node;
1303    let mut current = parent(node)?;
1304    let mut indirect = false;
1305    loop {
1306        // This field lookup scans earlier siblings. Generated C initializer
1307        // lists can be enormous, so only ask for fields on binder-shaped nodes.
1308        match current.kind() {
1309            kind if CPP_DECLARATOR_WRAPPERS.contains(&kind) => {
1310                let field = field_name(current, child);
1311                if field.is_some() && field != Some("declarator") {
1312                    return None;
1313                }
1314                indirect |= matches!(kind, "pointer_declarator" | "reference_declarator");
1315            }
1316            "function_declarator" => {
1317                let field = field_name(current, child);
1318                if field != Some("declarator") || !indirect {
1319                    return None;
1320                }
1321            }
1322            "init_declarator" => {
1323                let field = field_name(current, child);
1324                if field != Some("declarator") {
1325                    return None;
1326                }
1327            }
1328            "declaration" => {
1329                let field = field_name(current, child);
1330                if field != Some("declarator") {
1331                    return None;
1332                }
1333                let local = std::iter::successors(parent(current), |node| parent(*node))
1334                    .take_while(|node| {
1335                        !matches!(
1336                            node.kind(),
1337                            "translation_unit"
1338                                | "field_declaration_list"
1339                                | "declaration_list"
1340                                | "namespace_definition"
1341                        )
1342                    })
1343                    .any(|node| {
1344                        matches!(
1345                            node.kind(),
1346                            "compound_statement" | "for_statement" | "condition_clause"
1347                        )
1348                    });
1349                // The name's scope starts at the end of its declarator, before
1350                // any initializer.
1351                let declarator = if child.kind() == "init_declarator" {
1352                    child.child_by_field_name("declarator")?
1353                } else {
1354                    child
1355                };
1356                return local.then_some(CppBinderOwner::Local(declarator));
1357            }
1358            "parameter_declaration"
1359            | "optional_parameter_declaration"
1360            | "variadic_parameter_declaration" => {
1361                let field = field_name(current, child);
1362                if field != Some("declarator") {
1363                    return None;
1364                }
1365                let parameter_parent = parent(current)?;
1366                let list = if parameter_parent.kind() == "explicit_object_parameter_declaration" {
1367                    // The explicit-object wrapper owns exactly `this` and this
1368                    // parameter; only then may its parent supply the list.
1369                    if parameter_parent.named_child(0).map(|node| node.kind()) != Some("this")
1370                        || parameter_parent.named_child(1) != Some(current)
1371                    {
1372                        return None;
1373                    }
1374                    parent(parameter_parent)?
1375                } else {
1376                    parameter_parent
1377                };
1378                if list.kind() != "parameter_list" {
1379                    return None;
1380                }
1381                let owner = parent(list)?;
1382                let binds = match owner.kind() {
1383                    "catch_clause" => true,
1384                    "lambda_declarator" | "abstract_function_declarator" => parent(owner)
1385                        .is_some_and(|lambda| {
1386                            lambda.kind() == "lambda_expression"
1387                                && lambda.child_by_field_name("declarator") == Some(owner)
1388                        }),
1389                    "function_declarator" => {
1390                        let mut declarator = owner;
1391                        loop {
1392                            let Some(up) = parent(declarator) else {
1393                                break false;
1394                            };
1395                            if up.kind() == "function_definition" {
1396                                break field_name_in_parent(up, declarator) == Some("declarator");
1397                            }
1398                            if !CPP_DECLARATOR_WRAPPERS.contains(&up.kind()) {
1399                                break false;
1400                            }
1401                            declarator = up;
1402                        }
1403                    }
1404                    _ => false,
1405                };
1406                return binds.then_some(CppBinderOwner::Parameter);
1407            }
1408            "for_range_loop" => {
1409                let field = field_name(current, child);
1410                return (field == Some("declarator")).then_some(CppBinderOwner::RangeFor(current));
1411            }
1412            "structured_binding_declarator" => {
1413                return Some(CppBinderOwner::StructuredBinding(current));
1414            }
1415            "lambda_capture_initializer" => {
1416                let field = field_name(current, child);
1417                return (field == Some("left")).then_some(CppBinderOwner::InitCapture);
1418            }
1419            _ => return None,
1420        }
1421        child = current;
1422        current = parent(current)?;
1423    }
1424}
1425
1426/// Whether `node` declares a C or C++ variable, climbing through the walk's
1427/// parent index: asking `Node::parent` re-descends from the root, which is
1428/// quadratic over a large file.
1429fn cpp_is_binder<'tree>(node: Node<'tree>, parents: &ParentIndex<'tree>) -> bool {
1430    cpp_binder_owner(node, |node| parents.parent(node), field_name_in_parent).is_some()
1431}
1432
1433/// The binding one C or C++ binder token introduces, and the interval it is
1434/// in effect over.
1435///
1436/// A parameter or init-capture is in effect over its whole function, lambda
1437/// or catch clause. A local is in effect from the end of its declarator: C
1438/// and C++ start a name's scope there, before its initializer, so in
1439/// `int x = x;` the right side reads the new `x`. A condition declaration is
1440/// therefore in effect over the rest of its `if`, including `else`. A
1441/// range-`for` variable is in effect over the loop body, and a structured
1442/// binding from the end of its binding declarator.
1443fn cpp_binding_activation(binder: Node<'_>, scope: Range) -> Option<BindingActivation> {
1444    let binding = |kind, hoisting, activation| {
1445        Some(BindingActivation {
1446            kind,
1447            hoisting,
1448            activation,
1449        })
1450    };
1451    let after = |node: Node<'_>| Range {
1452        start_byte: node.end_byte(),
1453        end_byte: scope.end_byte,
1454        start_line: node.end_position().row + 1,
1455        end_line: scope.end_line,
1456    };
1457    match cpp_binder_owner(binder, |node| node.parent(), field_name_in_parent)? {
1458        CppBinderOwner::Parameter | CppBinderOwner::InitCapture => {
1459            binding(BindingKind::Parameter, HoistingClass::ScopeWide, scope)
1460        }
1461        CppBinderOwner::Local(declarator) => binding(
1462            BindingKind::Local,
1463            HoistingClass::SourceOrder,
1464            after(declarator),
1465        ),
1466        CppBinderOwner::RangeFor(loop_node) => binding(
1467            BindingKind::LoopVariable,
1468            HoistingClass::DeclaredHead,
1469            node_range(loop_node.child_by_field_name("body")?),
1470        ),
1471        CppBinderOwner::StructuredBinding(declarator) => binding(
1472            BindingKind::Local,
1473            HoistingClass::SourceOrder,
1474            after(declarator),
1475        ),
1476    }
1477}
1478
1479impl StructuralSpec for CppStructuralSpec {
1480    fn language(&self) -> Language {
1481        Language::Cpp
1482    }
1483
1484    fn supports_boolean_literal_value(&self) -> bool {
1485        true
1486    }
1487
1488    fn supports_string_literal_value(&self) -> bool {
1489        true
1490    }
1491
1492    fn string_literal_value_may_be_absent(&self, node: Node<'_>, source: &str) -> bool {
1493        matches!(node.kind(), "string_literal" | "raw_string_literal")
1494            && cpp_string_literal_value(node, source).is_none()
1495    }
1496
1497    fn string_literal_value(&self, node: Node<'_>, source: &str) -> Option<String> {
1498        cpp_string_literal_value(node, source)
1499    }
1500
1501    fn kind_table(&self) -> &'static [(&'static str, NormalizedKind)] {
1502        CPP_KIND_TABLE
1503    }
1504
1505    fn statement_fact_syntax(
1506        &self,
1507    ) -> Option<&dyn brokk_bifrost_core::analyzer::statement_facts::producer::StatementFactSyntax>
1508    {
1509        Some(self)
1510    }
1511
1512    fn generator_construct(
1513        &self,
1514        node: Node<'_>,
1515        _kind: NormalizedKind,
1516        source: &str,
1517    ) -> Option<&'static str> {
1518        statement_fact_kind(node, source).map(StatementFactKind::construct)
1519    }
1520
1521    fn refine_kind(
1522        &self,
1523        node: Node<'_>,
1524        kind: NormalizedKind,
1525        enclosing: Option<NormalizedKind>,
1526        source: &str,
1527        _context: &CallSiteContext,
1528    ) -> NormalizedKind {
1529        if kind == NormalizedKind::Function
1530            && (enclosing == Some(NormalizedKind::Class)
1531                || scoped_function_definition(node).is_some())
1532        {
1533            if is_constructor_definition(node, source) {
1534                NormalizedKind::Constructor
1535            } else {
1536                NormalizedKind::Method
1537            }
1538        } else {
1539            kind
1540        }
1541    }
1542
1543    fn supports_kind(&self, kind: NormalizedKind) -> bool {
1544        matches!(
1545            kind,
1546            NormalizedKind::Method | NormalizedKind::Constructor | NormalizedKind::SyntaxError
1547        ) || self
1548            .kind_table()
1549            .iter()
1550            .any(|(_, fact_kind)| fact_kind.satisfies(kind))
1551    }
1552
1553    fn supports_role(&self, role: Role) -> bool {
1554        !matches!(
1555            role,
1556            Role::Kwarg | Role::Decorator | Role::Iterable | Role::Element
1557        )
1558    }
1559
1560    fn call_site_context(&self, root: Node<'_>, source: &str) -> CallSiteContext {
1561        CallSiteContext::with_macro_derived_callees(function_like_macro_names(root, source))
1562    }
1563
1564    /// A `new_expression` is a constructor call, and a call whose callee names
1565    /// a function-like macro of this translation unit has an argument list
1566    /// that belongs to the macro, not to the callable that finally runs
1567    /// (#1478). `CALL_TWICE(2)` parses as an ordinary call of two source
1568    /// arguments even when the expansion calls a three-parameter callable, so
1569    /// the honest answer is unknown coverage and no argument rows at all —
1570    /// never a fabricated list an exact-arity assertion could read as clean.
1571    ///
1572    /// The boundary is deliberate: only macros defined in this file are
1573    /// known here, because that is what this file's parse tree contains. A
1574    /// macro defined in an included header leaves the site exact, which is
1575    /// the same answer the analyzer gives today.
1576    fn call_site_facts(
1577        &self,
1578        node: Node<'_>,
1579        source: &str,
1580        context: &CallSiteContext,
1581    ) -> Option<CallSiteFacts> {
1582        if node.kind() == "new_expression" {
1583            return Some(CallSiteFacts::of_kind(CallKind::Constructor));
1584        }
1585        let callee = node.child_by_field_name("function")?;
1586        (callee.kind() == "identifier"
1587            && context.is_macro_derived_callee(&source[callee.start_byte()..callee.end_byte()]))
1588        .then(|| CallSiteFacts::of_coverage(CallShapeCoverage::UnknownMacroDerived))
1589    }
1590
1591    fn occurrence_role_support(&self) -> &OccurrenceRoleSupport {
1592        static SUPPORT: OccurrenceRoleSupport = OccurrenceRoleSupport::NONE
1593            .supported(OccurrenceRole::MemberPosition)
1594            .supported(OccurrenceRole::ValueReference)
1595            .supported(OccurrenceRole::Binder);
1596        &SUPPORT
1597    }
1598
1599    fn lexical_environment_support(&self) -> &LexicalEnvironmentSupport {
1600        // C and C++ derive scopes and binding intervals; import binders and
1601        // the package clause are not derived. The call seams report
1602        // per-candidate callable applicability (#1478 M3).
1603        static SUPPORT: LexicalEnvironmentSupport = LexicalEnvironmentSupport::NONE
1604            .supported(EnvironmentAxis::Scopes)
1605            .supported(EnvironmentAxis::BindingIntervals)
1606            .supported(EnvironmentAxis::CallableApplicability);
1607        &SUPPORT
1608    }
1609
1610    /// An `if` statement is a scope: a C++ condition or init-statement
1611    /// declaration is in effect in both branches and nowhere after.
1612    fn scope_formation(&self, kind: NormalizedKind) -> ScopeFormation {
1613        if matches!(kind, NormalizedKind::If | NormalizedKind::Switch) {
1614            ScopeFormation::BindingScope
1615        } else {
1616            default_scope_formation(kind)
1617        }
1618    }
1619
1620    fn binding_activation(&self, binder: Node<'_>, scope: Range) -> Option<BindingActivation> {
1621        cpp_binding_activation(binder, scope)
1622    }
1623
1624    fn materialization_support(&self) -> &DeclarationMaterializationSupport {
1625        &CPP_MATERIALIZATION_SUPPORT
1626    }
1627
1628    fn reference_edge_support(&self) -> &ReferenceEdgeSupport {
1629        &INVERSE_REFERENCE_EDGE_SUPPORT
1630    }
1631
1632    fn identity_route_support(&self) -> &IdentityRouteSupport {
1633        // C++'s occurrence adapter is shallow, so it claims no path axes. Its
1634        // declaration layer keeps prototype/body occurrences distinct, which
1635        // the physical-grouping axis carries, and the analyzer now labels each
1636        // of those occurrences a head or a body and pairs a prototype with the
1637        // out-of-line callable body that defines it, so the
1638        // declaration-definition peer relation is supplied as typed rows with
1639        // the body occurrence's own range as provenance (#1650). Classes stay
1640        // outside that relation: a same-file forward declaration is not a
1641        // distinct occurrence, and across files a class carries no linkage
1642        // evidence to pair on.
1643        static SUPPORT: IdentityRouteSupport = IdentityRouteSupport::NONE
1644            .supported_axis(IdentityAxis::CanonicalIdentity)
1645            .supported_axis(IdentityAxis::PhysicalGrouping)
1646            .supported_relation(RouteHopKind::NestedOwner)
1647            .supported_relation(RouteHopKind::DeclarationDefinitionPeer);
1648        &SUPPORT
1649    }
1650
1651    fn extract(&self, node: Node<'_>, kind: NormalizedKind, sink: &mut RoleSink<'_>) {
1652        if let Some(role) = cpp_member_position(node) {
1653            sink.occurrence_role(node, role);
1654        } else if cpp_is_binder(node, sink.parents()) {
1655            sink.occurrence_role(node, OccurrenceRole::Binder);
1656        }
1657
1658        match kind {
1659            NormalizedKind::Call => {
1660                let function_field = if node.kind() == "new_expression" {
1661                    "type"
1662                } else {
1663                    "function"
1664                };
1665                if let Some(function) = node.child_by_field_name(function_field) {
1666                    attach_terminal_callee(
1667                        sink,
1668                        function,
1669                        terminal_callee_leaf(function, callee_spine_step),
1670                    );
1671                    // The callee token of a free-function call is a plain value
1672                    // read, and it is the only occurrence the call site leaves
1673                    // behind when the function is not indexed (#3466). Member
1674                    // calls are excluded: their terminal field is already the
1675                    // member-position occurrence, and classifying it twice would
1676                    // report one call site as two. A composite callee
1677                    // expression names its own callee at an inner node
1678                    // (`f()()`), so it is excluded too.
1679                    if node.kind() == "call_expression"
1680                        && !matches!(function.kind(), "field_expression" | "call_expression")
1681                        && let Some(callee) = expression_name_node(function)
1682                        && self.kind_table().iter().any(|(node_kind, kind)| {
1683                            *node_kind == callee.kind() && self.should_extract(callee, *kind)
1684                        })
1685                    {
1686                        sink.occurrence_role(callee, OccurrenceRole::ValueReference);
1687                    }
1688                    if function.kind() == "field_expression"
1689                        && let Some(argument) = function.child_by_field_name("argument")
1690                    {
1691                        attach_role_with_derived_name(
1692                            sink,
1693                            Role::Receiver,
1694                            argument,
1695                            expression_name_node,
1696                        );
1697                    }
1698                    attach_qualified_scope_receiver(sink, function);
1699                }
1700                if let Some(arguments) = node.child_by_field_name("arguments") {
1701                    attach_positional_argument_roles(sink, arguments, expression_name_node);
1702                }
1703            }
1704            NormalizedKind::FieldAccess => {
1705                if let Some(field) = node.child_by_field_name("field") {
1706                    attach_role_with_derived_name(sink, Role::Field, field, expression_name_node);
1707                    if let Some(name) = expression_name_node(field) {
1708                        sink.set_name(name);
1709                    }
1710                }
1711                if let Some(argument) = node.child_by_field_name("argument") {
1712                    attach_role_with_derived_name(
1713                        sink,
1714                        Role::Object,
1715                        argument,
1716                        expression_name_node,
1717                    );
1718                }
1719            }
1720            NormalizedKind::Function | NormalizedKind::Method | NormalizedKind::Constructor => {
1721                if let Some(name) = node
1722                    .child_by_field_name("declarator")
1723                    .and_then(declarator_name_node)
1724                {
1725                    sink.set_name(name);
1726                }
1727            }
1728            NormalizedKind::Module => {
1729                if let Some(name) = namespace_name_node(node) {
1730                    sink.set_name(name);
1731                }
1732            }
1733            NormalizedKind::Class | NormalizedKind::Declaration => {
1734                if let Some(name) = node
1735                    .child_by_field_name("name")
1736                    .and_then(declarator_name_node)
1737                    .or_else(|| node.child_by_field_name("name"))
1738                {
1739                    sink.set_name(name);
1740                }
1741            }
1742            NormalizedKind::Assignment => match node.kind() {
1743                "init_declarator" => {
1744                    if let Some(declarator) = node.child_by_field_name("declarator") {
1745                        attach_role_with_derived_name(
1746                            sink,
1747                            Role::Left,
1748                            declarator,
1749                            declarator_name_node,
1750                        );
1751                        if let Some(name) = declarator_name_node(declarator) {
1752                            sink.set_name(name);
1753                        }
1754                    }
1755                    if let Some(value) = node.child_by_field_name("value") {
1756                        attach_role_with_derived_name(
1757                            sink,
1758                            Role::Right,
1759                            value,
1760                            expression_name_node,
1761                        );
1762                    }
1763                }
1764                "assignment_expression" => {
1765                    if let Some(left) = node.child_by_field_name("left") {
1766                        attach_role_with_derived_name(sink, Role::Left, left, expression_name_node);
1767                    }
1768                    if let Some(right) = node.child_by_field_name("right") {
1769                        attach_role_with_derived_name(
1770                            sink,
1771                            Role::Right,
1772                            right,
1773                            expression_name_node,
1774                        );
1775                    }
1776                }
1777                _ => {}
1778            },
1779            NormalizedKind::Import => {
1780                if let Some(path) = node.child_by_field_name("path") {
1781                    if let Some(name) = unquoted_include_span(path) {
1782                        sink.role_named_span(Role::Module, path, name);
1783                    } else {
1784                        attach_role_with_derived_name(
1785                            sink,
1786                            Role::Module,
1787                            path,
1788                            expression_name_node,
1789                        );
1790                    }
1791                }
1792            }
1793            NormalizedKind::Identifier => match expression_name_node(node) {
1794                Some(name) => sink.set_name(name),
1795                None => sink.set_name(node),
1796            },
1797            _ => {}
1798        }
1799    }
1800}
1801
1802#[cfg(test)]
1803mod tests {
1804    use super::CPP_STRUCTURAL_SPEC;
1805    use super::cpp_binder_owner;
1806    use super::cpp_member_position;
1807    use super::field_name_in_parent;
1808    use super::node_range;
1809    use brokk_bifrost_core::analyzer::source_facts::PrimarySourceFactCollector;
1810    use brokk_bifrost_core::analyzer::structural::collector::StructuralFactCollector;
1811    use brokk_bifrost_core::analyzer::structural::facts::StructuralFactRows;
1812    use brokk_bifrost_core::analyzer::structural::kinds::NormalizedKind;
1813    use brokk_bifrost_core::analyzer::structural::occurrences::OccurrenceRole;
1814    use brokk_bifrost_core::analyzer::structural::resolution::BindingKind;
1815    use brokk_bifrost_core::analyzer::structural::spec::{CompiledKinds, RoleSink, StructuralSpec};
1816    use brokk_bifrost_core::analyzer::tree_walk::ParentIndex;
1817    use brokk_bifrost_core::hash::HashMap;
1818    use brokk_bifrost_test_macros::hardwon;
1819    use tree_sitter::Parser;
1820
1821    #[test]
1822    #[hardwon(
1823        "e3c20990a105: quicksilver round 4 on brokk-bifrost-cpp: unrelated comparisons suppress alloca-in-loop"
1824    )]
1825    fn alloca_bound_must_constrain_loop_variable() {
1826        for (condition, expected) in [
1827            ("i < n && enabled < 1", true),
1828            ("i < n || i < 1", true),
1829            ("i < 1", false),
1830            ("1 > i && enabled", false),
1831        ] {
1832            let source = format!(
1833                "void f(int n, int enabled) {{ for (int i=0; {condition}; ++i) {{ alloca(16); }} }}"
1834            );
1835            let mut parser = Parser::new();
1836            parser
1837                .set_language(&tree_sitter_cpp::LANGUAGE.into())
1838                .unwrap();
1839            let tree = parser.parse(&source, None).unwrap();
1840            let mut stack = vec![tree.root_node()];
1841            let mut actual = None;
1842            while let Some(node) = stack.pop() {
1843                if node.kind() == "call_expression" {
1844                    actual = Some(super::alloca_is_in_unbounded_loop(node, &source));
1845                }
1846                stack.extend(super::named_children_iter(node));
1847            }
1848            assert_eq!(actual, Some(expected), "{source}");
1849        }
1850    }
1851
1852    #[test]
1853    #[hardwon(
1854        "e3c20990a105: quicksilver round 4 on brokk-bifrost-cpp: integer switches borrow unrelated enum cases"
1855    )]
1856    fn integer_switch_is_not_an_enum_switch() {
1857        let source = "enum E { A, B }; void f(int value) { switch(value) { case A: break; } }";
1858        let mut parser = Parser::new();
1859        parser
1860            .set_language(&tree_sitter_cpp::LANGUAGE.into())
1861            .unwrap();
1862        let tree = parser.parse(source, None).unwrap();
1863        let mut stack = vec![tree.root_node()];
1864        let mut checked = false;
1865        while let Some(node) = stack.pop() {
1866            if node.kind() == "switch_statement" {
1867                checked = true;
1868                assert!(!super::enum_switch_is_missing_case(node, source));
1869            }
1870            stack.extend(super::named_children_iter(node));
1871        }
1872        assert!(checked);
1873    }
1874
1875    #[test]
1876    #[hardwon(
1877        "e3c20990a105: quicksilver round 4 on brokk-bifrost-cpp: enum coverage needs scoped local declaration evidence"
1878    )]
1879    fn enum_switch_uses_local_type_evidence() {
1880        for (source, expected) in [
1881            (
1882                "enum E { A,B }; void f(E e) { switch(e) {case A:break;} }",
1883                vec![true],
1884            ),
1885            (
1886                "enum E { A,B }; void f() { E e=A; switch(e) {case A:break;} }",
1887                vec![true],
1888            ),
1889            (
1890                "enum class E { A,B }; void f(E e) { switch(e) {case E::A:break;} }",
1891                vec![true],
1892            ),
1893            (
1894                "namespace ns { enum class E { A,B }; } void f(ns::E e) { switch(e) {case ns::E::A:break;} }",
1895                vec![true],
1896            ),
1897            (
1898                "enum E { A,B }; struct S { E state; }; void f(S s) { switch(s.state) {case A:break;} }",
1899                vec![true],
1900            ),
1901            (
1902                "enum E { A,B }; struct S { E state; }; void f() { S s; switch(s.state) {case A:break;} }",
1903                vec![true],
1904            ),
1905            (
1906                "enum E { A,B }; void f(E e) { { int e=0; switch(e) {case A:break;} } switch(e) {case A:break;} }",
1907                vec![false, true],
1908            ),
1909            (
1910                "enum E { A,B }; void f(E e) { { int e=0; } switch(e) {case A:break;} }",
1911                vec![true],
1912            ),
1913            (
1914                "enum E { A,B }; void f() { switch(e) {case A:break;} E e=A; }",
1915                vec![false],
1916            ),
1917            (
1918                "enum E { A,B }; using Alias=E; void f(Alias e) { switch(e) {case A:break;} }",
1919                vec![false],
1920            ),
1921            (
1922                "enum E { A,B }; void f(E e) { switch(e==A) {case A:break;} }",
1923                vec![false],
1924            ),
1925            (
1926                "enum E { A,B }; E e; void f() { switch(e) {case A:break;} }",
1927                vec![false],
1928            ),
1929            (
1930                "enum E { A,B }; void f(E &e) { switch(e) {case A:break;} }",
1931                vec![true],
1932            ),
1933            (
1934                "enum E { A,B }; void f(E *e) { switch(e) {case A:break;} }",
1935                vec![false],
1936            ),
1937            (
1938                "enum E { A,B }; struct S { E state; }; void f(S *s) { switch(s->state) {case A:break;} }",
1939                vec![true],
1940            ),
1941            (
1942                "enum E { A,B }; struct S { int state; }; void f(S s) { switch(s.state) {case A:break;} }",
1943                vec![false],
1944            ),
1945            (
1946                "enum E { A,B }; struct Inner { E state; }; struct Outer { Inner inner; }; void f(Outer s) { switch(s.inner.state) {case A:break;} }",
1947                vec![true],
1948            ),
1949            (
1950                "void f() { enum class E { A,B }; E e=E::A; switch(e) {case E::A:break;} }",
1951                vec![true],
1952            ),
1953            (
1954                "struct S { enum class E { A,B }; E state; }; void f(S s) { switch(s.state) {case S::E::A:break;} }",
1955                vec![true],
1956            ),
1957            (
1958                "namespace n { namespace m { enum class E { A,B }; } } void f(n::m::E e) { switch(e) {case n::m::E::A:break;} }",
1959                vec![true],
1960            ),
1961            (
1962                "enum E { A,B }; void f() { using E=int; E e=0; switch(e) {case A:break;} }",
1963                vec![false],
1964            ),
1965            (
1966                "enum E { A,B }; void f(E e) { { int e(); switch(e) {case A:break;} } }",
1967                vec![false],
1968            ),
1969            (
1970                "enum E { A,B }; void f(E e) { auto g=[e]() { switch(e) {case A:break;} }; }",
1971                vec![false],
1972            ),
1973            (
1974                "enum E { A,B }; void f() { auto g=[](E e) { switch(e) {case A:break;} }; }",
1975                vec![true],
1976            ),
1977            (
1978                "namespace n::m { enum class E { A,B }; } void f(n::m::E e) { switch(e) {case n::m::E::A:break;} }",
1979                vec![true],
1980            ),
1981            (
1982                "void f() { enum E { A,B } e=A; switch(e) {case A:break;} }",
1983                vec![true],
1984            ),
1985            (
1986                "enum E { A,B }; void f(E (&values)[2]) { for (E e : values) { switch(e) {case A:break;} } }",
1987                vec![true],
1988            ),
1989            (
1990                "enum E { A,B }; namespace n { enum E { A,C }; } void f() { using n::E; E e; switch(e) {case A:break;} }",
1991                vec![false],
1992            ),
1993            (
1994                "enum E { A,B }; namespace n { enum E { A }; void f(E); } void n::f(E e) { switch(e) {case n::A:break;} }",
1995                vec![false],
1996            ),
1997            (
1998                "enum E { A,B }; void f(E e) { switch(int e=0; e) {case A:break;} }",
1999                vec![false],
2000            ),
2001            (
2002                "enum E { A,B }; void f() { switch(E e=A; e) {case A:break;} }",
2003                vec![true],
2004            ),
2005            (
2006                "enum E { A,B }; template<typename E> void f(E e) { switch(e) {case A:break;} }",
2007                vec![false],
2008            ),
2009            (
2010                "enum E { A,B }; template<typename... T> void f(T... e) { switch(e) {case A:break;} }",
2011                vec![false],
2012            ),
2013            (
2014                "namespace n { enum E { A,B }; } namespace m { enum E { A }; } namespace r { namespace n=m; void f(n::E e) { switch(e) {case m::A:break;} } }",
2015                vec![false],
2016            ),
2017            (
2018                "struct R { enum E { A,B }; }; struct S { enum E { A }; }; void f() { using R=S; R::E e; switch(e) {case S::A:break;} }",
2019                vec![false],
2020            ),
2021            (
2022                "enum E { A,B }; struct Base { enum E { A }; }; struct S: Base { void f(E e) { switch(e) {case A:break;} } };",
2023                vec![false],
2024            ),
2025            (
2026                "enum E { A,B }; struct S { void f() { E e; switch(e) {case A:break;} } enum E { A }; };",
2027                vec![false],
2028            ),
2029        ] {
2030            let mut parser = Parser::new();
2031            parser
2032                .set_language(&tree_sitter_cpp::LANGUAGE.into())
2033                .unwrap();
2034            let tree = parser.parse(source, None).unwrap();
2035            assert!(
2036                !tree.root_node().has_error(),
2037                "{source}: {}",
2038                tree.root_node().to_sexp()
2039            );
2040            let mut stack = vec![tree.root_node()];
2041            let mut results = Vec::new();
2042            while let Some(node) = stack.pop() {
2043                if node.kind() == "switch_statement" {
2044                    results.push((
2045                        node.start_byte(),
2046                        super::enum_switch_is_missing_case(node, source),
2047                    ));
2048                }
2049                stack.extend(super::named_children_iter(node));
2050            }
2051            results.sort_unstable_by_key(|(start, _)| *start);
2052            assert_eq!(
2053                results.into_iter().map(|(_, v)| v).collect::<Vec<_>>(),
2054                expected,
2055                "{source}"
2056            );
2057        }
2058    }
2059
2060    fn collect_cpp_structural_facts(source: &str) {
2061        collect_structural_rows(source);
2062    }
2063
2064    fn collect_structural_rows(source: &str) -> StructuralFactRows {
2065        let mut parser = Parser::new();
2066        parser
2067            .set_language(&tree_sitter_cpp::LANGUAGE.into())
2068            .expect("C++ grammar");
2069        let tree = parser.parse(source, None).expect("C++ parse");
2070        let root = tree.root_node();
2071        let context = super::CPP_STRUCTURAL_SPEC.call_site_context(root, source);
2072        let compiled = CompiledKinds::compile(
2073            &tree_sitter_cpp::LANGUAGE.into(),
2074            super::CPP_STRUCTURAL_SPEC.kind_table(),
2075        );
2076        let mut structural = StructuralFactCollector::new(
2077            &super::CPP_STRUCTURAL_SPEC,
2078            source,
2079            &context,
2080            ParentIndex::new(root),
2081            usize::MAX,
2082            None,
2083        );
2084        let mut source_facts = PrimarySourceFactCollector::new(source);
2085        let mut pending = vec![(root, None)];
2086        while let Some((node, parent)) = pending.pop() {
2087            let mut child_parent = parent;
2088            if node.is_named()
2089                && let Some(raw_kind) = compiled.kind_of(&node)
2090                && super::CPP_STRUCTURAL_SPEC.should_extract(node, raw_kind)
2091            {
2092                let kind = super::CPP_STRUCTURAL_SPEC.refine_kind(
2093                    node,
2094                    raw_kind,
2095                    parent.map(|id| structural.normalized_kind(id)),
2096                    source,
2097                    &context,
2098                );
2099                let id = structural
2100                    .enter(node, kind, parent, &mut source_facts)
2101                    .expect("unbounded C++ structural collector");
2102                let mut sink = structural.role_sink(&mut source_facts);
2103                super::CPP_STRUCTURAL_SPEC.extract(node, kind, &mut sink);
2104                structural
2105                    .accept_roles(id, sink.into_parts())
2106                    .expect("unbounded C++ structural roles");
2107                child_parent = Some(id);
2108            }
2109            for index in (0..node.named_child_count()).rev() {
2110                if let Some(child) = node.named_child(index) {
2111                    pending.push((child, child_parent));
2112                }
2113            }
2114        }
2115        structural
2116            .finish(root)
2117            .expect("C++ structural collection finishes")
2118    }
2119
2120    fn member_occurrences(source: &str) -> Vec<(usize, &str, OccurrenceRole)> {
2121        let mut parser = Parser::new();
2122        parser
2123            .set_language(&tree_sitter_cpp::LANGUAGE.into())
2124            .expect("C++ grammar");
2125        let tree = parser.parse(source, None).expect("C++ parse");
2126        assert!(
2127            !tree.root_node().has_error(),
2128            "{}",
2129            tree.root_node().to_sexp()
2130        );
2131        let mut found = Vec::new();
2132        let mut pending = vec![tree.root_node()];
2133        while let Some(node) = pending.pop() {
2134            if let Some(role) = cpp_member_position(node) {
2135                found.push((
2136                    node.start_byte(),
2137                    &source[node.start_byte()..node.end_byte()],
2138                    role,
2139                ));
2140            }
2141            for index in (0..node.named_child_count()).rev() {
2142                if let Some(child) = node.named_child(index) {
2143                    pending.push(child);
2144                }
2145            }
2146        }
2147        found
2148    }
2149
2150    #[test]
2151    #[hardwon("#4505: generated C initializer identifiers triggered repeated sibling scans")]
2152    fn binder_classification_scans_large_initializer_lists_linearly() {
2153        use std::fmt::Write as _;
2154
2155        let mut source = String::from("int values[] = {");
2156        for index in 0..4096 {
2157            write!(source, "item_{index},").expect("append generated initializer item");
2158        }
2159        source.push_str("};\n");
2160
2161        let mut parser = Parser::new();
2162        parser
2163            .set_language(&tree_sitter_cpp::LANGUAGE.into())
2164            .expect("C++ grammar");
2165        let tree = parser.parse(&source, None).expect("C++ parse");
2166        assert!(
2167            !tree.root_node().has_error(),
2168            "{}",
2169            tree.root_node().to_sexp()
2170        );
2171        let parents = ParentIndex::new(tree.root_node());
2172        let mut pending = vec![tree.root_node()];
2173        let mut identifiers = 0usize;
2174        let mut sibling_steps = 0usize;
2175        while let Some(node) = pending.pop() {
2176            if node.kind() == "identifier" {
2177                identifiers += 1;
2178                let _ = cpp_binder_owner(
2179                    node,
2180                    |node| parents.parent(node),
2181                    |parent, child| {
2182                        let mut cursor = parent.walk();
2183                        if !cursor.goto_first_child() {
2184                            return None;
2185                        }
2186                        loop {
2187                            sibling_steps += 1;
2188                            if cursor.node() == child {
2189                                return cursor.field_name();
2190                            }
2191                            if !cursor.goto_next_sibling() {
2192                                return None;
2193                            }
2194                        }
2195                    },
2196                );
2197            }
2198            let mut cursor = node.walk();
2199            let children = node.children(&mut cursor).collect::<Vec<_>>();
2200            pending.extend(children.into_iter().rev());
2201        }
2202
2203        assert!(
2204            identifiers >= 4096,
2205            "parsed {identifiers} initializer identifiers"
2206        );
2207        assert!(
2208            sibling_steps <= identifiers * 4,
2209            "binder field lookup walked {sibling_steps} siblings for {identifiers} identifiers"
2210        );
2211    }
2212
2213    #[test]
2214    #[brokk_bifrost_test_macros::hardwon(
2215        "#4407: ABI 15 lambda declarators lost parameter binder identity"
2216    )]
2217    fn lambda_parameters_are_binders_without_leaking_into_callable_bodies() {
2218        let source = concat!(
2219            "int enclosing(int outer) {\n",
2220            "    return [outer](int lambda) {\n",
2221            "        return [lambda](int nested) {\n",
2222            "            return outer + lambda + nested;\n",
2223            "        }(lambda);\n",
2224            "    }(outer);\n",
2225            "}\n",
2226        );
2227        let mut parser = Parser::new();
2228        parser
2229            .set_language(&tree_sitter_cpp::LANGUAGE.into())
2230            .expect("C++ grammar");
2231        let tree = parser.parse(source, None).expect("C++ parse");
2232        assert!(
2233            !tree.root_node().has_error(),
2234            "{}",
2235            tree.root_node().to_sexp()
2236        );
2237
2238        let identifier_at = |start_byte| {
2239            let mut pending = vec![tree.root_node()];
2240            while let Some(node) = pending.pop() {
2241                if node.kind() == "identifier" && node.start_byte() == start_byte {
2242                    return Some(node);
2243                }
2244                for index in (0..node.named_child_count()).rev() {
2245                    if let Some(child) = node.named_child(index) {
2246                        pending.push(child);
2247                    }
2248                }
2249            }
2250            None
2251        };
2252        let outer_parameter =
2253            identifier_at(source.find("int outer").expect("outer parameter") + "int ".len())
2254                .expect("outer parameter");
2255        let lambda_parameter =
2256            identifier_at(source.find("int lambda").expect("lambda parameter") + "int ".len())
2257                .expect("lambda parameter");
2258        let nested_parameter =
2259            identifier_at(source.find("int nested").expect("nested parameter") + "int ".len())
2260                .expect("nested parameter");
2261
2262        for parameter in [outer_parameter, lambda_parameter, nested_parameter] {
2263            assert_eq!(
2264                cpp_binder_owner(parameter, |node| node.parent(), field_name_in_parent),
2265                Some(super::CppBinderOwner::Parameter)
2266            );
2267            assert_eq!(
2268                super::cpp_binding_activation(parameter, node_range(tree.root_node()))
2269                    .map(|activation| activation.kind),
2270                Some(BindingKind::Parameter)
2271            );
2272        }
2273
2274        for (start, name) in [
2275            (
2276                source
2277                    .find("return outer + lambda")
2278                    .expect("outer reference")
2279                    + "return ".len(),
2280                "outer",
2281            ),
2282            (
2283                source
2284                    .find("outer + lambda + nested")
2285                    .expect("lambda reference")
2286                    + "outer + ".len(),
2287                "lambda",
2288            ),
2289            (
2290                source.find("lambda + nested;").expect("nested reference") + "lambda + ".len(),
2291                "nested",
2292            ),
2293        ] {
2294            let reference = identifier_at(start).expect("body reference identifier");
2295            assert_eq!(
2296                cpp_binder_owner(reference, |node| node.parent(), field_name_in_parent),
2297                None,
2298                "body reference {name:?} was classified as a binder"
2299            );
2300        }
2301    }
2302
2303    #[test]
2304    #[brokk_bifrost_test_macros::hardwon(
2305        "#4407: ABI 15 explicit-object receivers lost parameter binder identity"
2306    )]
2307    fn cpp_explicit_object_parameter_is_a_parameter_binder_without_body_leak() {
2308        let source = concat!(
2309            "struct Visitor {\n",
2310            "    int visit(this Visitor const& self, int ordinary) {\n",
2311            "        return self.value + ordinary;\n",
2312            "    }\n",
2313            "};\n",
2314            "using Callback = void (*)(int nested);\n",
2315        );
2316        let mut parser = Parser::new();
2317        parser
2318            .set_language(&tree_sitter_cpp::LANGUAGE.into())
2319            .expect("C++ grammar");
2320        let tree = parser.parse(source, None).expect("C++ parse");
2321        assert!(
2322            !tree.root_node().has_error(),
2323            "{}",
2324            tree.root_node().to_sexp()
2325        );
2326
2327        let identifier_at = |start: usize, len: usize| {
2328            tree.root_node()
2329                .descendant_for_byte_range(start, start + len)
2330                .filter(|node| node.kind() == "identifier")
2331                .expect("identifier at source span")
2332        };
2333        let receiver = identifier_at(source.find("self,").expect("receiver binder"), 4);
2334        let receiver_body = identifier_at(
2335            source.find("return self").expect("receiver body reference") + "return ".len(),
2336            4,
2337        );
2338        let function_type_parameter =
2339            identifier_at(source.find("nested").expect("function type"), 6);
2340        let parents = ParentIndex::new(tree.root_node());
2341
2342        assert_eq!(receiver.kind(), "identifier");
2343        assert_eq!(
2344            cpp_binder_owner(receiver, |node| node.parent(), field_name_in_parent),
2345            Some(super::CppBinderOwner::Parameter)
2346        );
2347        assert!(super::cpp_is_binder(receiver, &parents));
2348        assert_eq!(
2349            super::cpp_binding_activation(receiver, node_range(tree.root_node()))
2350                .map(|activation| activation.kind),
2351            Some(BindingKind::Parameter)
2352        );
2353        assert_eq!(
2354            cpp_binder_owner(receiver_body, |node| node.parent(), field_name_in_parent),
2355            None,
2356            "the receiver read in the body is not another binder"
2357        );
2358        assert!(!super::cpp_is_binder(receiver_body, &parents));
2359        assert_eq!(
2360            cpp_binder_owner(
2361                function_type_parameter,
2362                |node| node.parent(),
2363                field_name_in_parent
2364            ),
2365            None,
2366            "a function-type parameter remains outside callable binding ownership"
2367        );
2368    }
2369
2370    #[test]
2371    fn attributed_declarator_resolves_its_declared_name() {
2372        let source = "int x [[maybe_unused]]; struct Widget { operator bool() const; };";
2373        let mut parser = Parser::new();
2374        parser
2375            .set_language(&tree_sitter_cpp::LANGUAGE.into())
2376            .expect("C++ grammar");
2377        let tree = parser.parse(source, None).expect("C++ parse");
2378        assert!(
2379            !tree.root_node().has_error(),
2380            "{}",
2381            tree.root_node().to_sexp()
2382        );
2383
2384        let mut pending = vec![tree.root_node()];
2385        let mut attributed = None;
2386        let mut conversion = None;
2387        while let Some(node) = pending.pop() {
2388            match node.kind() {
2389                "attributed_declarator" => attributed = Some(node),
2390                "operator_cast" => conversion = Some(node),
2391                _ => {}
2392            }
2393            for index in (0..node.named_child_count()).rev() {
2394                if let Some(child) = node.named_child(index) {
2395                    pending.push(child);
2396                }
2397            }
2398        }
2399        let attributed = attributed.expect("attributed declarator");
2400        let name = super::declarator_name_node(attributed).expect("declarator name");
2401
2402        assert_eq!(&source[name.byte_range()], "x");
2403        let conversion = conversion.expect("conversion operator");
2404        assert_eq!(
2405            super::declarator_name_node(conversion).map(|node| node.kind()),
2406            Some("operator_cast")
2407        );
2408    }
2409
2410    #[test]
2411    fn cpp_member_position_is_limited_to_member_access_and_calls() {
2412        let source = concat!(
2413            "struct Widget {\n",
2414            "    int value;\n",
2415            "    int method(int label) {\n",
2416            "        return this->value + label.value + label.method()\n",
2417            "            + label.template convert<int>() + label.ns::member;\n",
2418            "    }\n",
2419            "};\n",
2420            "int build(Widget widget) {\n",
2421            "    Widget result{.value = widget.value};\n",
2422            "    return widget.method(result.value);\n",
2423            "}\n",
2424        );
2425        let found = member_occurrences(source);
2426        let member_texts = found
2427            .iter()
2428            .map(|(_, text, role)| (*text, *role))
2429            .collect::<Vec<_>>();
2430
2431        assert_eq!(
2432            member_texts,
2433            vec![
2434                ("value", OccurrenceRole::MemberPosition),
2435                ("value", OccurrenceRole::MemberPosition),
2436                ("method", OccurrenceRole::MemberPosition),
2437                ("convert", OccurrenceRole::MemberPosition),
2438                ("member", OccurrenceRole::MemberPosition),
2439                ("value", OccurrenceRole::MemberPosition),
2440                ("method", OccurrenceRole::MemberPosition),
2441                ("value", OccurrenceRole::MemberPosition),
2442            ]
2443        );
2444
2445        let at = |needle: &str| source.find(needle).expect("fixture token");
2446        for receiver in ["this->", "label.value", "widget.value", "result.value"] {
2447            let receiver_start = at(receiver);
2448            assert!(
2449                found.iter().all(|(offset, _, _)| *offset != receiver_start),
2450                "receiver was classified: {receiver:?}"
2451            );
2452        }
2453        let non_members = [
2454            at("Widget {"),
2455            at("int value") + "int ".len(),
2456            at("int method") + "int ".len(),
2457            at(".value =") + 1,
2458        ];
2459        for unrelated_start in non_members {
2460            assert!(
2461                found
2462                    .iter()
2463                    .all(|(offset, _, _)| *offset != unrelated_start),
2464                "non-member identifier at byte {unrelated_start} was classified"
2465            );
2466        }
2467    }
2468
2469    #[test]
2470    #[brokk_bifrost_test_macros::hardwon(
2471        "#3466: C and C++ free-function calls published no resolver occurrence"
2472    )]
2473    fn cpp_occurrence_support_declares_member_position_and_free_callees() {
2474        let support = super::CPP_STRUCTURAL_SPEC.occurrence_role_support();
2475        assert!(support.is_supported(OccurrenceRole::MemberPosition));
2476        assert!(support.is_supported(OccurrenceRole::ValueReference));
2477        for role in [
2478            OccurrenceRole::ReceiverPosition,
2479            OccurrenceRole::LabelOrKey,
2480            OccurrenceRole::DeclarationName,
2481        ] {
2482            assert!(
2483                !support.is_supported(role),
2484                "unexpected C++ support for {role:?}"
2485            );
2486        }
2487    }
2488
2489    #[test]
2490    fn cpp_string_literals_publish_decoded_values() {
2491        let source = r#"
2492const char *ordinary = "http://example.test/a\n";
2493const char *raw = R"(https://example.test/path)";
2494const char *wide = L"wide";
2495const char character = 'x';
2496const char *mixed = R"(\u0041)" "\u0042";
2497"#;
2498        let rows = collect_structural_rows(source);
2499        let values = rows
2500            .nodes()
2501            .iter()
2502            .filter(|node| node.kind == NormalizedKind::StringLiteral)
2503            .map(|node| node.string_value.clone())
2504            .collect::<Vec<_>>();
2505
2506        assert_eq!(
2507            values,
2508            vec![
2509                Some("http://example.test/a\n".to_owned()),
2510                Some("https://example.test/path".to_owned()),
2511                None,
2512                None,
2513                Some(r"\u0041".to_owned()),
2514                Some("B".to_owned()),
2515            ]
2516        );
2517    }
2518
2519    #[test]
2520    fn cpp_numeric_string_escapes_follow_scalar_and_ascii_boundaries() {
2521        // The grammar selects escape_sequence nodes; Unicode scalar validity
2522        // and the portable ASCII byte policy independently decide their values.
2523        let mut cases = vec![
2524            (
2525                r"\101\x42\u0043\U00000044".to_owned(),
2526                Some("ABCD".to_owned()),
2527            ),
2528            (r"\177".to_owned(), Some("\u{7f}".to_owned())),
2529            (r"\200".to_owned(), None),
2530            (r"\377".to_owned(), None),
2531            (r"\x7f".to_owned(), Some("\u{7f}".to_owned())),
2532            (r"\x80".to_owned(), None),
2533            (r"\x0041".to_owned(), Some("A".to_owned())),
2534            (r"\x007f".to_owned(), Some("\u{7f}".to_owned())),
2535            (r"\x0080".to_owned(), None),
2536            (r"\xfffffffff".to_owned(), None),
2537        ];
2538        for scalar in [
2539            0,
2540            0x7f,
2541            0x80,
2542            0xd7ff,
2543            0xd800,
2544            0xdfff,
2545            0xe000,
2546            0x10ffff,
2547            0x110000,
2548            u32::MAX,
2549        ] {
2550            let expected = char::from_u32(scalar).map(|character| character.to_string());
2551            cases.push((format!("\\U{scalar:08x}"), expected.clone()));
2552            if scalar <= 0xffff {
2553                cases.push((format!("\\u{scalar:04x}"), expected));
2554            }
2555        }
2556        for (escape, expected) in cases {
2557            let source = format!("const char *value = \"{escape}\";");
2558            let mut parser = Parser::new();
2559            parser
2560                .set_language(&tree_sitter_cpp::LANGUAGE.into())
2561                .unwrap();
2562            let tree = parser.parse(&source, None).unwrap();
2563            assert!(!tree.root_node().has_error(), "{source}");
2564            let mut stack = vec![tree.root_node()];
2565            let mut escapes = Vec::new();
2566            while let Some(node) = stack.pop() {
2567                if node.kind() == "escape_sequence" {
2568                    escapes.push(node.byte_range());
2569                }
2570                stack.extend(node.named_children(&mut node.walk()));
2571            }
2572            assert!(!escapes.is_empty(), "grammar did not select {source}");
2573            if escape.starts_with(r"\x00") {
2574                let expected_span = 21..21 + escape.len();
2575                assert_eq!(
2576                    escapes.as_slice(),
2577                    std::slice::from_ref(&expected_span),
2578                    "{source}"
2579                );
2580            }
2581            let rows = collect_structural_rows(&source);
2582            let values: Vec<_> = rows
2583                .nodes()
2584                .iter()
2585                .filter(|node| node.kind == NormalizedKind::StringLiteral)
2586                .map(|node| node.string_value.clone())
2587                .collect();
2588            assert_eq!(values, vec![expected], "{source}, escapes={escapes:?}");
2589        }
2590    }
2591
2592    /// The callee token of a free-function call is the only occurrence a call
2593    /// site leaves behind when the function is not indexed (#3466). Member
2594    /// calls stay member-position-only, and a composite callee expression
2595    /// names its own callee at an inner node.
2596    #[test]
2597    #[brokk_bifrost_test_macros::hardwon(
2598        "#3466: C/C++ resolver call sites had no boundary row or callee occurrence"
2599    )]
2600    fn cpp_free_function_callees_are_value_references() {
2601        let source = concat!(
2602            "int bound(void) { return 1; }\n",
2603            "struct Widget { int method(void) { return 0; } };\n",
2604            "int go(struct Widget *widget) {\n",
2605            "    return getenv(\"PATH\") != 0\n",
2606            "        + ns::getenv(\"USER\") != 0\n",
2607            "        + bound()\n",
2608            "        + widget->method()\n",
2609            "        + bound()();\n",
2610            "}\n",
2611        );
2612        let mut parser = Parser::new();
2613        parser
2614            .set_language(&tree_sitter_cpp::LANGUAGE.into())
2615            .expect("C++ grammar");
2616        let tree = parser.parse(source, None).expect("C++ parse");
2617        assert!(
2618            !tree.root_node().has_error(),
2619            "{}",
2620            tree.root_node().to_sexp()
2621        );
2622
2623        // Drive the same extraction entry the file walk drives: every fact
2624        // node admitted by the compiled kind table, through a real RoleSink.
2625        // The sink addresses occurrences by fact id, so the test keeps the
2626        // fact id to start byte mapping to name the tokens.
2627        let language: tree_sitter::Language = tree_sitter_cpp::LANGUAGE.into();
2628        let compiled = CompiledKinds::compile(&language, CPP_STRUCTURAL_SPEC.kind_table());
2629        let mut start_by_fact = HashMap::default();
2630        let mut extractions = Vec::new();
2631        let mut pending = vec![tree.root_node()];
2632        while let Some(node) = pending.pop() {
2633            if node.is_named()
2634                && let Some(kind) = compiled.kind_of(&node)
2635                && CPP_STRUCTURAL_SPEC.should_extract(node, kind)
2636            {
2637                start_by_fact.insert(node.id(), node.start_byte());
2638                extractions.push((node.start_byte(), node, kind));
2639            }
2640            for index in (0..node.named_child_count()).rev() {
2641                if let Some(child) = node.named_child(index) {
2642                    pending.push(child);
2643                }
2644            }
2645        }
2646        extractions.sort_by_key(|(start, _, _)| *start);
2647        let mut source_facts =
2648            brokk_bifrost_core::analyzer::source_facts::PrimarySourceFactCollector::new(source);
2649        let parents = ParentIndex::new(tree.root_node());
2650        let mut sink = RoleSink::new(source, &mut source_facts, 64, None, &parents);
2651        for (_, node, kind) in extractions {
2652            CPP_STRUCTURAL_SPEC.extract(node, kind, &mut sink);
2653        }
2654        let (_, _, occurrences, stop) = sink.into_parts();
2655        assert_eq!(stop, None);
2656
2657        let roles_at = |needle: &str| {
2658            let start = source.find(needle).expect("fixture token");
2659            occurrences
2660                .iter()
2661                .filter(|occurrence| start_by_fact[&occurrence.target_node] == start)
2662                .map(|occurrence| occurrence.role)
2663                .collect::<Vec<_>>()
2664        };
2665        // Free-function callees are value reads, including a qualified callee
2666        // whose terminal name is the identifier and the callee of the inner
2667        // call in `bound()()`.
2668        assert_eq!(
2669            roles_at("getenv(\"PATH\")"),
2670            vec![OccurrenceRole::ValueReference]
2671        );
2672        assert_eq!(
2673            roles_at("getenv(\"USER\")"),
2674            vec![OccurrenceRole::ValueReference],
2675            "the terminal name of a qualified callee is the value read"
2676        );
2677        assert_eq!(roles_at("bound()\n"), vec![OccurrenceRole::ValueReference]);
2678        // A member call's terminal field stays one member-position occurrence;
2679        // the call itself adds no second row for the same token.
2680        assert_eq!(roles_at("method()"), vec![OccurrenceRole::MemberPosition]);
2681        // The receiver of a member call is neither a value read of the callee
2682        // nor a member position.
2683        assert!(roles_at("widget->").is_empty());
2684    }
2685
2686    /// Tree-sitter recovers the valid `this->operator[](...)` expression as a
2687    /// call whose function is the unfactored `this` node. That node must not
2688    /// receive a value-reference occurrence role.
2689    #[test]
2690    fn cpp_subscript_operator_through_this_does_not_emit_role_for_non_fact() {
2691        collect_cpp_structural_facts(
2692            "struct Channel { int operator[](int); int at(int i) { return this->operator[](i); } };",
2693        );
2694    }
2695}
2696
2697#[cfg(test)]
2698mod grammar_boundary_tests {
2699    use super::*;
2700
2701    #[test]
2702    fn expression_and_pointer_declarator_name_fields() {
2703        let source = "void run() { auto p = new ns::Widget(); receiver.method<int>(); int (*callback)(int) = nullptr; int (ordinary)(int); }";
2704        let tree = crate::diagnostics::parse_cpp_tree(source);
2705        assert!(
2706            !tree.root_node().has_error(),
2707            "{}",
2708            tree.root_node().to_sexp()
2709        );
2710        let mut stack = vec![tree.root_node()];
2711        let mut names = Vec::new();
2712        let mut binders = Vec::new();
2713        while let Some(node) = stack.pop() {
2714            if matches!(node.kind(), "new_expression" | "field_expression") {
2715                let field = if node.kind() == "new_expression" {
2716                    "type"
2717                } else {
2718                    "field"
2719                };
2720                let child = node.child_by_field_name(field).unwrap();
2721                names.push((
2722                    node.kind(),
2723                    child.kind(),
2724                    expression_name_node(node).map(|n| &source[n.byte_range()]),
2725                ));
2726            }
2727            if node.kind() == "identifier"
2728                && let Some(name @ ("callback" | "ordinary")) = node_text(node, source)
2729            {
2730                let wrapper = if name == "callback" {
2731                    "pointer_declarator"
2732                } else {
2733                    "parenthesized_declarator"
2734                };
2735                assert_eq!(node.parent().unwrap().kind(), wrapper);
2736                binders.push((
2737                    name,
2738                    cpp_binder_owner(node, |n| n.parent(), field_name_in_parent)
2739                        .is_some_and(|owner| matches!(owner, CppBinderOwner::Local(_))),
2740                ));
2741            }
2742            stack.extend(
2743                node.named_children(&mut node.walk())
2744                    .collect::<Vec<_>>()
2745                    .into_iter()
2746                    .rev(),
2747            );
2748        }
2749        assert_eq!(
2750            names,
2751            [
2752                ("new_expression", "qualified_identifier", Some("Widget")),
2753                ("field_expression", "template_method", Some("method"))
2754            ]
2755        );
2756        assert_eq!(binders, [("callback", true), ("ordinary", false)]);
2757    }
2758
2759    #[test]
2760    #[brokk_bifrost_test_macros::hardwon(
2761        "6ec52f232835: quicksilver round 4 survivor review: dependent member names lost their terminal token"
2762    )]
2763    fn dependent_member_name_grammar_boundary() {
2764        let source = "template<class T> void f(T receiver) { receiver.template method<int>(); }";
2765        let tree = crate::diagnostics::parse_cpp_tree(source);
2766        assert!(!tree.root_node().has_error());
2767        let mut stack = vec![tree.root_node()];
2768        let mut names = Vec::new();
2769        while let Some(node) = stack.pop() {
2770            if node.kind() == "dependent_name" {
2771                assert!(node.child_by_field_name("name").is_none());
2772                assert_eq!(node.named_child(0).unwrap().kind(), "template_method");
2773                assert_eq!(
2774                    declarator_name_node(node).map(|name| &source[name.byte_range()]),
2775                    Some("method")
2776                );
2777                assert_eq!(
2778                    terminal_callee_leaf(node.parent().unwrap(), callee_spine_step)
2779                        .map(|name| &source[name.byte_range()]),
2780                    Some("method")
2781                );
2782                names.push(expression_name_node(node).map(|n| &source[n.byte_range()]));
2783            }
2784            stack.extend(node.named_children(&mut node.walk()));
2785        }
2786        assert_eq!(names, [Some("method")]);
2787    }
2788
2789    #[test]
2790    fn conditional_macro_name_fields() {
2791        let source = "#if ON\n#define FIRST(x) x\n#elif ALT\n#define SECOND(x) x\n#else\n#define THIRD(x) x\n#endif\nvoid f() {}\n";
2792        let tree = crate::diagnostics::parse_cpp_tree(source);
2793        assert!(!tree.root_node().has_error());
2794        let mut stack = vec![tree.root_node()];
2795        let mut definitions = Vec::new();
2796        while let Some(node) = stack.pop() {
2797            if node.kind() == "preproc_function_def" {
2798                let name = node.child_by_field_name("name").unwrap();
2799                definitions.push((
2800                    node_text(name, source).unwrap(),
2801                    node.parent().unwrap().kind(),
2802                ));
2803            }
2804            stack.extend(
2805                node.named_children(&mut node.walk())
2806                    .collect::<Vec<_>>()
2807                    .into_iter()
2808                    .rev(),
2809            );
2810        }
2811        assert_eq!(
2812            definitions,
2813            [
2814                ("FIRST", "preproc_if"),
2815                ("SECOND", "preproc_elif"),
2816                ("THIRD", "preproc_else"),
2817            ]
2818        );
2819        let mut names: Vec<_> = function_like_macro_names(tree.root_node(), source)
2820            .into_iter()
2821            .collect();
2822        names.sort();
2823        assert_eq!(names, ["FIRST", "SECOND", "THIRD"]);
2824    }
2825}
2826
2827#[cfg(test)]
2828mod result_use_tests {
2829    use super::{CppCallResultUseIndex, cpp_call_result_use};
2830    use brokk_bifrost_core::analyzer::structural::result_use::{
2831        CallResultUse, CallResultUseOpenReason, IntentionalDiscardKind,
2832    };
2833    use tree_sitter::Parser;
2834
2835    fn tree(source: &str) -> tree_sitter::Tree {
2836        let mut parser = Parser::new();
2837        parser
2838            .set_language(&tree_sitter_cpp::LANGUAGE.into())
2839            .expect("C++ grammar");
2840        parser.parse(source, None).expect("C++ tree")
2841    }
2842
2843    fn calls<'tree>(tree: &'tree tree_sitter::Tree, source: &str) -> Vec<tree_sitter::Node<'tree>> {
2844        let mut found = Vec::new();
2845        let mut stack = vec![tree.root_node()];
2846        while let Some(node) = stack.pop() {
2847            if node.kind() == "call_expression" && !super::cpp_cast_call(node, source) {
2848                found.push(node);
2849            }
2850            for index in (0..node.named_child_count()).rev() {
2851                stack.push(node.named_child(index).expect("named child"));
2852            }
2853        }
2854        found.sort_by_key(|node| node.start_byte());
2855        found
2856    }
2857
2858    #[test]
2859    fn expression_statement_void_cast_and_nested_contexts_are_distinct() {
2860        let source = concat!(
2861            "int f();\n",
2862            "void sink(int);\n",
2863            "void run() {\n",
2864            "    f();\n",
2865            "    (void)f();\n",
2866            "    static_cast<void>(f());\n",
2867            "    sink(f());\n",
2868            "    return;\n",
2869            "}\n",
2870        );
2871        let tree = tree(source);
2872        assert!(
2873            !tree.root_node().has_error(),
2874            "{}",
2875            tree.root_node().to_sexp()
2876        );
2877        let calls = calls(&tree, source);
2878        assert_eq!(calls.len(), 5);
2879        assert_eq!(
2880            cpp_call_result_use(calls[0], source).for_port(0),
2881            CallResultUse::Discarded
2882        );
2883        assert!(matches!(
2884            cpp_call_result_use(calls[1], source).for_port(0),
2885            CallResultUse::IntentionalDiscard(IntentionalDiscardKind::CppVoidCast)
2886        ));
2887        assert!(matches!(
2888            cpp_call_result_use(calls[2], source).for_port(0),
2889            CallResultUse::IntentionalDiscard(IntentionalDiscardKind::CppVoidCast)
2890        ));
2891        assert_eq!(
2892            cpp_call_result_use(calls[3], source).for_port(0),
2893            CallResultUse::Discarded
2894        );
2895        assert_eq!(
2896            cpp_call_result_use(calls[4], source).for_port(0),
2897            CallResultUse::Consumed
2898        );
2899    }
2900
2901    #[test]
2902    fn lambda_tail_and_recovered_syntax_are_open() {
2903        // The macro-declaration grammar splits a bare `f(,)` into an
2904        // identifier and a separate ERROR with no call expression at all, so
2905        // the recovered call is spelled `f(+)` here: it still produces a
2906        // call_expression whose argument list carries the ERROR that marks
2907        // the syntax as recovered.
2908        let source = "int f(); void run() { auto value = [] { return f(); }; f(+); }";
2909        let tree = tree(source);
2910        assert!(tree.root_node().has_error());
2911        let calls = calls(&tree, source);
2912        assert!(matches!(
2913            cpp_call_result_use(calls[0], source).for_port(0),
2914            CallResultUse::Open(CallResultUseOpenReason::DeferredContext)
2915        ));
2916        assert_eq!(
2917            cpp_call_result_use(calls[1], source).for_port(0),
2918            CallResultUse::Open(CallResultUseOpenReason::RecoveredSyntax)
2919        );
2920    }
2921
2922    #[test]
2923    fn exact_index_keeps_call_spans_separate() {
2924        let source = "int f(); void run() { f(); }";
2925        let tree = tree(source);
2926        let calls = calls(&tree, source);
2927        let index = CppCallResultUseIndex::new(tree.root_node(), source);
2928        assert_eq!(
2929            index
2930                .at_span(calls[0].start_byte(), calls[0].end_byte())
2931                .expect("indexed call")
2932                .for_port(0),
2933            CallResultUse::Discarded
2934        );
2935        assert!(index.at_span(source.len(), source.len()).is_err());
2936    }
2937
2938    #[test]
2939    fn result_use_grammar_boundary_sites_and_recovery() {
2940        // Spellings are the independent site oracle: casts are syntax wrappers,
2941        // allocations are expressions, and an ERROR ancestor invalidates a site.
2942        for (source, expected) in [
2943            (
2944                "void run() { dynamic_cast<T*>(a()); static_cast<T*>(b()); reinterpret_cast<T*>(c()); const_cast<T*>(d()); new W(); auto p = new X(); sink(new Y()); }",
2945                vec![
2946                    ("a()", CallResultUse::Consumed),
2947                    ("b()", CallResultUse::Consumed),
2948                    ("c()", CallResultUse::Consumed),
2949                    ("d()", CallResultUse::Consumed),
2950                    ("new W()", CallResultUse::Discarded),
2951                    ("new X()", CallResultUse::Consumed),
2952                    ("sink(new Y())", CallResultUse::Discarded),
2953                    ("new Y()", CallResultUse::Consumed),
2954                ],
2955            ),
2956            (
2957                "void run() { try { f(); } }",
2958                vec![(
2959                    "f()",
2960                    CallResultUse::Open(CallResultUseOpenReason::RecoveredSyntax),
2961                )],
2962            ),
2963        ] {
2964            let tree = tree(source);
2965            let mut stack = vec![tree.root_node()];
2966            let mut grammar_sites = Vec::new();
2967            let mut recovery_witness = false;
2968            while let Some(node) = stack.pop() {
2969                if matches!(node.kind(), "call_expression" | "new_expression") {
2970                    grammar_sites.push(node.byte_range());
2971                    if source[node.byte_range()] == *"f()" {
2972                        assert!(!node.has_error());
2973                        assert!(!node.parent().unwrap().is_error());
2974                        let mut parent = node.parent();
2975                        while let Some(ancestor) = parent {
2976                            recovery_witness |= ancestor.is_error();
2977                            parent = ancestor.parent();
2978                        }
2979                    }
2980                }
2981                stack.extend(node.named_children(&mut node.walk()));
2982            }
2983            if source.contains("try") {
2984                assert!(recovery_witness, "{}", tree.root_node().to_sexp());
2985            } else {
2986                assert!(!tree.root_node().has_error());
2987                assert_eq!(
2988                    grammar_sites.len(),
2989                    12,
2990                    "four cast wrappers plus eight sites"
2991                );
2992            }
2993            let index = CppCallResultUseIndex::new(tree.root_node(), source);
2994            let actual: Vec<_> = index
2995                .sites()
2996                .iter()
2997                .map(|site| (&source[site.start_byte..site.end_byte], site.for_port(0)))
2998                .collect();
2999            assert_eq!(actual, expected, "{source}");
3000        }
3001    }
3002
3003    #[test]
3004    #[brokk_bifrost_test_macros::hardwon(
3005        "6ec52f232835: quicksilver round 4 survivor review: void pointer casts falsely discarded source values"
3006    )]
3007    fn pointer_to_void_casts_consume_the_source_value() {
3008        let source = "int* make(); void run() { auto p = (void*)make(); auto q = static_cast<void*>(make()); }";
3009        let tree = tree(source);
3010        assert!(!tree.root_node().has_error());
3011        let mut stack = vec![tree.root_node()];
3012        let mut type_declarators = Vec::new();
3013        while let Some(node) = stack.pop() {
3014            if node.kind() == "type_descriptor" {
3015                type_declarators.push(node.child_by_field_name("declarator").map(|n| n.kind()));
3016            }
3017            stack.extend(node.named_children(&mut node.walk()));
3018        }
3019        assert_eq!(
3020            type_declarators,
3021            [
3022                Some("abstract_pointer_declarator"),
3023                Some("abstract_pointer_declarator")
3024            ]
3025        );
3026        let index = CppCallResultUseIndex::new(tree.root_node(), source);
3027        // Each source result feeds a pointer conversion and then an initializer.
3028        // Neither conversion discards a value by casting it to scalar void.
3029        let uses: Vec<_> = index.sites().iter().map(|site| site.for_port(0)).collect();
3030        assert_eq!(uses, [CallResultUse::Consumed, CallResultUse::Consumed]);
3031    }
3032}