Skip to main content

brokk_bifrost_cpp/
source_facts.rs

1//! Declaration properties interpreted while the coordinated producer owns syntax.
2
3use crate::declarations::{
4    cpp_callable_identity_suffix, cpp_callable_is_structural_constructor,
5    cpp_comparable_parameter_shapes, cpp_declarator_adds_indirection,
6    cpp_macro_swallowed_access_label, extract_function_declarator, node_text,
7};
8use crate::graph::resolver::{
9    cpp_declared_field_type_fact, cpp_type_name_components, declarator_name_node,
10    declarator_names_function_type, parse_cpp_integer_literal as parse_integer_literal,
11    structured_alias_type_target,
12};
13use brokk_bifrost_core::analyzer::cpp_facts::*;
14use brokk_bifrost_core::analyzer::source_facts::{
15    PrimarySourceFactCollector, SourceDeclarationId, SourceOccurrenceId,
16};
17use brokk_bifrost_core::analyzer::tree_walk::{ParentIndex, node_range};
18use brokk_bifrost_core::analyzer::{CodeUnit, Range};
19use brokk_bifrost_core::hash::HashMap;
20use tree_sitter::{Node, Parser};
21
22/// Parse one source snapshot into the expression-only projection used by RQL.
23/// This helper is intentionally query-scoped: it owns no cross-file cache and
24/// retains only the source arena and rows for this one file.
25pub fn parse_cpp_expression_source_facts(
26    source: &str,
27) -> brokk_bifrost_core::analyzer::cpp_facts::CppExpressionSourceFacts {
28    let mut parser = Parser::new();
29    parser
30        .set_language(&tree_sitter_cpp::LANGUAGE.into())
31        .expect("the linked tree-sitter-cpp grammar matches this tree-sitter version");
32    let tree = parser.parse(source, None).expect("uncancelled C++ parse");
33    let mut collector = PrimarySourceFactCollector::new(source);
34    let named_record_sizes = named_record_size_index(tree.root_node(), source);
35    let mut expressions = Vec::new();
36    let mut stack = vec![tree.root_node()];
37    while let Some(node) = stack.pop() {
38        if node.is_named() {
39            let occurrence = collector.intern_node(node);
40            if let Some(fact) =
41                capture_expression_fact(node, source, occurrence, &named_record_sizes)
42            {
43                expressions.push(fact);
44            }
45        }
46        let mut cursor = node.walk();
47        let children = node.named_children(&mut cursor).collect::<Vec<_>>();
48        stack.extend(children.into_iter().rev());
49    }
50    brokk_bifrost_core::analyzer::cpp_facts::CppExpressionSourceFacts {
51        source: collector.finish(),
52        expressions,
53    }
54}
55
56/// Capture one expression-shaped row while the primary tree is live. The
57/// caller has already selected the occurrence; this function only interprets
58/// the selected AST node and never searches source text for syntax.
59pub(crate) fn capture_expression_fact(
60    node: Node<'_>,
61    source: &str,
62    occurrence: SourceOccurrenceId,
63    named_record_sizes: &HashMap<String, Option<u64>>,
64) -> Option<CppExpressionFact> {
65    match node.kind() {
66        "number_literal" => {
67            let literal_text = node_text(node, source).trim().to_owned();
68            Some(
69                CppExpressionFact::new(occurrence, CppExpressionKind::IntegerLiteral)
70                    .with_literal(literal_text),
71            )
72        }
73        "string_literal" | "raw_string_literal" => {
74            let literal_text = node_text(node, source).trim().to_owned();
75            Some(
76                CppExpressionFact::new(occurrence, CppExpressionKind::StringLiteral)
77                    .with_literal(literal_text),
78            )
79        }
80        "parameter_declaration" => capture_parameter(node, source, occurrence, named_record_sizes),
81        "field_declaration" => capture_bit_field(node, source, occurrence)
82            .or_else(|| capture_function_signature(node, source, occurrence)),
83        "enum_specifier" => capture_enum_definition(node, source, occurrence),
84        "enumerator" => capture_enumerator(node, source, occurrence),
85        "function_definition" | "declaration" => {
86            capture_function_signature(node, source, occurrence)
87        }
88        "for_statement" | "for_range_loop" => capture_loop_variable(node, source, occurrence),
89        "sizeof_expression" => capture_sizeof(node, source, occurrence),
90        _ => None,
91    }
92}
93
94trait CppExpressionFactBuilder {
95    fn with_literal(self, literal: String) -> Self;
96}
97
98impl CppExpressionFactBuilder for CppExpressionFact {
99    fn with_literal(mut self, literal: String) -> Self {
100        self.integer_value = parse_integer_literal(&literal);
101        self.literal_text = Some(literal);
102        self.complete()
103    }
104}
105
106fn capture_parameter(
107    node: Node<'_>,
108    source: &str,
109    occurrence: SourceOccurrenceId,
110    named_record_sizes: &HashMap<String, Option<u64>>,
111) -> Option<CppExpressionFact> {
112    let declarator = node.child_by_field_name("declarator")?;
113    let shape = declarator_shape(declarator, source);
114    let (type_text, _type_form, signedness, width_bits) =
115        type_properties(node.child_by_field_name("type"), source);
116    let name = crate::structural::declarator_name_node(declarator)
117        .map(|name| node_text(name, source).to_owned());
118    let kind = if shape.has_array {
119        CppExpressionKind::ArrayParameter
120    } else {
121        CppExpressionKind::FunctionParameter
122    };
123    let mut fact = CppExpressionFact::new(occurrence, kind);
124    fact.name = name;
125    fact.type_text = type_text;
126    fact.type_form = shape.top;
127    fact.signedness = signedness;
128    fact.width_bits = width_bits;
129    fact.array_extent = shape.array_extent;
130    fact.array_is_reference = Some(shape.has_reference);
131    fact.parameter_by_value = Some(!shape.has_reference);
132    fact.member_function = Some(enclosing_member_function(node, declarator));
133    let type_size = exact_parameter_type_size(node, source, named_record_sizes);
134    fact.type_size_bytes = type_size;
135    fact.type_size_exact = Some(type_size.is_some());
136    if shape.has_array {
137        Some(if shape.array_extent.is_some() {
138            fact.complete()
139        } else {
140            fact.open("array extent is not a literal")
141        })
142    } else {
143        Some(match type_size {
144            Some(_) => fact.complete(),
145            None => fact.open("parameter type size is not exact"),
146        })
147    }
148}
149
150fn capture_bit_field(
151    node: Node<'_>,
152    source: &str,
153    occurrence: SourceOccurrenceId,
154) -> Option<CppExpressionFact> {
155    let clause = named_child(node, "bitfield_clause")?;
156    let width_node = clause
157        .child_by_field_name("value")
158        .or_else(|| clause.child_by_field_name("width"))
159        .or_else(|| {
160            let mut cursor = clause.walk();
161            clause
162                .named_children(&mut cursor)
163                .find(|child| child.kind() == "number_literal")
164        });
165    let declarator = node.child_by_field_name("declarator");
166    let name = declarator
167        .and_then(crate::structural::declarator_name_node)
168        .map(|name| node_text(name, source).to_owned());
169    let name = name.filter(|name| !name.is_empty());
170    let (type_text, type_form, signedness, width_bits) =
171        type_properties(node.child_by_field_name("type"), source);
172    let mut fact = CppExpressionFact::new(occurrence, CppExpressionKind::BitField);
173    fact.name = name;
174    fact.type_text = type_text;
175    fact.type_form = type_form;
176    fact.signedness = signedness;
177    fact.width_bits = width_bits;
178    fact.member_function =
179        Some(declarator.is_some_and(|declarator| enclosing_member_function(node, declarator)));
180    fact.bit_field_anonymous = Some(fact.name.is_none());
181    fact.bit_field_width = width_node
182        .map(|width| node_text(width, source))
183        .and_then(parse_integer_literal)
184        .and_then(|width| u64::try_from(width).ok());
185    Some(match fact.bit_field_width {
186        Some(_) => fact.complete(),
187        None => fact.open("bit-field width is not a literal"),
188    })
189}
190
191fn capture_enum_definition(
192    node: Node<'_>,
193    source: &str,
194    occurrence: SourceOccurrenceId,
195) -> Option<CppExpressionFact> {
196    let mut fact = CppExpressionFact::new(occurrence, CppExpressionKind::EnumDefinition);
197    fact.name = node
198        .child_by_field_name("name")
199        .map(|name| node_text(name, source).to_owned());
200    fact.enum_scoped = Some({
201        let mut cursor = node.walk();
202        node.children(&mut cursor)
203            .any(|child| matches!(child.kind(), "class" | "struct"))
204    });
205    Some(fact.complete())
206}
207
208fn capture_enumerator(
209    node: Node<'_>,
210    source: &str,
211    occurrence: SourceOccurrenceId,
212) -> Option<CppExpressionFact> {
213    let mut fact = CppExpressionFact::new(occurrence, CppExpressionKind::Enumerator);
214    fact.name = node
215        .child_by_field_name("name")
216        .map(|name| node_text(name, source).to_owned())
217        .or_else(|| {
218            let mut cursor = node.walk();
219            node.named_children(&mut cursor)
220                .find(|child| child.kind() == "identifier")
221                .map(|name| node_text(name, source).to_owned())
222        });
223    let value = node.child_by_field_name("value");
224    fact.has_initializer = Some(value.is_some());
225    fact.enum_value =
226        value.and_then(|value| parse_integer_literal(node_text(value, source).trim()));
227    fact.enum_has_implicit_before_nonreference = enum_has_implicit_before_nonreference(node);
228    fact.enum_ordinal = node.parent().and_then(|parent| {
229        let mut ordinal = 0u32;
230        let mut cursor = parent.walk();
231        for sibling in parent.named_children(&mut cursor) {
232            if sibling.id() == node.id() {
233                return Some(ordinal);
234            }
235            if sibling.kind() == "enumerator" {
236                ordinal = ordinal.saturating_add(1);
237            }
238        }
239        None
240    });
241    Some(if fact.name.is_some() {
242        fact.complete()
243    } else {
244        fact.open("enumerator name is unavailable")
245    })
246}
247
248fn capture_function_signature(
249    node: Node<'_>,
250    source: &str,
251    occurrence: SourceOccurrenceId,
252) -> Option<CppExpressionFact> {
253    let declarator = first_descendant_kind(node, "function_declarator")?;
254    let (type_text, type_form, signedness, width_bits) =
255        type_properties(node.child_by_field_name("type"), source);
256    let mut fact = CppExpressionFact::new(occurrence, CppExpressionKind::FunctionSignature);
257    fact.name = crate::structural::declarator_name_node(declarator)
258        .map(|name| node_text(name, source).to_owned());
259    fact.type_text = type_text;
260    fact.type_form = type_form;
261    fact.signedness = signedness;
262    fact.width_bits = width_bits;
263    fact.member_function = Some(enclosing_member_function(node, declarator));
264    fact.return_top_level_const = Some(declaration_has_direct_const_qualifier(node, source));
265    fact.member_function_const = Some(declaration_has_direct_const_qualifier(declarator, source));
266    Some(fact.complete())
267}
268
269fn capture_loop_variable(
270    node: Node<'_>,
271    source: &str,
272    occurrence: SourceOccurrenceId,
273) -> Option<CppExpressionFact> {
274    let name = loop_binding_name(node, source);
275    let type_node = node.child_by_field_name("type").or_else(|| {
276        node.child_by_field_name("initializer")
277            .and_then(|init| init.child_by_field_name("type"))
278    });
279    let (type_text, type_form, signedness, width_bits) = type_properties(type_node, source);
280    let mut fact = CppExpressionFact::new(occurrence, CppExpressionKind::LoopVariable);
281    fact.name = name;
282    fact.type_text = type_text;
283    fact.type_form = type_form;
284    fact.signedness = signedness;
285    fact.width_bits = width_bits;
286    fact.loop_has_short_ancestor = fact
287        .name
288        .as_deref()
289        .map(|_| has_short_loop_ancestor(node, source));
290    Some(if fact.name.is_some() {
291        fact.complete()
292    } else {
293        fact.open("loop binding name is unavailable")
294    })
295}
296
297fn capture_sizeof(
298    node: Node<'_>,
299    source: &str,
300    occurrence: SourceOccurrenceId,
301) -> Option<CppExpressionFact> {
302    let operand_kind = if node.child_by_field_name("type").is_some() {
303        CppSizeofOperandKind::Type
304    } else if node.child_by_field_name("value").is_some() {
305        CppSizeofOperandKind::Expression
306    } else {
307        return Some(
308            CppExpressionFact::new(occurrence, CppExpressionKind::SizeofExpression)
309                .open("sizeof operand is unavailable"),
310        );
311    };
312    let operand = node
313        .child_by_field_name("value")
314        .or_else(|| node.child_by_field_name("type"));
315    let mut side_effect = false;
316    let mut stack = operand.into_iter().collect::<Vec<_>>();
317    while let Some(current) = stack.pop() {
318        if matches!(
319            current.kind(),
320            "call_expression"
321                | "assignment_expression"
322                | "update_expression"
323                | "new_expression"
324                | "delete_expression"
325                | "comma_expression"
326        ) {
327            side_effect = true;
328            break;
329        }
330        let mut cursor = current.walk();
331        stack.extend(current.named_children(&mut cursor));
332    }
333    let mut fact = CppExpressionFact::new(occurrence, CppExpressionKind::SizeofExpression);
334    fact.sizeof_operand_kind = Some(operand_kind);
335    fact.sizeof_operand_is_parameter = sizeof_operand_is_parameter(node, operand, source);
336    fact.sizeof_has_side_effect = Some(side_effect);
337    Some(fact.complete())
338}
339
340fn enclosing_member_function(node: Node<'_>, declarator: Node<'_>) -> bool {
341    let mut ancestor = node.parent();
342    while let Some(current) = ancestor {
343        if matches!(
344            current.kind(),
345            "class_specifier" | "struct_specifier" | "union_specifier"
346        ) {
347            return true;
348        }
349        ancestor = current.parent();
350    }
351    first_descendant_kind(declarator, "qualified_identifier")
352        .and_then(|qualified| qualified.child_by_field_name("scope"))
353        .is_some_and(|scope| first_descendant_kind(scope, "type_identifier").is_some())
354}
355
356fn enum_has_implicit_before_nonreference(node: Node<'_>) -> Option<bool> {
357    let mut ancestor = node.parent();
358    while let Some(current) = ancestor {
359        if current.kind() == "enum_specifier" {
360            let list = first_descendant_kind(current, "enumerator_list")?;
361            let mut cursor = list.walk();
362            let enumerators = list
363                .named_children(&mut cursor)
364                .filter(|child| child.kind() == "enumerator")
365                .collect::<Vec<_>>();
366            let current_index = enumerators
367                .iter()
368                .position(|enumerator| enumerator.id() == node.id())?;
369            if node.child_by_field_name("value").is_none()
370                || current_index == 0
371                || current_index + 1 >= enumerators.len()
372            {
373                return Some(false);
374            }
375            let mut implicit_before_nonreference = false;
376            for (index, enumerator) in enumerators.iter().enumerate() {
377                if enumerator.child_by_field_name("value").is_none()
378                    && enumerators[index + 1..]
379                        .iter()
380                        .any(|later| later.child_by_field_name("value").is_some())
381                {
382                    implicit_before_nonreference = true;
383                    break;
384                }
385            }
386            return Some(implicit_before_nonreference);
387        }
388        ancestor = current.parent();
389    }
390    None
391}
392
393fn loop_binding_name(node: Node<'_>, source: &str) -> Option<String> {
394    let binding = node.child_by_field_name("declarator").or_else(|| {
395        node.child_by_field_name("initializer")
396            .and_then(first_declaration_or_name)
397    })?;
398    let name = crate::structural::declarator_name_node(binding)?;
399    Some(node_text(name, source).to_owned())
400}
401
402fn has_short_loop_ancestor(node: Node<'_>, source: &str) -> bool {
403    let mut ancestor = node.parent();
404    while let Some(current) = ancestor {
405        if matches!(current.kind(), "for_statement" | "for_range_loop")
406            && loop_binding_name(current, source).is_some_and(|name| name.chars().count() == 1)
407        {
408            return true;
409        }
410        ancestor = current.parent();
411    }
412    false
413}
414
415fn sizeof_operand_is_parameter(
416    node: Node<'_>,
417    operand: Option<Node<'_>>,
418    source: &str,
419) -> Option<bool> {
420    let operand = operand?;
421    let name_node = if matches!(operand.kind(), "identifier" | "field_identifier") {
422        Some(operand)
423    } else {
424        first_descendant_kind(operand, "identifier")
425    }?;
426    let name = node_text(name_node, source);
427    let mut ancestor = node.parent();
428    while let Some(current) = ancestor {
429        if current.kind() == "function_definition" {
430            let mut stack = vec![current];
431            while let Some(candidate) = stack.pop() {
432                if candidate.kind() == "parameter_declaration"
433                    && candidate
434                        .child_by_field_name("declarator")
435                        .and_then(crate::structural::declarator_name_node)
436                        .is_some_and(|candidate_name| node_text(candidate_name, source) == name)
437                {
438                    return Some(true);
439                }
440                let mut cursor = candidate.walk();
441                let children = candidate.named_children(&mut cursor).collect::<Vec<_>>();
442                stack.extend(children.into_iter().rev());
443            }
444            return Some(false);
445        }
446        ancestor = current.parent();
447    }
448    None
449}
450
451fn exact_parameter_type_size(
452    node: Node<'_>,
453    source: &str,
454    named_record_sizes: &HashMap<String, Option<u64>>,
455) -> Option<u64> {
456    // Only a scalar/by-value declarator has the size of its written type.
457    // Pointer ABI size and adjusted array parameters are not known here;
458    // references likewise carry no exact-size evidence in this projection.
459    if node
460        .child_by_field_name("declarator")
461        .is_some_and(cpp_declarator_adds_indirection)
462    {
463        return None;
464    }
465    let type_node = node.child_by_field_name("type")?;
466    let type_text = node_text(type_node, source).trim();
467    match type_text {
468        "char" | "signed char" | "unsigned char" => Some(1),
469        _ if matches!(
470            type_node.kind(),
471            "type_identifier" | "qualified_identifier" | "scoped_type_identifier"
472        ) =>
473        {
474            named_record_sizes.get(type_text).copied().flatten()
475        }
476        _ => None,
477    }
478}
479
480pub(crate) fn named_record_size_index(
481    root: Node<'_>,
482    source: &str,
483) -> HashMap<String, Option<u64>> {
484    let mut sizes = HashMap::default();
485    let mut stack = vec![root];
486    while let Some(node) = stack.pop() {
487        if matches!(
488            node.kind(),
489            "class_specifier" | "struct_specifier" | "union_specifier"
490        ) && node.child_by_field_name("name").is_some()
491        {
492            let name = node
493                .child_by_field_name("name")
494                .expect("record name was checked above");
495            let name = node_text(name, source).trim();
496            if !name.is_empty() {
497                sizes
498                    .entry(name.to_owned())
499                    .or_insert_with(|| exact_char_record_size(node, source));
500            }
501        }
502        let mut cursor = node.walk();
503        let children = node.named_children(&mut cursor).collect::<Vec<_>>();
504        stack.extend(children.into_iter().rev());
505    }
506    sizes
507}
508
509fn exact_char_record_size(record: Node<'_>, source: &str) -> Option<u64> {
510    let fields = first_descendant_kind(record, "field_declaration_list")?;
511    let mut cursor = fields.walk();
512    let declarations = fields
513        .named_children(&mut cursor)
514        .filter(|child| child.kind() == "field_declaration")
515        .collect::<Vec<_>>();
516    if declarations.is_empty() {
517        return None;
518    }
519    let mut size = 0u64;
520    for field in declarations {
521        if named_child(field, "bitfield_clause").is_some() {
522            return None;
523        }
524        let type_node = field.child_by_field_name("type")?;
525        let type_text = node_text(type_node, source).trim();
526        if !matches!(type_text, "char" | "signed char" | "unsigned char") {
527            return None;
528        }
529        let mut cursor = field.walk();
530        let mut declarators = field
531            .children_by_field_name("declarator", &mut cursor)
532            .peekable();
533        declarators.peek()?;
534        for declarator in declarators {
535            let shape = declarator_shape(declarator, source);
536            let field_size = if shape.has_array {
537                shape.array_extent?
538            } else if shape.top == CppTypeForm::Unknown {
539                1
540            } else {
541                return None;
542            };
543            size = if record.kind() == "union_specifier" {
544                size.max(field_size)
545            } else {
546                size.checked_add(field_size)?
547            };
548        }
549    }
550    Some(size)
551}
552
553fn named_child<'tree>(node: Node<'tree>, kind: &str) -> Option<Node<'tree>> {
554    let mut cursor = node.walk();
555    node.named_children(&mut cursor)
556        .find(|child| child.kind() == kind)
557}
558
559fn first_descendant_kind<'tree>(node: Node<'tree>, kind: &str) -> Option<Node<'tree>> {
560    let mut stack = vec![node];
561    while let Some(current) = stack.pop() {
562        if current.kind() == kind {
563            return Some(current);
564        }
565        let mut cursor = current.walk();
566        let children = current.named_children(&mut cursor).collect::<Vec<_>>();
567        stack.extend(children.into_iter().rev());
568    }
569    None
570}
571
572fn first_declaration_or_name(node: Node<'_>) -> Option<Node<'_>> {
573    if matches!(node.kind(), "declaration" | "parameter_declaration") {
574        return node.child_by_field_name("declarator");
575    }
576    if matches!(
577        node.kind(),
578        "identifier" | "field_identifier" | "reference_declarator" | "array_declarator"
579    ) {
580        return Some(node);
581    }
582    first_descendant_kind(node, "declaration")
583        .and_then(|declaration| declaration.child_by_field_name("declarator"))
584        .or_else(|| first_descendant_kind(node, "identifier"))
585}
586
587struct DeclaratorShape {
588    top: CppTypeForm,
589    has_array: bool,
590    has_reference: bool,
591    array_extent: Option<u64>,
592}
593
594fn declarator_shape(declarator: Node<'_>, source: &str) -> DeclaratorShape {
595    let mut current = Some(declarator);
596    let mut top = CppTypeForm::Unknown;
597    let mut has_array = false;
598    let mut has_reference = false;
599    let mut array_extent = None;
600    while let Some(node) = current {
601        match node.kind() {
602            "pointer_declarator" => {
603                if top == CppTypeForm::Unknown {
604                    top = CppTypeForm::Pointer;
605                }
606                current = node.child_by_field_name("declarator");
607            }
608            "reference_declarator" => {
609                has_reference = true;
610                if top == CppTypeForm::Unknown {
611                    top = CppTypeForm::Reference;
612                }
613                current = node
614                    .child_by_field_name("declarator")
615                    .or_else(|| node.named_child(0));
616            }
617            "array_declarator" => {
618                has_array = true;
619                if top == CppTypeForm::Unknown {
620                    top = CppTypeForm::Array;
621                }
622                array_extent = node
623                    .child_by_field_name("size")
624                    .or_else(|| node.child_by_field_name("value"))
625                    .and_then(|size| parse_integer_literal(node_text(size, source)))
626                    .and_then(|size| u64::try_from(size).ok());
627                current = node.child_by_field_name("declarator");
628            }
629            "function_declarator" => {
630                if top == CppTypeForm::Unknown {
631                    top = CppTypeForm::Function;
632                }
633                current = node.child_by_field_name("declarator");
634            }
635            "init_declarator" | "parenthesized_declarator" | "attributed_declarator" => {
636                current = node
637                    .child_by_field_name("declarator")
638                    .or_else(|| node.named_child(0));
639            }
640            _ => current = None,
641        }
642    }
643    DeclaratorShape {
644        top,
645        has_array,
646        has_reference,
647        array_extent,
648    }
649}
650
651fn type_properties(
652    type_node: Option<Node<'_>>,
653    source: &str,
654) -> (Option<String>, CppTypeForm, CppSignedness, Option<u16>) {
655    let Some(type_node) = type_node else {
656        return (None, CppTypeForm::Unknown, CppSignedness::Unknown, None);
657    };
658    let text = node_text(type_node, source).trim().to_owned();
659    let kind = type_node.kind();
660    let builtin = matches!(kind, "primitive_type" | "sized_type_specifier")
661        || matches!(
662            text.as_str(),
663            "bool"
664                | "char"
665                | "signed char"
666                | "unsigned char"
667                | "short"
668                | "short int"
669                | "unsigned short"
670                | "unsigned short int"
671                | "int"
672                | "unsigned"
673                | "unsigned int"
674                | "long"
675                | "long int"
676                | "unsigned long"
677                | "unsigned long int"
678                | "long long"
679                | "long long int"
680                | "unsigned long long"
681                | "unsigned long long int"
682        );
683    let type_form = if builtin {
684        CppTypeForm::Builtin
685    } else if matches!(
686        kind,
687        "type_identifier"
688            | "qualified_identifier"
689            | "scoped_type_identifier"
690            | "template_type"
691            | "enum_specifier"
692    ) {
693        CppTypeForm::Named
694    } else {
695        CppTypeForm::Unknown
696    };
697    let signedness = if text.split_whitespace().any(|part| part == "unsigned") {
698        CppSignedness::Unsigned
699    } else if text.split_whitespace().any(|part| part == "signed") {
700        CppSignedness::Signed
701    } else if builtin
702        && matches!(
703            text.as_str(),
704            "char" | "int" | "short" | "long" | "long long"
705        )
706    {
707        CppSignedness::Ambiguous
708    } else {
709        CppSignedness::Unknown
710    };
711    let width_bits = match text.as_str() {
712        "bool" => Some(1),
713        "char" | "signed char" | "unsigned char" => Some(8),
714        "short" | "short int" | "signed short" | "signed short int" | "unsigned short"
715        | "unsigned short int" => Some(16),
716        "int" | "signed int" | "unsigned" | "unsigned int" => Some(32),
717        "long long"
718        | "long long int"
719        | "signed long long"
720        | "signed long long int"
721        | "unsigned long long"
722        | "unsigned long long int" => Some(64),
723        _ => None,
724    };
725    (Some(text), type_form, signedness, width_bits)
726}
727
728fn declaration_has_direct_const_qualifier(node: Node<'_>, source: &str) -> bool {
729    let mut cursor = node.walk();
730    node.named_children(&mut cursor)
731        .any(|child| child.kind() == "type_qualifier" && node_text(child, source).trim() == "const")
732}
733
734/// Parse the bounded C++ statement rows used by the statement-fact RQL
735/// relation. This is query-lifetime data; it owns no cross-file state.
736pub fn parse_statement_fact_rows(source: &str) -> StatementFactRows {
737    let mut parser = Parser::new();
738    parser
739        .set_language(&tree_sitter_cpp::LANGUAGE.into())
740        .expect("the linked tree-sitter-cpp grammar matches this tree-sitter version");
741    let tree = parser.parse(source, None).expect("uncancelled C++ parse");
742    brokk_bifrost_core::analyzer::statement_facts::producer::capture_statement_facts(
743        &crate::structural::CPP_STRUCTURAL_SPEC,
744        tree.root_node(),
745        source,
746    )
747}
748
749/// Parse one source snapshot into the class and exception projection used by
750/// RQL. The rows are query-lifetime and own no cross-file state.
751pub fn parse_cpp_class_fact_rows(source: &str) -> CppClassFactRows {
752    let mut parser = Parser::new();
753    parser
754        .set_language(&tree_sitter_cpp::LANGUAGE.into())
755        .expect("the linked tree-sitter-cpp grammar matches this tree-sitter version");
756    let tree = parser.parse(source, None).expect("uncancelled C++ parse");
757    let root = tree.root_node();
758    let ancestry = ParentIndex::new(root);
759    let mut rows = CppClassFactRows::default();
760    let mut stack = vec![root];
761    while let Some(node) = stack.pop() {
762        if node.is_named() {
763            capture_class_fact_rows(node, source, &ancestry, &mut rows);
764        }
765        let mut cursor = node.walk();
766        let children: Vec<_> = node.named_children(&mut cursor).collect();
767        stack.extend(children.into_iter().rev());
768    }
769    rows
770}
771
772pub(crate) fn base_specifier_from_node(
773    node: Node<'_>,
774    source: &str,
775    is_virtual: bool,
776    access: CppAccessSpecifier,
777) -> Option<CppBaseSpecifierFact> {
778    let components = cpp_type_name_components(node, source)?;
779    base_specifier_fact(node, components, is_virtual, access)
780}
781
782pub(crate) fn base_specifier_fact(
783    node: Node<'_>,
784    components: Vec<String>,
785    is_virtual: bool,
786    access: CppAccessSpecifier,
787) -> Option<CppBaseSpecifierFact> {
788    (!components.is_empty()).then_some(CppBaseSpecifierFact {
789        absolute: node.child(0).is_some_and(|token| token.kind() == "::"),
790        components,
791        is_virtual,
792        access,
793    })
794}
795
796pub(crate) fn declaration_name<'tree>(
797    node: Node<'tree>,
798    unit: &CodeUnit,
799    source: &str,
800) -> Option<Node<'tree>> {
801    if let Some(name) = node.child_by_field_name("name") {
802        return crate::structural::declarator_name_node(name);
803    }
804    let mut cursor = node.walk();
805    node.children_by_field_name("declarator", &mut cursor)
806        .find_map(|declarator| {
807            let name = crate::structural::declarator_name_node(declarator)?;
808            (node_text(name, source) == unit.identifier()).then_some(name)
809        })
810}
811
812/// Capture the structured type properties of one field declaration while its
813/// declaration AST is still available.
814pub(crate) fn capture_field_type(
815    node: Node<'_>,
816    field_name: &str,
817    source: &str,
818) -> (Option<CppDeclaredFieldTypeFact>, bool) {
819    if let Some(recovered) = crate::declarations::recovered_pyobject_head_field(node, source)
820        && node_text(recovered.name, source) == field_name
821    {
822        return (
823            Some(CppDeclaredFieldTypeFact {
824                type_text: node_text(recovered.type_node, source).to_owned(),
825                indirection: recovered.pointer_depth(),
826                binds_indirectly: recovered.pointer_depth() > 0,
827                template_arguments: None,
828            }),
829            false,
830        );
831    }
832    let Some(type_node) = node.child_by_field_name("type") else {
833        return (None, false);
834    };
835    let mut cursor = node.walk();
836    let declarator = node
837        .children_by_field_name("declarator", &mut cursor)
838        .find(|declarator| {
839            crate::structural::declarator_name_node(*declarator)
840                .is_some_and(|name| node_text(name, source) == field_name)
841        });
842    let names_function_type = declarator.is_some_and(declarator_names_function_type);
843    let field_type = cpp_declared_field_type_fact(node, type_node, field_name, source);
844    (field_type, names_function_type)
845}
846
847/// Capture one `namespace name = target;` definition while the primary tree is
848/// live. The target path, the enclosing namespaces and the guard environment
849/// come from the same structured helpers that using declarations use.
850pub(crate) fn capture_namespace_alias(
851    node: Node<'_>,
852    source: &str,
853    ancestry: &ParentIndex<'_>,
854    namespaces: &crate::graph::resolver::OrphanedNamespaceScopeIndex,
855    collector: &mut PrimarySourceFactCollector<'_>,
856) -> Option<CppNamespaceAliasFact> {
857    if node.kind() != "namespace_alias_definition" {
858        return None;
859    }
860    let name = node.child_by_field_name("name")?;
861    let mut cursor = node.walk();
862    let target = node.named_children(&mut cursor).find(|child| {
863        matches!(
864            child.kind(),
865            "namespace_identifier" | "nested_namespace_specifier" | "splice_specifier"
866        ) && child.id() != name.id()
867    })?;
868    let block = std::iter::successors(ancestry.parent(node), |current| ancestry.parent(*current))
869        .take_while(|current| {
870            !matches!(current.kind(), "namespace_definition" | "translation_unit")
871        })
872        .find(|current| current.kind() == "compound_statement");
873    Some(CppNamespaceAliasFact {
874        occurrence: collector.intern_node(node),
875        name: node_text(name, source).to_owned(),
876        target: crate::graph::resolver::cpp_name_component_nodes(target)
877            .filter(|components| !components.is_empty())
878            .map(|components| {
879                components
880                    .into_iter()
881                    .map(|component| node_text(component, source).to_owned())
882                    .collect()
883            }),
884        target_global: target.child(0).is_some_and(|child| child.kind() == "::"),
885        namespace: namespaces.enclosing_namespace_components(node, source),
886        block: block.map(|block| collector.intern_node(block)),
887        guards: crate::graph::resolver::binding_site_guards(node, source)
888            .as_ref()
889            .map(crate::source_context::cpp_guard_set_from_runtime),
890    })
891}
892
893pub(crate) fn capture_declaration(
894    declaration: SourceDeclarationId,
895    node: Node<'_>,
896    unit: &CodeUnit,
897    source: &str,
898    ancestry: &ParentIndex<'_>,
899) -> CppDeclarationSourceFact {
900    let mut fact = CppDeclarationSourceFact::new(declaration);
901    if matches!(node.kind(), "alias_declaration" | "type_definition")
902        && crate::graph::resolver::alias_has_visible_file_scope(node)
903        && let Some(name) = declaration_name(node, unit, source)
904        && let Some(name) =
905            crate::graph::resolver::normalize_reference_name(node_text(name, source))
906        && let Some(target) = node.child_by_field_name("type")
907        && let Some(target) =
908            crate::graph::resolver::normalize_reference_name(node_text(target, source))
909    {
910        fact.file_scope_alias = Some(CppFileScopeAliasFact {
911            name,
912            target,
913            namespace: crate::graph::resolver::enclosing_namespace_context(node, source),
914        });
915    }
916    let mut owners = Vec::new();
917    let mut current = ancestry.parent(node);
918    while let Some(parent) = current {
919        if matches!(
920            parent.kind(),
921            "namespace_definition"
922                | "class_specifier"
923                | "struct_specifier"
924                | "union_specifier"
925                | "enum_specifier"
926        ) && let Some(name) = parent.child_by_field_name("name")
927        {
928            owners.push(node_text(name, source).to_owned());
929        }
930        current = ancestry.parent(parent);
931    }
932    owners.reverse();
933    owners.push(unit.identifier().to_owned());
934    fact.lexical_path = owners;
935    // A function-local class and its members are scoped by their callable
936    // and block, which the written class chain alone cannot spell: it would
937    // give a local `Widget` the path of a global one. Their structured
938    // identity is that scope, so the path follows it.
939    if crate::graph::resolver::is_function_local_unit(unit) {
940        let interner = brokk_bifrost_core::analyzer::fq_name::segment_interner();
941        fact.lexical_path = unit
942            .fq()
943            .segments()
944            .iter()
945            .map(|&segment| interner.resolve(segment).0.to_owned())
946            .collect();
947    }
948    if matches!(
949        node.kind(),
950        "class_specifier" | "struct_specifier" | "union_specifier" | "enum_specifier"
951    ) {
952        fact.class_strength = if node.child_by_field_name("body").is_some() {
953            CppClassDeclarationStrength::Full
954        } else {
955            CppClassDeclarationStrength::Forward
956        };
957        if node.kind() == "enum_specifier" {
958            let mut cursor = node.walk();
959            fact.enum_kind = if node
960                .children(&mut cursor)
961                .any(|child| matches!(child.kind(), "class" | "struct"))
962            {
963                CppEnumOwnerKind::Scoped
964            } else {
965                CppEnumOwnerKind::Unscoped
966            };
967        }
968        let mut cursor = node.walk();
969        for base_clause in node
970            .named_children(&mut cursor)
971            .filter(|child| child.kind() == "base_class_clause")
972        {
973            let mut is_virtual = false;
974            let mut cursor = base_clause.walk();
975            for child in base_clause.children(&mut cursor) {
976                match child.kind() {
977                    "," => is_virtual = false,
978                    "virtual" => is_virtual = true,
979                    "type_identifier"
980                    | "qualified_identifier"
981                    | "scoped_type_identifier"
982                    | "template_type" => {
983                        if let Some(base) = base_specifier_from_node(
984                            child,
985                            source,
986                            is_virtual,
987                            base_access_specifier(base_clause, child, node.kind()),
988                        ) {
989                            fact.bases.push(base);
990                        }
991                        is_virtual = false;
992                    }
993                    _ => {}
994                }
995            }
996        }
997    }
998    let mut cursor = node.walk();
999    let declarator = node
1000        .children_by_field_name("declarator", &mut cursor)
1001        .find(|declarator| {
1002            crate::structural::declarator_name_node(*declarator)
1003                .is_some_and(|name| node_text(name, source) == unit.identifier())
1004        });
1005    if unit.is_function() {
1006        let callable = if node.kind() == "function_declarator" {
1007            Some(node)
1008        } else {
1009            node.child_by_field_name("declarator")
1010        };
1011        if let Some(declarator) = callable {
1012            if let Some(name) = declarator_name_node(declarator)
1013                && let Some(mut components) = cpp_type_name_components(name, source)
1014            {
1015                components.pop();
1016                fact.written_owner = components;
1017            }
1018            let mut chain = Some(declarator);
1019            while let Some(current) = chain {
1020                if current.kind() == "function_declarator" {
1021                    fact.callable_comparable_shapes =
1022                        Some(cpp_comparable_parameter_shapes(current, source, ancestry));
1023                    fact.callable_identity_suffix = cpp_callable_identity_suffix(current, source);
1024                    fact.callable_is_constructor =
1025                        cpp_callable_is_structural_constructor(current, source, ancestry);
1026                    fact.callable_is_deduction_guide =
1027                        cpp_callable_is_deduction_guide(node, current, unit, source);
1028                    fact.callable_is_template = ancestry.parent(node).is_some_and(|parent| {
1029                        parent.kind() == "template_declaration"
1030                            && parent
1031                                .named_child(parent.named_child_count().saturating_sub(1))
1032                                .is_some_and(|declaration| declaration.id() == node.id())
1033                    });
1034                    // Only identity qualifiers participate in overload hiding.
1035                    // The declarator can also contain override/final specifiers.
1036                    fact.trailing_qualifiers =
1037                        fact.callable_identity_suffix.clone().unwrap_or_default();
1038                    break;
1039                }
1040                chain = current.child_by_field_name("declarator");
1041            }
1042        }
1043    }
1044    if unit.is_field() {
1045        let (field_type, names_function_type) = capture_field_type(node, unit.identifier(), source);
1046        fact.field_type = field_type;
1047        fact.names_function_type = names_function_type;
1048    }
1049    let alias_type = if matches!(node.kind(), "alias_declaration" | "type_definition") {
1050        node.child_by_field_name("type")
1051    } else if unit.is_class() {
1052        crate::declarations::recovered_alias_type_node(node, unit.identifier(), source)
1053    } else {
1054        None
1055    };
1056    if let Some(alias_type) = alias_type {
1057        let alias_declarator = if node.kind() == "type_definition" {
1058            declarator
1059        } else {
1060            alias_type.child_by_field_name("declarator")
1061        };
1062        fact.names_function_type = alias_declarator.is_some_and(declarator_names_function_type);
1063        fact.adds_indirection = alias_declarator.is_some_and(cpp_declarator_adds_indirection);
1064        if !fact.names_function_type {
1065            fact.alias_target = structured_alias_type_target(alias_type, source);
1066            let mut target = alias_type;
1067            while target.kind() == "type_descriptor" {
1068                let Some(inner) = target.child_by_field_name("type") else {
1069                    break;
1070                };
1071                target = inner;
1072            }
1073            if matches!(
1074                target.kind(),
1075                "class_specifier" | "struct_specifier" | "union_specifier" | "enum_specifier"
1076            ) && let Some(name) = target.child_by_field_name("name")
1077            {
1078                target = name;
1079            }
1080            fact.alias_target_text = Some(node_text(target, source).to_owned());
1081        }
1082    }
1083    fact
1084}
1085
1086/// Add the class and exception rows whose meaning lives below a declaration
1087/// node. This is called by the primary iterative walk, while the tree and its
1088/// parent index are still owned by the producer.
1089pub(crate) fn capture_class_fact_rows(
1090    node: Node<'_>,
1091    source: &str,
1092    ancestry: &ParentIndex<'_>,
1093    rows: &mut CppClassFactRows,
1094) {
1095    match node.kind() {
1096        "class_specifier" | "struct_specifier" | "union_specifier" => {
1097            let mut path = enclosing_owner_path(node, ancestry, source);
1098            if let Some(name) = node.child_by_field_name("name") {
1099                path.push(node_text(name, source).to_owned());
1100            }
1101            let is_interface = node
1102                .child_by_field_name("body")
1103                .is_some_and(|body| tree_contains_pure_virtual(body, source));
1104            rows.classes.push(CppClassFact {
1105                range: node_range(node),
1106                path,
1107                is_interface,
1108            });
1109        }
1110        "function_definition" | "declaration" | "field_declaration" => {
1111            if let Some(member) = capture_member_fact(node, source, ancestry) {
1112                rows.members.push(member);
1113            }
1114        }
1115        "catch_clause" => {
1116            rows.catches.push(capture_catch_fact(node, source));
1117        }
1118        "throw_statement" => {
1119            rows.throws.push(capture_throw_fact(node, source));
1120        }
1121        _ => {}
1122    }
1123}
1124
1125fn capture_member_fact(
1126    node: Node<'_>,
1127    source: &str,
1128    ancestry: &ParentIndex<'_>,
1129) -> Option<CppMemberFact> {
1130    let function_declarator = extract_function_declarator(node)?;
1131    let name_node = declarator_name_node(function_declarator)?;
1132    let name = node_text(name_node, source).to_owned();
1133    let mut owner = enclosing_owner_path(node, ancestry, source);
1134    let written_owner = cpp_type_name_components(name_node, source)
1135        .map(|mut components| {
1136            components.pop();
1137            components
1138        })
1139        .unwrap_or_default();
1140    append_owner_components(&mut owner, &written_owner);
1141    let owner_name = owner.last().map(String::as_str);
1142    let role = if name == "operator=" {
1143        CppMemberRole::AssignmentOperator
1144    } else if name.strip_prefix('~').is_some() {
1145        CppMemberRole::Destructor
1146    } else if owner_name == Some(name.as_str()) {
1147        CppMemberRole::Constructor
1148    } else {
1149        CppMemberRole::Method
1150    };
1151    let (copy_parameter, move_parameter, remaining_parameters_defaulted) =
1152        callable_parameter_shape(function_declarator, source, ancestry, owner_name);
1153    let special_member = match role {
1154        CppMemberRole::Destructor => CppSpecialMemberKind::Destructor,
1155        CppMemberRole::Constructor if copy_parameter => CppSpecialMemberKind::CopyConstructor,
1156        CppMemberRole::Constructor if move_parameter => CppSpecialMemberKind::MoveConstructor,
1157        CppMemberRole::Constructor if function_parameter_count(function_declarator) == 0 => {
1158            CppSpecialMemberKind::DefaultConstructor
1159        }
1160        CppMemberRole::AssignmentOperator if copy_parameter => CppSpecialMemberKind::CopyAssignment,
1161        CppMemberRole::AssignmentOperator if move_parameter => CppSpecialMemberKind::MoveAssignment,
1162        _ => CppSpecialMemberKind::None,
1163    };
1164    let state = if tree_contains_kind(node, "delete_method_clause") {
1165        CppSpecialMemberState::Deleted
1166    } else if tree_contains_kind(node, "default_method_clause") {
1167        CppSpecialMemberState::Defaulted
1168    } else {
1169        CppSpecialMemberState::Declared
1170    };
1171    let access = member_access_specifier(node, source, ancestry);
1172    let assignment_return = if role == CppMemberRole::AssignmentOperator {
1173        assignment_return_shape(node, source, owner_name)
1174    } else {
1175        CppAssignmentReturnShape::Unknown
1176    };
1177    let initializer_target = if role == CppMemberRole::Constructor {
1178        constructor_initializer_target(node, source, owner_name)
1179    } else {
1180        None
1181    };
1182    let delegation_calls = if role == CppMemberRole::Constructor {
1183        constructor_delegation_calls(node, source, ancestry, owner_name)
1184    } else {
1185        Vec::new()
1186    };
1187    Some(CppMemberFact {
1188        range: node_range(node),
1189        owner,
1190        name,
1191        role,
1192        special_member,
1193        state,
1194        access,
1195        copy_parameter,
1196        remaining_parameters_defaulted,
1197        assignment_return,
1198        initializer_target,
1199        delegation_calls,
1200        pure_virtual: tree_contains_pure_virtual(node, source),
1201    })
1202}
1203
1204fn capture_catch_fact(node: Node<'_>, source: &str) -> CppCatchFact {
1205    let parameter = node
1206        .child_by_field_name("parameters")
1207        .and_then(|parameters| parameters.named_child(0));
1208    let type_node = parameter.and_then(|parameter| parameter.child_by_field_name("type"));
1209    let declarator = parameter.and_then(|parameter| parameter.child_by_field_name("declarator"));
1210    let value_category = declarator
1211        .map(classify_parameter_declarator)
1212        .unwrap_or(CppParameterValueCategory::Value);
1213    let type_name = type_node
1214        .and_then(|type_node| cpp_type_name_components(type_node, source))
1215        .unwrap_or_default();
1216    let class_type = type_node.is_some_and(|type_node| {
1217        !matches!(
1218            type_node.kind(),
1219            "primitive_type" | "sized_type_specifier" | "auto" | "decltype"
1220        )
1221    });
1222    CppCatchFact {
1223        range: node_range(node),
1224        value_category,
1225        type_name,
1226        class_type,
1227    }
1228}
1229
1230fn capture_throw_fact(node: Node<'_>, source: &str) -> CppThrowFact {
1231    let expression = node.named_child(0);
1232    let (operand_shape, thrown_type) = match expression {
1233        None => (CppThrowOperandShape::Rethrow, Vec::new()),
1234        Some(expression) if expression.kind() == "new_expression" => (
1235            CppThrowOperandShape::Pointer,
1236            expression
1237                .child_by_field_name("type")
1238                .and_then(|type_node| cpp_type_name_components(type_node, source))
1239                .unwrap_or_default(),
1240        ),
1241        Some(_) => (CppThrowOperandShape::Value, Vec::new()),
1242    };
1243    CppThrowFact {
1244        range: node_range(node),
1245        operand_shape,
1246        thrown_type,
1247    }
1248}
1249
1250fn function_parameter_count(function: Node<'_>) -> usize {
1251    function
1252        .child_by_field_name("parameters")
1253        .map_or(0, |parameters| parameters.named_child_count())
1254}
1255
1256fn callable_parameter_shape(
1257    function: Node<'_>,
1258    source: &str,
1259    ancestry: &ParentIndex<'_>,
1260    owner_name: Option<&str>,
1261) -> (bool, bool, bool) {
1262    let Some(parameters) = function.child_by_field_name("parameters") else {
1263        return (false, false, true);
1264    };
1265    let parameter_nodes: Vec<_> = parameters.named_children(&mut parameters.walk()).collect();
1266    let remaining_parameters_defaulted = parameter_nodes.len() > 1
1267        && parameter_nodes
1268            .iter()
1269            .skip(1)
1270            .all(|parameter| parameter.child_by_field_name("default_value").is_some());
1271    let Some(first) = parameter_nodes.first().copied() else {
1272        return (false, false, remaining_parameters_defaulted);
1273    };
1274    let Some(_type_node) = first.child_by_field_name("type") else {
1275        return (false, false, remaining_parameters_defaulted);
1276    };
1277    let Some(owner_name) = owner_name else {
1278        return (false, false, remaining_parameters_defaulted);
1279    };
1280    let comparable = cpp_comparable_parameter_shapes(function, source, ancestry);
1281    let Some(CppComparableSlot::Shape(parameter)) = comparable.first() else {
1282        return (false, false, remaining_parameters_defaulted);
1283    };
1284    let reference = match parameter.node(parameter.root()) {
1285        CppComparableNode::Reference { inner } => Some(*inner),
1286        _ => None,
1287    };
1288    let Some(inner) = reference else {
1289        return (false, false, remaining_parameters_defaulted);
1290    };
1291    let CppComparableNode::Named { name, .. } = parameter.node(inner) else {
1292        return (false, false, remaining_parameters_defaulted);
1293    };
1294    let same_owner = name.path().last().is_some_and(|name| name == owner_name);
1295    if !same_owner {
1296        return (false, false, remaining_parameters_defaulted);
1297    }
1298    let rvalue = first
1299        .child_by_field_name("declarator")
1300        .is_some_and(|declarator| declarator_contains_rvalue_reference(declarator));
1301    let copy = !rvalue;
1302    let move_parameter = rvalue;
1303    (copy, move_parameter, remaining_parameters_defaulted)
1304}
1305
1306fn declarator_contains_rvalue_reference(node: Node<'_>) -> bool {
1307    let mut stack = vec![node];
1308    while let Some(current) = stack.pop() {
1309        if crate::declarations::reference_declarator_is_rvalue(current) {
1310            return true;
1311        }
1312        let mut cursor = current.walk();
1313        stack.extend(current.named_children(&mut cursor));
1314    }
1315    false
1316}
1317
1318fn classify_parameter_declarator(node: Node<'_>) -> CppParameterValueCategory {
1319    if declarator_contains_rvalue_reference(node) {
1320        CppParameterValueCategory::RValueReference
1321    } else {
1322        let mut stack = vec![node];
1323        while let Some(current) = stack.pop() {
1324            if current.kind() == "reference_declarator" {
1325                return CppParameterValueCategory::LValueReference;
1326            }
1327            if current.kind() == "pointer_declarator" {
1328                return CppParameterValueCategory::Pointer;
1329            }
1330            let mut cursor = current.walk();
1331            stack.extend(current.named_children(&mut cursor));
1332        }
1333        CppParameterValueCategory::Value
1334    }
1335}
1336
1337fn assignment_return_shape(
1338    node: Node<'_>,
1339    source: &str,
1340    owner_name: Option<&str>,
1341) -> CppAssignmentReturnShape {
1342    let mut current = node.child_by_field_name("declarator");
1343    let mut reference = false;
1344    let mut pointer = false;
1345    while let Some(declarator) = current {
1346        reference |= declarator.kind() == "reference_declarator";
1347        pointer |= declarator.kind() == "pointer_declarator";
1348        current = declarator.child_by_field_name("declarator");
1349    }
1350    if !reference {
1351        return if pointer {
1352            CppAssignmentReturnShape::Unknown
1353        } else {
1354            CppAssignmentReturnShape::Value
1355        };
1356    }
1357    let return_type = node.child_by_field_name("type");
1358    if owner_name.is_some_and(|owner| {
1359        return_type
1360            .and_then(|type_node| cpp_type_name_components(type_node, source))
1361            .and_then(|components| components.last().cloned())
1362            .is_some_and(|name| name == owner)
1363    }) {
1364        CppAssignmentReturnShape::ReferenceToThis
1365    } else {
1366        CppAssignmentReturnShape::ReferenceOther
1367    }
1368}
1369
1370fn constructor_initializer_target(
1371    node: Node<'_>,
1372    source: &str,
1373    owner_name: Option<&str>,
1374) -> Option<Vec<String>> {
1375    let owner_name = owner_name?;
1376    let mut cursor = node.walk();
1377    let initializer_list = node
1378        .named_children(&mut cursor)
1379        .find(|child| child.kind() == "field_initializer_list")?;
1380    let mut cursor = initializer_list.walk();
1381    initializer_list
1382        .named_children(&mut cursor)
1383        .filter(|child| child.kind() == "field_initializer")
1384        .find_map(|initializer| {
1385            let name = initializer
1386                .child_by_field_name("name")
1387                .or_else(|| initializer.child_by_field_name("field"))
1388                .or_else(|| {
1389                    let mut cursor = initializer.walk();
1390                    initializer.named_children(&mut cursor).find(|child| {
1391                        matches!(
1392                            child.kind(),
1393                            "field_identifier"
1394                                | "type_identifier"
1395                                | "qualified_identifier"
1396                                | "scoped_type_identifier"
1397                        )
1398                    })
1399                })?;
1400            let components = cpp_type_name_components(name, source)?;
1401            components
1402                .last()
1403                .is_some_and(|component| component == owner_name)
1404                .then_some(components)
1405        })
1406}
1407
1408fn constructor_delegation_calls(
1409    node: Node<'_>,
1410    source: &str,
1411    ancestry: &ParentIndex<'_>,
1412    owner_name: Option<&str>,
1413) -> Vec<Range> {
1414    let Some(owner_name) = owner_name else {
1415        return Vec::new();
1416    };
1417    let Some(body) = node.child_by_field_name("body") else {
1418        return Vec::new();
1419    };
1420    let mut stack = vec![body];
1421    let mut calls = Vec::new();
1422    while let Some(current) = stack.pop() {
1423        if current.kind() == "call_expression"
1424            && ancestry
1425                .parent(current)
1426                .is_some_and(|parent| parent.kind() == "expression_statement")
1427            && let Some(function) = current.child_by_field_name("function")
1428            && function.kind() == "identifier"
1429            && node_text(function, source) == owner_name
1430        {
1431            calls.push(node_range(current));
1432        }
1433        let mut cursor = current.walk();
1434        stack.extend(current.named_children(&mut cursor));
1435    }
1436    calls
1437}
1438
1439fn enclosing_owner_path(node: Node<'_>, ancestry: &ParentIndex<'_>, source: &str) -> Vec<String> {
1440    let mut owners = Vec::new();
1441    let mut current = ancestry.parent(node);
1442    while let Some(parent) = current {
1443        if matches!(
1444            parent.kind(),
1445            "namespace_definition"
1446                | "class_specifier"
1447                | "struct_specifier"
1448                | "union_specifier"
1449                | "enum_specifier"
1450        ) && let Some(name) = parent.child_by_field_name("name")
1451        {
1452            owners.push(node_text(name, source).to_owned());
1453        }
1454        current = ancestry.parent(parent);
1455    }
1456    owners.reverse();
1457    owners
1458}
1459
1460fn append_owner_components(owner: &mut Vec<String>, written: &[String]) {
1461    let overlap = (0..=owner.len().min(written.len()))
1462        .rev()
1463        .find(|length| owner[owner.len().saturating_sub(*length)..] == written[..*length])
1464        .unwrap_or(0);
1465    owner.extend(written[overlap..].iter().cloned());
1466}
1467
1468fn member_access_specifier(
1469    node: Node<'_>,
1470    source: &str,
1471    ancestry: &ParentIndex<'_>,
1472) -> CppAccessSpecifier {
1473    let mut current = ancestry.parent(node);
1474    while let Some(parent) = current {
1475        if matches!(
1476            parent.kind(),
1477            "class_specifier" | "struct_specifier" | "union_specifier"
1478        ) {
1479            let default = if parent.kind() == "class_specifier" {
1480                CppAccessSpecifier::Private
1481            } else {
1482                CppAccessSpecifier::Public
1483            };
1484            let Some(body) = parent.child_by_field_name("body") else {
1485                return CppAccessSpecifier::Unknown;
1486            };
1487            let mut access = default;
1488            let mut cursor = body.walk();
1489            for child in body.named_children(&mut cursor) {
1490                if child.start_byte() >= node.start_byte() {
1491                    break;
1492                }
1493                if child.kind() == "access_specifier" {
1494                    access = match child.child(0).map(|keyword| keyword.kind()) {
1495                        Some("public") => CppAccessSpecifier::Public,
1496                        Some("protected") => CppAccessSpecifier::Protected,
1497                        Some("private") => CppAccessSpecifier::Private,
1498                        _ => CppAccessSpecifier::Unknown,
1499                    };
1500                } else if let Some(label) = cpp_macro_swallowed_access_label(child, source) {
1501                    access = match label.access {
1502                        "public" => CppAccessSpecifier::Public,
1503                        "protected" => CppAccessSpecifier::Protected,
1504                        _ => CppAccessSpecifier::Private,
1505                    };
1506                }
1507            }
1508            return access;
1509        }
1510        current = ancestry.parent(parent);
1511    }
1512    CppAccessSpecifier::Unknown
1513}
1514
1515pub(crate) fn base_access_specifier(
1516    clause: Node<'_>,
1517    base: Node<'_>,
1518    class_kind: &str,
1519) -> CppAccessSpecifier {
1520    let default = if matches!(class_kind, "struct_specifier" | "union_specifier") {
1521        CppAccessSpecifier::Public
1522    } else {
1523        CppAccessSpecifier::Private
1524    };
1525    let mut access = default;
1526    let mut cursor = clause.walk();
1527    for child in clause.children(&mut cursor) {
1528        if child.start_byte() >= base.start_byte() {
1529            break;
1530        }
1531        if child.kind() == "," {
1532            access = default;
1533        } else if child.kind() == "access_specifier" {
1534            access = match child.child(0).map(|keyword| keyword.kind()) {
1535                Some("public") => CppAccessSpecifier::Public,
1536                Some("protected") => CppAccessSpecifier::Protected,
1537                Some("private") => CppAccessSpecifier::Private,
1538                _ => CppAccessSpecifier::Unknown,
1539            };
1540        }
1541    }
1542    access
1543}
1544
1545fn tree_contains_kind(node: Node<'_>, kind: &str) -> bool {
1546    let mut stack = vec![node];
1547    while let Some(current) = stack.pop() {
1548        if current.kind() == kind {
1549            return true;
1550        }
1551        let mut cursor = current.walk();
1552        stack.extend(current.named_children(&mut cursor));
1553    }
1554    false
1555}
1556
1557fn tree_contains_pure_virtual(node: Node<'_>, source: &str) -> bool {
1558    let mut stack = vec![node];
1559    while let Some(current) = stack.pop() {
1560        if current.kind() == "field_declaration"
1561            && current
1562                .child_by_field_name("default_value")
1563                .is_some_and(|value| {
1564                    value.kind() == "number_literal" && node_text(value, source).trim() == "0"
1565                })
1566            && current
1567                .child_by_field_name("declarator")
1568                .and_then(extract_function_declarator)
1569                .is_some()
1570        {
1571            return true;
1572        }
1573        let mut cursor = current.walk();
1574        stack.extend(current.named_children(&mut cursor));
1575    }
1576    tree_contains_kind(node, "pure_virtual_clause")
1577}
1578
1579fn cpp_callable_is_deduction_guide(
1580    declaration: Node<'_>,
1581    function_declarator: Node<'_>,
1582    unit: &CodeUnit,
1583    source: &str,
1584) -> bool {
1585    if declaration.kind() != "declaration"
1586        || declaration.child_by_field_name("type").is_some()
1587        || function_declarator.kind() != "function_declarator"
1588    {
1589        return false;
1590    }
1591    let mut cursor = function_declarator.walk();
1592    function_declarator
1593        .named_children(&mut cursor)
1594        .any(|child| child.kind() == "trailing_return_type")
1595        && declarator_name_node(function_declarator)
1596            .is_some_and(|name| node_text(name, source) == unit.identifier())
1597}
1598
1599/// One mounted, generation-selected canonical declaration family.
1600#[derive(Debug, Clone)]
1601pub struct CppFileSourceFacts {
1602    pub source: brokk_bifrost_core::analyzer::source_facts::SourceFactRows,
1603    pub facts: CppSourceFacts,
1604    pub declaration_units: brokk_bifrost_core::hash::HashMap<SourceDeclarationId, Vec<CodeUnit>>,
1605    by_unit: brokk_bifrost_core::hash::HashMap<CodeUnit, Vec<usize>>,
1606}
1607
1608impl CppFileSourceFacts {
1609    pub fn new(
1610        source: brokk_bifrost_core::analyzer::source_facts::SourceFactRows,
1611        facts: CppSourceFacts,
1612        declaration_units: brokk_bifrost_core::hash::HashMap<SourceDeclarationId, Vec<CodeUnit>>,
1613    ) -> Self {
1614        assert!(
1615            facts.valid_links(&source),
1616            "invalid C++ canonical source links"
1617        );
1618        let mut by_unit: brokk_bifrost_core::hash::HashMap<_, Vec<_>> = Default::default();
1619        for (index, fact) in facts.declarations.iter().enumerate() {
1620            if let Some(units) = declaration_units.get(&fact.declaration) {
1621                for unit in units {
1622                    by_unit.entry(unit.clone()).or_default().push(index);
1623                }
1624            }
1625        }
1626        Self {
1627            source,
1628            facts,
1629            declaration_units,
1630            by_unit,
1631        }
1632    }
1633
1634    pub fn for_unit(&self, unit: &CodeUnit) -> impl Iterator<Item = &CppDeclarationSourceFact> {
1635        self.by_unit
1636            .get(unit)
1637            .into_iter()
1638            .flatten()
1639            .map(|index| &self.facts.declarations[*index])
1640    }
1641
1642    pub fn estimated_retained_bytes(&self) -> usize {
1643        self.source.estimated_bytes()
1644            + self.facts.estimated_retained_bytes()
1645            + self
1646                .declaration_units
1647                .values()
1648                .map(|units| units.capacity() * std::mem::size_of::<CodeUnit>())
1649                .sum::<usize>()
1650            + self
1651                .by_unit
1652                .values()
1653                .map(|indices| indices.capacity() * std::mem::size_of::<usize>())
1654                .sum::<usize>()
1655    }
1656}
1657
1658/// One source-backed navigation alternative for a mounted declaration.
1659#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1660pub struct CppNavigationOccurrence {
1661    pub range: brokk_bifrost_core::analyzer::Range,
1662    pub role: CppOccurrenceRole,
1663    pub conditional_family: Option<(usize, usize)>,
1664}
1665
1666/// Canonical declaration context with IDs resolved in its own dialect arena.
1667#[derive(Debug, Clone, PartialEq, Eq)]
1668pub struct CppDeclarationOccurrence {
1669    pub fact: CppDeclarationSourceFact,
1670    pub range: brokk_bifrost_core::analyzer::Range,
1671    pub name_range: Option<brokk_bifrost_core::analyzer::Range>,
1672    pub exhaustive_family: Option<(usize, usize)>,
1673    pub displaced_namespace_closing_brace: Option<usize>,
1674}
1675
1676impl CppFileSourceFacts {
1677    pub fn declaration_occurrences(&self, unit: &CodeUnit) -> Vec<CppDeclarationOccurrence> {
1678        self.for_unit(unit)
1679            .map(|fact| {
1680                let declaration = self.source.declaration(fact.declaration);
1681                CppDeclarationOccurrence {
1682                    range: self.source.occurrence(declaration.occurrence).range,
1683                    name_range: declaration.name.map(|id| self.source.occurrence(id).range),
1684                    exhaustive_family: fact.exhaustive_conditional_family.map(|id| {
1685                        let range = self.source.occurrence(id).range;
1686                        (range.start_byte, range.end_byte)
1687                    }),
1688                    displaced_namespace_closing_brace: fact
1689                        .displaced_namespace_closing_brace
1690                        .map(|id| self.source.occurrence(id).range.start_byte),
1691                    fact: fact.clone(),
1692                }
1693            })
1694            .collect()
1695    }
1696
1697    pub fn navigation_occurrence(
1698        &self,
1699        fact: &CppDeclarationSourceFact,
1700    ) -> CppNavigationOccurrence {
1701        let declaration = self.source.declaration(fact.declaration);
1702        let range = self.source.occurrence(declaration.occurrence).range;
1703        let conditional_family = fact.conditional_family.map(|id| {
1704            let range = self.source.occurrence(id).range;
1705            (range.start_byte, range.end_byte)
1706        });
1707        CppNavigationOccurrence {
1708            range,
1709            role: fact.occurrence_role,
1710            conditional_family,
1711        }
1712    }
1713}
1714
1715#[cfg(test)]
1716mod tests {
1717    use super::*;
1718
1719    #[test]
1720    #[brokk_bifrost_test_macros::hardwon(
1721        "db00de0653f1: quicksilver round 4 on brokk-bifrost-cpp: range bindings, member const and numeric values used wrong syntax"
1722    )]
1723    fn source_fact_grammar_boundary() {
1724        let source = "void f() { for (char i : xs) { for (char item : xs) {} } }\nstruct C { void f(const int x); void g() const; };\nint n[] = {0X10, 0B10, 1uLL, 2Lu, 010};\n";
1725        let mut parser = Parser::new();
1726        parser
1727            .set_language(&tree_sitter_cpp::LANGUAGE.into())
1728            .unwrap();
1729        let tree = parser.parse(source, None).unwrap();
1730        assert!(!tree.root_node().has_error());
1731        // Hand-written half-open spans pin which grammar fields carry these facts.
1732        let mut stack = vec![tree.root_node()];
1733        let mut loops = Vec::new();
1734        let mut qualifiers = Vec::new();
1735        let mut literals = Vec::new();
1736        while let Some(node) = stack.pop() {
1737            match node.kind() {
1738                "for_range_loop" => {
1739                    assert!(node.child_by_field_name("left").is_none());
1740                    loops.push((
1741                        node.child_by_field_name("type").unwrap().byte_range(),
1742                        node.child_by_field_name("declarator").unwrap().byte_range(),
1743                    ));
1744                }
1745                "type_qualifier" => {
1746                    qualifiers.push((node.parent().unwrap().kind(), node.byte_range()))
1747                }
1748                "number_literal" => literals.push(node.byte_range()),
1749                _ => {}
1750            }
1751            let children: Vec<_> = node.named_children(&mut node.walk()).collect();
1752            stack.extend(children.into_iter().rev());
1753        }
1754        assert_eq!(loops, [(16..20, 21..22), (36..40, 41..45)]);
1755        assert_eq!(
1756            qualifiers,
1757            [
1758                ("parameter_declaration", 77..82),
1759                ("function_declarator", 100..105)
1760            ]
1761        );
1762        assert_eq!(literals, [121..125, 127..131, 133..137, 139..142, 144..147]);
1763        let rows = parse_cpp_expression_source_facts(source);
1764        let bindings: Vec<_> = rows
1765            .expressions
1766            .iter()
1767            .filter(|f| f.kind == CppExpressionKind::LoopVariable)
1768            .map(|f| {
1769                (
1770                    f.name.as_deref(),
1771                    f.type_text.as_deref(),
1772                    f.loop_has_short_ancestor,
1773                )
1774            })
1775            .collect();
1776        let methods: Vec<_> = rows
1777            .expressions
1778            .iter()
1779            .filter(|f| {
1780                f.kind == CppExpressionKind::FunctionSignature && f.member_function == Some(true)
1781            })
1782            .map(|f| (f.name.as_deref(), f.member_function_const))
1783            .collect();
1784        let values: Vec<_> = rows
1785            .expressions
1786            .iter()
1787            .filter(|f| f.kind == CppExpressionKind::IntegerLiteral)
1788            .map(|f| f.integer_value)
1789            .collect();
1790        assert_eq!(
1791            (bindings, methods, values),
1792            (
1793                vec![
1794                    (Some("i"), Some("char"), Some(false)),
1795                    (Some("item"), Some("char"), Some(true))
1796                ],
1797                vec![(Some("f"), Some(false)), (Some("g"), Some(true))],
1798                vec![Some(16), Some(2), Some(1), Some(2), Some(8)]
1799            )
1800        );
1801        // The C++20 init-statement is not the range binding. A traditional
1802        // declaration-initialized inner loop still sees the short range name.
1803        let rows = parse_cpp_expression_source_facts(
1804            "void f() { for (int setup = 0; char i : xs) { for (int j = 0; j < 3; ++j) {} } }",
1805        );
1806        let bindings: Vec<_> = rows
1807            .expressions
1808            .iter()
1809            .filter(|f| f.kind == CppExpressionKind::LoopVariable)
1810            .map(|f| {
1811                (
1812                    f.name.as_deref(),
1813                    f.type_text.as_deref(),
1814                    f.loop_has_short_ancestor,
1815                )
1816            })
1817            .collect();
1818        assert_eq!(
1819            bindings,
1820            [
1821                (Some("i"), Some("char"), Some(false)),
1822                (Some("j"), Some("int"), Some(true))
1823            ]
1824        );
1825    }
1826
1827    #[test]
1828    #[brokk_bifrost_test_macros::hardwon(
1829        "db00de0653f1: quicksilver round 4 on brokk-bifrost-cpp: base access leaked across commas"
1830    )]
1831    fn source_fact_base_access_defaults() {
1832        // [class.access.base]: omitted access is decided independently per base.
1833        let source = "struct A {}; struct B {}; struct S : private A, B {}; class C : public A, B {}; struct P : protected A {};";
1834        let mut parser = Parser::new();
1835        parser
1836            .set_language(&tree_sitter_cpp::LANGUAGE.into())
1837            .unwrap();
1838        let tree = parser.parse(source, None).unwrap();
1839        assert!(!tree.root_node().has_error());
1840        let mut stack = vec![tree.root_node()];
1841        let mut access = Vec::new();
1842        while let Some(node) = stack.pop() {
1843            if node.kind() == "base_class_clause" {
1844                for base in node
1845                    .named_children(&mut node.walk())
1846                    .filter(|n| n.kind() == "type_identifier")
1847                {
1848                    access.push(base_access_specifier(
1849                        node,
1850                        base,
1851                        node.parent().unwrap().kind(),
1852                    ));
1853                }
1854            }
1855            let children: Vec<_> = node.named_children(&mut node.walk()).collect();
1856            stack.extend(children.into_iter().rev());
1857        }
1858        assert_eq!(
1859            access,
1860            [
1861                CppAccessSpecifier::Private,
1862                CppAccessSpecifier::Public,
1863                CppAccessSpecifier::Public,
1864                CppAccessSpecifier::Private,
1865                CppAccessSpecifier::Protected
1866            ]
1867        );
1868    }
1869
1870    #[test]
1871    #[brokk_bifrost_test_macros::hardwon(
1872        "db00de0653f1: quicksilver round 4 on brokk-bifrost-cpp: parameter indirection reused pointee size"
1873    )]
1874    fn source_fact_parameter_sizes_respect_indirection() {
1875        let rows = parse_cpp_expression_source_facts(
1876            "void f(char a, signed char b, unsigned char c, char *p, char &r, char xs[3]);",
1877        );
1878        let sizes: Vec<_> = rows
1879            .expressions
1880            .iter()
1881            .filter(|f| {
1882                f.name.is_some()
1883                    && matches!(
1884                        f.kind,
1885                        CppExpressionKind::FunctionParameter | CppExpressionKind::ArrayParameter
1886                    )
1887            })
1888            .map(|f| (f.name.as_deref(), f.type_size_bytes, f.type_size_exact))
1889            .collect();
1890        assert_eq!(
1891            sizes,
1892            [
1893                (Some("a"), Some(1), Some(true)),
1894                (Some("b"), Some(1), Some(true)),
1895                (Some("c"), Some(1), Some(true)),
1896                (Some("p"), None, Some(false)),
1897                (Some("r"), None, Some(false)),
1898                (Some("xs"), None, Some(false))
1899            ]
1900        );
1901    }
1902
1903    #[test]
1904    #[brokk_bifrost_test_macros::hardwon(
1905        "db00de0653f1: quicksilver round 4 on brokk-bifrost-cpp: union sizes summed and later field declarators vanished"
1906    )]
1907    fn source_fact_record_sizes_follow_member_layout() {
1908        let rows = parse_cpp_expression_source_facts(
1909            "union U { char a[2]; char b[3]; }; struct S { char a, b; }; void f(U u, S s);",
1910        );
1911        let sizes: Vec<_> = rows
1912            .expressions
1913            .iter()
1914            .filter(|f| f.kind == CppExpressionKind::FunctionParameter)
1915            .map(|f| (f.name.as_deref(), f.type_size_bytes))
1916            .collect();
1917        // [class.union] requires room for the largest member; char has size one.
1918        assert_eq!(sizes, [(Some("u"), Some(3)), (Some("s"), Some(2))]);
1919    }
1920
1921    const REFERENCES: &str = "struct C {\n C(C& a); C(const C& a); C(C&& a); C(const C&& a);\n C(C&& a, int n = 0); C(C* a);\n C& operator=(const C& a); C& operator=(C&& a);\n operator C&(); operator C&&();\n};\nC& l = c; C&& r = f();\nvoid f() { try {} catch(C& e) {} try {} catch(const C& e) {} try {} catch(C&& e) {} }\nstruct V {\n V(V& a);\n V& operator=(V& a);\n V(const V& a);\n V& operator=(const V& a);\n V(volatile V& a);\n V& operator=(volatile V& a);\n V(const volatile V& a);\n V& operator=(const volatile V& a);\n V(V& a, int n = 0);\n V(volatile V& a, int n = 0);\n};\n";
1922
1923    #[test]
1924    #[brokk_bifrost_test_macros::hardwon(
1925        "d4f00f8567e4: quicksilver round 4 on brokk-bifrost-cpp: unnamed && tokens hid rvalue references"
1926    )]
1927    #[brokk_bifrost_test_macros::hardwon(
1928        "d4f00f8567e4: quicksilver round 4 on brokk-bifrost-cpp: a mutable C& copy constructor was not classified as copy"
1929    )]
1930    fn cpp_reference_token_grammar() {
1931        let mut parser = Parser::new();
1932        parser
1933            .set_language(&tree_sitter_cpp::LANGUAGE.into())
1934            .unwrap();
1935        let tree = parser.parse(REFERENCES, None).unwrap();
1936        assert!(!tree.root_node().has_error());
1937        // Half-open byte spans from the pinned grammar boundary table. The
1938        // reference wrapper has no fields; the parameter owns `declarator`.
1939        let expected = "reference_declarator 15..18 & 15..16 identifier 17..18
1940reference_declarator 30..33 & 30..31 identifier 32..33
1941reference_declarator 39..43 && 39..41 identifier 42..43
1942reference_declarator 55..59 && 55..57 identifier 58..59
1943reference_declarator 66..70 && 66..68 identifier 69..70
1944reference_declarator 95..118 & 95..96 function_declarator 97..118
1945reference_declarator 114..117 & 114..115 identifier 116..117
1946reference_declarator 121..139 & 121..122 function_declarator 123..139
1947reference_declarator 134..138 && 134..136 identifier 137..138
1948abstract_reference_declarator 152..155 & 152..153 abstract_function_declarator 153..155
1949abstract_reference_declarator 167..171 && 167..169 abstract_function_declarator 169..171
1950reference_declarator 177..180 & 177..178 identifier 179..180
1951reference_declarator 187..191 && 187..189 identifier 190..191
1952reference_declarator 224..227 & 224..225 identifier 226..227
1953reference_declarator 252..255 & 252..253 identifier 254..255
1954reference_declarator 274..278 && 274..276 identifier 277..278
1955reference_declarator 300..303 & 300..301 identifier 302..303
1956reference_declarator 308..325 & 308..309 function_declarator 310..325
1957reference_declarator 321..324 & 321..322 identifier 323..324
1958reference_declarator 337..340 & 337..338 identifier 339..340
1959reference_declarator 345..368 & 345..346 function_declarator 347..368
1960reference_declarator 364..367 & 364..365 identifier 366..367
1961reference_declarator 383..386 & 383..384 identifier 385..386
1962reference_declarator 391..417 & 391..392 function_declarator 393..417
1963reference_declarator 413..416 & 413..414 identifier 415..416
1964reference_declarator 438..441 & 438..439 identifier 440..441
1965reference_declarator 446..478 & 446..447 function_declarator 448..478
1966reference_declarator 474..477 & 474..475 identifier 476..477
1967reference_declarator 484..487 & 484..485 identifier 486..487
1968reference_declarator 514..517 & 514..515 identifier 516..517";
1969        let mut stack = vec![tree.root_node()];
1970        let mut actual = Vec::new();
1971        let mut references = Vec::new();
1972        let mut qualifiers = Vec::new();
1973        while let Some(node) = stack.pop() {
1974            if node.kind() == "type_qualifier" && node.start_byte() >= 285 {
1975                assert_eq!(node.parent().unwrap().kind(), "parameter_declaration");
1976                qualifiers.push((
1977                    node.utf8_text(REFERENCES.as_bytes()).unwrap(),
1978                    node.byte_range(),
1979                ));
1980            }
1981            if matches!(
1982                node.kind(),
1983                "reference_declarator" | "abstract_reference_declarator"
1984            ) {
1985                let token = node.child(0).unwrap();
1986                let wrapped = node.named_child(0).unwrap();
1987                assert!(!token.is_named());
1988                assert!(node.child_by_field_name("declarator").is_none());
1989                assert_eq!(node.field_name_for_child(0), None);
1990                assert_eq!(node.field_name_for_child(1), None);
1991                if node.parent().unwrap().kind() == "parameter_declaration" {
1992                    assert_eq!(
1993                        node.parent().unwrap().child_by_field_name("declarator"),
1994                        Some(node)
1995                    );
1996                }
1997                actual.push(format!(
1998                    "{} {:?} {} {:?} {} {:?}",
1999                    node.kind(),
2000                    node.byte_range(),
2001                    token.kind(),
2002                    token.byte_range(),
2003                    wrapped.kind(),
2004                    wrapped.byte_range()
2005                ));
2006                references.push(node);
2007            }
2008            let children: Vec<_> = node.named_children(&mut node.walk()).collect();
2009            stack.extend(children.into_iter().rev());
2010        }
2011        assert_eq!(actual.join("\n"), expected);
2012        assert_eq!(
2013            qualifiers,
2014            [
2015                ("const", 330..335),
2016                ("const", 357..362),
2017                ("volatile", 373..381),
2018                ("volatile", 403..411),
2019                ("const", 422..427),
2020                ("volatile", 428..436),
2021                ("const", 458..463),
2022                ("volatile", 464..472),
2023                ("volatile", 504..512),
2024            ]
2025        );
2026        for node in references {
2027            let token = node.child(0).unwrap();
2028            let wrapped = node.named_child(0).unwrap();
2029            // A return wrapper also contains the function's parameters. The
2030            // producer calls this helper on parameter declarators only.
2031            if wrapped.kind() == "function_declarator" {
2032                continue;
2033            }
2034            assert_eq!(
2035                declarator_contains_rvalue_reference(node),
2036                token.kind() == "&&",
2037                "reference at {:?}",
2038                node.byte_range()
2039            );
2040        }
2041        let rows = parse_cpp_class_fact_rows(REFERENCES);
2042        use CppSpecialMemberKind::{
2043            CopyAssignment, CopyConstructor, MoveAssignment, MoveConstructor, None as NotSpecial,
2044        };
2045        // Pin the defect's public class/catch consequences as well as its
2046        // grammar boundary, including all cv-qualified lvalue references.
2047        let members: Vec<_> = rows
2048            .members
2049            .iter()
2050            .take(8)
2051            .map(|member| member.special_member)
2052            .collect();
2053        assert_eq!(
2054            members,
2055            [
2056                CopyConstructor,
2057                CopyConstructor,
2058                MoveConstructor,
2059                MoveConstructor,
2060                MoveConstructor,
2061                NotSpecial,
2062                CopyAssignment,
2063                MoveAssignment
2064            ]
2065        );
2066        assert!(rows.members[4].remaining_parameters_defaulted);
2067        let cv_members: Vec<_> = rows
2068            .members
2069            .iter()
2070            .filter(|member| member.owner == ["V"])
2071            .collect();
2072        assert_eq!(
2073            cv_members
2074                .iter()
2075                .map(|member| member.special_member)
2076                .collect::<Vec<_>>(),
2077            [
2078                CopyConstructor,
2079                CopyAssignment,
2080                CopyConstructor,
2081                CopyAssignment,
2082                CopyConstructor,
2083                CopyAssignment,
2084                CopyConstructor,
2085                CopyAssignment,
2086                CopyConstructor,
2087                CopyConstructor
2088            ]
2089        );
2090        assert!(cv_members.iter().all(|member| member.copy_parameter));
2091        assert!(
2092            cv_members[8..]
2093                .iter()
2094                .all(|member| member.remaining_parameters_defaulted)
2095        );
2096        assert_eq!(
2097            rows.catches
2098                .iter()
2099                .map(|catch| catch.value_category)
2100                .collect::<Vec<_>>(),
2101            [
2102                CppParameterValueCategory::LValueReference,
2103                CppParameterValueCategory::LValueReference,
2104                CppParameterValueCategory::RValueReference
2105            ]
2106        );
2107    }
2108
2109    #[test]
2110    fn specialized_declaration_name_grammar_boundary() {
2111        for (source, field_kind, expected, offset) in [
2112            ("struct Plain {};", "type_identifier", "Plain", 7),
2113            ("template<> struct Box<int> {};", "template_type", "Box", 18),
2114            (
2115                "struct ns::Qualified {};",
2116                "qualified_identifier",
2117                "Qualified",
2118                11,
2119            ),
2120        ] {
2121            let tree = crate::diagnostics::parse_cpp_tree(source);
2122            assert!(!tree.root_node().has_error());
2123            let mut stack = vec![tree.root_node()];
2124            let mut names = Vec::new();
2125            while let Some(node) = stack.pop() {
2126                if node.kind() == "struct_specifier" {
2127                    let field = node.child_by_field_name("name").unwrap();
2128                    assert_eq!(field.kind(), field_kind);
2129                    let unit = CodeUnit::new(
2130                        brokk_bifrost_core::analyzer::ProjectFile::new(
2131                            std::env::temp_dir(),
2132                            "names.cpp",
2133                        ),
2134                        brokk_bifrost_core::analyzer::model::CodeUnitType::Class,
2135                        "",
2136                        expected,
2137                    );
2138                    let name = declaration_name(node, &unit, source).unwrap();
2139                    names.push((node_text(name, source), name.byte_range()));
2140                }
2141                stack.extend(node.named_children(&mut node.walk()));
2142            }
2143            assert_eq!(names, [(expected, offset..offset + expected.len())]);
2144        }
2145    }
2146}