brokk-bifrost-cpp 0.11.0

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
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 std::ops::Range;
use tree_sitter::{Node, Parser};

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

/// 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,
}

/// 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.
pub fn object_macro_replacement_fields(replacement: &str) -> Vec<MacroReplacementField> {
    if replacement.trim().is_empty() {
        return Vec::new();
    }
    let normalized_replacement = normalize_macro_continuations(replacement);
    const PREFIX: &str = "struct __bifrost_macro_fields { ";
    let synthetic = format!("{PREFIX}{normalized_replacement} }};");
    let mut parser = Parser::new();
    if parser
        .set_language(&tree_sitter_cpp::LANGUAGE.into())
        .is_err()
    {
        return Vec::new();
    }
    let Some(tree) = parser.parse(&synthetic, None) else {
        return Vec::new();
    };
    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 Some(declarator) = declaration
            .child_by_field_name("declarator")
            .or_else(|| declaration.named_child(1))
        else {
            continue;
        };
        let Some(name) = macro_replacement_declarator_name(declarator, &synthetic) else {
            continue;
        };
        let Some(declaration_text) =
            declaration_text_without_synthetic_prefix(declaration, replacement, PREFIX.len())
        else {
            continue;
        };
        fields.push(MacroReplacementField {
            name,
            declaration: declaration_text,
        });
    }
    fields
}

/// Keep preprocessor line continuations as byte-preserving whitespace before
/// reparsing an opaque replacement. The parser's replacement node includes
/// the backslash/newline pair, while C's preprocessing phase treats it as one
/// logical line. Replacing both bytes (and CRLF's three bytes) keeps every
/// tree-sitter byte range mapped directly to the original replacement.
fn normalize_macro_continuations(replacement: &str) -> String {
    let source = replacement.as_bytes();
    let mut normalized = source.to_vec();
    let mut index = 0;
    while index + 1 < source.len() {
        if source[index] == b'\\' && source[index + 1] == b'\n' {
            normalized[index] = b' ';
            normalized[index + 1] = b' ';
            index += 2;
        } else if index + 2 < source.len()
            && source[index] == b'\\'
            && source[index + 1] == b'\r'
            && source[index + 2] == b'\n'
        {
            normalized[index] = b' ';
            normalized[index + 1] = b' ';
            normalized[index + 2] = b' ';
            index += 3;
        } else {
            index += 1;
        }
    }
    String::from_utf8(normalized).expect("source text must remain valid UTF-8")
}

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)),
    }
}

fn declaration_text_without_synthetic_prefix(
    node: Node<'_>,
    source: &str,
    prefix_len: usize,
) -> Option<String> {
    let start = node.start_byte().checked_sub(prefix_len)?;
    let end = node.end_byte().checked_sub(prefix_len)?;
    (end <= source.len()).then(|| source[start..end].to_string())
}

/// 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 synthetic = format!("{PREFIX}{replacement}; }}");
    let mut parser = Parser::new();
    if parser
        .set_language(&tree_sitter_cpp::LANGUAGE.into())
        .is_err()
    {
        return Vec::new();
    }
    let Some(tree) = parser.parse(&synthetic, None) else {
        return Vec::new();
    };
    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 start = component.start_byte().checked_sub(PREFIX.len())?;
                    let end = component.end_byte().checked_sub(PREFIX.len())?;
                    (end <= replacement.len())
                        .then_some(node.start_byte() + start..node.start_byte() + 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);
                }
            }
        }
        for index in (0..current.named_child_count()).rev() {
            if let Some(child) = current.named_child(index) {
                stack.push(child);
            }
        }
    }
    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" => {
                stack.push(current.child_by_field_name("name")?);
                if let Some(scope) = current.child_by_field_name("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(())
}

#[cfg(test)]
mod tests {
    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]
    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]
    fn object_macro_replacement_fields_are_structured_and_direct_only() {
        let fields = object_macro_replacement_fields(
            r#"int public_value; \
             union { int nested_value; }; \
             unsigned private_value;"#,
        );
        assert_eq!(
            fields,
            vec![
                MacroReplacementField {
                    name: "public_value".to_string(),
                    declaration: "int public_value;".to_string(),
                },
                MacroReplacementField {
                    name: "private_value".to_string(),
                    declaration: "unsigned private_value;".to_string(),
                },
            ]
        );
        assert!(object_macro_replacement_fields("not a declaration").is_empty());
    }

    #[test]
    fn macro_reparse_ignores_function_like_and_non_code_text() {
        let function_like = "#define SETTINGS(Type) (*Type::GetInstance())\n";
        assert!(references(function_like).is_empty());

        let text = "#define SETTINGS \"SettingsImpl::GetInstance()\"\n";
        assert!(references(text).is_empty());
    }
}