brokk-bifrost-cpp 0.15.2

C++ language knowledge for brokk-bifrost: declarations and macro-sentinel recovery, include-graph visibility, out-of-line member identity reconciliation, and usage-graph resolution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
use crate::declarations::node_text;
use crate::graph::resolver::{
    cpp_name_component_nodes, cpp_type_name_components, is_globally_qualified_cpp_name,
    is_nested_type_node, qualified_owner_components,
};
use brokk_bifrost_core::analyzer::cpp_facts::CppDeclaredFieldTypeFact;
use brokk_bifrost_core::analyzer::tree_walk::push_named_children_reversed;
use std::ops::{ControlFlow, Range};
use tree_sitter::{Node, Parser};

/// A grammar context around embedded source with physical byte origins.
/// Consumers of a sentinel tree count non-extra named children.
/// Error nodes are preserved: recovery callers inspect them, while callers
/// requiring a complete construct reject `tree.root_node().has_error()`.
pub(crate) struct SentinelParse {
    pub source: String,
    pub tree: tree_sitter::Tree,
    /// Byte origins relative to the embedded source, excluding the prefix.
    /// Synthetic suffix bytes and the final boundary map to its original end.
    pub original_offsets: Vec<Range<usize>>,
    prefix_len: usize,
}

impl SentinelParse {
    pub fn original_range(&self, node: Node<'_>) -> Option<Range<usize>> {
        let start = node.start_byte().checked_sub(self.prefix_len)?;
        let end = node.end_byte().checked_sub(self.prefix_len)?;
        Some(
            self.original_offsets.get(start)?.start
                ..self.original_offsets.get(end.checked_sub(1)?)?.end,
        )
    }
}

/// Embedded bytes and their physical origins. Ordinary source regions retain
/// their exact spelling; opaque preprocessing replacements need phase-2 splicing.
pub(crate) struct SentinelInput {
    pub source: String,
    pub original_offsets: Vec<Range<usize>>,
}

impl SentinelInput {
    pub fn replacement(source: &str) -> Self {
        let (source, original_offsets) = normalize_macro_continuations(source);
        Self {
            source,
            original_offsets,
        }
    }

    pub fn region(source: &str) -> Self {
        let mut original_offsets = (0..source.len()).map(|i| i..i + 1).collect::<Vec<_>>();
        original_offsets.push(source.len()..source.len());
        Self {
            source: source.to_owned(),
            original_offsets,
        }
    }
}

pub(crate) fn parse_sentinel(prefix: &str, embedded: SentinelInput, suffix: &str) -> SentinelParse {
    let SentinelInput {
        source: replacement,
        mut original_offsets,
    } = embedded;
    let original_end = original_offsets
        .last()
        .expect("embedded source includes its final boundary")
        .end;
    debug_assert_eq!(original_offsets.len(), replacement.len() + 1);
    // A preproc_arg can include a trailing line comment. End it before any
    // synthetic punctuation, including an expression's terminating semicolon.
    let source = format!("{prefix}{replacement}\n{suffix}");
    original_offsets.extend(std::iter::repeat_n(
        original_end..original_end,
        1 + suffix.len(),
    ));
    let mut parser = Parser::new();
    parser
        .set_language(&tree_sitter_cpp::LANGUAGE.into())
        .expect("C++ grammar matches the parser ABI");
    let tree = parser
        .parse(&source, None)
        .expect("sentinel parse has no cancellation or timeout");
    SentinelParse {
        source,
        tree,
        original_offsets,
        prefix_len: prefix.len(),
    }
}

/// Whether an expression denotes C++'s implicit object receiver.
///
/// `this` is the implicit object only where C++ compiles the source; it is an
/// ordinary identifier in a `.c` file or a header compiled as C. Parentheses
/// and pointer expressions transparently wrap the receiver.
pub(crate) fn receiver_is_self_like(mut node: Node<'_>, reference_is_c: bool) -> bool {
    loop {
        match node.kind() {
            "this" => return !reference_is_c,
            "pointer_expression" | "parenthesized_expression" => {
                let Some(inner) = node
                    .child_by_field_name("argument")
                    .or_else(|| node.named_child(0))
                else {
                    return false;
                };
                node = inner;
            }
            _ => return false,
        }
    }
}

pub(crate) fn has_function_scope_ancestor(mut node: Node<'_>) -> bool {
    while let Some(parent) = node.parent() {
        if matches!(parent.kind(), "function_definition" | "lambda_expression") {
            return true;
        }
        node = parent;
    }
    false
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MacroReplacementTypeReference {
    pub components: Vec<String>,
    pub component_ranges: Vec<Range<usize>>,
    pub global: bool,
}

/// Whether an identifier is a callable declaration name retained beneath C++
/// error recovery.
///
/// A C prototype using the traditional `__P((...))` wrapper can be parsed as a
/// pointer declarator whose first child is `ERROR(identifier)` and whose
/// declarator is a function declarator for the macro invocation. The identifier
/// is still a real declaration reference to the callable's later definition,
/// even though the ordinary census intentionally excludes the whole ERROR
/// subtree. Keep this predicate limited to that declaration-shaped CST so
/// arbitrary recovery leaves do not enter inverse membership.
pub fn is_cpp_recovered_callable_declaration_reference(node: Node<'_>) -> bool {
    if !matches!(node.kind(), "identifier" | "field_identifier") {
        return false;
    }
    let Some(error) = node.parent().filter(|parent| parent.is_error()) else {
        return false;
    };
    let Some(pointer) = error.parent().filter(|parent| {
        parent.kind() == "pointer_declarator"
            && parent.named_child(0) == Some(error)
            && parent
                .child_by_field_name("declarator")
                .is_some_and(|declarator| declarator.kind() == "function_declarator")
    }) else {
        return false;
    };
    pointer.parent().is_some_and(|declaration| {
        declaration.kind() == "declaration"
            && declaration.child_by_field_name("declarator") == Some(pointer)
    })
}

/// One direct field declaration recovered from an object-like macro
/// replacement. The replacement is parsed as the body of a synthetic struct,
/// so the name and declaration text come from C/C++ grammar nodes rather than
/// from a textual macro expansion.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MacroReplacementField {
    pub name: String,
    pub declaration: String,
    pub field_type: Option<CppDeclaredFieldTypeFact>,
    pub names_function_type: bool,
}

/// The structured content of one object-like field-list macro replacement:
/// the members it declares itself, and the names of the field-list macros it
/// composes in turn. Composition is kept as names rather than resolved here
/// because a nested name's active replacement is a property of the
/// preprocessor environment at the invocation, not of this replacement.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ObjectMacroReplacement {
    pub fields: Vec<MacroReplacementField>,
    pub nested: Vec<String>,
}

impl ObjectMacroReplacement {
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty() && self.nested.is_empty()
    }

    /// The members and nested names both replacements declare identically.
    ///
    /// An include closure can carry mutually exclusive definitions of one
    /// field-list macro (libuv defines `UV_HANDLE_PRIVATE_FIELDS` in both
    /// `uv/unix.h` and `uv/win.h`). Whichever header the compilation actually
    /// took, every member in this intersection is present, and every member
    /// that depends on the branch is left unproven.
    pub fn intersect(&self, other: &Self) -> Self {
        Self {
            fields: self
                .fields
                .iter()
                .filter(|field| other.fields.contains(field))
                .cloned()
                .collect(),
            nested: self
                .nested
                .iter()
                .filter(|name| other.nested.contains(name))
                .cloned()
                .collect(),
        }
    }
}

/// Recover direct fields hidden in an object-like macro replacement.
///
/// A field-list macro is valid in more than one owner, so this helper returns
/// only the declaration-shaped children of the synthetic field list. Nested
/// aggregate promotion remains the owner's normal structured aggregate logic;
/// treating nested members as direct fields here would leak them across owners.
///
/// A replacement that ends in another field-list macro's name is reported as
/// composition rather than refused: the grammar has no member rule for a bare
/// identifier, so tree-sitter marks it as one `type_identifier` with a MISSING
/// `;`. Every other malformed region still refuses the whole replacement, so an
/// unsupported spelling stays unproven instead of donating partial members.
pub fn object_macro_replacement(replacement: &str) -> ObjectMacroReplacement {
    if replacement.trim().is_empty() {
        return ObjectMacroReplacement::default();
    }
    const PREFIX: &str = "struct __bifrost_macro_fields { ";
    let parsed = parse_sentinel(PREFIX, SentinelInput::replacement(replacement), " };");
    let synthetic = parsed.source.as_str();
    let tree = &parsed.tree;
    let original_offsets = &parsed.original_offsets;
    let mut stack = vec![tree.root_node()];
    let body = loop {
        let Some(current) = stack.pop() else {
            return ObjectMacroReplacement::default();
        };
        if current.kind() == "struct_specifier"
            && let Some(body) = current.child_by_field_name("body")
        {
            break body;
        }
        let mut cursor = current.walk();
        for child in current.named_children(&mut cursor) {
            stack.push(child);
        }
    };
    let mut recovered = ObjectMacroReplacement::default();
    let mut composed_terminators = Vec::new();
    let mut cursor = body.walk();
    for declaration in body.named_children(&mut cursor) {
        if !matches!(declaration.kind(), "declaration" | "field_declaration") {
            continue;
        }
        if let Some((name, terminator)) = nested_object_macro_invocation(declaration, synthetic) {
            recovered.nested.push(name);
            composed_terminators.push(terminator.id());
            continue;
        }
        let Some(declarator) = declaration.child_by_field_name("declarator").or_else(|| {
            let mut cursor = declaration.walk();
            declaration
                .named_children(&mut cursor)
                .filter(|child| !child.is_extra())
                .nth(1)
        }) else {
            continue;
        };
        let Some(name) = macro_replacement_declarator_name(declarator, synthetic) else {
            continue;
        };
        let start = declaration
            .start_byte()
            .checked_sub(PREFIX.len())
            .and_then(|start| original_offsets.get(start));
        let end = declaration
            .end_byte()
            .checked_sub(PREFIX.len())
            .and_then(|end| original_offsets.get(end.checked_sub(1)?));
        let Some((start, end)) = start.zip(end) else {
            continue;
        };
        let declaration_text = replacement[start.start..end.end].to_string();
        let (field_type, names_function_type) =
            crate::source_facts::capture_field_type(declaration, &name, synthetic);
        recovered.fields.push(MacroReplacementField {
            name,
            declaration: declaration_text,
            field_type,
            names_function_type,
        });
    }
    if !malformed_regions_are_composition(tree.root_node(), &composed_terminators) {
        return ObjectMacroReplacement::default();
    }
    recovered
}

/// The name a nested field-list macro invocation contributes, with the MISSING
/// `;` tree-sitter inserted for it. A member list holding only another macro's
/// name has no grammar rule, so the invocation reaches the tree as exactly one
/// `type_identifier` followed by that missing terminator.
fn nested_object_macro_invocation<'tree>(
    declaration: Node<'tree>,
    source: &str,
) -> Option<(String, Node<'tree>)> {
    if declaration.kind() != "field_declaration" {
        return None;
    }
    let mut cursor = declaration.walk();
    let children = declaration.children(&mut cursor).collect::<Vec<_>>();
    let [name, terminator] = children.as_slice() else {
        return None;
    };
    if name.kind() != "type_identifier" || terminator.kind() != ";" || !terminator.is_missing() {
        return None;
    }
    let text = node_text(*name, source).trim();
    (!text.is_empty()).then(|| (text.to_string(), *terminator))
}

/// Whether every malformed region of a reparsed replacement is one of the
/// MISSING terminators nested composition already accounts for. Any other
/// error means the replacement is not a structured member list, and the whole
/// replacement is refused rather than donating the members that did parse.
fn malformed_regions_are_composition(root: Node<'_>, composed_terminators: &[usize]) -> bool {
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if !node.has_error() && !node.is_missing() {
            continue;
        }
        if (node.is_error() || node.is_missing()) && !composed_terminators.contains(&node.id()) {
            return false;
        }
        let mut cursor = node.walk();
        let children = node.children(&mut cursor).collect::<Vec<_>>();
        stack.extend(children);
    }
    true
}

/// One member declaration recovered from an aggregate region tree-sitter could
/// not place. `range` is the member's own byte range in the original source.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RecoveredAggregateField {
    pub name: String,
    pub declaration: String,
    pub range: Range<usize>,
    pub field_type: Option<CppDeclaredFieldTypeFact>,
    pub names_function_type: bool,
}

/// Recover the direct members of an aggregate body region the ordinary parse
/// could not place.
///
/// An object-like field-list macro invocation inside a member list has no
/// grammar rule, so tree-sitter collapses the aggregate's head and body into
/// one `ERROR` container and the members after the invocation lose their
/// declaration shape. Reparsing the exact byte slice that follows the
/// invocation as a synthetic aggregate body restores that shape from the
/// grammar, and every returned range maps back to the original source.
pub fn recovered_aggregate_fields(
    source: &str,
    span: Range<usize>,
) -> Vec<RecoveredAggregateField> {
    let Some(region) = source.get(span.clone()) else {
        return Vec::new();
    };
    if region.trim().is_empty() {
        return Vec::new();
    }
    const PREFIX: &str = "struct __bifrost_recovered_members { ";
    let parsed = parse_sentinel(PREFIX, SentinelInput::region(region), " };");
    let synthetic = parsed.source.as_str();
    let tree = &parsed.tree;
    if tree.root_node().has_error() {
        return Vec::new();
    }
    let mut stack = vec![tree.root_node()];
    let body = loop {
        let Some(current) = stack.pop() else {
            return Vec::new();
        };
        if current.kind() == "struct_specifier"
            && let Some(body) = current.child_by_field_name("body")
        {
            break body;
        }
        let mut cursor = current.walk();
        for child in current.named_children(&mut cursor) {
            stack.push(child);
        }
    };
    let mut fields = Vec::new();
    let mut cursor = body.walk();
    for declaration in body.named_children(&mut cursor) {
        if !matches!(declaration.kind(), "declaration" | "field_declaration") {
            continue;
        }
        let mut declarator_cursor = declaration.walk();
        for declarator in declaration.children_by_field_name("declarator", &mut declarator_cursor) {
            let Some(name) = macro_replacement_declarator_name(declarator, synthetic) else {
                continue;
            };
            let Some(range) = parsed.original_range(declaration) else {
                continue;
            };
            let Some(declaration_text) = region.get(range.clone()).map(str::to_owned) else {
                continue;
            };
            let (field_type, names_function_type) =
                crate::source_facts::capture_field_type(declaration, &name, synthetic);
            let start = span.start + range.start;
            let end = span.start + range.end;
            fields.push(RecoveredAggregateField {
                name,
                declaration: declaration_text,
                range: start..end,
                field_type,
                names_function_type,
            });
        }
    }
    fields
}

/// The complete replacement list of an object-like `#define`.
///
/// tree-sitter-cpp lexes a comment inside a replacement as an extra, which
/// ends the `preproc_arg` token and the `preproc_def` node with it: libuv's
/// `UV_HANDLE_FIELDS` reports `void* data;` as its whole replacement and loses
/// the eight members that follow the next comment. A replacement list is one
/// preprocessing logical line (C17 5.1.1.2), so its extent is the directive's
/// own line-continuation run, which the grammar's token boundaries do not
/// describe. The AST supplies the start; the returned slice is then parsed by
/// tree-sitter like any other replacement.
pub fn object_macro_replacement_span(node: Node<'_>, source: &str) -> Option<Range<usize>> {
    if node.kind() != "preproc_def" {
        return None;
    }
    let start = node.child_by_field_name("name")?.end_byte();
    macro_replacement_span(source, start)
}

/// The complete logical-line replacement list of a function-like `#define`.
///
/// Comments are tokenized as extras by tree-sitter-cpp and can truncate the
/// `preproc_arg` value. Start immediately after the parameter list so a
/// replacement that begins with a comment remains source backed even when it
/// has no value node. Follow the preprocessing continuation run to recover the
/// bytes that belong to the replacement. The returned span includes the
/// original backslash/newline bytes so callers can retain source coordinates.
pub fn function_macro_replacement_span(node: Node<'_>, source: &str) -> Option<Range<usize>> {
    let parameters = match node.kind() {
        "preproc_function_def" => node.child_by_field_name("parameters"),
        "preproc_def" => {
            // A comment-truncated function macro can recover as an object
            // directive whose ERROR child still owns the parameter list.
            let mut stack = vec![node];
            let mut parameters = None;
            while let Some(part) = stack.pop() {
                if part.kind() == "preproc_params" {
                    parameters = Some(part);
                    break;
                }
                if part == node || part.is_error() {
                    push_named_children_reversed(part, &mut stack);
                }
            }
            parameters
        }
        _ => None,
    }?;
    macro_replacement_span(source, parameters.end_byte())
}

fn macro_replacement_span(source: &str, start: usize) -> Option<Range<usize>> {
    (start <= source.len()).then(|| start..logical_line_end(start, source))
}

/// Return the end of the preprocessing logical line beginning at `start`.
/// A physical newline belongs to the replacement while it is preceded by a
/// continuation backslash (with an optional CR before the newline).
fn logical_line_end(start: usize, source: &str) -> usize {
    let bytes = source.as_bytes();
    let mut index = start;
    while index < bytes.len() {
        if bytes[index] != b'\n' {
            index += 1;
            continue;
        }
        let mut previous = index;
        if previous > start && bytes[previous - 1] == b'\r' {
            previous -= 1;
        }
        if previous > start && bytes[previous - 1] == b'\\' {
            index += 1;
            continue;
        }
        break;
    }
    index
}

/// Apply translation phase 2 (C 5.1.1.2): delete a backslash-newline pair,
/// allowing the surrounding bytes to form a single preprocessing token.
/// Each normalized byte maps back to its physical source byte;
/// consumers parse the joined text and report ranges in the physical source.
fn normalize_macro_continuations(replacement: &str) -> (String, Vec<Range<usize>>) {
    let source = replacement.as_bytes();
    let mut normalized = Vec::with_capacity(source.len());
    let mut original_offsets = Vec::with_capacity(source.len() + 1);
    let mut index = 0;
    while index < source.len() {
        if source[index..].starts_with(b"\\\n") {
            index += 2;
        } else if source[index..].starts_with(b"\\\r\n") {
            index += 3;
        } else {
            original_offsets.push(index..index + 1);
            normalized.push(source[index]);
            index += 1;
        }
    }
    original_offsets.push(source.len()..source.len());
    (
        String::from_utf8(normalized).expect("source text remains valid UTF-8"),
        original_offsets,
    )
}

fn macro_replacement_declarator_name(node: Node<'_>, source: &str) -> Option<String> {
    match node.kind() {
        "identifier" | "field_identifier" | "type_identifier" | "qualified_identifier" => {
            let name = node_text(node, source).trim();
            (!name.is_empty()).then(|| name.to_string())
        }
        "function_declarator" => None,
        _ => node
            .child_by_field_name("declarator")
            .or_else(|| node.child_by_field_name("name"))
            .and_then(|child| macro_replacement_declarator_name(child, source)),
    }
}

/// Recover type-bearing syntax hidden inside an object-like macro replacement.
///
/// Tree-sitter deliberately keeps the replacement of `#define NAME value` as
/// one opaque `preproc_arg`. Reparse that exact byte slice as a C++ expression
/// and return only references proven by the resulting tree: ordinary type
/// nodes and the owner prefixes of qualified values such as `Owner::member`.
/// Every returned range is mapped back to the original file.
pub fn object_macro_replacement_type_references(
    node: Node<'_>,
    source: &str,
) -> Vec<MacroReplacementTypeReference> {
    if node.kind() != "preproc_arg"
        || !node.parent().is_some_and(|parent| {
            parent.kind() == "preproc_def"
                && parent
                    .child_by_field_name("value")
                    .is_some_and(|value| value == node)
        })
    {
        return Vec::new();
    }
    let Some(replacement) = source.get(node.start_byte()..node.end_byte()) else {
        return Vec::new();
    };
    const PREFIX: &str = "void __bifrost_macro_reference() { ";
    let parsed = parse_sentinel(PREFIX, SentinelInput::replacement(replacement), "; }");
    let synthetic = parsed.source.as_str();
    let tree = &parsed.tree;
    if tree.root_node().has_error() {
        return Vec::new();
    }

    let mut references = Vec::new();
    let mut stack = vec![tree.root_node()];
    while let Some(current) = stack.pop() {
        let structured = if matches!(
            current.kind(),
            "type_identifier" | "scoped_type_identifier" | "template_type"
        ) && !is_nested_type_node(current)
        {
            cpp_type_name_components(current, synthetic)
                .zip(cpp_name_component_nodes(current))
                .map(|(components, nodes)| {
                    (components, nodes, is_globally_qualified_cpp_name(current))
                })
        } else if current.kind() == "qualified_identifier"
            && !current.parent().is_some_and(|parent| {
                matches!(
                    parent.kind(),
                    "qualified_identifier" | "scoped_identifier" | "scoped_type_identifier"
                )
            })
        {
            qualified_owner_components(current, synthetic)
                .map(|owner| (owner.names, owner.nodes, owner.global))
        } else {
            None
        };
        if let Some((components, component_nodes, global)) = structured {
            let component_ranges = component_nodes
                .into_iter()
                .map(|component| {
                    let range = parsed.original_range(component)?;
                    (range.end <= replacement.len())
                        .then_some(node.start_byte() + range.start..node.start_byte() + range.end)
                })
                .collect::<Option<Vec<_>>>();
            if let Some(component_ranges) = component_ranges
                && component_ranges.len() == components.len()
            {
                let reference = MacroReplacementTypeReference {
                    components,
                    component_ranges,
                    global,
                };
                if !references.contains(&reference) {
                    references.push(reference);
                }
            }
        }
        push_named_children_reversed(current, &mut stack);
    }
    references
}

#[derive(Clone)]
pub struct QualifiedCallableValue<'tree> {
    pub qualified: Node<'tree>,
    pub global: bool,
    pub owner_components: Vec<Node<'tree>>,
    pub member: Node<'tree>,
}

/// Recognize an explicit address-of qualified callable value such as
/// `&Owner::method` or `&namespace::Owner::method`.
///
/// The returned nodes come exclusively from the C++ grammar's named fields. In
/// particular, a nested namespace/type owner remains a structured subtree rather
/// than being reconstructed from source text.
pub fn explicit_qualified_callable_value(node: Node<'_>) -> Option<QualifiedCallableValue<'_>> {
    if node.kind() != "pointer_expression" || node.child_by_field_name("operator")?.kind() != "&" {
        return None;
    }
    let qualified = node.child_by_field_name("argument")?;
    qualified_callable_value_from_node(qualified)
}

/// Recognize a qualified callable used as an expression value.
///
/// Calls use their own arity-aware path. Address-of expressions use the
/// explicit path above. This arm covers structured values such as
/// `bind(Owner::method)` and `callback = namespace::function`.
pub fn qualified_callable_value(node: Node<'_>) -> Option<QualifiedCallableValue<'_>> {
    if let Some(value) = explicit_qualified_callable_value(node) {
        return Some(value);
    }
    if node.kind() != "qualified_identifier" {
        return None;
    }
    if crate::graph::resolver::is_declaration_name(node) {
        return None;
    }
    if node.parent().is_some_and(|parent| {
        parent.child_by_field_name("type") == Some(node)
            || (parent.kind() == "call_expression"
                && parent.child_by_field_name("function") == Some(node))
            || (parent.kind() == "pointer_expression"
                && parent.child_by_field_name("argument") == Some(node))
            || matches!(
                parent.kind(),
                "qualified_identifier" | "scoped_identifier" | "scoped_type_identifier"
            )
    }) {
        return None;
    }
    qualified_callable_value_from_node(node)
}

fn qualified_callable_value_from_node(qualified: Node<'_>) -> Option<QualifiedCallableValue<'_>> {
    if qualified.kind() != "qualified_identifier" {
        return None;
    }
    let mut components = Vec::new();
    let global = qualified.child_by_field_name("scope").is_none()
        && qualified.child(0).is_some_and(|child| child.kind() == "::");
    append_qualified_components(qualified, &mut components)?;
    let member = components.pop()?;
    if components.is_empty() {
        return None;
    }
    Some(QualifiedCallableValue {
        qualified,
        global,
        owner_components: components,
        member,
    })
}

fn append_qualified_components<'tree>(node: Node<'tree>, out: &mut Vec<Node<'tree>>) -> Option<()> {
    let mut stack = vec![node];
    while let Some(current) = stack.pop() {
        match current.kind() {
            "identifier" | "namespace_identifier" | "type_identifier" | "operator_name" => {
                out.push(current)
            }
            "qualified_identifier" | "scoped_identifier" => {
                let (scope, name) = qualified_name_parts(current)?;
                stack.push(name);
                if let Some(scope) = scope {
                    stack.push(scope);
                } else if current.child(0).is_none_or(|child| child.kind() != "::") {
                    return None;
                }
            }
            "template_type" | "template_function" => {
                stack.push(current.child_by_field_name("name")?);
            }
            "nested_namespace_specifier" => {
                for index in (0..current.named_child_count()).rev() {
                    stack.push(current.named_child(index)?);
                }
            }
            _ => return None,
        }
    }
    Some(())
}

pub(super) fn qualified_name_parts<'tree>(
    node: Node<'tree>,
) -> Option<(Option<Node<'tree>>, Node<'tree>)> {
    Some((
        node.child_by_field_name("scope"),
        node.child_by_field_name("name")?,
    ))
}

/// Hide grammar-owned comments inside function-like replacements from the
/// primary parser. Otherwise tree-sitter can terminate `preproc_arg` at the
/// comment and read the rest of the directive as surrounding C/C++ code.
/// Replacement analysis still reads the original source and reparses the full
/// logical span; included ranges preserve every original byte coordinate.
/// `tree` must be the unmasked C++ grammar tree for these exact source bytes.
/// A caller can retain that tree only after complete discovery returns `None`.
/// Interrupted discovery never offers a partial set of included ranges.
pub fn function_macro_included_ranges(
    source: &str,
    tree: &tree_sitter::Tree,
    mut should_stop: impl FnMut() -> bool,
) -> ControlFlow<(), Option<Vec<tree_sitter::Range>>> {
    let mut replacements = Vec::new();
    let mut comments = Vec::new();
    let mut stack = vec![tree.root_node()];
    while let Some(node) = stack.pop() {
        if should_stop() {
            return ControlFlow::Break(());
        }
        if let Some(span) = function_macro_replacement_span(node, source) {
            replacements.push(span);
        }
        if node.kind() == "comment" {
            comments.push(node.range());
        }
        push_named_children_reversed(node, &mut stack);
    }
    let mut masked_comments = Vec::new();
    for comment in comments {
        if should_stop() {
            return ControlFlow::Break(());
        }
        for span in &replacements {
            if should_stop() {
                return ControlFlow::Break(());
            }
            if span.start <= comment.start_byte && span.end >= comment.end_byte {
                masked_comments.push(comment);
                break;
            }
        }
    }
    let mut comments = masked_comments;
    if comments.is_empty() {
        return ControlFlow::Continue(None);
    }
    if should_stop() {
        return ControlFlow::Break(());
    }
    comments.sort_by_key(|range| range.start_byte);
    if should_stop() {
        return ControlFlow::Break(());
    }
    let mut included = Vec::new();
    let mut start_byte = 0;
    let mut start_point = tree_sitter::Point::new(0, 0);
    for comment in comments {
        if should_stop() {
            return ControlFlow::Break(());
        }
        if start_byte < comment.start_byte {
            included.push(tree_sitter::Range {
                start_byte,
                end_byte: comment.start_byte,
                start_point,
                end_point: comment.start_point,
            });
        }
        start_byte = comment.end_byte;
        start_point = comment.end_point;
    }
    if start_byte < source.len() {
        included.push(tree_sitter::Range {
            start_byte,
            end_byte: source.len(),
            start_point,
            end_point: tree.root_node().end_position(),
        });
    }
    ControlFlow::Continue(Some(included))
}

#[cfg(test)]
mod tests {
    use brokk_bifrost_test_macros::hardwon;
    #[test]
    #[hardwon(
        "e3c20990a105: quicksilver round 4 on brokk-bifrost-cpp: line splicing split macro field tokens"
    )]
    fn macro_splices_join_tokens() {
        for newline in ["\n", "\r\n"] {
            let source = format!("in\\{newline}t val\\{newline}ue;\\{newline}int after;");
            let replacement = object_macro_replacement(&source);
            assert_eq!(
                replacement
                    .fields
                    .iter()
                    .map(|field| field.name.as_str())
                    .collect::<Vec<_>>(),
                ["value", "after"]
            );
            assert_eq!(
                replacement.fields[0].declaration,
                source[..source.find(';').unwrap() + 1]
            );
            assert_eq!(replacement.fields[1].declaration, "int after;");
            assert_eq!(
                replacement.fields[0].field_type.as_ref().unwrap().type_text,
                "int"
            );
        }
    }

    #[test]
    #[hardwon(
        "e3c20990a105: quicksilver round 4 on brokk-bifrost-cpp: recovered aggregate lost repeated declarators"
    )]
    fn quicksilver_recovered_aggregate_multi_declarators() {
        let source = "int left, right;";
        let fields = recovered_aggregate_fields(source, 0..source.len());
        assert_eq!(
            fields
                .iter()
                .map(|field| field.name.as_str())
                .collect::<Vec<_>>(),
            ["left", "right"]
        );
        for field in fields {
            assert_eq!(field.declaration, source);
            assert_eq!(&source[field.range], source);
            assert_eq!(field.field_type.unwrap().type_text, "int");
        }
    }

    #[test]
    #[hardwon(
        "05fbd05c6bd7: C/C++ macro recovery previously lost or invented structured declarations"
    )]
    fn issue_3089_macro_comments_do_not_consume_caller_function() {
        let source = "#define PROCESS(handle, block) \\\ndo { /* comment */ \\\n  int event; \\\n  if (handle) block \\\n} while (0)\nstatic void caller(int handle) { PROCESS(handle, { event; }); }\n";
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(&tree_sitter_cpp::LANGUAGE.into())
            .unwrap();
        let tree = parser.parse(source, None).unwrap();
        let ranges = super::function_macro_included_ranges(source, &tree, || false)
            .continue_value()
            .expect("complete discovery")
            .expect("macro comments");
        let mut parser = tree_sitter::Parser::new();
        parser
            .set_language(&tree_sitter_cpp::LANGUAGE.into())
            .unwrap();
        parser.set_included_ranges(&ranges).unwrap();
        let tree = parser.parse(source, None).unwrap();
        let mut stack = vec![tree.root_node()];
        let mut functions = Vec::new();
        while let Some(node) = stack.pop() {
            if node.kind() == "function_definition" {
                functions.push(node);
            }
            super::push_named_children_reversed(node, &mut stack);
        }
        assert_eq!(functions.len(), 1, "{}", tree.root_node().to_sexp());
        assert_eq!(
            super::node_text(
                functions[0]
                    .child_by_field_name("declarator")
                    .unwrap()
                    .child_by_field_name("declarator")
                    .unwrap(),
                source
            ),
            "caller"
        );
    }
    use super::*;

    fn references(source: &str) -> Vec<MacroReplacementTypeReference> {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_cpp::LANGUAGE.into())
            .expect("C++ grammar");
        let tree = parser.parse(source, None).expect("macro fixture tree");
        let value = tree
            .root_node()
            .named_child(0)
            .and_then(|definition| definition.child_by_field_name("value"))
            .expect("macro replacement");
        object_macro_replacement_type_references(value, source)
    }

    #[test]
    #[hardwon(
        "3d330d262275: C/C++ macro recovery previously lost or invented structured declarations"
    )]
    fn object_macro_replacement_reparse_preserves_type_ranges() {
        let source = "#define SETTINGS (*api::SettingsImpl::GetInstance())\n";
        let references = references(source);
        let reference = references
            .iter()
            .find(|reference| reference.components == ["api", "SettingsImpl"])
            .expect("qualified callable owner");
        let rendered = reference
            .component_ranges
            .iter()
            .map(|range| &source[range.clone()])
            .collect::<Vec<_>>();
        assert_eq!(rendered, ["api", "SettingsImpl"]);
    }

    #[test]
    #[hardwon(
        "3d77aac19607: C/C++ macro recovery previously lost or invented structured declarations"
    )]
    fn object_macro_replacement_fields_are_structured_and_direct_only() {
        let replacement = object_macro_replacement(
            r#"int public_value; \
             union { int nested_value; }; \
             unsigned private_value;"#,
        );
        assert_eq!(
            replacement.fields,
            vec![
                MacroReplacementField {
                    name: "public_value".to_string(),
                    declaration: "int public_value;".to_string(),
                    field_type: Some(CppDeclaredFieldTypeFact {
                        type_text: "int".to_string(),
                        indirection: 0,
                        binds_indirectly: false,
                        template_arguments: None,
                    }),
                    names_function_type: false,
                },
                MacroReplacementField {
                    name: "private_value".to_string(),
                    declaration: "unsigned private_value;".to_string(),
                    field_type: Some(CppDeclaredFieldTypeFact {
                        type_text: "unsigned".to_string(),
                        indirection: 0,
                        binds_indirectly: false,
                        template_arguments: None,
                    }),
                    names_function_type: false,
                },
            ]
        );
        assert!(replacement.nested.is_empty());
        assert!(object_macro_replacement("not a declaration").is_empty());
    }

    /// libuv's `UV_HANDLE_FIELDS` interleaves `/* public */`-style comments
    /// with its members and ends by composing `UV_HANDLE_PRIVATE_FIELDS`
    /// (issue #2985). tree-sitter ends the `preproc_arg` token, and the
    /// `preproc_def` node with it, at the first of those comments.
    #[test]
    #[hardwon(
        "5e7361a53510: C/C++ macro recovery previously lost or invented structured declarations"
    )]
    fn comment_split_replacement_keeps_every_member_and_its_composition() {
        let source = "#define UV_HANDLE_FIELDS                    \\\n\
                      \x20 /* public */                            \\\n\
                      \x20 void* data;                             \\\n\
                      \x20 /* read-only */                         \\\n\
                      \x20 uv_loop_t* loop;                        \\\n\
                      \x20 UV_HANDLE_PRIVATE_FIELDS                \\\n\
                      \nstruct uv_handle_s { UV_HANDLE_FIELDS };\n";
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_cpp::LANGUAGE.into())
            .expect("C++ grammar");
        let tree = parser.parse(source, None).expect("macro fixture tree");
        let mut stack = vec![tree.root_node()];
        let definition = loop {
            let current = stack.pop().expect("the fixture defines one object macro");
            if current.kind() == "preproc_def" {
                break current;
            }
            let mut cursor = current.walk();
            for child in current.named_children(&mut cursor) {
                stack.push(child);
            }
        };
        let value = definition
            .child_by_field_name("value")
            .expect("truncated replacement token");
        assert_eq!(
            source[value.byte_range()]
                .trim_end()
                .trim_end_matches('\\')
                .trim_end(),
            "void* data;"
        );

        let span = object_macro_replacement_span(definition, source).expect("replacement span");
        let replacement = object_macro_replacement(&source[span]);
        assert_eq!(
            replacement
                .fields
                .iter()
                .map(|field| field.name.as_str())
                .collect::<Vec<_>>(),
            ["data", "loop"]
        );
        assert_eq!(replacement.nested, ["UV_HANDLE_PRIVATE_FIELDS"]);
    }

    #[test]
    #[hardwon(
        "5e7361a53510: C/C++ macro recovery previously lost or invented structured declarations"
    )]
    fn malformed_replacement_regions_still_refuse_the_whole_replacement() {
        assert!(object_macro_replacement("int ok; struct {").is_empty());
    }

    #[test]
    #[hardwon(
        "5e7361a53510: C/C++ macro recovery previously lost or invented structured declarations"
    )]
    fn conflicting_replacements_keep_only_the_members_both_declare() {
        let unix = object_macro_replacement("uv_handle_t* next_closing; unsigned int flags;");
        let windows = object_macro_replacement("uv_handle_t* endgame_next; unsigned int flags;");
        assert_eq!(
            unix.intersect(&windows).fields,
            vec![MacroReplacementField {
                name: "flags".to_string(),
                declaration: "unsigned int flags;".to_string(),
                field_type: Some(CppDeclaredFieldTypeFact {
                    type_text: "unsigned int".to_string(),
                    indirection: 0,
                    binds_indirectly: false,
                    template_arguments: None,
                }),
                names_function_type: false,
            }]
        );
    }

    #[test]
    #[hardwon(
        "5e7361a53510: C/C++ macro recovery previously lost or invented structured declarations"
    )]
    fn collapsed_aggregate_members_recover_their_names_and_ranges() {
        let source = "struct uv_signal_s {\n  UV_HANDLE_FIELDS\n  uv_signal_cb signal_cb;\n};";
        let span = source.find("uv_signal_cb").expect("member start")
            ..source.find("signal_cb;").expect("member end") + "signal_cb;".len();
        let fields = recovered_aggregate_fields(source, span);
        assert_eq!(
            fields
                .iter()
                .map(|field| (field.name.as_str(), field.declaration.as_str()))
                .collect::<Vec<_>>(),
            [("signal_cb", "uv_signal_cb signal_cb;")]
        );
        assert_eq!(&source[fields[0].range.clone()], "uv_signal_cb signal_cb;");
    }

    #[test]
    fn function_macro_comment_boundary_grammar() {
        // Comments touching either replacement boundary must be masked just
        // like interior comments; replacement declarations cannot escape into
        // the containing translation unit.
        for replacement in [
            "/*head*/ int phantom;",
            "int phantom; /*tail*/",
            "int /*middle*/ phantom;",
        ] {
            let source = format!("#define F(){replacement}\nvoid caller() {{ F(); }}\n");
            let mut parser = tree_sitter::Parser::new();
            parser
                .set_language(&tree_sitter_cpp::LANGUAGE.into())
                .unwrap();
            let raw = parser.parse(&source, None).unwrap();
            let ranges = super::function_macro_included_ranges(&source, &raw, || false)
                .continue_value()
                .unwrap()
                .expect("comment masking is required");
            parser.set_included_ranges(&ranges).unwrap();
            let tree = parser.parse(&source, None).unwrap();
            let declarations: Vec<_> = tree
                .root_node()
                .named_children(&mut tree.root_node().walk())
                .map(|n| n.kind())
                .collect();
            assert_eq!(
                declarations,
                ["preproc_function_def", "function_definition"],
                "{source}: {}",
                tree.root_node().to_sexp()
            );
            let caller = tree.root_node().named_child(1).unwrap();
            assert_eq!(&source[caller.byte_range()], "void caller() { F(); }");
        }
    }
}