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) -> CppStatementFactRows {
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    let mut rows = CppStatementFactRows::default();
743    let mut stack = vec![tree.root_node()];
744    while let Some(node) = stack.pop() {
745        if node.is_named() {
746            crate::structural::capture_statement_fact_rows(node, source, &mut rows);
747        }
748        let mut cursor = node.walk();
749        let children: Vec<_> = node.named_children(&mut cursor).collect();
750        stack.extend(children.into_iter().rev());
751    }
752    rows
753}
754
755/// Parse one source snapshot into the class and exception projection used by
756/// RQL. The rows are query-lifetime and own no cross-file state.
757pub fn parse_cpp_class_fact_rows(source: &str) -> CppClassFactRows {
758    let mut parser = Parser::new();
759    parser
760        .set_language(&tree_sitter_cpp::LANGUAGE.into())
761        .expect("the linked tree-sitter-cpp grammar matches this tree-sitter version");
762    let tree = parser.parse(source, None).expect("uncancelled C++ parse");
763    let root = tree.root_node();
764    let ancestry = ParentIndex::new(root);
765    let mut rows = CppClassFactRows::default();
766    let mut stack = vec![root];
767    while let Some(node) = stack.pop() {
768        if node.is_named() {
769            capture_class_fact_rows(node, source, &ancestry, &mut rows);
770        }
771        let mut cursor = node.walk();
772        let children: Vec<_> = node.named_children(&mut cursor).collect();
773        stack.extend(children.into_iter().rev());
774    }
775    rows
776}
777
778pub(crate) fn base_specifier_from_node(
779    node: Node<'_>,
780    source: &str,
781    is_virtual: bool,
782    access: CppAccessSpecifier,
783) -> Option<CppBaseSpecifierFact> {
784    let components = cpp_type_name_components(node, source)?;
785    base_specifier_fact(node, components, is_virtual, access)
786}
787
788pub(crate) fn base_specifier_fact(
789    node: Node<'_>,
790    components: Vec<String>,
791    is_virtual: bool,
792    access: CppAccessSpecifier,
793) -> Option<CppBaseSpecifierFact> {
794    (!components.is_empty()).then_some(CppBaseSpecifierFact {
795        absolute: node.child(0).is_some_and(|token| token.kind() == "::"),
796        components,
797        is_virtual,
798        access,
799    })
800}
801
802pub(crate) fn declaration_name<'tree>(
803    node: Node<'tree>,
804    unit: &CodeUnit,
805    source: &str,
806) -> Option<Node<'tree>> {
807    if let Some(name) = node.child_by_field_name("name") {
808        return crate::structural::declarator_name_node(name);
809    }
810    let mut cursor = node.walk();
811    node.children_by_field_name("declarator", &mut cursor)
812        .find_map(|declarator| {
813            let name = crate::structural::declarator_name_node(declarator)?;
814            (node_text(name, source) == unit.identifier()).then_some(name)
815        })
816}
817
818/// Capture the structured type properties of one field declaration while its
819/// declaration AST is still available.
820pub(crate) fn capture_field_type(
821    node: Node<'_>,
822    field_name: &str,
823    source: &str,
824) -> (Option<CppDeclaredFieldTypeFact>, bool) {
825    if let Some(recovered) = crate::declarations::recovered_pyobject_head_field(node, source)
826        && node_text(recovered.name, source) == field_name
827    {
828        return (
829            Some(CppDeclaredFieldTypeFact {
830                type_text: node_text(recovered.type_node, source).to_owned(),
831                indirection: recovered.pointer_depth(),
832                binds_indirectly: recovered.pointer_depth() > 0,
833                template_arguments: None,
834            }),
835            false,
836        );
837    }
838    let Some(type_node) = node.child_by_field_name("type") else {
839        return (None, false);
840    };
841    let mut cursor = node.walk();
842    let declarator = node
843        .children_by_field_name("declarator", &mut cursor)
844        .find(|declarator| {
845            crate::structural::declarator_name_node(*declarator)
846                .is_some_and(|name| node_text(name, source) == field_name)
847        });
848    let names_function_type = declarator.is_some_and(declarator_names_function_type);
849    let field_type = cpp_declared_field_type_fact(node, type_node, field_name, source);
850    (field_type, names_function_type)
851}
852
853/// Capture one `namespace name = target;` definition while the primary tree is
854/// live. The target path, the enclosing namespaces and the guard environment
855/// come from the same structured helpers that using declarations use.
856pub(crate) fn capture_namespace_alias(
857    node: Node<'_>,
858    source: &str,
859    ancestry: &ParentIndex<'_>,
860    namespaces: &crate::graph::resolver::OrphanedNamespaceScopeIndex,
861    collector: &mut PrimarySourceFactCollector<'_>,
862) -> Option<CppNamespaceAliasFact> {
863    if node.kind() != "namespace_alias_definition" {
864        return None;
865    }
866    let name = node.child_by_field_name("name")?;
867    let mut cursor = node.walk();
868    let target = node.named_children(&mut cursor).find(|child| {
869        matches!(
870            child.kind(),
871            "namespace_identifier" | "nested_namespace_specifier" | "splice_specifier"
872        ) && child.id() != name.id()
873    })?;
874    let block = std::iter::successors(ancestry.parent(node), |current| ancestry.parent(*current))
875        .take_while(|current| {
876            !matches!(current.kind(), "namespace_definition" | "translation_unit")
877        })
878        .find(|current| current.kind() == "compound_statement");
879    Some(CppNamespaceAliasFact {
880        occurrence: collector.intern_node(node),
881        name: node_text(name, source).to_owned(),
882        target: crate::graph::resolver::cpp_name_component_nodes(target)
883            .filter(|components| !components.is_empty())
884            .map(|components| {
885                components
886                    .into_iter()
887                    .map(|component| node_text(component, source).to_owned())
888                    .collect()
889            }),
890        target_global: target.child(0).is_some_and(|child| child.kind() == "::"),
891        namespace: namespaces.enclosing_namespace_components(node, source),
892        block: block.map(|block| collector.intern_node(block)),
893        guards: crate::graph::resolver::binding_site_guards(node, source)
894            .as_ref()
895            .map(crate::source_context::cpp_guard_set_from_runtime),
896    })
897}
898
899pub(crate) fn capture_declaration(
900    declaration: SourceDeclarationId,
901    node: Node<'_>,
902    unit: &CodeUnit,
903    source: &str,
904    ancestry: &ParentIndex<'_>,
905) -> CppDeclarationSourceFact {
906    let mut fact = CppDeclarationSourceFact::new(declaration);
907    if matches!(node.kind(), "alias_declaration" | "type_definition")
908        && crate::graph::resolver::alias_has_visible_file_scope(node)
909        && let Some(name) = declaration_name(node, unit, source)
910        && let Some(name) =
911            crate::graph::resolver::normalize_reference_name(node_text(name, source))
912        && let Some(target) = node.child_by_field_name("type")
913        && let Some(target) =
914            crate::graph::resolver::normalize_reference_name(node_text(target, source))
915    {
916        fact.file_scope_alias = Some(CppFileScopeAliasFact {
917            name,
918            target,
919            namespace: crate::graph::resolver::enclosing_namespace_context(node, source),
920        });
921    }
922    let mut owners = Vec::new();
923    let mut current = ancestry.parent(node);
924    while let Some(parent) = current {
925        if matches!(
926            parent.kind(),
927            "namespace_definition"
928                | "class_specifier"
929                | "struct_specifier"
930                | "union_specifier"
931                | "enum_specifier"
932        ) && let Some(name) = parent.child_by_field_name("name")
933        {
934            owners.push(node_text(name, source).to_owned());
935        }
936        current = ancestry.parent(parent);
937    }
938    owners.reverse();
939    owners.push(unit.identifier().to_owned());
940    fact.lexical_path = owners;
941    if matches!(
942        node.kind(),
943        "class_specifier" | "struct_specifier" | "union_specifier" | "enum_specifier"
944    ) {
945        fact.class_strength = if node.child_by_field_name("body").is_some() {
946            CppClassDeclarationStrength::Full
947        } else {
948            CppClassDeclarationStrength::Forward
949        };
950        if node.kind() == "enum_specifier" {
951            let mut cursor = node.walk();
952            fact.enum_kind = if node
953                .children(&mut cursor)
954                .any(|child| matches!(child.kind(), "class" | "struct"))
955            {
956                CppEnumOwnerKind::Scoped
957            } else {
958                CppEnumOwnerKind::Unscoped
959            };
960        }
961        let mut cursor = node.walk();
962        for base_clause in node
963            .named_children(&mut cursor)
964            .filter(|child| child.kind() == "base_class_clause")
965        {
966            let mut is_virtual = false;
967            let mut cursor = base_clause.walk();
968            for child in base_clause.children(&mut cursor) {
969                match child.kind() {
970                    "," => is_virtual = false,
971                    "virtual" => is_virtual = true,
972                    "type_identifier"
973                    | "qualified_identifier"
974                    | "scoped_type_identifier"
975                    | "template_type" => {
976                        if let Some(base) = base_specifier_from_node(
977                            child,
978                            source,
979                            is_virtual,
980                            base_access_specifier(base_clause, child, node.kind()),
981                        ) {
982                            fact.bases.push(base);
983                        }
984                        is_virtual = false;
985                    }
986                    _ => {}
987                }
988            }
989        }
990    }
991    let mut cursor = node.walk();
992    let declarator = node
993        .children_by_field_name("declarator", &mut cursor)
994        .find(|declarator| {
995            crate::structural::declarator_name_node(*declarator)
996                .is_some_and(|name| node_text(name, source) == unit.identifier())
997        });
998    if unit.is_function() {
999        let callable = if node.kind() == "function_declarator" {
1000            Some(node)
1001        } else {
1002            node.child_by_field_name("declarator")
1003        };
1004        if let Some(declarator) = callable {
1005            if let Some(name) = declarator_name_node(declarator)
1006                && let Some(mut components) = cpp_type_name_components(name, source)
1007            {
1008                components.pop();
1009                fact.written_owner = components;
1010            }
1011            let mut chain = Some(declarator);
1012            while let Some(current) = chain {
1013                if current.kind() == "function_declarator" {
1014                    fact.callable_comparable_shapes =
1015                        Some(cpp_comparable_parameter_shapes(current, source, ancestry));
1016                    fact.callable_identity_suffix = cpp_callable_identity_suffix(current, source);
1017                    fact.callable_is_constructor =
1018                        cpp_callable_is_structural_constructor(current, source, ancestry);
1019                    fact.callable_is_deduction_guide =
1020                        cpp_callable_is_deduction_guide(node, current, unit, source);
1021                    fact.callable_is_template = ancestry.parent(node).is_some_and(|parent| {
1022                        parent.kind() == "template_declaration"
1023                            && parent
1024                                .named_child(parent.named_child_count().saturating_sub(1))
1025                                .is_some_and(|declaration| declaration.id() == node.id())
1026                    });
1027                    // Only identity qualifiers participate in overload hiding.
1028                    // The declarator can also contain override/final specifiers.
1029                    fact.trailing_qualifiers =
1030                        fact.callable_identity_suffix.clone().unwrap_or_default();
1031                    break;
1032                }
1033                chain = current.child_by_field_name("declarator");
1034            }
1035        }
1036    }
1037    if unit.is_field() {
1038        let (field_type, names_function_type) = capture_field_type(node, unit.identifier(), source);
1039        fact.field_type = field_type;
1040        fact.names_function_type = names_function_type;
1041    }
1042    let alias_type = if matches!(node.kind(), "alias_declaration" | "type_definition") {
1043        node.child_by_field_name("type")
1044    } else if unit.is_class() {
1045        crate::declarations::recovered_alias_type_node(node, unit.identifier(), source)
1046    } else {
1047        None
1048    };
1049    if let Some(alias_type) = alias_type {
1050        let alias_declarator = if node.kind() == "type_definition" {
1051            declarator
1052        } else {
1053            alias_type.child_by_field_name("declarator")
1054        };
1055        fact.names_function_type = alias_declarator.is_some_and(declarator_names_function_type);
1056        fact.adds_indirection = alias_declarator.is_some_and(cpp_declarator_adds_indirection);
1057        if !fact.names_function_type {
1058            fact.alias_target = structured_alias_type_target(alias_type, source);
1059            let mut target = alias_type;
1060            while target.kind() == "type_descriptor" {
1061                let Some(inner) = target.child_by_field_name("type") else {
1062                    break;
1063                };
1064                target = inner;
1065            }
1066            if matches!(
1067                target.kind(),
1068                "class_specifier" | "struct_specifier" | "union_specifier" | "enum_specifier"
1069            ) && let Some(name) = target.child_by_field_name("name")
1070            {
1071                target = name;
1072            }
1073            fact.alias_target_text = Some(node_text(target, source).to_owned());
1074        }
1075    }
1076    fact
1077}
1078
1079/// Add the class and exception rows whose meaning lives below a declaration
1080/// node. This is called by the primary iterative walk, while the tree and its
1081/// parent index are still owned by the producer.
1082pub(crate) fn capture_class_fact_rows(
1083    node: Node<'_>,
1084    source: &str,
1085    ancestry: &ParentIndex<'_>,
1086    rows: &mut CppClassFactRows,
1087) {
1088    match node.kind() {
1089        "class_specifier" | "struct_specifier" | "union_specifier" => {
1090            let mut path = enclosing_owner_path(node, ancestry, source);
1091            if let Some(name) = node.child_by_field_name("name") {
1092                path.push(node_text(name, source).to_owned());
1093            }
1094            let is_interface = node
1095                .child_by_field_name("body")
1096                .is_some_and(|body| tree_contains_pure_virtual(body, source));
1097            rows.classes.push(CppClassFact {
1098                range: node_range(node),
1099                path,
1100                is_interface,
1101            });
1102        }
1103        "function_definition" | "declaration" | "field_declaration" => {
1104            if let Some(member) = capture_member_fact(node, source, ancestry) {
1105                rows.members.push(member);
1106            }
1107        }
1108        "catch_clause" => {
1109            rows.catches.push(capture_catch_fact(node, source));
1110        }
1111        "throw_statement" => {
1112            rows.throws.push(capture_throw_fact(node, source));
1113        }
1114        _ => {}
1115    }
1116}
1117
1118fn capture_member_fact(
1119    node: Node<'_>,
1120    source: &str,
1121    ancestry: &ParentIndex<'_>,
1122) -> Option<CppMemberFact> {
1123    let function_declarator = extract_function_declarator(node)?;
1124    let name_node = declarator_name_node(function_declarator)?;
1125    let name = node_text(name_node, source).to_owned();
1126    let mut owner = enclosing_owner_path(node, ancestry, source);
1127    let written_owner = cpp_type_name_components(name_node, source)
1128        .map(|mut components| {
1129            components.pop();
1130            components
1131        })
1132        .unwrap_or_default();
1133    append_owner_components(&mut owner, &written_owner);
1134    let owner_name = owner.last().map(String::as_str);
1135    let role = if name == "operator=" {
1136        CppMemberRole::AssignmentOperator
1137    } else if name.strip_prefix('~').is_some() {
1138        CppMemberRole::Destructor
1139    } else if owner_name == Some(name.as_str()) {
1140        CppMemberRole::Constructor
1141    } else {
1142        CppMemberRole::Method
1143    };
1144    let (copy_parameter, move_parameter, remaining_parameters_defaulted) =
1145        callable_parameter_shape(function_declarator, source, ancestry, owner_name);
1146    let special_member = match role {
1147        CppMemberRole::Destructor => CppSpecialMemberKind::Destructor,
1148        CppMemberRole::Constructor if copy_parameter => CppSpecialMemberKind::CopyConstructor,
1149        CppMemberRole::Constructor if move_parameter => CppSpecialMemberKind::MoveConstructor,
1150        CppMemberRole::Constructor if function_parameter_count(function_declarator) == 0 => {
1151            CppSpecialMemberKind::DefaultConstructor
1152        }
1153        CppMemberRole::AssignmentOperator if copy_parameter => CppSpecialMemberKind::CopyAssignment,
1154        CppMemberRole::AssignmentOperator if move_parameter => CppSpecialMemberKind::MoveAssignment,
1155        _ => CppSpecialMemberKind::None,
1156    };
1157    let state = if tree_contains_kind(node, "delete_method_clause") {
1158        CppSpecialMemberState::Deleted
1159    } else if tree_contains_kind(node, "default_method_clause") {
1160        CppSpecialMemberState::Defaulted
1161    } else {
1162        CppSpecialMemberState::Declared
1163    };
1164    let access = member_access_specifier(node, source, ancestry);
1165    let assignment_return = if role == CppMemberRole::AssignmentOperator {
1166        assignment_return_shape(node, source, owner_name)
1167    } else {
1168        CppAssignmentReturnShape::Unknown
1169    };
1170    let initializer_target = if role == CppMemberRole::Constructor {
1171        constructor_initializer_target(node, source, owner_name)
1172    } else {
1173        None
1174    };
1175    let delegation_calls = if role == CppMemberRole::Constructor {
1176        constructor_delegation_calls(node, source, ancestry, owner_name)
1177    } else {
1178        Vec::new()
1179    };
1180    Some(CppMemberFact {
1181        range: node_range(node),
1182        owner,
1183        name,
1184        role,
1185        special_member,
1186        state,
1187        access,
1188        copy_parameter,
1189        remaining_parameters_defaulted,
1190        assignment_return,
1191        initializer_target,
1192        delegation_calls,
1193        pure_virtual: tree_contains_pure_virtual(node, source),
1194    })
1195}
1196
1197fn capture_catch_fact(node: Node<'_>, source: &str) -> CppCatchFact {
1198    let parameter = node
1199        .child_by_field_name("parameters")
1200        .and_then(|parameters| parameters.named_child(0));
1201    let type_node = parameter.and_then(|parameter| parameter.child_by_field_name("type"));
1202    let declarator = parameter.and_then(|parameter| parameter.child_by_field_name("declarator"));
1203    let value_category = declarator
1204        .map(classify_parameter_declarator)
1205        .unwrap_or(CppParameterValueCategory::Value);
1206    let type_name = type_node
1207        .and_then(|type_node| cpp_type_name_components(type_node, source))
1208        .unwrap_or_default();
1209    let class_type = type_node.is_some_and(|type_node| {
1210        !matches!(
1211            type_node.kind(),
1212            "primitive_type" | "sized_type_specifier" | "auto" | "decltype"
1213        )
1214    });
1215    CppCatchFact {
1216        range: node_range(node),
1217        value_category,
1218        type_name,
1219        class_type,
1220    }
1221}
1222
1223fn capture_throw_fact(node: Node<'_>, source: &str) -> CppThrowFact {
1224    let expression = node.named_child(0);
1225    let (operand_shape, thrown_type) = match expression {
1226        None => (CppThrowOperandShape::Rethrow, Vec::new()),
1227        Some(expression) if expression.kind() == "new_expression" => (
1228            CppThrowOperandShape::Pointer,
1229            expression
1230                .child_by_field_name("type")
1231                .and_then(|type_node| cpp_type_name_components(type_node, source))
1232                .unwrap_or_default(),
1233        ),
1234        Some(_) => (CppThrowOperandShape::Value, Vec::new()),
1235    };
1236    CppThrowFact {
1237        range: node_range(node),
1238        operand_shape,
1239        thrown_type,
1240    }
1241}
1242
1243fn function_parameter_count(function: Node<'_>) -> usize {
1244    function
1245        .child_by_field_name("parameters")
1246        .map_or(0, |parameters| parameters.named_child_count())
1247}
1248
1249fn callable_parameter_shape(
1250    function: Node<'_>,
1251    source: &str,
1252    ancestry: &ParentIndex<'_>,
1253    owner_name: Option<&str>,
1254) -> (bool, bool, bool) {
1255    let Some(parameters) = function.child_by_field_name("parameters") else {
1256        return (false, false, true);
1257    };
1258    let parameter_nodes: Vec<_> = parameters.named_children(&mut parameters.walk()).collect();
1259    let remaining_parameters_defaulted = parameter_nodes.len() > 1
1260        && parameter_nodes
1261            .iter()
1262            .skip(1)
1263            .all(|parameter| parameter.child_by_field_name("default_value").is_some());
1264    let Some(first) = parameter_nodes.first().copied() else {
1265        return (false, false, remaining_parameters_defaulted);
1266    };
1267    let Some(_type_node) = first.child_by_field_name("type") else {
1268        return (false, false, remaining_parameters_defaulted);
1269    };
1270    let Some(owner_name) = owner_name else {
1271        return (false, false, remaining_parameters_defaulted);
1272    };
1273    let comparable = cpp_comparable_parameter_shapes(function, source, ancestry);
1274    let Some(CppComparableSlot::Shape(parameter)) = comparable.first() else {
1275        return (false, false, remaining_parameters_defaulted);
1276    };
1277    let reference = match parameter.node(parameter.root()) {
1278        CppComparableNode::Reference { inner } => Some(*inner),
1279        _ => None,
1280    };
1281    let Some(inner) = reference else {
1282        return (false, false, remaining_parameters_defaulted);
1283    };
1284    let CppComparableNode::Named { name, .. } = parameter.node(inner) else {
1285        return (false, false, remaining_parameters_defaulted);
1286    };
1287    let same_owner = name.path().last().is_some_and(|name| name == owner_name);
1288    if !same_owner {
1289        return (false, false, remaining_parameters_defaulted);
1290    }
1291    let rvalue = first
1292        .child_by_field_name("declarator")
1293        .is_some_and(|declarator| declarator_contains_rvalue_reference(declarator));
1294    let copy = !rvalue;
1295    let move_parameter = rvalue;
1296    (copy, move_parameter, remaining_parameters_defaulted)
1297}
1298
1299fn declarator_contains_rvalue_reference(node: Node<'_>) -> bool {
1300    let mut stack = vec![node];
1301    while let Some(current) = stack.pop() {
1302        if crate::declarations::reference_declarator_is_rvalue(current) {
1303            return true;
1304        }
1305        let mut cursor = current.walk();
1306        stack.extend(current.named_children(&mut cursor));
1307    }
1308    false
1309}
1310
1311fn classify_parameter_declarator(node: Node<'_>) -> CppParameterValueCategory {
1312    if declarator_contains_rvalue_reference(node) {
1313        CppParameterValueCategory::RValueReference
1314    } else {
1315        let mut stack = vec![node];
1316        while let Some(current) = stack.pop() {
1317            if current.kind() == "reference_declarator" {
1318                return CppParameterValueCategory::LValueReference;
1319            }
1320            if current.kind() == "pointer_declarator" {
1321                return CppParameterValueCategory::Pointer;
1322            }
1323            let mut cursor = current.walk();
1324            stack.extend(current.named_children(&mut cursor));
1325        }
1326        CppParameterValueCategory::Value
1327    }
1328}
1329
1330fn assignment_return_shape(
1331    node: Node<'_>,
1332    source: &str,
1333    owner_name: Option<&str>,
1334) -> CppAssignmentReturnShape {
1335    let mut current = node.child_by_field_name("declarator");
1336    let mut reference = false;
1337    let mut pointer = false;
1338    while let Some(declarator) = current {
1339        reference |= declarator.kind() == "reference_declarator";
1340        pointer |= declarator.kind() == "pointer_declarator";
1341        current = declarator.child_by_field_name("declarator");
1342    }
1343    if !reference {
1344        return if pointer {
1345            CppAssignmentReturnShape::Unknown
1346        } else {
1347            CppAssignmentReturnShape::Value
1348        };
1349    }
1350    let return_type = node.child_by_field_name("type");
1351    if owner_name.is_some_and(|owner| {
1352        return_type
1353            .and_then(|type_node| cpp_type_name_components(type_node, source))
1354            .and_then(|components| components.last().cloned())
1355            .is_some_and(|name| name == owner)
1356    }) {
1357        CppAssignmentReturnShape::ReferenceToThis
1358    } else {
1359        CppAssignmentReturnShape::ReferenceOther
1360    }
1361}
1362
1363fn constructor_initializer_target(
1364    node: Node<'_>,
1365    source: &str,
1366    owner_name: Option<&str>,
1367) -> Option<Vec<String>> {
1368    let owner_name = owner_name?;
1369    let mut cursor = node.walk();
1370    let initializer_list = node
1371        .named_children(&mut cursor)
1372        .find(|child| child.kind() == "field_initializer_list")?;
1373    let mut cursor = initializer_list.walk();
1374    initializer_list
1375        .named_children(&mut cursor)
1376        .filter(|child| child.kind() == "field_initializer")
1377        .find_map(|initializer| {
1378            let name = initializer
1379                .child_by_field_name("name")
1380                .or_else(|| initializer.child_by_field_name("field"))
1381                .or_else(|| {
1382                    let mut cursor = initializer.walk();
1383                    initializer.named_children(&mut cursor).find(|child| {
1384                        matches!(
1385                            child.kind(),
1386                            "field_identifier"
1387                                | "type_identifier"
1388                                | "qualified_identifier"
1389                                | "scoped_type_identifier"
1390                        )
1391                    })
1392                })?;
1393            let components = cpp_type_name_components(name, source)?;
1394            components
1395                .last()
1396                .is_some_and(|component| component == owner_name)
1397                .then_some(components)
1398        })
1399}
1400
1401fn constructor_delegation_calls(
1402    node: Node<'_>,
1403    source: &str,
1404    ancestry: &ParentIndex<'_>,
1405    owner_name: Option<&str>,
1406) -> Vec<Range> {
1407    let Some(owner_name) = owner_name else {
1408        return Vec::new();
1409    };
1410    let Some(body) = node.child_by_field_name("body") else {
1411        return Vec::new();
1412    };
1413    let mut stack = vec![body];
1414    let mut calls = Vec::new();
1415    while let Some(current) = stack.pop() {
1416        if current.kind() == "call_expression"
1417            && ancestry
1418                .parent(current)
1419                .is_some_and(|parent| parent.kind() == "expression_statement")
1420            && let Some(function) = current.child_by_field_name("function")
1421            && function.kind() == "identifier"
1422            && node_text(function, source) == owner_name
1423        {
1424            calls.push(node_range(current));
1425        }
1426        let mut cursor = current.walk();
1427        stack.extend(current.named_children(&mut cursor));
1428    }
1429    calls
1430}
1431
1432fn enclosing_owner_path(node: Node<'_>, ancestry: &ParentIndex<'_>, source: &str) -> Vec<String> {
1433    let mut owners = Vec::new();
1434    let mut current = ancestry.parent(node);
1435    while let Some(parent) = current {
1436        if matches!(
1437            parent.kind(),
1438            "namespace_definition"
1439                | "class_specifier"
1440                | "struct_specifier"
1441                | "union_specifier"
1442                | "enum_specifier"
1443        ) && let Some(name) = parent.child_by_field_name("name")
1444        {
1445            owners.push(node_text(name, source).to_owned());
1446        }
1447        current = ancestry.parent(parent);
1448    }
1449    owners.reverse();
1450    owners
1451}
1452
1453fn append_owner_components(owner: &mut Vec<String>, written: &[String]) {
1454    let overlap = (0..=owner.len().min(written.len()))
1455        .rev()
1456        .find(|length| owner[owner.len().saturating_sub(*length)..] == written[..*length])
1457        .unwrap_or(0);
1458    owner.extend(written[overlap..].iter().cloned());
1459}
1460
1461fn member_access_specifier(
1462    node: Node<'_>,
1463    source: &str,
1464    ancestry: &ParentIndex<'_>,
1465) -> CppAccessSpecifier {
1466    let mut current = ancestry.parent(node);
1467    while let Some(parent) = current {
1468        if matches!(
1469            parent.kind(),
1470            "class_specifier" | "struct_specifier" | "union_specifier"
1471        ) {
1472            let default = if parent.kind() == "class_specifier" {
1473                CppAccessSpecifier::Private
1474            } else {
1475                CppAccessSpecifier::Public
1476            };
1477            let Some(body) = parent.child_by_field_name("body") else {
1478                return CppAccessSpecifier::Unknown;
1479            };
1480            let mut access = default;
1481            let mut cursor = body.walk();
1482            for child in body.named_children(&mut cursor) {
1483                if child.start_byte() >= node.start_byte() {
1484                    break;
1485                }
1486                if child.kind() == "access_specifier" {
1487                    access = match child.child(0).map(|keyword| keyword.kind()) {
1488                        Some("public") => CppAccessSpecifier::Public,
1489                        Some("protected") => CppAccessSpecifier::Protected,
1490                        Some("private") => CppAccessSpecifier::Private,
1491                        _ => CppAccessSpecifier::Unknown,
1492                    };
1493                } else if let Some(label) = cpp_macro_swallowed_access_label(child, source) {
1494                    access = match label.access {
1495                        "public" => CppAccessSpecifier::Public,
1496                        "protected" => CppAccessSpecifier::Protected,
1497                        _ => CppAccessSpecifier::Private,
1498                    };
1499                }
1500            }
1501            return access;
1502        }
1503        current = ancestry.parent(parent);
1504    }
1505    CppAccessSpecifier::Unknown
1506}
1507
1508pub(crate) fn base_access_specifier(
1509    clause: Node<'_>,
1510    base: Node<'_>,
1511    class_kind: &str,
1512) -> CppAccessSpecifier {
1513    let default = if matches!(class_kind, "struct_specifier" | "union_specifier") {
1514        CppAccessSpecifier::Public
1515    } else {
1516        CppAccessSpecifier::Private
1517    };
1518    let mut access = default;
1519    let mut cursor = clause.walk();
1520    for child in clause.children(&mut cursor) {
1521        if child.start_byte() >= base.start_byte() {
1522            break;
1523        }
1524        if child.kind() == "," {
1525            access = default;
1526        } else if child.kind() == "access_specifier" {
1527            access = match child.child(0).map(|keyword| keyword.kind()) {
1528                Some("public") => CppAccessSpecifier::Public,
1529                Some("protected") => CppAccessSpecifier::Protected,
1530                Some("private") => CppAccessSpecifier::Private,
1531                _ => CppAccessSpecifier::Unknown,
1532            };
1533        }
1534    }
1535    access
1536}
1537
1538fn tree_contains_kind(node: Node<'_>, kind: &str) -> bool {
1539    let mut stack = vec![node];
1540    while let Some(current) = stack.pop() {
1541        if current.kind() == kind {
1542            return true;
1543        }
1544        let mut cursor = current.walk();
1545        stack.extend(current.named_children(&mut cursor));
1546    }
1547    false
1548}
1549
1550fn tree_contains_pure_virtual(node: Node<'_>, source: &str) -> bool {
1551    let mut stack = vec![node];
1552    while let Some(current) = stack.pop() {
1553        if current.kind() == "field_declaration"
1554            && current
1555                .child_by_field_name("default_value")
1556                .is_some_and(|value| {
1557                    value.kind() == "number_literal" && node_text(value, source).trim() == "0"
1558                })
1559            && current
1560                .child_by_field_name("declarator")
1561                .and_then(extract_function_declarator)
1562                .is_some()
1563        {
1564            return true;
1565        }
1566        let mut cursor = current.walk();
1567        stack.extend(current.named_children(&mut cursor));
1568    }
1569    tree_contains_kind(node, "pure_virtual_clause")
1570}
1571
1572fn cpp_callable_is_deduction_guide(
1573    declaration: Node<'_>,
1574    function_declarator: Node<'_>,
1575    unit: &CodeUnit,
1576    source: &str,
1577) -> bool {
1578    if declaration.kind() != "declaration"
1579        || declaration.child_by_field_name("type").is_some()
1580        || function_declarator.kind() != "function_declarator"
1581    {
1582        return false;
1583    }
1584    let mut cursor = function_declarator.walk();
1585    function_declarator
1586        .named_children(&mut cursor)
1587        .any(|child| child.kind() == "trailing_return_type")
1588        && declarator_name_node(function_declarator)
1589            .is_some_and(|name| node_text(name, source) == unit.identifier())
1590}
1591
1592/// One mounted, generation-selected canonical declaration family.
1593#[derive(Debug, Clone)]
1594pub struct CppFileSourceFacts {
1595    pub source: brokk_bifrost_core::analyzer::source_facts::SourceFactRows,
1596    pub facts: CppSourceFacts,
1597    pub declaration_units: brokk_bifrost_core::hash::HashMap<SourceDeclarationId, Vec<CodeUnit>>,
1598    by_unit: brokk_bifrost_core::hash::HashMap<CodeUnit, Vec<usize>>,
1599}
1600
1601impl CppFileSourceFacts {
1602    pub fn new(
1603        source: brokk_bifrost_core::analyzer::source_facts::SourceFactRows,
1604        facts: CppSourceFacts,
1605        declaration_units: brokk_bifrost_core::hash::HashMap<SourceDeclarationId, Vec<CodeUnit>>,
1606    ) -> Self {
1607        assert!(
1608            facts.valid_links(&source),
1609            "invalid C++ canonical source links"
1610        );
1611        let mut by_unit: brokk_bifrost_core::hash::HashMap<_, Vec<_>> = Default::default();
1612        for (index, fact) in facts.declarations.iter().enumerate() {
1613            if let Some(units) = declaration_units.get(&fact.declaration) {
1614                for unit in units {
1615                    by_unit.entry(unit.clone()).or_default().push(index);
1616                }
1617            }
1618        }
1619        Self {
1620            source,
1621            facts,
1622            declaration_units,
1623            by_unit,
1624        }
1625    }
1626
1627    pub fn for_unit(&self, unit: &CodeUnit) -> impl Iterator<Item = &CppDeclarationSourceFact> {
1628        self.by_unit
1629            .get(unit)
1630            .into_iter()
1631            .flatten()
1632            .map(|index| &self.facts.declarations[*index])
1633    }
1634
1635    pub fn estimated_retained_bytes(&self) -> usize {
1636        self.source.estimated_bytes()
1637            + self.facts.estimated_retained_bytes()
1638            + self
1639                .declaration_units
1640                .values()
1641                .map(|units| units.capacity() * std::mem::size_of::<CodeUnit>())
1642                .sum::<usize>()
1643            + self
1644                .by_unit
1645                .values()
1646                .map(|indices| indices.capacity() * std::mem::size_of::<usize>())
1647                .sum::<usize>()
1648    }
1649}
1650
1651/// One source-backed navigation alternative for a mounted declaration.
1652#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1653pub struct CppNavigationOccurrence {
1654    pub range: brokk_bifrost_core::analyzer::Range,
1655    pub role: CppOccurrenceRole,
1656    pub conditional_family: Option<(usize, usize)>,
1657}
1658
1659/// Canonical declaration context with IDs resolved in its own dialect arena.
1660#[derive(Debug, Clone, PartialEq, Eq)]
1661pub struct CppDeclarationOccurrence {
1662    pub fact: CppDeclarationSourceFact,
1663    pub range: brokk_bifrost_core::analyzer::Range,
1664    pub name_range: Option<brokk_bifrost_core::analyzer::Range>,
1665    pub exhaustive_family: Option<(usize, usize)>,
1666    pub displaced_namespace_closing_brace: Option<usize>,
1667}
1668
1669impl CppFileSourceFacts {
1670    pub fn declaration_occurrences(&self, unit: &CodeUnit) -> Vec<CppDeclarationOccurrence> {
1671        self.for_unit(unit)
1672            .map(|fact| {
1673                let declaration = self.source.declaration(fact.declaration);
1674                CppDeclarationOccurrence {
1675                    range: self.source.occurrence(declaration.occurrence).range,
1676                    name_range: declaration.name.map(|id| self.source.occurrence(id).range),
1677                    exhaustive_family: fact.exhaustive_conditional_family.map(|id| {
1678                        let range = self.source.occurrence(id).range;
1679                        (range.start_byte, range.end_byte)
1680                    }),
1681                    displaced_namespace_closing_brace: fact
1682                        .displaced_namespace_closing_brace
1683                        .map(|id| self.source.occurrence(id).range.start_byte),
1684                    fact: fact.clone(),
1685                }
1686            })
1687            .collect()
1688    }
1689
1690    pub fn navigation_occurrence(
1691        &self,
1692        fact: &CppDeclarationSourceFact,
1693    ) -> CppNavigationOccurrence {
1694        let declaration = self.source.declaration(fact.declaration);
1695        let range = self.source.occurrence(declaration.occurrence).range;
1696        let conditional_family = fact.conditional_family.map(|id| {
1697            let range = self.source.occurrence(id).range;
1698            (range.start_byte, range.end_byte)
1699        });
1700        CppNavigationOccurrence {
1701            range,
1702            role: fact.occurrence_role,
1703            conditional_family,
1704        }
1705    }
1706}
1707
1708#[cfg(test)]
1709mod tests {
1710    use super::*;
1711
1712    #[test]
1713    #[brokk_bifrost_test_macros::hardwon(
1714        "db00de0653f1: quicksilver round 4 on brokk-bifrost-cpp: range bindings, member const and numeric values used wrong syntax"
1715    )]
1716    fn source_fact_grammar_boundary() {
1717        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";
1718        let mut parser = Parser::new();
1719        parser
1720            .set_language(&tree_sitter_cpp::LANGUAGE.into())
1721            .unwrap();
1722        let tree = parser.parse(source, None).unwrap();
1723        assert!(!tree.root_node().has_error());
1724        // Hand-written half-open spans pin which grammar fields carry these facts.
1725        let mut stack = vec![tree.root_node()];
1726        let mut loops = Vec::new();
1727        let mut qualifiers = Vec::new();
1728        let mut literals = Vec::new();
1729        while let Some(node) = stack.pop() {
1730            match node.kind() {
1731                "for_range_loop" => {
1732                    assert!(node.child_by_field_name("left").is_none());
1733                    loops.push((
1734                        node.child_by_field_name("type").unwrap().byte_range(),
1735                        node.child_by_field_name("declarator").unwrap().byte_range(),
1736                    ));
1737                }
1738                "type_qualifier" => {
1739                    qualifiers.push((node.parent().unwrap().kind(), node.byte_range()))
1740                }
1741                "number_literal" => literals.push(node.byte_range()),
1742                _ => {}
1743            }
1744            let children: Vec<_> = node.named_children(&mut node.walk()).collect();
1745            stack.extend(children.into_iter().rev());
1746        }
1747        assert_eq!(loops, [(16..20, 21..22), (36..40, 41..45)]);
1748        assert_eq!(
1749            qualifiers,
1750            [
1751                ("parameter_declaration", 77..82),
1752                ("function_declarator", 100..105)
1753            ]
1754        );
1755        assert_eq!(literals, [121..125, 127..131, 133..137, 139..142, 144..147]);
1756        let rows = parse_cpp_expression_source_facts(source);
1757        let bindings: Vec<_> = rows
1758            .expressions
1759            .iter()
1760            .filter(|f| f.kind == CppExpressionKind::LoopVariable)
1761            .map(|f| {
1762                (
1763                    f.name.as_deref(),
1764                    f.type_text.as_deref(),
1765                    f.loop_has_short_ancestor,
1766                )
1767            })
1768            .collect();
1769        let methods: Vec<_> = rows
1770            .expressions
1771            .iter()
1772            .filter(|f| {
1773                f.kind == CppExpressionKind::FunctionSignature && f.member_function == Some(true)
1774            })
1775            .map(|f| (f.name.as_deref(), f.member_function_const))
1776            .collect();
1777        let values: Vec<_> = rows
1778            .expressions
1779            .iter()
1780            .filter(|f| f.kind == CppExpressionKind::IntegerLiteral)
1781            .map(|f| f.integer_value)
1782            .collect();
1783        assert_eq!(
1784            (bindings, methods, values),
1785            (
1786                vec![
1787                    (Some("i"), Some("char"), Some(false)),
1788                    (Some("item"), Some("char"), Some(true))
1789                ],
1790                vec![(Some("f"), Some(false)), (Some("g"), Some(true))],
1791                vec![Some(16), Some(2), Some(1), Some(2), Some(8)]
1792            )
1793        );
1794        // The C++20 init-statement is not the range binding. A traditional
1795        // declaration-initialized inner loop still sees the short range name.
1796        let rows = parse_cpp_expression_source_facts(
1797            "void f() { for (int setup = 0; char i : xs) { for (int j = 0; j < 3; ++j) {} } }",
1798        );
1799        let bindings: Vec<_> = rows
1800            .expressions
1801            .iter()
1802            .filter(|f| f.kind == CppExpressionKind::LoopVariable)
1803            .map(|f| {
1804                (
1805                    f.name.as_deref(),
1806                    f.type_text.as_deref(),
1807                    f.loop_has_short_ancestor,
1808                )
1809            })
1810            .collect();
1811        assert_eq!(
1812            bindings,
1813            [
1814                (Some("i"), Some("char"), Some(false)),
1815                (Some("j"), Some("int"), Some(true))
1816            ]
1817        );
1818    }
1819
1820    #[test]
1821    #[brokk_bifrost_test_macros::hardwon(
1822        "db00de0653f1: quicksilver round 4 on brokk-bifrost-cpp: base access leaked across commas"
1823    )]
1824    fn source_fact_base_access_defaults() {
1825        // [class.access.base]: omitted access is decided independently per base.
1826        let source = "struct A {}; struct B {}; struct S : private A, B {}; class C : public A, B {}; struct P : protected A {};";
1827        let mut parser = Parser::new();
1828        parser
1829            .set_language(&tree_sitter_cpp::LANGUAGE.into())
1830            .unwrap();
1831        let tree = parser.parse(source, None).unwrap();
1832        assert!(!tree.root_node().has_error());
1833        let mut stack = vec![tree.root_node()];
1834        let mut access = Vec::new();
1835        while let Some(node) = stack.pop() {
1836            if node.kind() == "base_class_clause" {
1837                for base in node
1838                    .named_children(&mut node.walk())
1839                    .filter(|n| n.kind() == "type_identifier")
1840                {
1841                    access.push(base_access_specifier(
1842                        node,
1843                        base,
1844                        node.parent().unwrap().kind(),
1845                    ));
1846                }
1847            }
1848            let children: Vec<_> = node.named_children(&mut node.walk()).collect();
1849            stack.extend(children.into_iter().rev());
1850        }
1851        assert_eq!(
1852            access,
1853            [
1854                CppAccessSpecifier::Private,
1855                CppAccessSpecifier::Public,
1856                CppAccessSpecifier::Public,
1857                CppAccessSpecifier::Private,
1858                CppAccessSpecifier::Protected
1859            ]
1860        );
1861    }
1862
1863    #[test]
1864    #[brokk_bifrost_test_macros::hardwon(
1865        "db00de0653f1: quicksilver round 4 on brokk-bifrost-cpp: parameter indirection reused pointee size"
1866    )]
1867    fn source_fact_parameter_sizes_respect_indirection() {
1868        let rows = parse_cpp_expression_source_facts(
1869            "void f(char a, signed char b, unsigned char c, char *p, char &r, char xs[3]);",
1870        );
1871        let sizes: Vec<_> = rows
1872            .expressions
1873            .iter()
1874            .filter(|f| {
1875                f.name.is_some()
1876                    && matches!(
1877                        f.kind,
1878                        CppExpressionKind::FunctionParameter | CppExpressionKind::ArrayParameter
1879                    )
1880            })
1881            .map(|f| (f.name.as_deref(), f.type_size_bytes, f.type_size_exact))
1882            .collect();
1883        assert_eq!(
1884            sizes,
1885            [
1886                (Some("a"), Some(1), Some(true)),
1887                (Some("b"), Some(1), Some(true)),
1888                (Some("c"), Some(1), Some(true)),
1889                (Some("p"), None, Some(false)),
1890                (Some("r"), None, Some(false)),
1891                (Some("xs"), None, Some(false))
1892            ]
1893        );
1894    }
1895
1896    #[test]
1897    #[brokk_bifrost_test_macros::hardwon(
1898        "db00de0653f1: quicksilver round 4 on brokk-bifrost-cpp: union sizes summed and later field declarators vanished"
1899    )]
1900    fn source_fact_record_sizes_follow_member_layout() {
1901        let rows = parse_cpp_expression_source_facts(
1902            "union U { char a[2]; char b[3]; }; struct S { char a, b; }; void f(U u, S s);",
1903        );
1904        let sizes: Vec<_> = rows
1905            .expressions
1906            .iter()
1907            .filter(|f| f.kind == CppExpressionKind::FunctionParameter)
1908            .map(|f| (f.name.as_deref(), f.type_size_bytes))
1909            .collect();
1910        // [class.union] requires room for the largest member; char has size one.
1911        assert_eq!(sizes, [(Some("u"), Some(3)), (Some("s"), Some(2))]);
1912    }
1913
1914    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";
1915
1916    #[test]
1917    #[brokk_bifrost_test_macros::hardwon(
1918        "d4f00f8567e4: quicksilver round 4 on brokk-bifrost-cpp: unnamed && tokens hid rvalue references"
1919    )]
1920    #[brokk_bifrost_test_macros::hardwon(
1921        "d4f00f8567e4: quicksilver round 4 on brokk-bifrost-cpp: a mutable C& copy constructor was not classified as copy"
1922    )]
1923    fn cpp_reference_token_grammar() {
1924        let mut parser = Parser::new();
1925        parser
1926            .set_language(&tree_sitter_cpp::LANGUAGE.into())
1927            .unwrap();
1928        let tree = parser.parse(REFERENCES, None).unwrap();
1929        assert!(!tree.root_node().has_error());
1930        // Half-open byte spans from the pinned grammar boundary table. The
1931        // reference wrapper has no fields; the parameter owns `declarator`.
1932        let expected = "reference_declarator 15..18 & 15..16 identifier 17..18
1933reference_declarator 30..33 & 30..31 identifier 32..33
1934reference_declarator 39..43 && 39..41 identifier 42..43
1935reference_declarator 55..59 && 55..57 identifier 58..59
1936reference_declarator 66..70 && 66..68 identifier 69..70
1937reference_declarator 95..118 & 95..96 function_declarator 97..118
1938reference_declarator 114..117 & 114..115 identifier 116..117
1939reference_declarator 121..139 & 121..122 function_declarator 123..139
1940reference_declarator 134..138 && 134..136 identifier 137..138
1941abstract_reference_declarator 152..155 & 152..153 abstract_function_declarator 153..155
1942abstract_reference_declarator 167..171 && 167..169 abstract_function_declarator 169..171
1943reference_declarator 177..180 & 177..178 identifier 179..180
1944reference_declarator 187..191 && 187..189 identifier 190..191
1945reference_declarator 224..227 & 224..225 identifier 226..227
1946reference_declarator 252..255 & 252..253 identifier 254..255
1947reference_declarator 274..278 && 274..276 identifier 277..278
1948reference_declarator 300..303 & 300..301 identifier 302..303
1949reference_declarator 308..325 & 308..309 function_declarator 310..325
1950reference_declarator 321..324 & 321..322 identifier 323..324
1951reference_declarator 337..340 & 337..338 identifier 339..340
1952reference_declarator 345..368 & 345..346 function_declarator 347..368
1953reference_declarator 364..367 & 364..365 identifier 366..367
1954reference_declarator 383..386 & 383..384 identifier 385..386
1955reference_declarator 391..417 & 391..392 function_declarator 393..417
1956reference_declarator 413..416 & 413..414 identifier 415..416
1957reference_declarator 438..441 & 438..439 identifier 440..441
1958reference_declarator 446..478 & 446..447 function_declarator 448..478
1959reference_declarator 474..477 & 474..475 identifier 476..477
1960reference_declarator 484..487 & 484..485 identifier 486..487
1961reference_declarator 514..517 & 514..515 identifier 516..517";
1962        let mut stack = vec![tree.root_node()];
1963        let mut actual = Vec::new();
1964        let mut references = Vec::new();
1965        let mut qualifiers = Vec::new();
1966        while let Some(node) = stack.pop() {
1967            if node.kind() == "type_qualifier" && node.start_byte() >= 285 {
1968                assert_eq!(node.parent().unwrap().kind(), "parameter_declaration");
1969                qualifiers.push((
1970                    node.utf8_text(REFERENCES.as_bytes()).unwrap(),
1971                    node.byte_range(),
1972                ));
1973            }
1974            if matches!(
1975                node.kind(),
1976                "reference_declarator" | "abstract_reference_declarator"
1977            ) {
1978                let token = node.child(0).unwrap();
1979                let wrapped = node.named_child(0).unwrap();
1980                assert!(!token.is_named());
1981                assert!(node.child_by_field_name("declarator").is_none());
1982                assert_eq!(node.field_name_for_child(0), None);
1983                assert_eq!(node.field_name_for_child(1), None);
1984                if node.parent().unwrap().kind() == "parameter_declaration" {
1985                    assert_eq!(
1986                        node.parent().unwrap().child_by_field_name("declarator"),
1987                        Some(node)
1988                    );
1989                }
1990                actual.push(format!(
1991                    "{} {:?} {} {:?} {} {:?}",
1992                    node.kind(),
1993                    node.byte_range(),
1994                    token.kind(),
1995                    token.byte_range(),
1996                    wrapped.kind(),
1997                    wrapped.byte_range()
1998                ));
1999                references.push(node);
2000            }
2001            let children: Vec<_> = node.named_children(&mut node.walk()).collect();
2002            stack.extend(children.into_iter().rev());
2003        }
2004        assert_eq!(actual.join("\n"), expected);
2005        assert_eq!(
2006            qualifiers,
2007            [
2008                ("const", 330..335),
2009                ("const", 357..362),
2010                ("volatile", 373..381),
2011                ("volatile", 403..411),
2012                ("const", 422..427),
2013                ("volatile", 428..436),
2014                ("const", 458..463),
2015                ("volatile", 464..472),
2016                ("volatile", 504..512),
2017            ]
2018        );
2019        for node in references {
2020            let token = node.child(0).unwrap();
2021            let wrapped = node.named_child(0).unwrap();
2022            // A return wrapper also contains the function's parameters. The
2023            // producer calls this helper on parameter declarators only.
2024            if wrapped.kind() == "function_declarator" {
2025                continue;
2026            }
2027            assert_eq!(
2028                declarator_contains_rvalue_reference(node),
2029                token.kind() == "&&",
2030                "reference at {:?}",
2031                node.byte_range()
2032            );
2033        }
2034        let rows = parse_cpp_class_fact_rows(REFERENCES);
2035        use CppSpecialMemberKind::{
2036            CopyAssignment, CopyConstructor, MoveAssignment, MoveConstructor, None as NotSpecial,
2037        };
2038        // Pin the defect's public class/catch consequences as well as its
2039        // grammar boundary, including all cv-qualified lvalue references.
2040        let members: Vec<_> = rows
2041            .members
2042            .iter()
2043            .take(8)
2044            .map(|member| member.special_member)
2045            .collect();
2046        assert_eq!(
2047            members,
2048            [
2049                CopyConstructor,
2050                CopyConstructor,
2051                MoveConstructor,
2052                MoveConstructor,
2053                MoveConstructor,
2054                NotSpecial,
2055                CopyAssignment,
2056                MoveAssignment
2057            ]
2058        );
2059        assert!(rows.members[4].remaining_parameters_defaulted);
2060        let cv_members: Vec<_> = rows
2061            .members
2062            .iter()
2063            .filter(|member| member.owner == ["V"])
2064            .collect();
2065        assert_eq!(
2066            cv_members
2067                .iter()
2068                .map(|member| member.special_member)
2069                .collect::<Vec<_>>(),
2070            [
2071                CopyConstructor,
2072                CopyAssignment,
2073                CopyConstructor,
2074                CopyAssignment,
2075                CopyConstructor,
2076                CopyAssignment,
2077                CopyConstructor,
2078                CopyAssignment,
2079                CopyConstructor,
2080                CopyConstructor
2081            ]
2082        );
2083        assert!(cv_members.iter().all(|member| member.copy_parameter));
2084        assert!(
2085            cv_members[8..]
2086                .iter()
2087                .all(|member| member.remaining_parameters_defaulted)
2088        );
2089        assert_eq!(
2090            rows.catches
2091                .iter()
2092                .map(|catch| catch.value_category)
2093                .collect::<Vec<_>>(),
2094            [
2095                CppParameterValueCategory::LValueReference,
2096                CppParameterValueCategory::LValueReference,
2097                CppParameterValueCategory::RValueReference
2098            ]
2099        );
2100    }
2101
2102    #[test]
2103    fn specialized_declaration_name_grammar_boundary() {
2104        for (source, field_kind, expected, offset) in [
2105            ("struct Plain {};", "type_identifier", "Plain", 7),
2106            ("template<> struct Box<int> {};", "template_type", "Box", 18),
2107            (
2108                "struct ns::Qualified {};",
2109                "qualified_identifier",
2110                "Qualified",
2111                11,
2112            ),
2113        ] {
2114            let tree = crate::diagnostics::parse_cpp_tree(source);
2115            assert!(!tree.root_node().has_error());
2116            let mut stack = vec![tree.root_node()];
2117            let mut names = Vec::new();
2118            while let Some(node) = stack.pop() {
2119                if node.kind() == "struct_specifier" {
2120                    let field = node.child_by_field_name("name").unwrap();
2121                    assert_eq!(field.kind(), field_kind);
2122                    let unit = CodeUnit::new(
2123                        brokk_bifrost_core::analyzer::ProjectFile::new(
2124                            std::env::temp_dir(),
2125                            "names.cpp",
2126                        ),
2127                        brokk_bifrost_core::analyzer::model::CodeUnitType::Class,
2128                        "",
2129                        expected,
2130                    );
2131                    let name = declaration_name(node, &unit, source).unwrap();
2132                    names.push((node_text(name, source), name.byte_range()));
2133                }
2134                stack.extend(node.named_children(&mut node.walk()));
2135            }
2136            assert_eq!(names, [(expected, offset..offset + expected.len())]);
2137        }
2138    }
2139}