Skip to main content

brokk_bifrost_cpp/
identity.rs

1//! Which C++ callable is which: declaration/definition roles, the linkage
2//! evidence that unifies a header declaration with its `.cpp` definition, and
3//! the #1134 resolution-time identity reconciliation built on top of both.
4//!
5//! Two things stay in `analyzer/cpp/identity.rs` on purpose:
6//!
7//! * [`cpp_header_body_files_are_related`] here takes the implementation file's
8//!   `#include` lines and the include-target index as arguments. The analysis
9//!   wrapper of the same name owns the `resolve_analyzer::<CppAnalyzer>`
10//!   downcast that produces them, because the searchtools identity block reaches
11//!   this predicate through `&dyn IAnalyzer` and there is no capability that
12//!   carries an `IncludeTargetIndex`.
13//! * The moka cells that memoize [`cpp_reconcile_candidates`] per member
14//!   identifier and [`cpp_reconcile_group`] per [`CppReconcileGroupKey`] stay
15//!   on the analyzer, as does every other cache, so `IAnalyzer::update` keeps
16//!   rebuilding them wholesale.
17
18use crate::declarations::{cpp_file_using_namespaces, cpp_member_fq, node_text};
19use crate::graph::CppGraphSource;
20use crate::graph::resolver::{
21    VisibilityIndex, cpp_type_name_components, declarator_name_node,
22    qualified_name_has_concrete_scope_separators,
23};
24use crate::graph_support::CppSource;
25use crate::imports::{IncludeTargetIndex, include_paths, resolve_include_targets_with_index};
26use crate::reconcile::{ReconciledIdentity, VisibleClass, reconcile_out_of_line_member_identity};
27use brokk_bifrost_core::analyzer::fq_name::{SegmentKind, segment_interner};
28use brokk_bifrost_core::analyzer::model::{CallableLinkage, Range};
29use brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path_fq;
30use brokk_bifrost_core::analyzer::tree_walk::{node_for_exact_range, subtree_contains};
31use brokk_bifrost_core::analyzer::{CodeUnit, CodeUnitIndex, Language, ProjectFile};
32use brokk_bifrost_core::hash::HashMap;
33use brokk_bifrost_core::path_utils::rel_path_string;
34use brokk_bifrost_core::profiling;
35use std::collections::BTreeSet;
36use std::sync::Arc;
37use tree_sitter::{Node, Parser, Tree};
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum CppCallableUnitRole {
41    DeclarationOnly,
42    Definition,
43    Both,
44    Unknown,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum CppOccurrenceRole {
49    DeclarationOnly,
50    Definition,
51    Both,
52    Unknown,
53}
54
55impl CppOccurrenceRole {
56    pub fn api_label(self) -> Option<&'static str> {
57        match self {
58            Self::DeclarationOnly => Some("declaration"),
59            Self::Definition => Some("definition"),
60            Self::Both | Self::Unknown => None,
61        }
62    }
63}
64
65pub struct CppOccurrenceClassifier {
66    tree: Tree,
67}
68
69impl CppOccurrenceClassifier {
70    pub fn new(source: &str) -> Option<Self> {
71        let mut parser = Parser::new();
72        parser
73            .set_language(&tree_sitter_cpp::LANGUAGE.into())
74            .ok()?;
75        parser.parse(source, None).map(|tree| Self { tree })
76    }
77
78    pub fn classify(&self, candidate: &CodeUnit, range: &Range) -> CppOccurrenceRole {
79        cpp_occurrence_role_for_range(self.tree.root_node(), candidate, range)
80    }
81}
82
83pub fn cpp_callable_unit_role(
84    index: &dyn CodeUnitIndex,
85    callable: &CodeUnit,
86) -> CppCallableUnitRole {
87    if !callable.is_callable() {
88        return CppCallableUnitRole::Unknown;
89    }
90    let mut declaration = false;
91    let mut definition = false;
92    for metadata in index.signature_metadata(callable) {
93        if metadata.is_declaration_only() {
94            declaration = true;
95        } else {
96            definition = true;
97        }
98    }
99    match (declaration, definition) {
100        (true, false) => CppCallableUnitRole::DeclarationOnly,
101        (false, true) => CppCallableUnitRole::Definition,
102        (true, true) => CppCallableUnitRole::Both,
103        (false, false) => CppCallableUnitRole::Unknown,
104    }
105}
106
107pub fn cpp_indexed_callable_linkage(
108    index: &dyn CodeUnitIndex,
109    callable: &CodeUnit,
110) -> Option<CallableLinkage> {
111    let mut external = false;
112    for metadata in index.signature_metadata(callable) {
113        match metadata.callable_linkage() {
114            Some(CallableLinkage::Internal) => return Some(CallableLinkage::Internal),
115            Some(CallableLinkage::External) => external = true,
116            None => {}
117        }
118    }
119    external.then_some(CallableLinkage::External)
120}
121
122/// Whether `left` and `right` are the same callable seen twice.
123///
124/// `header_body_related` is the include-evidence predicate; the analysis wrapper
125/// supplies it because reaching an `IncludeTargetIndex` needs the analyzer
126/// downcast this crate cannot perform.
127pub fn cpp_callable_definitions_share_identity_evidence(
128    index: &dyn CodeUnitIndex,
129    left: &CodeUnit,
130    right: &CodeUnit,
131    header_body_related: impl Fn(&ProjectFile, &ProjectFile) -> bool,
132) -> bool {
133    left.source() == right.source()
134        || (left.fq_name() == right.fq_name()
135            && left.signature() == right.signature()
136            && matches!(
137                cpp_indexed_callable_linkage(index, left),
138                Some(CallableLinkage::External)
139            )
140            && matches!(
141                cpp_indexed_callable_linkage(index, right),
142                Some(CallableLinkage::External)
143            )
144            && header_body_related(left.source(), right.source()))
145}
146
147/// The same evidence, with the signature-string conjunct answered by the
148/// resolved parameter comparison instead.
149///
150/// The persisted signature embeds each parameter type exactly as it was
151/// spelled, and a header declaration and its out-of-line body routinely spell
152/// one type two ways - `msg_t *` inside `namespace zmq` against `zmq::msg_t *`
153/// at file scope - so string equality alone refuses to unify the very pair this
154/// predicate exists to unify (#2010). [`VisibilityIndex::same_logical_callable`]
155/// compares the strings first and resolves the written parameter names only
156/// when they differ, so this is strictly the wider relation; every other
157/// conjunct - equal `fq_name`, external linkage on both sides, and the include
158/// evidence relating the two files - is unchanged.
159///
160/// Definition lookup uses this variant. The workspace-scale scans keep the
161/// string form above, where the candidate set is the whole index.
162pub fn cpp_callable_definitions_share_identity_evidence_with_visibility(
163    analyzer: &CppGraphSource<'_>,
164    visibility: &VisibilityIndex<'_>,
165    left: &CodeUnit,
166    right: &CodeUnit,
167    header_body_related: impl Fn(&ProjectFile, &ProjectFile) -> bool,
168) -> bool {
169    left.source() == right.source()
170        || (left.fq_name() == right.fq_name()
171            && visibility.same_logical_callable(analyzer, left, right)
172            && matches!(
173                cpp_indexed_callable_linkage(analyzer.index, left),
174                Some(CallableLinkage::External)
175            )
176            && matches!(
177                cpp_indexed_callable_linkage(analyzer.index, right),
178                Some(CallableLinkage::External)
179            )
180            && header_body_related(left.source(), right.source()))
181}
182
183/// Return whether `node` is one of the names declared by a range-for
184/// declarator. Follow only declarator fields. This keeps identifiers in array
185/// bounds and attributes in the range-for header as references.
186pub fn cpp_is_range_for_binding_name(node: Node<'_>) -> bool {
187    let mut current = Some(node);
188    while let Some(candidate) = current {
189        let Some(parent) = candidate.parent() else {
190            return false;
191        };
192        if parent.kind() == "for_range_loop" {
193            return parent
194                .child_by_field_name("declarator")
195                .is_some_and(|declarator| {
196                    cpp_range_for_declarator_contains_name(declarator, node)
197                });
198        }
199        current = Some(parent);
200    }
201    false
202}
203
204/// Return whether `node` is part of a conversion operator's target type.
205///
206/// A C++ conversion operator has no return type. Its target is part of the
207/// operator declaration identity, so inverse usage analysis deliberately does
208/// not report it as a type reference (#1489). Keep census probes on the same
209/// semantic surface by recognizing only components structurally contained by
210/// tree-sitter's `operator_cast` node. Types used in the function body and
211/// ordinary or overloaded-operator return types never cross that node.
212pub fn cpp_is_conversion_operator_target_type(mut node: Node<'_>) -> bool {
213    while let Some(parent) = node.parent() {
214        if parent.kind() == "operator_cast" {
215            return true;
216        }
217        if matches!(
218            parent.kind(),
219            "function_declarator" | "declaration" | "function_definition" | "translation_unit"
220        ) {
221            return false;
222        }
223        node = parent;
224    }
225    false
226}
227
228/// Return whether `node` is a character token that C++ recovery parsed as an
229/// unnamed parameter type in a class-scope macro invocation.
230///
231/// Tree-sitter does not expand macros. A call such as `STRING_(Name, 'x')`
232/// where declarations are expected can therefore become a malformed function
233/// declaration. Its character argument has an exact CST shape: the opening and
234/// closing quote are separate direct `ERROR` siblings around an otherwise
235/// clean `parameter_declaration(type_identifier)`. That middle identifier is
236/// neither a declaration nor a reference.
237pub fn cpp_is_recovered_macro_character_token_type(node: Node<'_>) -> bool {
238    if node.kind() != "type_identifier" {
239        return false;
240    }
241    let Some(parameter) = node.parent() else {
242        return false;
243    };
244    if parameter.kind() != "parameter_declaration"
245        || parameter.child_by_field_name("type") != Some(node)
246        || parameter.child_by_field_name("declarator").is_some()
247        || parameter
248            .parent()
249            .is_none_or(|parent| parent.kind() != "parameter_list")
250    {
251        return false;
252    }
253
254    parameter
255        .prev_named_sibling()
256        .is_some_and(cpp_is_recovered_character_quote)
257        && parameter
258            .next_named_sibling()
259            .is_some_and(cpp_is_recovered_character_quote)
260}
261
262fn cpp_is_recovered_character_quote(node: Node<'_>) -> bool {
263    node.is_error()
264        && node.child_count() == 1
265        && node
266            .child(0)
267            .is_some_and(|quote| !quote.is_named() && quote.kind() == "'")
268}
269
270/// Return whether `node` is the declarator name of a constructor or destructor
271/// -- the declaration occurrence itself, never a reference to one.
272///
273/// A declaration site is not a usage probe, so the reference differential must
274/// not seed one (#1834). The indexed-declaration-name filter the seeder already
275/// applies misses these two shapes:
276///
277/// * The identifier inside a `destructor_name`. The census proposes both
278///   `~Foo` and its inner `Foo`, while the indexed declaration name range
279///   covers only the `~Foo` span, so the inner identifier survives the filter.
280/// * A declarator the parse never recovered as a declaration. `class MACRO Foo
281///   { ... }` and a bare `MACRO_NAMESPACE_BEGIN` before `class Foo { ... }`
282///   both recover as a `function_definition` whose declarator is a lone
283///   identifier -- a shape valid C++ cannot produce -- with the class body as
284///   its `compound_statement`. Every declaration inside it that the grammar can
285///   read as an expression becomes one, so `Foo();` reads as a call of `Foo`,
286///   which the census then grades as a tier-1 forward gap.
287///
288/// Both tests are structural. Constructor calls stay references: `new Foo(...)`
289/// is a `new_expression` type, `Foo x(...)` is a declaration whose type field
290/// holds the name, and `: base_(x)` is a `field_initializer`. None of them is a
291/// `function_declarator` declarator or a callee inside a recovered class body.
292pub fn cpp_is_constructor_or_destructor_declarator_name(node: Node<'_>, source: &str) -> bool {
293    cpp_is_declared_constructor_or_destructor_name(node)
294        || cpp_is_recovered_constructor_or_destructor_name(node, source)
295}
296
297/// The parsed-as-declared shape: the grammar's `constructor_or_destructor_
298/// declaration` and `constructor_or_destructor_definition`, both aliased to
299/// `declaration`/`function_definition` and both recognizable by the absence of
300/// a `type` field -- exactly what distinguishes a constructor or destructor
301/// from every other C++ callable, which must name a return type.
302fn cpp_is_declared_constructor_or_destructor_name(node: Node<'_>) -> bool {
303    let mut name = node;
304    if let Some(parent) = name.parent()
305        && parent.kind() == "destructor_name"
306    {
307        name = parent;
308    }
309    // `Foo::Foo`, `A::B::Foo` and `Foo<T>::~Foo` reach the declarator through
310    // the qualified name's `name` field. The `scope` segments stay references:
311    // they name the owning type.
312    while let Some(parent) = name.parent() {
313        if parent.kind() != "qualified_identifier"
314            || parent.child_by_field_name("name") != Some(name)
315        {
316            break;
317        }
318        name = parent;
319    }
320    let Some(declarator) = name.parent() else {
321        return false;
322    };
323    if declarator.kind() != "function_declarator"
324        || declarator.child_by_field_name("declarator") != Some(name)
325    {
326        return false;
327    }
328    let Some(owner) = declarator.parent() else {
329        return false;
330    };
331    matches!(owner.kind(), "declaration" | "function_definition")
332        && owner.child_by_field_name("declarator") == Some(declarator)
333        && owner.child_by_field_name("type").is_none()
334}
335
336/// The recovered shape: a callee that names the class whose body the parse
337/// turned into a `compound_statement`.
338///
339/// Two conditions hold together, and both are needed. The nearest enclosing
340/// `function_definition` must declare a bare `identifier` -- valid C++ always
341/// declares a `function_declarator` there, so this shape only ever comes out of
342/// the class-body recovery. And the callee must name one of the identifiers in
343/// that recovery's header, which is where the class name is: `class MACRO Foo`
344/// and `class MACRO Foo : public Base` both keep `Foo` in the header even
345/// though the second leaves `Base` as the recovered declarator.
346///
347/// Together they keep genuine calls references. A recursive `f(n - 1);` sits in
348/// a real body, whose declarator is a `function_declarator`. A method body
349/// inside the recovered class body is itself a real `function_definition`, so
350/// `RAPIDJSON_ASSERT(false)` inside one keeps its own nearest owner. A macro
351/// invocation such as `DISALLOW_COPY_AND_ASSIGN(Foo);` in the recovered body
352/// does not name the class, so it stays proposed.
353fn cpp_is_recovered_constructor_or_destructor_name(node: Node<'_>, source: &str) -> bool {
354    if node.kind() != "identifier" {
355        return false;
356    }
357    let Some(call) = node.parent() else {
358        return false;
359    };
360    if call.kind() != "call_expression" || call.child_by_field_name("function") != Some(node) {
361        return false;
362    }
363    let mut current = call.parent();
364    while let Some(ancestor) = current {
365        if ancestor.kind() == "function_definition" {
366            return ancestor
367                .child_by_field_name("declarator")
368                .is_some_and(|declarator| declarator.kind() == "identifier")
369                && cpp_recovered_class_header_names(ancestor, node_text(node, source), source);
370        }
371        current = ancestor.parent();
372    }
373    false
374}
375
376/// Whether `name` is spelled by an identifier in the recovered class header --
377/// everything the recovery kept before the body it mistook for a function body.
378fn cpp_recovered_class_header_names(definition: Node<'_>, name: &str, source: &str) -> bool {
379    let header_end = definition
380        .child_by_field_name("body")
381        .map_or_else(|| definition.end_byte(), |body| body.start_byte());
382    let mut stack = vec![definition];
383    while let Some(node) = stack.pop() {
384        if node.start_byte() >= header_end {
385            continue;
386        }
387        if matches!(
388            node.kind(),
389            "identifier" | "type_identifier" | "namespace_identifier"
390        ) && node_text(node, source) == name
391        {
392            return true;
393        }
394        let mut cursor = node.walk();
395        for child in node.named_children(&mut cursor) {
396            stack.push(child);
397        }
398    }
399    false
400}
401
402fn cpp_range_for_declarator_contains_name(declarator: Node<'_>, target: Node<'_>) -> bool {
403    let mut pending = vec![declarator];
404    while let Some(candidate) = pending.pop() {
405        match candidate.kind() {
406            "identifier" | "field_identifier" => {
407                if cpp_same_node(candidate, target) {
408                    return true;
409                }
410            }
411            "structured_binding_declarator" => {
412                let mut cursor = candidate.walk();
413                if candidate
414                    .named_children(&mut cursor)
415                    .any(|name| cpp_same_node(name, target))
416                {
417                    return true;
418                }
419            }
420            "pointer_declarator"
421            | "reference_declarator"
422            | "array_declarator"
423            | "attributed_declarator"
424            | "parenthesized_declarator"
425            | "function_declarator"
426            | "init_declarator" => {
427                if let Some(inner) = cpp_range_for_inner_declarator(candidate) {
428                    pending.push(inner);
429                }
430            }
431            _ => {}
432        }
433    }
434    false
435}
436
437fn cpp_range_for_inner_declarator(node: Node<'_>) -> Option<Node<'_>> {
438    node.child_by_field_name("declarator").or_else(|| {
439        let mut cursor = node.walk();
440        node.named_children(&mut cursor).find(|child| {
441            matches!(
442                child.kind(),
443                "identifier"
444                    | "field_identifier"
445                    | "structured_binding_declarator"
446                    | "pointer_declarator"
447                    | "reference_declarator"
448                    | "array_declarator"
449                    | "attributed_declarator"
450                    | "parenthesized_declarator"
451                    | "function_declarator"
452                    | "init_declarator"
453            )
454        })
455    })
456}
457
458fn cpp_same_node(left: Node<'_>, right: Node<'_>) -> bool {
459    left.id() == right.id()
460        && left.start_byte() == right.start_byte()
461        && left.end_byte() == right.end_byte()
462}
463
464/// Direct include evidence relates one header declaration to one implementation
465/// file without pretending that every external name in a workspace belongs to
466/// one linker unit.
467///
468/// `implementation_imports` are that file's raw `#include` lines; the analysis
469/// wrapper reads them off the analyzer along with `include_targets`.
470pub fn cpp_header_body_files_are_related(
471    left: &ProjectFile,
472    right: &ProjectFile,
473    implementation_imports: &[String],
474    include_targets: &IncludeTargetIndex,
475) -> bool {
476    let (header, implementation) = if cpp_source_path_is_header(left) {
477        (left, right)
478    } else if cpp_source_path_is_header(right) {
479        (right, left)
480    } else {
481        return false;
482    };
483    if cpp_source_path_is_header(implementation) {
484        return false;
485    }
486    implementation_imports
487        .iter()
488        .flat_map(|import| include_paths(std::slice::from_ref(import)))
489        .any(|include| {
490            let targets =
491                resolve_include_targets_with_index(implementation, &include, include_targets);
492            targets.len() == 1 && targets.first() == Some(header)
493        })
494}
495
496/// Which of `left`/`right` the include evidence would read as the header, if
497/// either. The analysis wrapper uses this to decide which file's imports to read
498/// before paying for them.
499pub fn cpp_header_body_implementation_file<'a>(
500    left: &'a ProjectFile,
501    right: &'a ProjectFile,
502) -> Option<&'a ProjectFile> {
503    let implementation = if cpp_source_path_is_header(left) {
504        right
505    } else if cpp_source_path_is_header(right) {
506        left
507    } else {
508        return None;
509    };
510    (!cpp_source_path_is_header(implementation)).then_some(implementation)
511}
512
513pub fn cpp_source_path_is_header(source: &ProjectFile) -> bool {
514    let path = rel_path_string(source).to_ascii_lowercase();
515    matches!(
516        path.rsplit('.').next(),
517        Some("h" | "hin" | "hh" | "hpp" | "hxx")
518    )
519}
520
521pub fn cpp_occurrence_role_for_range(
522    root: Node<'_>,
523    candidate: &CodeUnit,
524    range: &Range,
525) -> CppOccurrenceRole {
526    if !candidate.is_callable() && !candidate.is_class() {
527        return CppOccurrenceRole::Both;
528    }
529    let Some(node) = cpp_declaration_node_for_range(root, range) else {
530        return CppOccurrenceRole::Unknown;
531    };
532    if candidate.is_callable() {
533        return if subtree_contains(node, |descendant| {
534            descendant.kind() == "function_definition"
535                && descendant.child_by_field_name("body").is_some()
536        }) {
537            CppOccurrenceRole::Definition
538        } else {
539            CppOccurrenceRole::DeclarationOnly
540        };
541    }
542    if node.kind() == "function_definition" && node.child_by_field_name("body").is_some() {
543        return CppOccurrenceRole::Definition;
544    }
545    if !subtree_contains(node, |descendant| {
546        matches!(
547            descendant.kind(),
548            "class_specifier" | "struct_specifier" | "union_specifier" | "enum_specifier"
549        )
550    }) {
551        return CppOccurrenceRole::Both;
552    }
553    if subtree_contains(node, |descendant| {
554        matches!(
555            descendant.kind(),
556            "class_specifier" | "struct_specifier" | "union_specifier" | "enum_specifier"
557        ) && descendant.child_by_field_name("body").is_some()
558    }) {
559        CppOccurrenceRole::Definition
560    } else {
561        CppOccurrenceRole::DeclarationOnly
562    }
563}
564
565fn cpp_declaration_node_for_range<'tree>(root: Node<'tree>, range: &Range) -> Option<Node<'tree>> {
566    node_for_exact_range(root, range).or_else(|| {
567        root.descendant_for_byte_range(range.start_byte, range.end_byte)
568            .and_then(|mut node| {
569                while node.start_byte() > range.start_byte || node.end_byte() < range.end_byte {
570                    node = node.parent()?;
571                }
572                Some(node)
573            })
574    })
575}
576
577/// The #1134 resolution-time identity-reconciliation overlay for one queried
578/// canonical `fq_name`.
579///
580/// For each out-of-line member definition whose per-file provisional identity
581/// the include-visible class table re-keys to this name, it holds a *re-keyed*
582/// `CodeUnit` -- a synthetic unit carrying the canonical identity but the
583/// definition's real `.cpp` source -- so a canonical query resolves the
584/// definition alongside its header declaration across every resolution surface
585/// (`definitions`, source blocks, occurrence roles, canonical selectors). The
586/// re-keyed unit is not in the store, so `provisional_of` maps it back to the
587/// stored provisional unit for range and signature-metadata lookups.
588#[derive(Default)]
589pub struct CppReconciledDefinitionIndex {
590    /// Re-keyed definitions belonging under the queried canonical `fq_name`.
591    pub rekeyed: Vec<CodeUnit>,
592    /// Re-keyed unit -> the stored provisional unit its indexed data lives under.
593    pub provisional_of: HashMap<CodeUnit, CodeUnit>,
594}
595
596/// Which candidates one reconcile group covers: a member identifier, and the
597/// terminal owner component that #1566's pre-filter admits.
598///
599/// This -- not the queried fq name -- is the unit reconciliation is a function
600/// of, and keying the memo by it is the #1908 fix. The old key was the queried
601/// fq name, so a bare identifier that 1,277 distinct owners answer produced
602/// 1,277 distinct keys, none of which ever hit, each re-running the identical
603/// `lookup_candidates_by_identifier` store read and re-scanning the identical
604/// 2,898-candidate set: 3.70M candidate evaluations for one request.
605///
606/// The owner terminal stays in the key rather than being dropped for a plain
607/// per-identifier map. Dropping it would mean reconciling every same-named
608/// candidate in the workspace on the first query for that identifier, which is
609/// exactly the cost #1566 removed -- chromium paid ~75 s per member query that
610/// way. `reconcile_skips_same_named_members_of_unrelated_classes_1566` pins it.
611#[derive(Debug, Clone, PartialEq, Eq, Hash)]
612pub struct CppReconcileGroupKey {
613    /// The queried name's terminal segment: the member identifier the
614    /// persisted identifier index is probed with.
615    pub member_identifier: String,
616    /// The terminal component of the queried name's penultimate segment, or
617    /// `None` for a single-segment (bare) query, where #1566's pre-filter is
618    /// inert and every candidate has to be reconciled.
619    pub owner_terminal: Option<String>,
620}
621
622/// Which member identifier and owner terminal a queried canonical name asks
623/// about, or `None` when the name has no terminal segment to probe with.
624///
625/// Parsed through the sanctioned input-edge parser rather than split here, and
626/// note `$` is not a segment boundary for it -- a nested owner chain stays one
627/// segment, so the terminal really is the member.
628pub fn cpp_reconcile_group_key(fq_name: &str) -> Option<CppReconcileGroupKey> {
629    let interner = segment_interner();
630    let query_fq = parse_symbol_path_fq(Language::Cpp, fq_name, interner);
631    let (member_identifier, _) = interner.resolve(query_fq.last()?);
632    if member_identifier.is_empty() {
633        return None;
634    }
635    // #1566 owner-terminal pre-filter: the reconciler only re-partitions a
636    // candidate's qualifier -- the class chain it emits is always a suffix
637    // of the candidate's owner segments (`reconcile.rs`) -- so the terminal
638    // `$` component of any identity it can produce equals the candidate's
639    // terminal owner segment. A candidate whose terminal owner differs
640    // from the queried name's penultimate segment can therefore never
641    // re-key onto it, and skipping it avoids the role check and, on
642    // whale repos, an include-closure class-table build per same-named
643    // candidate in the repo.
644    let owner_terminal = query_fq.segments().len().checked_sub(2).map(|penultimate| {
645        let (text, _) = interner.resolve(query_fq.segments()[penultimate]);
646        // fqname-M4: the input-edge parser above deliberately keeps a nested
647        // owner chain as one `$`-joined segment (no structured sub-segments
648        // exist at this surface), so the terminal component must come from
649        // the raw text.
650        text.rsplit_once('$')
651            .map_or(text, |(_, tail)| tail)
652            .to_string()
653    });
654    Some(CppReconcileGroupKey {
655        member_identifier: member_identifier.to_string(),
656        owner_terminal,
657    })
658}
659
660/// Every callable declaration in the workspace sharing one member identifier,
661/// bucketed by its terminal owner segment.
662///
663/// One store read and one pass over the candidate set per identifier, memoized
664/// on the analyzer. Before #1908 both were re-run once per queried fq name.
665pub struct CppReconcileCandidates {
666    by_owner_terminal: HashMap<String, Vec<CodeUnit>>,
667    /// Every bucketed candidate, in the order the sorted candidate set
668    /// produced them. What a bare query has to reconcile, since #1566's
669    /// pre-filter cannot narrow it.
670    all: Vec<CodeUnit>,
671}
672
673impl CppReconcileCandidates {
674    /// The candidates a group key admits: one owner-terminal bucket, or every
675    /// candidate for a bare query.
676    fn for_group(&self, key: &CppReconcileGroupKey) -> &[CodeUnit] {
677        match &key.owner_terminal {
678            Some(owner_terminal) => self
679                .by_owner_terminal
680                .get(owner_terminal)
681                .map_or(&[][..], Vec::as_slice),
682            None => &self.all,
683        }
684    }
685
686    /// Every bucketed candidate, once. What a cache weigher has to charge for.
687    pub fn iter(&self) -> impl Iterator<Item = &CodeUnit> {
688        self.all.iter()
689    }
690
691    /// How many bucket entries reference those candidates. A candidate with no
692    /// owner segment is in no bucket, so this is not `len`.
693    pub fn bucketed_len(&self) -> usize {
694        self.by_owner_terminal.values().map(Vec::len).sum()
695    }
696}
697
698/// Read and bucket every callable declaration sharing `member_identifier`.
699///
700/// `keep_going` is polled per candidate batch; `None` means the caller's
701/// deadline expired and nothing may be memoized, because a truncated candidate
702/// set is indistinguishable from an identifier with fewer namesakes and every
703/// later reconcile reading it would silently lose definitions (#1908 fix D,
704/// the same contract `visible_type_units_while` carries).
705pub fn cpp_reconcile_candidates(
706    cpp: &dyn CppSource,
707    member_identifier: &str,
708    keep_going: &dyn Fn() -> bool,
709) -> Option<CppReconcileCandidates> {
710    let candidates: BTreeSet<CodeUnit> = {
711        let _lookup =
712            profiling::scope_with(|| format!("cpp.reconcile.lookup[{member_identifier}]"));
713        cpp.lookup_candidates_by_identifier(member_identifier)
714    };
715    profiling::note_with(|| {
716        format!(
717            "cpp.reconcile.candidates[{member_identifier}] n={}",
718            candidates.len()
719        )
720    });
721
722    let interner = segment_interner();
723    let mut by_owner_terminal: HashMap<String, Vec<CodeUnit>> = HashMap::default();
724    let mut all = Vec::new();
725    for (index, unit) in candidates.into_iter().enumerate() {
726        // Bucketing is a segment walk per candidate, cheap next to the role
727        // check and class-table build the groups pay, so the poll runs per
728        // batch rather than per candidate.
729        if index % CANDIDATE_BUCKETING_POLL_STRIDE == 0 && !keep_going() {
730            return None;
731        }
732        if !unit.is_callable() {
733            continue;
734        }
735        let owner_terminal = unit
736            .fq()
737            .segments()
738            .iter()
739            .filter_map(|&segment| {
740                let (text, kind) = interner.resolve(segment);
741                // Candidate fq segments carry real boundaries (each nested
742                // class is its own `SegmentKind::Nested` segment), so the
743                // segment text is already the terminal component.
744                matches!(
745                    kind,
746                    SegmentKind::Package | SegmentKind::Type | SegmentKind::Nested
747                )
748                .then_some(text)
749            })
750            .last();
751        if let Some(owner_terminal) = owner_terminal {
752            by_owner_terminal
753                .entry(owner_terminal.to_string())
754                .or_default()
755                .push(unit.clone());
756        }
757        all.push(unit);
758    }
759    Some(CppReconcileCandidates {
760        by_owner_terminal,
761        all,
762    })
763}
764
765/// How many candidates the bucketing pass walks between deadline polls.
766const CANDIDATE_BUCKETING_POLL_STRIDE: usize = 256;
767
768/// Reconcile every candidate one group key admits, grouped by the canonical
769/// `fq_name` each re-keyed definition belongs under.
770///
771/// Deliberately **not** a workspace-wide index: building one would need a full
772/// declaration scan, and a warm forward lookup must not trigger one
773/// (`tests/analyzer_persistence.rs`'s candidate-bounded contract). Instead each
774/// group reconciles only the candidates the persisted terminal identifier
775/// index already offers, which is the same bounded lookup the ordinary
776/// resolution path uses.
777///
778/// A definition whose reconciled identity equals its provisional one (the
779/// overwhelming majority, including genuine `ns1::ns2::Klass::method` namespace
780/// chains) contributes nothing.
781///
782/// `None` means `keep_going` went false mid-scan. Nothing may be memoized
783/// then; see [`cpp_reconcile_candidates`].
784pub fn cpp_reconcile_group(
785    cpp: &dyn CppSource,
786    key: &CppReconcileGroupKey,
787    candidates: &CppReconcileCandidates,
788    keep_going: &dyn Fn() -> bool,
789    on_candidate: &dyn Fn(),
790) -> Option<HashMap<String, Arc<CppReconciledDefinitionIndex>>> {
791    let _scope = profiling::scope_with(|| {
792        format!(
793            "cpp.reconciled.build[{}#{}]",
794            key.member_identifier,
795            key.owner_terminal.as_deref().unwrap_or("*")
796        )
797    });
798    let mut groups: HashMap<String, CppReconciledDefinitionIndex> = HashMap::default();
799    let mut using_by_file: HashMap<ProjectFile, Arc<Vec<String>>> = HashMap::default();
800    for unit in candidates.for_group(key) {
801        // Per candidate, not per batch: each iteration below can run a role
802        // check (0.265 ms mean in the #1908 trace) and an include-visible
803        // class-table read, so an atomic load per iteration is free by
804        // comparison.
805        if !keep_going() {
806            return None;
807        }
808        on_candidate();
809        // Lazy: `fq_name` clones a String, and this loop runs once per
810        // same-named candidate the group admits.
811        let _candidate =
812            profiling::scope_with(|| format!("cpp.reconcile.candidate[{}]", unit.fq_name()));
813        let role = {
814            let _role = profiling::scope("cpp.reconcile.role");
815            cpp_callable_unit_role(cpp, unit)
816        };
817        if !matches!(
818            role,
819            CppCallableUnitRole::Definition | CppCallableUnitRole::Both
820        ) {
821            continue;
822        }
823        let Some(reconciled) = cpp_reconcile_definition_identity(cpp, unit, &mut using_by_file)
824        else {
825            continue;
826        };
827        let canonical_fq = reconciled.fq_name();
828        // A candidate that already carries the canonical identity is the
829        // stored declaration, not a re-keying of it. Before #1908 this read
830        // `unit.fq_name() == fq_name` against the queried name, checked before
831        // the reconcile; against the group's canonical key it is the same
832        // predicate for the same (query, candidate) pair, because a candidate
833        // only ever lands under its own reconciled identity.
834        if unit.fq_name() == canonical_fq {
835            continue;
836        }
837        // Re-key onto the canonical identity while keeping the definition's
838        // real `.cpp` source and signature, so it resolves as a definition
839        // alongside its header declaration under the canonical `fq_name`.
840        // The structured `FqName` is rebuilt from the *canonical* package and
841        // owner chain through the same emission helper extraction uses, so
842        // the re-keyed unit carries real segment boundaries: owner lookup
843        // (`default_parent_fq_name`) is a pure segment pop, where an empty
844        // `fq` would mean "no owner" rather than "not yet migrated".
845        let short_name = format!("{}.{}", reconciled.owner_chain, reconciled.member);
846        let fq = cpp_member_fq(&reconciled.package, &short_name);
847        let rekeyed = CodeUnit::with_signature_and_fq(
848            unit.source().clone(),
849            unit.kind(),
850            reconciled.package,
851            short_name,
852            unit.signature().map(str::to_string),
853            unit.is_synthetic(),
854            fq,
855        );
856        let index = groups.entry(canonical_fq).or_default();
857        index.rekeyed.push(rekeyed.clone());
858        index.provisional_of.insert(rekeyed, unit.clone());
859    }
860    Some(
861        groups
862            .into_iter()
863            .map(|(canonical_fq, index)| (canonical_fq, Arc::new(index)))
864            .collect(),
865    )
866}
867
868/// Reconcile one out-of-line member definition's provisional identity against
869/// the class table visible to its file. Returns `None` for anything that is
870/// not a re-keyable out-of-line member or that the class table does not
871/// confirm. A one-segment class qualifier is valid when a structured using
872/// namespace and the visible class table confirm its package.
873fn cpp_reconcile_definition_identity(
874    cpp: &dyn CppSource,
875    unit: &CodeUnit,
876    using_by_file: &mut HashMap<ProjectFile, Arc<Vec<String>>>,
877) -> Option<ReconciledIdentity> {
878    // Read the full source-order qualifier off the definition's *structured*
879    // `FqName` -- the namespace (`Package`) segments followed by the
880    // class-nesting (`Type`/`Nested`) ones, with the terminal `Member` as the
881    // member name. The segment boundaries were recorded at extraction, so
882    // nothing here re-infers them by splitting the rendered name on a guessed
883    // delimiter (the shape `tests/no_stringly_name_parsing.rs` guards). The
884    // reconciler then re-partitions this whole sequence against the class
885    // table, so extraction need not have decided where the namespace ends and
886    // the class chain begins.
887    let interner = segment_interner();
888    let mut provisional_owner_segments: Vec<&str> = Vec::new();
889    let mut member: Option<&str> = None;
890    for &segment in unit.fq().segments() {
891        let (text, kind) = interner.resolve(segment);
892        match kind {
893            SegmentKind::Package | SegmentKind::Type | SegmentKind::Nested => {
894                // A `Member` is always terminal in a cpp callable's chain; a
895                // qualifier segment after one would mean the identity is not
896                // the plain `namespace... class... member` shape this handles.
897                if member.is_some() {
898                    return None;
899                }
900                if !text.is_empty() {
901                    provisional_owner_segments.push(text);
902                }
903            }
904            SegmentKind::Member => member = Some(text),
905            _ => return None,
906        }
907    }
908    let member = member?;
909    // Existing multi-segment reconciliation uses the provisional structured
910    // FqName because it preserves template-owner normalization. Read the
911    // declarator only for the previously unsupported one-segment shape, where
912    // extraction can prepend a guessed using namespace.
913    let structured_owner_segments =
914        cpp_structured_out_of_line_owner_segments(cpp, unit).filter(|segments| segments.len() == 1);
915    let owner_segments = structured_owner_segments.as_ref().map_or_else(
916        || provisional_owner_segments,
917        |segments| segments.iter().map(String::as_str).collect(),
918    );
919    if owner_segments.is_empty() {
920        return None;
921    }
922
923    let using = using_by_file
924        .entry(unit.source().clone())
925        .or_insert_with(|| {
926            Arc::new(
927                cpp.file_source(unit.source())
928                    .map(|source| cpp_file_using_namespaces(&source))
929                    .unwrap_or_default(),
930            )
931        })
932        .clone();
933    let mut namespace_candidates: Vec<&str> = vec![""];
934    namespace_candidates.extend(using.iter().map(String::as_str));
935
936    let visible = {
937        let _visible = profiling::scope_with(|| {
938            format!("cpp.reconcile.visible[{}]", rel_path_string(unit.source()))
939        });
940        cpp.visible_type_units(unit.source())
941    };
942    let class_table: Vec<VisibleClass> = visible
943        .iter()
944        .filter(|candidate| candidate.is_class())
945        .map(|candidate| VisibleClass {
946            package: candidate.package_name(),
947            nested_short_name: candidate.short_name(),
948        })
949        .collect();
950
951    reconcile_out_of_line_member_identity(
952        &owner_segments,
953        member,
954        &namespace_candidates,
955        &class_table,
956    )
957}
958
959/// Read the owner qualifier from the definition declarator itself.
960///
961/// Per-file extraction can prepend one guessed using namespace to a bare
962/// `Class::member` definition. That provisional package is not source syntax.
963/// Reconciliation must compare the real qualifier against every structured
964/// using target and let the visible class table select the namespace.
965fn cpp_structured_out_of_line_owner_segments(
966    cpp: &dyn CppSource,
967    unit: &CodeUnit,
968) -> Option<Vec<String>> {
969    let prepared = cpp.prepared_syntax(unit.source())?;
970    let root = prepared.tree().root_node();
971    for range in cpp.ranges(unit) {
972        let mut current = cpp_declaration_node_for_range(root, &range)?;
973        let function = loop {
974            if current.kind() == "function_definition" {
975                break current;
976            }
977            current = current.parent()?;
978        };
979        if function.child_by_field_name("body").is_none() {
980            continue;
981        }
982        let declarator = function.child_by_field_name("declarator")?;
983        let name = declarator_name_node(declarator)?;
984        if !qualified_name_has_concrete_scope_separators(name) {
985            continue;
986        }
987        let mut components = cpp_type_name_components(name, prepared.source())?;
988        components.pop()?;
989        if !components.is_empty() {
990            return Some(components);
991        }
992    }
993    None
994}
995
996#[cfg(test)]
997mod tests {
998    use super::*;
999
1000    fn parse_cpp(source: &str) -> Tree {
1001        let mut parser = Parser::new();
1002        parser
1003            .set_language(&tree_sitter_cpp::LANGUAGE.into())
1004            .expect("cpp language");
1005        parser.parse(source, None).expect("cpp tree")
1006    }
1007
1008    fn is_declarator_name(tree: &Tree, source: &str, start: usize, text: &str) -> bool {
1009        let end = start + text.len();
1010        assert_eq!(&source[start..end], text, "the probe must name the token");
1011        let node = tree
1012            .root_node()
1013            .named_descendant_for_byte_range(start, end)
1014            .expect("a node spans the probed range");
1015        assert_eq!(
1016            (node.start_byte(), node.end_byte()),
1017            (start, end),
1018            "the probed range must be exactly one node: {}",
1019            node.to_sexp()
1020        );
1021        cpp_is_constructor_or_destructor_declarator_name(node, source)
1022    }
1023
1024    fn is_conversion_target(tree: &Tree, source: &str, start: usize, text: &str) -> bool {
1025        let end = start + text.len();
1026        assert_eq!(&source[start..end], text, "the probe must name the token");
1027        let node = tree
1028            .root_node()
1029            .named_descendant_for_byte_range(start, end)
1030            .expect("a node spans the probed range");
1031        assert_eq!(
1032            (node.start_byte(), node.end_byte()),
1033            (start, end),
1034            "the probed range must be exactly one node: {}",
1035            node.to_sexp()
1036        );
1037        cpp_is_conversion_operator_target_type(node)
1038    }
1039
1040    fn is_recovered_macro_character_type(
1041        tree: &Tree,
1042        source: &str,
1043        start: usize,
1044        text: &str,
1045    ) -> bool {
1046        let end = start + text.len();
1047        assert_eq!(&source[start..end], text, "the probe must name the token");
1048        let node = tree
1049            .root_node()
1050            .named_descendant_for_byte_range(start, end)
1051            .expect("a node spans the probed range");
1052        cpp_is_recovered_macro_character_token_type(node)
1053    }
1054
1055    #[test]
1056    fn recovered_macro_character_tokens_are_not_type_references() {
1057        let source = concat!(
1058            "struct I {};\n",
1059            "#define STRING_TOKEN_(name, ...)\n",
1060            "struct Schema {\n",
1061            "  STRING_TOKEN_(MaxItems, 'm', 'I')\n",
1062            "  void ordinary(I value);\n",
1063            "  void malformed(I value, @);\n",
1064            "  void use() { I value; consume('I'); }\n",
1065            "};\n",
1066        );
1067        let tree = parse_cpp(source);
1068        let recovered_m = source.find("'m'").expect("recovered m") + 1;
1069        let recovered_i = source.find("'I'").expect("recovered I") + 1;
1070        for (label, start, text) in [
1071            ("lowercase character token", recovered_m, "m"),
1072            ("uppercase character token", recovered_i, "I"),
1073        ] {
1074            assert!(
1075                is_recovered_macro_character_type(&tree, source, start, text),
1076                "{label} must match the exact recovery role"
1077            );
1078        }
1079
1080        let macro_first_argument = source.find("MaxItems").expect("macro first argument");
1081        let ordinary = source.find("ordinary(I").expect("ordinary parameter") + "ordinary(".len();
1082        let malformed =
1083            source.find("malformed(I").expect("malformed parameter") + "malformed(".len();
1084        let local = source
1085            .find("I value; consume")
1086            .expect("local type reference");
1087        let expression_character = source.rfind("'I'").expect("expression character") + 1;
1088        for (label, start, text) in [
1089            ("unquoted macro argument", macro_first_argument, "MaxItems"),
1090            ("ordinary parameter type", ordinary, "I"),
1091            ("parameter beside another error", malformed, "I"),
1092            ("local type reference", local, "I"),
1093            ("expression character literal", expression_character, "I"),
1094        ] {
1095            assert!(
1096                !is_recovered_macro_character_type(&tree, source, start, text),
1097                "{label} must remain outside the recovery role"
1098            );
1099        }
1100    }
1101
1102    #[test]
1103    fn conversion_operator_target_components_are_identity_syntax_only() {
1104        let source = concat!(
1105            "namespace other { struct Target {}; template<class T> struct Box {}; }\n",
1106            "using other::Target;\n",
1107            "struct Source {\n",
1108            "  operator Target() const;\n",
1109            "  operator other::Target() const { return other::Target{}; }\n",
1110            "  template<class T> operator other::Box<T>() const { return {}; }\n",
1111            "  operator other::Target const&() const;\n",
1112            "  operator other::Target*() const;\n",
1113            "  other::Target ordinary() const {\n",
1114            "    return reinterpret_cast<other::Target&>(*this);\n",
1115            "  }\n",
1116            "  other::Target operator+() const { return {}; }\n",
1117            "};\n",
1118        );
1119        let tree = parse_cpp(source);
1120
1121        let bare = source.find("operator Target").expect("bare target") + "operator ".len();
1122        let qualified = source
1123            .find("operator other::Target()")
1124            .expect("qualified target")
1125            + "operator ".len();
1126        let template = source
1127            .find("operator other::Box<T>")
1128            .expect("template target")
1129            + "operator ".len();
1130        let cv_reference = source
1131            .find("operator other::Target const&")
1132            .expect("cv-reference target")
1133            + "operator other::".len();
1134        let pointer = source
1135            .find("operator other::Target*")
1136            .expect("pointer target")
1137            + "operator other::".len();
1138
1139        for (label, start, text) in [
1140            ("bare target", bare, "Target"),
1141            ("qualified target scope", qualified, "other"),
1142            (
1143                "qualified target name",
1144                qualified + "other::".len(),
1145                "Target",
1146            ),
1147            ("template target scope", template, "other"),
1148            ("template target name", template + "other::".len(), "Box"),
1149            (
1150                "template target argument",
1151                template + "other::Box<".len(),
1152                "T",
1153            ),
1154            ("cv-reference target", cv_reference, "Target"),
1155            ("pointer target", pointer, "Target"),
1156        ] {
1157            assert!(
1158                is_conversion_target(&tree, source, start, text),
1159                "the {label} at byte {start} belongs to the conversion identity"
1160            );
1161        }
1162
1163        let ordinary_return = source
1164            .find("other::Target ordinary")
1165            .expect("ordinary return");
1166        let body_cast = source
1167            .find("reinterpret_cast<other::Target")
1168            .expect("body cast")
1169            + "reinterpret_cast<".len();
1170        let overloaded_return = source
1171            .find("other::Target operator+")
1172            .expect("overloaded operator return");
1173        for (label, start) in [
1174            ("ordinary return type", ordinary_return),
1175            ("body cast target", body_cast),
1176            ("overloaded-operator return type", overloaded_return),
1177        ] {
1178            assert!(
1179                !is_conversion_target(&tree, source, start, "other"),
1180                "the {label} at byte {start} stays a reference"
1181            );
1182        }
1183    }
1184
1185    /// The parsed-as-declared shape, in class and out of line. The names that
1186    /// surround a declarator stay references: the owning scope of an out-of-line
1187    /// definition, a parameter type that happens to be the class, and the class
1188    /// name itself.
1189    #[test]
1190    fn declared_constructor_and_destructor_declarator_names_are_not_references() {
1191        let source = concat!(
1192            "class Foo {\n",
1193            "public:\n",
1194            "  Foo();\n",
1195            "  Foo(const Foo&);\n",
1196            "  ~Foo();\n",
1197            "  void m();\n",
1198            "};\n",
1199            "Foo::Foo() {}\n",
1200            "Foo::~Foo() {}\n",
1201            "void Foo::m() {}\n",
1202        );
1203        let tree = parse_cpp(source);
1204
1205        for (label, start, text) in [
1206            (
1207                "constructor declaration",
1208                source.find("Foo();").expect("ctor"),
1209                "Foo",
1210            ),
1211            (
1212                "copy constructor declaration",
1213                source.find("Foo(const Foo&);").expect("copy ctor"),
1214                "Foo",
1215            ),
1216            (
1217                "destructor name",
1218                source.find("~Foo();").expect("dtor"),
1219                "~Foo",
1220            ),
1221            (
1222                "identifier inside the destructor name",
1223                source.find("~Foo();").expect("dtor") + "~".len(),
1224                "Foo",
1225            ),
1226            (
1227                "out-of-line constructor definition name",
1228                source.find("Foo::Foo() {}").expect("out-of-line ctor") + "Foo::".len(),
1229                "Foo",
1230            ),
1231            (
1232                "out-of-line destructor definition name",
1233                source.find("Foo::~Foo() {}").expect("out-of-line dtor") + "Foo::".len(),
1234                "~Foo",
1235            ),
1236        ] {
1237            assert!(
1238                is_declarator_name(&tree, source, start, text),
1239                "the {label} at byte {start} is a declaration occurrence"
1240            );
1241        }
1242
1243        for (label, start, text) in [
1244            (
1245                "class name",
1246                source.find("class Foo {").expect("class") + "class ".len(),
1247                "Foo",
1248            ),
1249            (
1250                "parameter type",
1251                source.find("const Foo&").expect("parameter type") + "const ".len(),
1252                "Foo",
1253            ),
1254            (
1255                "owning scope of an out-of-line constructor",
1256                source.find("Foo::Foo() {}").expect("out-of-line ctor"),
1257                "Foo",
1258            ),
1259            (
1260                "owning scope of an out-of-line destructor",
1261                source.find("Foo::~Foo() {}").expect("out-of-line dtor"),
1262                "Foo",
1263            ),
1264            (
1265                "out-of-line method name",
1266                source.find("void Foo::m() {}").expect("out-of-line method") + "void Foo::".len(),
1267                "m",
1268            ),
1269        ] {
1270            assert!(
1271                !is_declarator_name(&tree, source, start, text),
1272                "the {label} at byte {start} stays a reference"
1273            );
1274        }
1275    }
1276
1277    /// Constructor CALL sites are references. `new D(...)`, the direct
1278    /// initialization `D x(...)`, a member initializer and a bare temporary
1279    /// statement all name the type, and none of them is a declarator.
1280    #[test]
1281    fn constructor_call_sites_stay_references() {
1282        let source = concat!(
1283            "struct B { B(int); };\n",
1284            "struct D : B {\n",
1285            "  D(int x) : B(x), base_(x) {}\n",
1286            "  int base_;\n",
1287            "};\n",
1288            "void g() {\n",
1289            "  D* p = new D(1);\n",
1290            "  D x(2);\n",
1291            "  D(3);\n",
1292            "  g();\n",
1293            "}\n",
1294        );
1295        let tree = parse_cpp(source);
1296
1297        let inline_declarator = source.find("D(int x)").expect("inline constructor");
1298        assert!(
1299            is_declarator_name(&tree, source, inline_declarator, "D"),
1300            "an inline constructor definition name is still a declarator"
1301        );
1302
1303        for (label, start, text) in [
1304            (
1305                "base member initializer",
1306                source.find(": B(x)").expect("base initializer") + ": ".len(),
1307                "B",
1308            ),
1309            (
1310                "field member initializer",
1311                source.find("base_(x) {}").expect("field initializer"),
1312                "base_",
1313            ),
1314            (
1315                "new expression type",
1316                source.find("new D(1)").expect("new expression") + "new ".len(),
1317                "D",
1318            ),
1319            (
1320                "direct initialization type",
1321                source.find("D x(2)").expect("direct initialization"),
1322                "D",
1323            ),
1324            (
1325                "temporary construction statement",
1326                source.find("D(3)").expect("temporary"),
1327                "D",
1328            ),
1329            (
1330                "recursive call in a real body",
1331                source.find("g();").expect("recursive call"),
1332                "g",
1333            ),
1334        ] {
1335            assert!(
1336                !is_declarator_name(&tree, source, start, text),
1337                "the {label} at byte {start} is a reference"
1338            );
1339        }
1340    }
1341
1342    /// The recovered shape (#1834): an export macro between `class` and the
1343    /// class name makes the parse read the class body as a function body and
1344    /// every constructor declaration in it as a call of the class's own name.
1345    /// The bodies the recovery left intact keep their references.
1346    #[test]
1347    fn a_constructor_declarator_the_parse_read_as_a_call_is_not_a_reference() {
1348        let source = concat!(
1349            "class SAMPLE_EXPORT Properties {\n",
1350            "  public:\n",
1351            "    Properties();\n",
1352            "    DISALLOW_COPY_AND_ASSIGN(Properties);\n",
1353            "    int size() const;\n",
1354            "    int total() { return size(); }\n",
1355            "};\n",
1356        );
1357        let tree = parse_cpp(source);
1358
1359        let recovered = source.find("Properties();").expect("recovered constructor");
1360        assert!(
1361            is_declarator_name(&tree, source, recovered, "Properties"),
1362            "a constructor declaration the parse read as a call is still a declarator"
1363        );
1364
1365        for (label, start, text) in [
1366            (
1367                "class name in the recovered header",
1368                source
1369                    .find("class SAMPLE_EXPORT Properties")
1370                    .expect("class")
1371                    + "class SAMPLE_EXPORT ".len(),
1372                "Properties",
1373            ),
1374            (
1375                "macro invocation in the recovered body",
1376                source
1377                    .find("DISALLOW_COPY_AND_ASSIGN(Properties);")
1378                    .expect("macro invocation"),
1379                "DISALLOW_COPY_AND_ASSIGN",
1380            ),
1381            (
1382                "call inside a method body the recovery kept",
1383                source.find("return size();").expect("member call") + "return ".len(),
1384                "size",
1385            ),
1386        ] {
1387            assert!(
1388                !is_declarator_name(&tree, source, start, text),
1389                "the {label} at byte {start} stays a reference"
1390            );
1391        }
1392    }
1393}